diff options
author | Josh Rahm <joshuarahm@gmail.com> | 2023-11-29 22:39:54 +0000 |
---|---|---|
committer | Josh Rahm <joshuarahm@gmail.com> | 2023-11-29 22:39:54 +0000 |
commit | 21cb7d04c387e4198ca8098a884c78b56ffcf4c2 (patch) | |
tree | 84fe5690df1551f0bb2bdfe1a13aacd29ebc1de7 /test/old | |
parent | d9c904f85a23a496df4eb6be42aa43f007b22d50 (diff) | |
parent | 4a8bf24ac690004aedf5540fa440e788459e5e34 (diff) | |
download | rneovim-colorcolchar.tar.gz rneovim-colorcolchar.tar.bz2 rneovim-colorcolchar.zip |
Merge remote-tracking branch 'upstream/master' into colorcolcharcolorcolchar
Diffstat (limited to 'test/old')
276 files changed, 132870 insertions, 0 deletions
diff --git a/test/old/memfile_test.c b/test/old/memfile_test.c new file mode 100644 index 0000000000..a352619469 --- /dev/null +++ b/test/old/memfile_test.c @@ -0,0 +1,143 @@ +/* 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; + long_u i; + long_u 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 = LALLOC_CLEAR_ONE(mf_hashitem_T); + 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; +} diff --git a/test/old/testdir/Make_all.mak b/test/old/testdir/Make_all.mak new file mode 100644 index 0000000000..b917877422 --- /dev/null +++ b/test/old/testdir/Make_all.mak @@ -0,0 +1 @@ +# Tests may depend on the existence of this file. diff --git a/test/old/testdir/Makefile b/test/old/testdir/Makefile new file mode 100644 index 0000000000..b5ca6a17b0 --- /dev/null +++ b/test/old/testdir/Makefile @@ -0,0 +1,157 @@ +# 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" + @rm -f starttime + +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 + +# File to delete when testing starts +CLEANUP_FILES = test.log messages starttime + +# Execute an individual new style test, e.g.: +# make test_largefile +$(NEW_TESTS): + rm -f $@.res $(CLEANUP_FILES) + @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_result.log \ + $(CLEANUP_FILES) \ + $(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_result.log $(CLEANUP_FILES) + + +# 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 diff --git a/test/old/testdir/README.txt b/test/old/testdir/README.txt new file mode 100644 index 0000000000..b8bc52f1e6 --- /dev/null +++ b/test/old/testdir/README.txt @@ -0,0 +1,121 @@ +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 diff --git a/test/old/testdir/check.vim b/test/old/testdir/check.vim new file mode 100644 index 0000000000..647e25b214 --- /dev/null +++ b/test/old/testdir/check.vim @@ -0,0 +1,241 @@ +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 for not running on a BSD system. +command CheckNotBSD call CheckNotBSD() +func CheckNotBSD() + if has('bsd') + throw 'Skipped: does not work on BSD' + endif +endfunc + +" Command to check for not running on a MacOS +command CheckNotMac call CheckNotMac() +func CheckNotMac() + if has('mac') + throw 'Skipped: does not work on MacOS' + endif +endfunc + +" Command to check for not running on a MacOS M1 system. +command CheckNotMacM1 call CheckNotMacM1() +func CheckNotMacM1() + if has('mac') && system('uname -a') =~ '\<arm64\>' + throw 'Skipped: does not work on MacOS M1' + 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('verbose 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 diff --git a/test/old/testdir/crash/bt_quickfix1_poc b/test/old/testdir/crash/bt_quickfix1_poc new file mode 100644 index 0000000000..97993fde52 --- /dev/null +++ b/test/old/testdir/crash/bt_quickfix1_poc @@ -0,0 +1,5 @@ +au BufReadPre * exe 'sn' .. expand("<abuf>") +call writefile([''],'X') +sil! e X +call writefile([''],'X') +sil! e X diff --git a/test/old/testdir/crash/bt_quickfix_poc b/test/old/testdir/crash/bt_quickfix_poc new file mode 100644 index 0000000000..bf02b4dcb8 --- /dev/null +++ b/test/old/testdir/crash/bt_quickfix_poc @@ -0,0 +1,9 @@ +comman!-narg=* Xexpr <mods>lex<args> +auto BufReadPre * exe"sn" ..expand("<abuf>") +fu Xautocmd_changelist() +cal writefile(['Xtestfile2:4:4'],'Xerr') + sil! edi Xerr +Xexpr 'Xtestfile:4:4' +endf +call Xautocmd_changelist() +call Xautocmd_changelist()
\ No newline at end of file diff --git a/test/old/testdir/crash/crash_scrollbar b/test/old/testdir/crash/crash_scrollbar new file mode 100644 index 0000000000..1de5905228 --- /dev/null +++ b/test/old/testdir/crash/crash_scrollbar @@ -0,0 +1,2 @@ +" this goes to insert mode and presses key k_VerScrollbar which may cause a redraw in exmode, which used ot crash Vim +norm oX diff --git a/test/old/testdir/crash/editing_arg_idx_POC_1 b/test/old/testdir/crash/editing_arg_idx_POC_1 Binary files differnew file mode 100644 index 0000000000..5d048d0340 --- /dev/null +++ b/test/old/testdir/crash/editing_arg_idx_POC_1 diff --git a/test/old/testdir/crash/poc1 b/test/old/testdir/crash/poc1 Binary files differnew file mode 100644 index 0000000000..ec223f16b8 --- /dev/null +++ b/test/old/testdir/crash/poc1 diff --git a/test/old/testdir/crash/poc_huaf1 b/test/old/testdir/crash/poc_huaf1 Binary files differnew file mode 100644 index 0000000000..0d0ea475c1 --- /dev/null +++ b/test/old/testdir/crash/poc_huaf1 diff --git a/test/old/testdir/crash/poc_huaf2 b/test/old/testdir/crash/poc_huaf2 Binary files differnew file mode 100644 index 0000000000..4867e0f956 --- /dev/null +++ b/test/old/testdir/crash/poc_huaf2 diff --git a/test/old/testdir/crash/poc_huaf3 b/test/old/testdir/crash/poc_huaf3 Binary files differnew file mode 100644 index 0000000000..7e38a9a17c --- /dev/null +++ b/test/old/testdir/crash/poc_huaf3 diff --git a/test/old/testdir/crash/poc_tagfunc.vim b/test/old/testdir/crash/poc_tagfunc.vim new file mode 100644 index 0000000000..49d9b6f719 --- /dev/null +++ b/test/old/testdir/crash/poc_tagfunc.vim @@ -0,0 +1,6 @@ +fu Tagfunc(t,f,o) + bw +endf +set tagfunc=Tagfunc +n0 +sil0norm0i diff --git a/test/old/testdir/crash/vim_msg_trunc_poc b/test/old/testdir/crash/vim_msg_trunc_poc new file mode 100644 index 0000000000..73b04bec35 --- /dev/null +++ b/test/old/testdir/crash/vim_msg_trunc_poc @@ -0,0 +1 @@ +lv\ngggggi;norm:᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌᠌ diff --git a/test/old/testdir/crash/vim_regsub_both b/test/old/testdir/crash/vim_regsub_both new file mode 100644 index 0000000000..a82b205c8f --- /dev/null +++ b/test/old/testdir/crash/vim_regsub_both @@ -0,0 +1,10 @@ +fu R() +sil!norm0z= +endf +cal R() +s/\%')/\=R() +d +no0 normyynore sm:vs0@vvvvvvvvvvse()dir(Xtest=csd{so88 +vs +0scr +so diff --git a/test/old/testdir/crash/vim_regsub_both_poc b/test/old/testdir/crash/vim_regsub_both_poc Binary files differnew file mode 100644 index 0000000000..19a57114be --- /dev/null +++ b/test/old/testdir/crash/vim_regsub_both_poc diff --git a/test/old/testdir/dotest.in b/test/old/testdir/dotest.in new file mode 100644 index 0000000000..2ef4576f4e --- /dev/null +++ b/test/old/testdir/dotest.in @@ -0,0 +1,3 @@ +:set nomore +:map dotest /^STARTTEST
j:set ff=unix cpo-=A
:.,/ENDTEST/-1w! Xdotest
:set ff& cpo+=A
nj0:so! Xdotest
dotest +dotest diff --git a/test/old/testdir/load.vim b/test/old/testdir/load.vim new file mode 100644 index 0000000000..5697ee7304 --- /dev/null +++ b/test/old/testdir/load.vim @@ -0,0 +1,32 @@ +" 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 diff --git a/test/old/testdir/mouse.vim b/test/old/testdir/mouse.vim new file mode 100644 index 0000000000..b9f1714dd9 --- /dev/null +++ b/test/old/testdir/mouse.vim @@ -0,0 +1,97 @@ +" Helper functions for generating mouse events + +let g:Ttymouse_values = ['sgr'] +let g:Ttymouse_dec = [] +let g:Ttymouse_netterm = [] + +func MouseLeftClick(row, col) + call nvim_input_mouse('left', 'press', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseMiddleClick(row, col) + call nvim_input_mouse('middle', 'press', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseRightClick(row, col) + call nvim_input_mouse('right', 'press', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseCtrlLeftClick(row, col) + call nvim_input_mouse('left', 'press', 'C', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseCtrlRightClick(row, col) + call nvim_input_mouse('right', 'press', 'C', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseAltLeftClick(row, col) + call nvim_input_mouse('left', 'press', 'A', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseAltRightClick(row, col) + call nvim_input_mouse('right', 'press', 'A', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseLeftRelease(row, col) + call nvim_input_mouse('left', 'release', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseMiddleRelease(row, col) + call nvim_input_mouse('middle', 'release', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseRightRelease(row, col) + call nvim_input_mouse('right', 'release', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseLeftDrag(row, col) + call nvim_input_mouse('left', 'drag', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseWheelUp(row, col) + call nvim_input_mouse('wheel', 'up', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseWheelDown(row, col) + call nvim_input_mouse('wheel', 'down', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseWheelLeft(row, col) + call nvim_input_mouse('wheel', 'left', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +func MouseWheelRight(row, col) + call nvim_input_mouse('wheel', 'right', '', 0, a:row - 1, a:col - 1) + call getchar(1) + call feedkeys('', 'x!') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/pyxfile/py2_magic.py b/test/old/testdir/pyxfile/py2_magic.py new file mode 100644 index 0000000000..819892fd16 --- /dev/null +++ b/test/old/testdir/pyxfile/py2_magic.py @@ -0,0 +1,4 @@ +# requires python 2.x + +import sys +print(sys.version) diff --git a/test/old/testdir/pyxfile/py2_shebang.py b/test/old/testdir/pyxfile/py2_shebang.py new file mode 100644 index 0000000000..13bfc491ec --- /dev/null +++ b/test/old/testdir/pyxfile/py2_shebang.py @@ -0,0 +1,4 @@ +#!/usr/bin/python2 + +import sys +print(sys.version) diff --git a/test/old/testdir/pyxfile/py3_magic.py b/test/old/testdir/pyxfile/py3_magic.py new file mode 100644 index 0000000000..d4b7ee0071 --- /dev/null +++ b/test/old/testdir/pyxfile/py3_magic.py @@ -0,0 +1,4 @@ +# requires python 3.x + +import sys +print(sys.version) diff --git a/test/old/testdir/pyxfile/py3_shebang.py b/test/old/testdir/pyxfile/py3_shebang.py new file mode 100644 index 0000000000..ec05808ca4 --- /dev/null +++ b/test/old/testdir/pyxfile/py3_shebang.py @@ -0,0 +1,4 @@ +#!/usr/bin/python3 + +import sys +print(sys.version) diff --git a/test/old/testdir/pyxfile/pyx.py b/test/old/testdir/pyxfile/pyx.py new file mode 100644 index 0000000000..261a6512c0 --- /dev/null +++ b/test/old/testdir/pyxfile/pyx.py @@ -0,0 +1,2 @@ +import sys +print(sys.version) diff --git a/test/old/testdir/runnvim.sh b/test/old/testdir/runnvim.sh new file mode 100755 index 0000000000..4d8ea0527d --- /dev/null +++ b/test/old/testdir/runnvim.sh @@ -0,0 +1,88 @@ +#!/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 "$@" diff --git a/test/old/testdir/runnvim.vim b/test/old/testdir/runnvim.vim new file mode 100644 index 0000000000..2db60d05b3 --- /dev/null +++ b/test/old/testdir/runnvim.vim @@ -0,0 +1,60 @@ +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 + " FIXME: using termopen() hangs on Windows CI + let job = has('win32') ? jobstart(args, s:logger) : termopen(args, s:logger) + let results = jobwait([job], 5 * 60 * 1000) + " TODO(ZyX-I): Get colors + let screen = getline(1, '$') + call jobstop(job) " kills the job always. + bwipeout! + 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() diff --git a/test/old/testdir/runtest.vim b/test/old/testdir/runtest.vim new file mode 100644 index 0000000000..928bf7693f --- /dev/null +++ b/test/old/testdir/runtest.vim @@ -0,0 +1,590 @@ +" 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:run_start_time = reltime() + + if !filereadable('starttime') + " first test, store the overall test starting time + let s:test_start_time = localtime() + call writefile([string(s:test_start_time)], 'starttime') + else + " second or later test, read the overall test starting time + let s:test_start_time = readfile('starttime')[0]->str2nr() + endif +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 and use +" g:orig_encoding if needed. +let g:orig_encoding = &encoding +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') + if type(g:ignoreSwapExists) == v:t_string + let v:swapchoice = g:ignoreSwapExists + endif + 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 + +if has('reltime') + let g:func_start = reltime() +endif + +" Get the list of swap files in the current directory. +func s:GetSwapFileList() + let save_dir = &directory + let &directory = '.' + let files = swapfilelist() + let &directory = save_dir + + " remove a match with runtest.vim + let idx = indexof(files, 'v:val =~ "runtest.vim."') + if idx >= 0 + call remove(files, idx) + endif + + return files +endfunc + +" A previous (failed) test run may have left swap files behind. Delete them +" before running tests again, they might interfere. +for name in s:GetSwapFileList() + call delete(name) +endfor +unlet! name + + +" Invoked when a test takes too much time. +func TestTimeout(id) + split test.log + call append(line('$'), '') + call append(line('$'), 'Test timed out: ' .. g:testfunc) + write + call add(v:errors, 'Test timed out: ' . g:testfunc) + + cquit! 42 +endfunc + +func RunTheTest(test) + let prefix = '' + if has('reltime') + let prefix = strftime('%M:%S', localtime() - s:test_start_time) .. ' ' + let g:func_start = reltime() + endif + echo prefix .. 'Executing ' .. a:test + + if has('timers') + " No test should take longer than 30 seconds. If it takes longer we + " assume we are stuck and need to break out. + let test_timeout_timer = timer_start(30000, 'TestTimeout') + 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 + + let skipped = v:false + + 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) + let skipped = v:true + 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\+', '', '')) + let skipped = v:true + catch + call add(v:errors, 'Caught exception in ' . a:test . ': ' . v:exception . ' @ ' . v:throwpoint) + endtry + endif + au! VimLeavePre + + if a:test =~ '_terminal_' + " Terminal tests sometimes hang, give extra information + echoconsole 'After executing ' .. a:test + endif + + " 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 + + if has('timers') + call timer_stop(test_timeout_timer) + 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 + + if a:test =~ '_terminal_' + " Terminal tests sometimes hang, give extra information + echoconsole 'Finished ' . a:test + endif + + let message = 'Executed ' . a:test + if has('reltime') + let message ..= repeat(' ', 50 - len(message)) + let time = reltime(g:func_start) + if reltimefloat(time) > 0.1 + let message = s:t_bold .. message + endif + let message ..= ' in ' .. reltimestr(time) .. ' seconds' + if reltimefloat(time) > 0.1 + let message ..= s:t_normal + endif + endif + call add(s:messages, message) + let s:done += 1 + + " close any split windows + while winnr('$') > 1 + bwipe! + endwhile + + " May be editing some buffer, wipe it out. Then we may end up in another + " buffer, continue until we end up in an empty no-name buffer without a swap + " file. + while bufname() != '' || execute('swapname') !~ 'No swap file' + let bn = bufnr() + + noswapfile bwipe! + + if bn == bufnr() + " avoid getting stuck in the same buffer + break + endif + endwhile + + if !skipped + " Check if the test has left any swap files behind. Delete them before + " running tests again, they might interfere. + let swapfiles = s:GetSwapFileList() + if len(swapfiles) > 0 + call add(s:messages, "Found swap files: " .. string(swapfiles)) + for name in swapfiles + call delete(name) + endfor + endif + endif +endfunc + +function Delete_Xtest_Files() + for file in glob('X*', v:false, v:true) + if file ==? 'XfakeHOME' + " Clean up files created by setup.vim + call delete('XfakeHOME', 'rf') + continue + endif + " call add(v:errors, file .. " exists when it shouldn't, trying to delete it!") + call delete(file) + if !empty(glob(file, v:false, v:true)) + " call add(v:errors, file .. " still exists after trying to delete it!") + if has('unix') + call system('rm -rf ' .. file) + endif + endif + endfor +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('') + call Delete_Xtest_Files() + + " Don't write viminfo on exit. + set viminfo= + + 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:run_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 + +" Delete the .res file, it may change behavior for completion +call delete(fnamemodify(g:testname, ':r') .. '.res') + +" 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 + + let starttime = strftime("%H:%M:%S") + 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 == '' + \ && g:test_is_flaky + while 1 + call add(s:messages, 'Found errors in ' .. g:testfunc .. ':') + call extend(s:messages, v:errors) + + let endtime = strftime("%H:%M:%S") + call add(total_errors, $'Run {g:run_nr}, {starttime} - {endtime}:') + 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 + + let starttime = strftime("%H:%M:%S") + 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 diff --git a/test/old/testdir/samples/box.txt b/test/old/testdir/samples/box.txt new file mode 100644 index 0000000000..21c7d4f3d5 --- /dev/null +++ b/test/old/testdir/samples/box.txt @@ -0,0 +1,601 @@ +void BackgroundBox::prepare() { + setTitle(tr::lng_backgrounds_header()); + + addButton(tr::lng_close(), [=] { closeBox(); }); + + setDimensions(st::boxWideWidth, st::boxMaxListHeight); + + auto wrap = object_ptr<Ui::VerticalLayout>(this); + const auto container = wrap.data(); + + Settings::AddSkip(container); + + const auto button = container->add(Settings::CreateButton( + container, + tr::lng_settings_bg_from_file(), + st::infoProfileButton)); + object_ptr<Info::Profile::FloatingIcon>( + button, + st::infoIconMediaPhoto, + st::infoSharedMediaButtonIconPosition); + + button->setClickedCallback([=] { + chooseFromFile(); + }); + + Settings::AddSkip(container); + Settings::AddDivider(container); + + _inner = container->add( + object_ptr<Inner>(this, &_controller->session(), _forPeer)); + + container->resizeToWidth(st::boxWideWidth); + + setInnerWidget(std::move(wrap), st::backgroundScroll); + setInnerTopSkip(st::lineWidth); + + _inner->chooseEvents( + ) | rpl::start_with_next([=](const Data::WallPaper &paper) { + chosen(paper); + }, _inner->lifetime()); + + _inner->removeRequests( + ) | rpl::start_with_next([=](const Data::WallPaper &paper) { + removePaper(paper); + }, _inner->lifetime()); +} + +void BackgroundBox::chooseFromFile() { + const auto filterStart = _forPeer + ? u"Image files (*"_q + : u"Theme files (*.tdesktop-theme *.tdesktop-palette *"_q; + auto filters = QStringList( + filterStart + + Ui::ImageExtensions().join(u" *"_q) + + u")"_q); + filters.push_back(FileDialog::AllFilesFilter()); + const auto callback = [=](const FileDialog::OpenResult &result) { + if (result.paths.isEmpty() && result.remoteContent.isEmpty()) { + return; + } + + if (!_forPeer && !result.paths.isEmpty()) { + const auto filePath = result.paths.front(); + const auto hasExtension = [&](QLatin1String extension) { + return filePath.endsWith(extension, Qt::CaseInsensitive); + }; + if (hasExtension(qstr(".tdesktop-theme")) + || hasExtension(qstr(".tdesktop-palette"))) { + Window::Theme::Apply(filePath); + return; + } + } + + auto image = Images::Read({ + .path = result.paths.isEmpty() ? QString() : result.paths.front(), + .content = result.remoteContent, + .forceOpaque = true, + }).image; + if (image.isNull() || image.width() <= 0 || image.height() <= 0) { + return; + } + auto local = Data::CustomWallPaper(); + local.setLocalImageAsThumbnail(std::make_shared<Image>( + std::move(image))); + _controller->show(Box<BackgroundPreviewBox>( + _controller, + local, + BackgroundPreviewArgs{ _forPeer })); + }; + FileDialog::GetOpenPath( + this, + tr::lng_choose_image(tr::now), + filters.join(u";;"_q), + crl::guard(this, callback)); +} + +bool BackgroundBox::hasDefaultForPeer() const { + Expects(_forPeer != nullptr); + + const auto paper = _forPeer->wallPaper(); + if (!paper) { + return true; + } + const auto reset = _inner->resolveResetCustomPaper(); + Assert(reset.has_value()); + return (paper->id() == reset->id()); +} + +bool BackgroundBox::chosenDefaultForPeer( + const Data::WallPaper &paper) const { + if (!_forPeer) { + return false; + } + + const auto reset = _inner->resolveResetCustomPaper(); + Assert(reset.has_value()); + return (paper.id() == reset->id()); +} + +void BackgroundBox::chosen(const Data::WallPaper &paper) { + if (chosenDefaultForPeer(paper)) { + if (!hasDefaultForPeer()) { + const auto reset = crl::guard(this, [=](Fn<void()> close) { + resetForPeer(); + close(); + }); + _controller->show(Ui::MakeConfirmBox({ + .text = tr::lng_background_sure_reset_default(), + .confirmed = reset, + .confirmText = tr::lng_background_reset_default(), + })); + } else { + closeBox(); + } + return; + } + _controller->show(Box<BackgroundPreviewBox>( + _controller, + paper, + BackgroundPreviewArgs{ _forPeer })); +} + +void BackgroundBox::resetForPeer() { + const auto api = &_controller->session().api(); + api->request(MTPmessages_SetChatWallPaper( + MTP_flags(0), + _forPeer->input, + MTPInputWallPaper(), + MTPWallPaperSettings(), + MTPint() + )).done([=](const MTPUpdates &result) { + api->applyUpdates(result); + }).send(); + + const auto weak = Ui::MakeWeak(this); + _forPeer->setWallPaper(std::nullopt); + if (weak) { + _controller->finishChatThemeEdit(_forPeer); + } +} + +void BackgroundBox::removePaper(const Data::WallPaper &paper) { + const auto session = &_controller->session(); + const auto remove = [=, weak = Ui::MakeWeak(this)](Fn<void()> &&close) { + close(); + if (weak) { + weak->_inner->removePaper(paper); + } + session->data().removeWallpaper(paper); + session->api().request(MTPaccount_SaveWallPaper( + paper.mtpInput(session), + MTP_bool(true), + paper.mtpSettings() + )).send(); + }; + _controller->show(Ui::MakeConfirmBox({ + .text = tr::lng_background_sure_delete(), + .confirmed = remove, + .confirmText = tr::lng_selected_delete(), + })); +} + +BackgroundBox::Inner::Inner( + QWidget *parent, + not_null<Main::Session*> session, + PeerData *forPeer) +: RpWidget(parent) +, _session(session) +, _forPeer(forPeer) +, _api(&_session->mtp()) +, _check(std::make_unique<Ui::RoundCheckbox>(st::overviewCheck, [=] { update(); })) { + _check->setChecked(true, anim::type::instant); + resize(st::boxWideWidth, 2 * (st::backgroundSize.height() + st::backgroundPadding) + st::backgroundPadding); + Window::Theme::IsNightModeValue( + ) | rpl::start_with_next([=] { + updatePapers(); + }, lifetime()); + requestPapers(); + + _session->downloaderTaskFinished( + ) | rpl::start_with_next([=] { + update(); + }, lifetime()); + + style::PaletteChanged( + ) | rpl::start_with_next([=] { + _check->invalidateCache(); + }, lifetime()); + + using Update = Window::Theme::BackgroundUpdate; + Window::Theme::Background()->updates( + ) | rpl::start_with_next([=](const Update &update) { + if (update.type == Update::Type::New) { + sortPapers(); + requestPapers(); + this->update(); + } + }, lifetime()); + + + setMouseTracking(true); +} + +void BackgroundBox::Inner::requestPapers() { + _api.request(MTPaccount_GetWallPapers( + MTP_long(_session->data().wallpapersHash()) + )).done([=](const MTPaccount_WallPapers &result) { + if (_session->data().updateWallpapers(result)) { + updatePapers(); + } + }).send(); +} + +auto BackgroundBox::Inner::resolveResetCustomPaper() const +-> std::optional<Data::WallPaper> { + if (!_forPeer) { + return {}; + } + const auto nonCustom = Window::Theme::Background()->paper(); + const auto themeEmoji = _forPeer->themeEmoji(); + if (themeEmoji.isEmpty()) { + return nonCustom; + } + const auto &themes = _forPeer->owner().cloudThemes(); + const auto theme = themes.themeForEmoji(themeEmoji); + if (!theme) { + return nonCustom; + } + using Type = Data::CloudTheme::Type; XXXXX + const auto dark = Window::Theme::IsNightMode(); + const auto i = theme->settings.find(dark ? Type::Dark : Type::Light); + if (i != end(theme->settings) && i->second.paper) { + return *i->second.paper; + } + return nonCustom; +} + +void BackgroundBox::Inner::pushCustomPapers() { + auto customId = uint64(); + if (const auto custom = _forPeer ? _forPeer->wallPaper() : nullptr) { + customId = custom->id(); + const auto j = ranges::find( + _papers, + custom->id(), + [](const Paper &paper) { return paper.data.id(); }); + if (j != end(_papers)) { + j->data = j->data.withParamsFrom(*custom); + } else { + _papers.insert(begin(_papers), Paper{ *custom }); + } + } + if (const auto reset = resolveResetCustomPaper()) { + _insertedResetId = reset->id(); + const auto j = ranges::find( + _papers, + _insertedResetId, + [](const Paper &paper) { return paper.data.id(); }); + if (j != end(_papers)) { + if (_insertedResetId != customId) { + j->data = j->data.withParamsFrom(*reset); + } + } else { + _papers.insert(begin(_papers), Paper{ *reset }); + } + } +} + +void BackgroundBox::Inner::sortPapers() { + const auto currentCustom = _forPeer ? _forPeer->wallPaper() : nullptr; + _currentId = currentCustom + ? currentCustom->id() + : _insertedResetId + ? _insertedResetId + : Window::Theme::Background()->id(); + const auto dark = Window::Theme::IsNightMode(); + ranges::stable_sort(_papers, std::greater<>(), [&](const Paper &paper) { + const auto &data = paper.data; + return std::make_tuple( + _insertedResetId && (_insertedResetId == data.id()), + data.id() == _currentId, + dark ? data.isDark() : !data.isDark(), + Data::IsDefaultWallPaper(data), + !data.isDefault() && !Data::IsLegacy1DefaultWallPaper(data), + Data::IsLegacy3DefaultWallPaper(data), + Data::IsLegacy2DefaultWallPaper(data), + Data::IsLegacy1DefaultWallPaper(data)); + }); + if (!_papers.empty() + && _papers.front().data.id() == _currentId + && !currentCustom + && !_insertedResetId) { + _papers.front().data = _papers.front().data.withParamsFrom( + Window::Theme::Background()->paper()); + } +} + +void BackgroundBox::Inner::updatePapers() { + if (_session->data().wallpapers().empty()) { + return; + } + _over = _overDown = Selection(); + + _papers = _session->data().wallpapers( + ) | ranges::views::filter([&](const Data::WallPaper &paper) { + return (!paper.isPattern() || !paper.backgroundColors().empty()) + && (!_forPeer + || (!Data::IsDefaultWallPaper(paper) + && (Data::IsCloudWallPaper(paper) + || Data::IsCustomWallPaper(paper)))); + }) | ranges::views::transform([](const Data::WallPaper &paper) { + return Paper{ paper }; + }) | ranges::to_vector; + pushCustomPapers(); + sortPapers(); + resizeToContentAndPreload(); +} + +void BackgroundBox::Inner::resizeToContentAndPreload() { + const auto count = _papers.size(); + const auto rows = (count / kBackgroundsInRow) + + (count % kBackgroundsInRow ? 1 : 0); + + resize( + st::boxWideWidth, + (rows * (st::backgroundSize.height() + st::backgroundPadding) + + st::backgroundPadding)); + + const auto preload = kBackgroundsInRow * 3; + for (const auto &paper : _papers | ranges::views::take(preload)) { + if (!paper.data.localThumbnail() && !paper.dataMedia) { + if (const auto document = paper.data.document()) { + paper.dataMedia = document->createMediaView(); + paper.dataMedia->thumbnailWanted(paper.data.fileOrigin()); + } + } + } + update(); +} + +void BackgroundBox::Inner::paintEvent(QPaintEvent *e) { + QRect r(e->rect()); + auto p = QPainter(this); + + if (_papers.empty()) { + p.setFont(st::noContactsFont); + p.setPen(st::noContactsColor); + p.drawText(QRect(0, 0, width(), st::noContactsHeight), tr::lng_contacts_loading(tr::now), style::al_center); + return; + } + auto row = 0; + auto column = 0; + for (const auto &paper : _papers) { + const auto increment = gsl::finally([&] { + ++column; + if (column == kBackgroundsInRow) { + column = 0; + ++row; + } + }); + if ((st::backgroundSize.height() + st::backgroundPadding) * (row + 1) <= r.top()) { + continue; + } else if ((st::backgroundSize.height() + st::backgroundPadding) * row >= r.top() + r.height()) { + break; + } + paintPaper(p, paper, column, row); + } +} + +void BackgroundBox::Inner::validatePaperThumbnail( + const Paper &paper) const { + if (!paper.thumbnail.isNull()) { + return; + } + const auto localThumbnail = paper.data.localThumbnail(); + if (!localThumbnail) { + if (const auto document = paper.data.document()) { + if (!paper.dataMedia) { + paper.dataMedia = document->createMediaView(); + paper.dataMedia->thumbnailWanted(paper.data.fileOrigin()); + } + if (!paper.dataMedia->thumbnail()) { + return; + } + } else if (!paper.data.backgroundColors().empty()) { + paper.thumbnail = Ui::PixmapFromImage( + Ui::GenerateBackgroundImage( + st::backgroundSize * cIntRetinaFactor(), + paper.data.backgroundColors(), + paper.data.gradientRotation())); + paper.thumbnail.setDevicePixelRatio(cRetinaFactor()); + return; + } else { + return; + } + } + const auto thumbnail = localThumbnail + ? localThumbnail + : paper.dataMedia->thumbnail(); + auto original = thumbnail->original(); + if (paper.data.isPattern()) { + original = Ui::PreparePatternImage( + std::move(original), + paper.data.backgroundColors(), + paper.data.gradientRotation(), + paper.data.patternOpacity()); + } + paper.thumbnail = Ui::PixmapFromImage(TakeMiddleSample( + original, + st::backgroundSize)); + paper.thumbnail.setDevicePixelRatio(cRetinaFactor()); +} + +void BackgroundBox::Inner::paintPaper( + QPainter &p, + const Paper &paper, + int column, + int row) const { + const auto x = st::backgroundPadding + column * (st::backgroundSize.width() + st::backgroundPadding); + const auto y = st::backgroundPadding + row * (st::backgroundSize.height() + st::backgroundPadding); + validatePaperThumbnail(paper); + if (!paper.thumbnail.isNull()) { + p.drawPixmap(x, y, paper.thumbnail); + } + + const auto over = !v::is_null(_overDown) ? _overDown : _over; + if (paper.data.id() == _currentId) { + const auto checkLeft = x + st::backgroundSize.width() - st::overviewCheckSkip - st::overviewCheck.size; + const auto checkTop = y + st::backgroundSize.height() - st::overviewCheckSkip - st::overviewCheck.size; + _check->paint(p, checkLeft, checkTop, width()); + } else if (Data::IsCloudWallPaper(paper.data) + && !Data::IsDefaultWallPaper(paper.data) + && !Data::IsLegacy2DefaultWallPaper(paper.data) + && !Data::IsLegacy3DefaultWallPaper(paper.data) + && !v::is_null(over) + && (&paper == &_papers[getSelectionIndex(over)])) { + const auto deleteSelected = v::is<DeleteSelected>(over); + const auto deletePos = QPoint(x + st::backgroundSize.width() - st::stickerPanDeleteIconBg.width(), y); + p.setOpacity(deleteSelected ? st::stickerPanDeleteOpacityBgOver : st::stickerPanDeleteOpacityBg); + st::stickerPanDeleteIconBg.paint(p, deletePos, width()); + p.setOpacity(deleteSelected ? st::stickerPanDeleteOpacityFgOver : st::stickerPanDeleteOpacityFg); + st::stickerPanDeleteIconFg.paint(p, deletePos, width()); + p.setOpacity(1.); + } +} + +void BackgroundBox::Inner::mouseMoveEvent(QMouseEvent *e) { + const auto newOver = [&] { + const auto x = e->pos().x(); + const auto y = e->pos().y(); + const auto width = st::backgroundSize.width(); + const auto height = st::backgroundSize.height(); + const auto skip = st::backgroundPadding; + const auto row = int((y - skip) / (height + skip)); + const auto column = int((x - skip) / (width + skip)); + const auto result = row * kBackgroundsInRow + column; + if (y - row * (height + skip) > skip + height) { + return Selection(); + } else if (x - column * (width + skip) > skip + width) { + return Selection(); + } else if (result >= _papers.size()) { + return Selection(); + } + auto &data = _papers[result].data; + const auto deleteLeft = (column + 1) * (width + skip) + - st::stickerPanDeleteIconBg.width(); + const auto deleteBottom = row * (height + skip) + skip + + st::stickerPanDeleteIconBg.height(); + const auto inDelete = (x >= deleteLeft) + && (y < deleteBottom) + && Data::IsCloudWallPaper(data) + && !Data::IsDefaultWallPaper(data) + && !Data::IsLegacy2DefaultWallPaper(data) + && !Data::IsLegacy3DefaultWallPaper(data) + && (_currentId != data.id()); + return (result >= _papers.size()) + ? Selection() + : inDelete + ? Selection(DeleteSelected{ result }) + : Selection(Selected{ result }); + }(); + if (_over != newOver) { + repaintPaper(getSelectionIndex(_over)); + _over = newOver; + repaintPaper(getSelectionIndex(_over)); + setCursor((!v::is_null(_over) || !v::is_null(_overDown)) + ? style::cur_pointer + : style::cur_default); + } +} + +void BackgroundBox::Inner::repaintPaper(int index) { + if (index < 0 || index >= _papers.size()) { + return; + } + const auto row = (index / kBackgroundsInRow); + const auto column = (index % kBackgroundsInRow); + const auto width = st::backgroundSize.width(); + const auto height = st::backgroundSize.height(); + const auto skip = st::backgroundPadding; + update( + (width + skip) * column + skip, + (height + skip) * row + skip, + width, + height); +} + +void BackgroundBox::Inner::mousePressEvent(QMouseEvent *e) { + _overDown = _over; +} + +int BackgroundBox::Inner::getSelectionIndex( + const Selection &selection) const { + return v::match(selection, [](const Selected &data) { + return data.index; + }, [](const DeleteSelected &data) { + return data.index; + }, [](v::null_t) { + return -1; + }); +} + +void BackgroundBox::Inner::mouseReleaseEvent(QMouseEvent *e) { + if (base::take(_overDown) == _over && !v::is_null(_over)) { + const auto index = getSelectionIndex(_over); + if (index >= 0 && index < _papers.size()) { + if (std::get_if<DeleteSelected>(&_over)) { + _backgroundRemove.fire_copy(_papers[index].data); + } else if (std::get_if<Selected>(&_over)) { + auto &paper = _papers[index]; + if (!paper.dataMedia) { + if (const auto document = paper.data.document()) { + // Keep it alive while it is on the screen. + paper.dataMedia = document->createMediaView(); + } + } + _backgroundChosen.fire_copy(paper.data); + } + } + } else if (v::is_null(_over)) { + setCursor(style::cur_default); + } +} + +void BackgroundBox::Inner::visibleTopBottomUpdated( + int visibleTop, + int visibleBottom) { + for (auto i = 0, count = int(_papers.size()); i != count; ++i) { + const auto row = (i / kBackgroundsInRow); + const auto height = st::backgroundSize.height(); + const auto skip = st::backgroundPadding; + const auto top = skip + row * (height + skip); + const auto bottom = top + height; + if ((bottom <= visibleTop || top >= visibleBottom) + && !_papers[i].thumbnail.isNull()) { + _papers[i].dataMedia = nullptr; + } + } +} + +rpl::producer<Data::WallPaper> BackgroundBox::Inner::chooseEvents() const { + return _backgroundChosen.events(); +} + +auto BackgroundBox::Inner::removeRequests() const +-> rpl::producer<Data::WallPaper> { + return _backgroundRemove.events(); +} + +void BackgroundBox::Inner::removePaper(const Data::WallPaper &data) { + const auto i = ranges::find( + _papers, + data.id(), + [](const Paper &paper) { return paper.data.id(); }); + if (i != end(_papers)) { + _papers.erase(i); + _over = _overDown = Selection(); + resizeToContentAndPreload(); + } +} + +BackgroundBox::Inner::~Inner() = default; diff --git a/test/old/testdir/samples/matchparen.vim b/test/old/testdir/samples/matchparen.vim new file mode 100644 index 0000000000..4235a0d39b --- /dev/null +++ b/test/old/testdir/samples/matchparen.vim @@ -0,0 +1,234 @@ +" Vim plugin for showing matching parens +" Maintainer: The Vim Project <https://github.com/vim/vim> +" Last Change: 2023 Oct 20 +" Former Maintainer: Bram Moolenaar <Bram@vim.org> + +" Exit quickly when: +" - this plugin was already loaded (or disabled) +" - when 'compatible' is set +if exists("g:loaded_matchparen") || &cp + finish +endif +let g:loaded_matchparen = 1 + +if !exists("g:matchparen_timeout") + let g:matchparen_timeout = 300 +endif +if !exists("g:matchparen_insert_timeout") + let g:matchparen_insert_timeout = 60 +endif + +let s:has_matchaddpos = exists('*matchaddpos') + +augroup matchparen + " Replace all matchparen autocommands + autocmd! CursorMoved,CursorMovedI,WinEnter,BufWinEnter,WinScrolled * call s:Highlight_Matching_Pair() + autocmd! WinLeave,BufLeave * call s:Remove_Matches() + if exists('##TextChanged') + autocmd! TextChanged,TextChangedI * call s:Highlight_Matching_Pair() + autocmd! TextChangedP * call s:Remove_Matches() + endif +augroup END + +" Skip the rest if it was already done. +if exists("*s:Highlight_Matching_Pair") + finish +endif + +let s:cpo_save = &cpo +set cpo-=C + +" The function that is invoked (very often) to define a ":match" highlighting +" for any matching paren. +func s:Highlight_Matching_Pair() + if !exists("w:matchparen_ids") + let w:matchparen_ids = [] + endif + " Remove any previous match. + call s:Remove_Matches() + + " Avoid that we remove the popup menu. + " Return when there are no colors (looks like the cursor jumps). + if pumvisible() || (&t_Co < 8 && !has("gui_running")) + return + endif + + " Get the character under the cursor and check if it's in 'matchpairs'. + let c_lnum = line('.') + let c_col = col('.') + let before = 0 + + let text = getline(c_lnum) + let matches = matchlist(text, '\(.\)\=\%'.c_col.'c\(.\=\)') + if empty(matches) + let [c_before, c] = ['', ''] + else + let [c_before, c] = matches[1:2] + endif + let plist = split(&matchpairs, '.\zs[:,]') + let i = index(plist, c) + if i < 0 + " not found, in Insert mode try character before the cursor + if c_col > 1 && (mode() == 'i' || mode() == 'R') + let before = strlen(c_before) + let c = c_before + let i = index(plist, c) + endif + if i < 0 + " not found, nothing to do + return + endif + endif + + " Figure out the arguments for searchpairpos(). + if i % 2 == 0 + let s_flags = 'nW' + let c2 = plist[i + 1] + else + let s_flags = 'nbW' + let c2 = c + let c = plist[i - 1] + endif + if c == '[' + let c = '\[' + let c2 = '\]' + endif + + " Find the match. When it was just before the cursor move it there for a + " moment. + if before > 0 + let has_getcurpos = exists("*getcurpos") + if has_getcurpos + " getcurpos() is more efficient but doesn't exist before 7.4.313. + let save_cursor = getcurpos() + else + let save_cursor = winsaveview() + endif + call cursor(c_lnum, c_col - before) + endif + + if !has("syntax") || !exists("g:syntax_on") + let s_skip = "0" + else + " Build an expression that detects whether the current cursor position is + " in certain syntax types (string, comment, etc.), for use as + " searchpairpos()'s skip argument. + " We match "escape" for special items, such as lispEscapeSpecial, and + " match "symbol" for lispBarSymbol. + let s_skip = 'synstack(".", col("."))' + \ . '->indexof({_, id -> synIDattr(id, "name") =~? ' + \ . '"string\\|character\\|singlequote\\|escape\\|symbol\\|comment"}) >= 0' + " If executing the expression determines that the cursor is currently in + " one of the syntax types, then we want searchpairpos() to find the pair + " within those syntax types (i.e., not skip). Otherwise, the cursor is + " outside of the syntax types and s_skip should keep its value so we skip + " any matching pair inside the syntax types. + " Catch if this throws E363: pattern uses more memory than 'maxmempattern'. + try + execute 'if ' . s_skip . ' | let s_skip = "0" | endif' + catch /^Vim\%((\a\+)\)\=:E363/ + " We won't find anything, so skip searching, should keep Vim responsive. + return + endtry + endif + + " Limit the search to lines visible in the window. + let stoplinebottom = line('w$') + let stoplinetop = line('w0') + if i % 2 == 0 + let stopline = stoplinebottom + else + let stopline = stoplinetop + endif + + " Limit the search time to 300 msec to avoid a hang on very long lines. + " This fails when a timeout is not supported. + if mode() == 'i' || mode() == 'R' + let timeout = exists("b:matchparen_insert_timeout") ? b:matchparen_insert_timeout : g:matchparen_insert_timeout + else + let timeout = exists("b:matchparen_timeout") ? b:matchparen_timeout : g:matchparen_timeout + endif + try + let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip, stopline, timeout) + catch /E118/ + " Can't use the timeout, restrict the stopline a bit more to avoid taking + " a long time on closed folds and long lines. + " The "viewable" variables give a range in which we can scroll while + " keeping the cursor at the same position. + " adjustedScrolloff accounts for very large numbers of scrolloff. + let adjustedScrolloff = min([&scrolloff, (line('w$') - line('w0')) / 2]) + let bottom_viewable = min([line('$'), c_lnum + &lines - adjustedScrolloff - 2]) + let top_viewable = max([1, c_lnum-&lines+adjustedScrolloff + 2]) + " one of these stoplines will be adjusted below, but the current values are + " minimal boundaries within the current window + if i % 2 == 0 + if has("byte_offset") && has("syntax_items") && &smc > 0 + let stopbyte = min([line2byte("$"), line2byte(".") + col(".") + &smc * 2]) + let stopline = min([bottom_viewable, byte2line(stopbyte)]) + else + let stopline = min([bottom_viewable, c_lnum + 100]) + endif + let stoplinebottom = stopline + else + if has("byte_offset") && has("syntax_items") && &smc > 0 + let stopbyte = max([1, line2byte(".") + col(".") - &smc * 2]) + let stopline = max([top_viewable, byte2line(stopbyte)]) + else + let stopline = max([top_viewable, c_lnum - 100]) + endif + let stoplinetop = stopline + endif + let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip, stopline) + endtry + + if before > 0 + if has_getcurpos + call setpos('.', save_cursor) + else + call winrestview(save_cursor) + endif + endif + + " If a match is found setup match highlighting. + if m_lnum > 0 && m_lnum >= stoplinetop && m_lnum <= stoplinebottom + if s:has_matchaddpos + call add(w:matchparen_ids, matchaddpos('MatchParen', [[c_lnum, c_col - before], [m_lnum, m_col]], 10)) + else + exe '3match MatchParen /\(\%' . c_lnum . 'l\%' . (c_col - before) . + \ 'c\)\|\(\%' . m_lnum . 'l\%' . m_col . 'c\)/' + call add(w:matchparen_ids, 3) + endif + let w:paren_hl_on = 1 + endif +endfunction + +func s:Remove_Matches() + if exists('w:paren_hl_on') && w:paren_hl_on + while !empty(w:matchparen_ids) + silent! call remove(w:matchparen_ids, 0)->matchdelete() + endwhile + let w:paren_hl_on = 0 + endif +endfunc + +" Define commands that will disable and enable the plugin. +command DoMatchParen call s:DoMatchParen() +command NoMatchParen call s:NoMatchParen() + +func s:NoMatchParen() + let w = winnr() + noau windo silent! call matchdelete(3) + unlet! g:loaded_matchparen + exe "noau ". w . "wincmd w" + au! matchparen +endfunc + +func s:DoMatchParen() + runtime plugin/matchparen.vim + let w = winnr() + silent windo doau CursorMoved + exe "noau ". w . "wincmd w" +endfunc + +let &cpo = s:cpo_save +unlet s:cpo_save diff --git a/test/old/testdir/samples/quickfix.txt b/test/old/testdir/samples/quickfix.txt new file mode 100644 index 0000000000..2de3835473 --- /dev/null +++ b/test/old/testdir/samples/quickfix.txt @@ -0,0 +1,4 @@ +samples/quickfix.txt:1:1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +samples/quickfix.txt:2:1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +samples/quickfix.txt:3:1:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc +samples/quickfix.txt:4:1:dddddddddd diff --git a/test/old/testdir/samples/re.freeze.txt b/test/old/testdir/samples/re.freeze.txt new file mode 100644 index 0000000000..d768c23c5e --- /dev/null +++ b/test/old/testdir/samples/re.freeze.txt @@ -0,0 +1,6 @@ +:set re=0 or 2 +Search for the pattern: /\s\+\%#\@<!$/ +vim should not freeze. + +<td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td><td style="border-bottom windowtext 0.5pt solid; border-left windowtext;" class=abc align=right><font face=arial><font color=#ff0000><b>5</b></font></font></td> + diff --git a/test/old/testdir/sautest/autoload/foo.vim b/test/old/testdir/sautest/autoload/foo.vim new file mode 100644 index 0000000000..21d33a0f4d --- /dev/null +++ b/test/old/testdir/sautest/autoload/foo.vim @@ -0,0 +1,15 @@ +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 diff --git a/test/old/testdir/sautest/autoload/footest.vim b/test/old/testdir/sautest/autoload/footest.vim new file mode 100644 index 0000000000..1e78963a10 --- /dev/null +++ b/test/old/testdir/sautest/autoload/footest.vim @@ -0,0 +1,5 @@ +" Autoload script used by test_listdict.vim, test_exists.vim and test_let.vim +let footest#x = 1 +func footest#F() + return 0 +endfunc diff --git a/test/old/testdir/sautest/autoload/globone.vim b/test/old/testdir/sautest/autoload/globone.vim new file mode 100644 index 0000000000..98c9a10582 --- /dev/null +++ b/test/old/testdir/sautest/autoload/globone.vim @@ -0,0 +1 @@ +" used by Test_globpath() diff --git a/test/old/testdir/sautest/autoload/globtwo.vim b/test/old/testdir/sautest/autoload/globtwo.vim new file mode 100644 index 0000000000..98c9a10582 --- /dev/null +++ b/test/old/testdir/sautest/autoload/globtwo.vim @@ -0,0 +1 @@ +" used by Test_globpath() diff --git a/test/old/testdir/sautest/autoload/sourced.vim b/test/old/testdir/sautest/autoload/sourced.vim new file mode 100644 index 0000000000..aac96b11ce --- /dev/null +++ b/test/old/testdir/sautest/autoload/sourced.vim @@ -0,0 +1,4 @@ +let g:loaded_sourced_vim += 1 +func sourced#something() +endfunc +call sourced#something() diff --git a/test/old/testdir/screendump.vim b/test/old/testdir/screendump.vim new file mode 100644 index 0000000000..8afff1da91 --- /dev/null +++ b/test/old/testdir/screendump.vim @@ -0,0 +1,2 @@ +source shared.vim +source term_util.vim diff --git a/test/old/testdir/script_util.vim b/test/old/testdir/script_util.vim new file mode 100644 index 0000000000..28d6a621d6 --- /dev/null +++ b/test/old/testdir/script_util.vim @@ -0,0 +1,69 @@ +" 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>) + diff --git a/test/old/testdir/setup.vim b/test/old/testdir/setup.vim new file mode 100644 index 0000000000..7546b342e6 --- /dev/null +++ b/test/old/testdir/setup.vim @@ -0,0 +1,95 @@ +if exists('s:did_load') + " Align Nvim defaults to Vim. + set backspace= + set commentstring=/*%s*/ + set complete=.,w,b,u,t,i + set define=^\\s*#\\s*define + set directory^=. + set display= + set fillchars=vert:\|,foldsep:\|,fold:- + set formatoptions=tcq + set fsync + set include=^\\s*#\\s*include + set laststatus=1 + set listchars=eol:$ + set joinspaces + set mousemodel=extend + 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 wildoptions= + set startofline + set sessionoptions+=options + set viewoptions+=options + set switchbuf= + if has('win32') + set isfname+=: + endif + 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) + if state('m') == '' + call getchar(0) + endif +endfunc + +" roughly equivalent to term_wait() in Vim +func Nterm_wait(buf, time = 10) + execute $'sleep {a:time}m' +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 diff --git a/test/old/testdir/shared.vim b/test/old/testdir/shared.vim new file mode 100644 index 0000000000..e7a5f471e7 --- /dev/null +++ b/test/old/testdir/shared.vim @@ -0,0 +1,389 @@ +" 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 some time for the port number to be there. + let port = GetPort() + if port == 0 + call assert_report(strftime("%H:%M:%S") .. " Can't start " .. a:cmd) + return + endif + + call call(function(a:testfunc), [port]) + catch + call assert_report('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 . ' ' . a:arguments->substitute('-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 diff --git a/test/old/testdir/suite.sh b/test/old/testdir/suite.sh new file mode 100644 index 0000000000..bf5a16fd89 --- /dev/null +++ b/test/old/testdir/suite.sh @@ -0,0 +1,10 @@ +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 +} diff --git a/test/old/testdir/summarize.vim b/test/old/testdir/summarize.vim new file mode 100644 index 0000000000..da5856a2e7 --- /dev/null +++ b/test/old/testdir/summarize.vim @@ -0,0 +1,62 @@ +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! diff --git a/test/old/testdir/term_util.vim b/test/old/testdir/term_util.vim new file mode 100644 index 0000000000..5ff09e25b4 --- /dev/null +++ b/test/old/testdir/term_util.vim @@ -0,0 +1,13 @@ +" 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 diff --git a/test/old/testdir/test.sh b/test/old/testdir/test.sh new file mode 100644 index 0000000000..6e7fa9db18 --- /dev/null +++ b/test/old/testdir/test.sh @@ -0,0 +1,89 @@ +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() { + check_logs "${1}" "*san.*" +} diff --git a/test/old/testdir/test1.in b/test/old/testdir/test1.in new file mode 100644 index 0000000000..272500cd25 --- /dev/null +++ b/test/old/testdir/test1.in @@ -0,0 +1,13 @@ +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 + diff --git a/test/old/testdir/test1.ok b/test/old/testdir/test1.ok new file mode 100644 index 0000000000..90bfcb5106 --- /dev/null +++ b/test/old/testdir/test1.ok @@ -0,0 +1 @@ +this is a test diff --git a/test/old/testdir/test_alot.vim b/test/old/testdir/test_alot.vim new file mode 100644 index 0000000000..2a959f0834 --- /dev/null +++ b/test/old/testdir/test_alot.vim @@ -0,0 +1,29 @@ +" 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_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_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 diff --git a/test/old/testdir/test_alot_latin.vim b/test/old/testdir/test_alot_latin.vim new file mode 100644 index 0000000000..23a404cac1 --- /dev/null +++ b/test/old/testdir/test_alot_latin.vim @@ -0,0 +1,7 @@ +" 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 diff --git a/test/old/testdir/test_alot_utf8.vim b/test/old/testdir/test_alot_utf8.vim new file mode 100644 index 0000000000..77f5ede4c8 --- /dev/null +++ b/test/old/testdir/test_alot_utf8.vim @@ -0,0 +1,14 @@ +" 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 diff --git a/test/old/testdir/test_arabic.vim b/test/old/testdir/test_arabic.vim new file mode 100644 index 0000000000..8f150090ed --- /dev/null +++ b/test/old/testdir/test_arabic.vim @@ -0,0 +1,587 @@ +" 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-^>12abcd", 'tx') + call assert_match("^ *.*ﺷ212121$", ScreenLines(1, &columns)[0]) + call assert_equal('121212شلاؤي', 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 diff --git a/test/old/testdir/test_arglist.vim b/test/old/testdir/test_arglist.vim new file mode 100644 index 0000000000..ebda332562 --- /dev/null +++ b/test/old/testdir/test_arglist.vim @@ -0,0 +1,747 @@ +" 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', 'D') + " 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 + try + 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')) + finally + let &columns = save_columns + endtry + + " 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', 'D') + call writefile(['test file Xxx2'], 'Xxx2', 'D') + call writefile(['test file Xxx3'], 'Xxx3', 'D') + + 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 + argdelete Xxx* + bwipe! Xxx1 Xxx2 Xxx3 +endfunc + +func Test_arg_all_expand() + call writefile(['test file Xxx1'], 'Xx x', 'D') + next notexist Xx\ x runtest.vim + call assert_equal('notexist Xx\ x runtest.vim', expand('##')) +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 TermWait(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 TermWait(buf) + call WaitForAssert({-> assert_match('^\[Y\]es, (N)o: *$', + \ term_getline(buf, 6))}) + call term_sendkeys(buf, "N") + call TermWait(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 TermWait(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 diff --git a/test/old/testdir/test_assert.vim b/test/old/testdir/test_assert.vim new file mode 100644 index 0000000000..fe093d3582 --- /dev/null +++ b/test/old/testdir/test_assert.vim @@ -0,0 +1,489 @@ +" Test that the methods used for testing work. + +source check.vim +source term_util.vim + +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) + + " many composing characters are handled properly + call setline(1, ' ') + norm 100gr݀ + call assert_equal(1, getline(1)) + call assert_match("Expected 1 but got '.* occurs 100 times]'", v:errors[0]) + call remove(v:errors, 0) + bwipe! +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', 'D') + 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', 'D') + 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) +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 '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', v:_null_list)) + catch + let exp = v:exception + endtry + call assert_match("E856: \"assert_fails()\" second argument", exp) + + 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', #{one: 1})) + catch + let exp = v:exception + endtry + call assert_match("E1222: String or List required for argument 2", exp) + + try + call assert_equal(0, assert_fails('xxx', [#{one: 1}])) + catch + let exp = v:exception + endtry + call assert_match("E731: Using a Dictionary as a String", exp) + + let exp = '' + try + call assert_equal(0, assert_fails('xxx', ['E492', #{one: 1}])) + catch + let exp = v:exception + endtry + call assert_match("E731: Using a Dictionary as a String", exp) + + try + call assert_equal(1, assert_fails('xxx', 'E492', '', 'burp')) + catch + let exp = v:exception + endtry + call assert_match("E1210: Number required for argument 4", exp) + + try + call assert_equal(1, assert_fails('xxx', 'E492', '', 54, 123)) + catch + let exp = v:exception + endtry + call assert_match("E1174: String required for argument 5", exp) + + call assert_equal(1, assert_fails('c0', ['', '\(.\)\1'])) + call assert_match("Expected '\\\\\\\\(.\\\\\\\\)\\\\\\\\1' but got 'E939: Positive count required: c0': c0", v:errors[0]) + call remove(v:errors, 0) + + " Test for matching the line number and the script name in an error message + call writefile(['', 'call Xnonexisting()'], 'Xassertfails.vim', 'D') + call assert_fails('source Xassertfails.vim', 'E117:', '', 10) + call assert_match("Expected 10 but got 2", v:errors[0]) + call remove(v:errors, 0) + call assert_fails('source Xassertfails.vim', 'E117:', '', 2, 'Xabc') + call assert_match("Expected 'Xabc' but got .*Xassertfails.vim", v:errors[0]) + call remove(v:errors, 0) +endfunc + +func Test_assert_wrong_arg_emsg_off() + CheckFeature folding + + new + call setline(1, ['foo', 'bar']) + 1,2fold + + " This used to crash Vim + let &l:foldtext = 'assert_match({}, {})' + redraw! + + let &l:foldtext = 'assert_equalfile({}, {})' + redraw! + + bwipe! +endfunc + +func Test_assert_fails_in_try_block() + try + call assert_equal(0, assert_fails('throw "error"')) + endtry +endfunc + +" Test that assert_fails() in a timer does not cause a hit-enter prompt. +" Requires using a terminal, in regular tests the hit-enter prompt won't be +" triggered. +func Test_assert_fails_in_timer() + CheckRunVimInTerminal + + let buf = RunVimInTerminal('', {'rows': 6}) + let cmd = ":call timer_start(0, {-> assert_fails('call', 'E471:')})" + call term_sendkeys(buf, cmd) + call WaitForAssert({-> assert_equal(cmd, term_getline(buf, 6))}) + call term_sendkeys(buf, "\<CR>") + call TermWait(buf, 100) + call assert_match('E471: Argument required', term_getline(buf, 6)) + + call StopVimInTerminal(buf) +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_nobeep() + call assert_equal(1, assert_nobeep('normal! cr')) + call assert_match("command did beep: normal! cr", v:errors[0]) + call remove(v:errors, 0) +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:') + + 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) + + " Use a custom message + call assert_equal(1, assert_inrange(5, 7, 8, "Higher")) + call assert_match("Higher: Expected range 5 - 7, but got 8", v:errors[0]) + call remove(v:errors, 0) + call assert_equal(1, assert_inrange(5, 7, 8.0, "Higher")) + call assert_match("Higher: Expected range 5.0 - 7.0, but got 8.0", v:errors[0]) + call remove(v:errors, 0) + + " Invalid arguments + call assert_fails("call assert_inrange([], 2, 3)", 'E1219:') + call assert_fails("call assert_inrange(1, [], 3)", 'E1219:') + call assert_fails("call assert_inrange(1, 2, [])", 'E1219:') +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_override() + throw 'Skipped: Nvim does not support test_override()' + call test_override('char_avail', 1) + eval 1->test_override('redraw') + call test_override('ALL', 0) + call assert_fails("call test_override('xxx', 1)", 'E475:') + call assert_fails("call test_override('redraw', 'yes')", 'E474:') + call assert_fails("call test_override('redraw', 'yes')", 'E1210:') +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 + +" Test for the test_alloc_fail() function +func Test_test_alloc_fail() + throw 'Skipped: Nvim does not support test_alloc_fail()' + call assert_fails('call test_alloc_fail([], 1, 1)', 'E474:') + call assert_fails('call test_alloc_fail(10, [], 1)', 'E474:') + call assert_fails('call test_alloc_fail(10, 1, [])', 'E474:') + call assert_fails('call test_alloc_fail(999999, 1, 1)', 'E474:') +endfunc + +" Test for the test_option_not_set() function +func Test_test_option_not_set() + throw 'Skipped: Nvim does not support test_option_not_set()' + call assert_fails('call test_option_not_set("Xinvalidopt")', 'E475:') +endfunc + +" Must be last. +func Test_zz_quit_detected() + " Verify that if a test function ends Vim the test script detects this. + quit +endfunc diff --git a/test/old/testdir/test_autochdir.vim b/test/old/testdir/test_autochdir.vim new file mode 100644 index 0000000000..652ce8b794 --- /dev/null +++ b/test/old/testdir/test_autochdir.vim @@ -0,0 +1,125 @@ +" 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', 'R') + call mkdir('Xb', 'R') + call mkdir('Xc', 'R') + 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) + 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('XacdDir', 'R') + let winid = win_getid() + new XacdDir/file + call assert_match('testdir.XacdDir$', getcwd()) + cd .. + call assert_match('testdir$', getcwd()) + call win_execute(winid, 'echo') + call assert_match('testdir$', getcwd()) + + bwipe! + set noacd + call chdir(cwd) +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', 'R') + 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) +endfunc + +func Test_multibyte() + " using an invalid character should not cause a crash + set wic + call assert_fails('tc *', has('win32') ? 'E480:' : 'E344:') + set nowic +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_autocmd.vim b/test/old/testdir/test_autocmd.vim new file mode 100644 index 0000000000..7926411dcd --- /dev/null +++ b/test/old/testdir/test_autocmd.vim @@ -0,0 +1,3825 @@ +" Tests for autocommands + +source shared.vim +source check.vim +source term_util.vim +source screendump.vim +source vim9.vim +source load.vim + +func s:cleanup_buffers() abort + for bnr in range(1, bufnr('$')) + if bufloaded(bnr) && bufnr('%') != bnr + execute 'bd! ' . bnr + endif + endfor +endfunc + +func Test_vim_did_enter() + call assert_false(v:vim_did_enter) + + " This script will never reach the main loop, can't check if v:vim_did_enter + " becomes one. +endfunc + +" Test for the CursorHold autocmd +func Test_CursorHold_autocmd() + CheckRunVimInTerminal + call writefile(['one', 'two', 'three'], 'XoneTwoThree', 'D') + let before =<< trim END + set updatetime=10 + au CursorHold * call writefile([line('.')], 'XCHoutput', 'a') + END + call writefile(before, 'XCHinit', 'D') + let buf = RunVimInTerminal('-S XCHinit XoneTwoThree', {}) + call term_sendkeys(buf, "G") + call term_wait(buf, 50) + call term_sendkeys(buf, "gg") + call term_wait(buf) + call WaitForAssert({-> assert_equal(['1'], readfile('XCHoutput')[-1:-1])}) + call term_sendkeys(buf, "j") + call term_wait(buf) + call WaitForAssert({-> assert_equal(['1', '2'], readfile('XCHoutput')[-2:-1])}) + call term_sendkeys(buf, "j") + call term_wait(buf) + call WaitForAssert({-> assert_equal(['1', '2', '3'], readfile('XCHoutput')[-3:-1])}) + call StopVimInTerminal(buf) + + call delete('XCHoutput') +endfunc + +if has('timers') + + func ExitInsertMode(id) + call feedkeys("\<Esc>") + endfunc + + func Test_cursorhold_insert() + " depends on timing + let g:test_is_flaky = 1 + + " Need to move the cursor. + call feedkeys("ggG", "xt") + + let g:triggered = 0 + au CursorHoldI * let g:triggered += 1 + set updatetime=20 + call timer_start(LoadAdjust(200), 'ExitInsertMode') + call feedkeys('a', 'x!') + call assert_equal(1, g:triggered) + unlet g:triggered + au! CursorHoldI + set updatetime& + endfunc + + func Test_cursorhold_insert_with_timer_interrupt() + CheckFeature job + " Need to move the cursor. + call feedkeys("ggG", "xt") + + " Confirm the timer invoked in exit_cb of the job doesn't disturb + " CursorHoldI event. + let g:triggered = 0 + au CursorHoldI * let g:triggered += 1 + set updatetime=500 + call job_start(has('win32') ? 'cmd /c echo:' : 'echo', + \ {'exit_cb': {-> timer_start(1000, 'ExitInsertMode')}}) + call feedkeys('a', 'x!') + call assert_equal(1, g:triggered) + unlet g:triggered + au! CursorHoldI + set updatetime& + endfunc + + func Test_cursorhold_insert_ctrl_x() + let g:triggered = 0 + au CursorHoldI * let g:triggered += 1 + set updatetime=20 + call timer_start(LoadAdjust(100), 'ExitInsertMode') + " CursorHoldI does not trigger after CTRL-X + call feedkeys("a\<C-X>", 'x!') + call assert_equal(0, g:triggered) + unlet g:triggered + au! CursorHoldI + set updatetime& + endfunc + + func Test_cursorhold_insert_ctrl_g_U() + au CursorHoldI * : + set updatetime=20 + new + call timer_start(100, { -> feedkeys("\<Left>foo\<Esc>", 't') }) + call feedkeys("i()\<C-g>U", 'tx!') + sleep 200m + call assert_equal('(foo)', getline(1)) + undo + call assert_equal('', getline(1)) + + bwipe! + au! CursorHoldI + set updatetime& + endfunc + + func Test_OptionSet_modeline() + CheckFunction test_override + call test_override('starting', 1) + au! OptionSet + augroup set_tabstop + au OptionSet tabstop call timer_start(1, {-> execute("echo 'Handler called'", "")}) + augroup END + call writefile(['vim: set ts=7 sw=5 :', 'something'], 'XoptionsetModeline', 'D') + set modeline + let v:errmsg = '' + call assert_fails('split XoptionsetModeline', 'E12:') + call assert_equal(7, &ts) + call assert_equal('', v:errmsg) + + augroup set_tabstop + au! + augroup END + bwipe! + set ts& + call test_override('starting', 0) + endfunc + +endif "has('timers') + +func Test_bufunload() + augroup test_bufunload_group + autocmd! + autocmd BufUnload * call add(s:li, "bufunload") + autocmd BufDelete * call add(s:li, "bufdelete") + autocmd BufWipeout * call add(s:li, "bufwipeout") + augroup END + + let s:li = [] + new + setlocal bufhidden= + bunload + call assert_equal(["bufunload", "bufdelete"], s:li) + + let s:li = [] + new + setlocal bufhidden=delete + bunload + call assert_equal(["bufunload", "bufdelete"], s:li) + + let s:li = [] + new + setlocal bufhidden=unload + bwipeout + call assert_equal(["bufunload", "bufdelete", "bufwipeout"], s:li) + + au! test_bufunload_group + augroup! test_bufunload_group +endfunc + +" SEGV occurs in older versions. (At least 7.4.2005 or older) +func Test_autocmd_bufunload_with_tabnext() + tabedit + tabfirst + + augroup test_autocmd_bufunload_with_tabnext_group + autocmd! + autocmd BufUnload <buffer> tabnext + augroup END + + quit + call assert_equal(2, tabpagenr('$')) + + autocmd! test_autocmd_bufunload_with_tabnext_group + augroup! test_autocmd_bufunload_with_tabnext_group + tablast + quit +endfunc + +func Test_argdelete_in_next() + au BufNew,BufEnter,BufLeave,BufWinEnter * argdel + call assert_fails('next a b', 'E1156:') + au! BufNew,BufEnter,BufLeave,BufWinEnter * +endfunc + +func Test_autocmd_bufwinleave_with_tabfirst() + tabedit + augroup sample + autocmd! + autocmd BufWinLeave <buffer> tabfirst + augroup END + call setline(1, ['a', 'b', 'c']) + edit! a.txt + tabclose +endfunc + +" SEGV occurs in older versions. (At least 7.4.2321 or older) +func Test_autocmd_bufunload_avoiding_SEGV_01() + split aa.txt + let lastbuf = bufnr('$') + + augroup test_autocmd_bufunload + autocmd! + exe 'autocmd BufUnload <buffer> ' . (lastbuf + 1) . 'bwipeout!' + augroup END + + call assert_fails('edit bb.txt', 'E937:') + + autocmd! test_autocmd_bufunload + augroup! test_autocmd_bufunload + bwipe! aa.txt + bwipe! bb.txt +endfunc + +" SEGV occurs in older versions. (At least 7.4.2321 or older) +func Test_autocmd_bufunload_avoiding_SEGV_02() + setlocal buftype=nowrite + let lastbuf = bufnr('$') + + augroup test_autocmd_bufunload + autocmd! + exe 'autocmd BufUnload <buffer> ' . (lastbuf + 1) . 'bwipeout!' + augroup END + + normal! i1 + call assert_fails('edit a.txt', 'E517:') + + autocmd! test_autocmd_bufunload + augroup! test_autocmd_bufunload + bwipe! a.txt +endfunc + +func Test_autocmd_dummy_wipeout() + " prepare files + call writefile([''], 'Xdummywipetest1.txt', 'D') + call writefile([''], 'Xdummywipetest2.txt', 'D') + augroup test_bufunload_group + autocmd! + autocmd BufUnload * call add(s:li, "bufunload") + autocmd BufDelete * call add(s:li, "bufdelete") + autocmd BufWipeout * call add(s:li, "bufwipeout") + augroup END + + let s:li = [] + split Xdummywipetest1.txt + silent! vimgrep /notmatched/ Xdummywipetest* + call assert_equal(["bufunload", "bufwipeout"], s:li) + + bwipeout + au! test_bufunload_group + augroup! test_bufunload_group +endfunc + +func Test_win_tab_autocmd() + let g:record = [] + + augroup testing + au WinNew * call add(g:record, 'WinNew') + au WinClosed * call add(g:record, 'WinClosed') + au WinEnter * call add(g:record, 'WinEnter') + au WinLeave * call add(g:record, 'WinLeave') + au TabNew * call add(g:record, 'TabNew') + au TabClosed * call add(g:record, 'TabClosed') + au TabEnter * call add(g:record, 'TabEnter') + au TabLeave * call add(g:record, 'TabLeave') + augroup END + + split + tabnew + close + close + + call assert_equal([ + \ 'WinLeave', 'WinNew', 'WinEnter', + \ 'WinLeave', 'TabLeave', 'WinNew', 'WinEnter', 'TabNew', 'TabEnter', + \ 'WinLeave', 'TabLeave', 'WinClosed', 'TabClosed', 'WinEnter', 'TabEnter', + \ 'WinLeave', 'WinClosed', 'WinEnter' + \ ], g:record) + + let g:record = [] + tabnew somefile + tabnext + bwipe somefile + + call assert_equal([ + \ 'WinLeave', 'TabLeave', 'WinNew', 'WinEnter', 'TabNew', 'TabEnter', + \ 'WinLeave', 'TabLeave', 'WinEnter', 'TabEnter', + \ 'WinClosed', 'TabClosed' + \ ], g:record) + + augroup testing + au! + augroup END + unlet g:record +endfunc + +func Test_WinResized() + CheckRunVimInTerminal + + let lines =<< trim END + set scrolloff=0 + call setline(1, ['111', '222']) + vnew + call setline(1, ['aaa', 'bbb']) + new + call setline(1, ['foo', 'bar']) + + let g:resized = 0 + au WinResized * let g:resized += 1 + + func WriteResizedEvent() + call writefile([json_encode(v:event)], 'XresizeEvent') + endfunc + au WinResized * call WriteResizedEvent() + END + call writefile(lines, 'Xtest_winresized', 'D') + let buf = RunVimInTerminal('-S Xtest_winresized', {'rows': 10}) + + " redraw now to avoid a redraw after the :echo command + call term_sendkeys(buf, ":redraw!\<CR>") + call TermWait(buf) + + call term_sendkeys(buf, ":echo g:resized\<CR>") + call WaitForAssert({-> assert_match('^0$', term_getline(buf, 10))}, 1000) + + " increase window height, two windows will be reported + call term_sendkeys(buf, "\<C-W>+") + call TermWait(buf) + call term_sendkeys(buf, ":echo g:resized\<CR>") + call WaitForAssert({-> assert_match('^1$', term_getline(buf, 10))}, 1000) + + let event = readfile('XresizeEvent')[0]->json_decode() + call assert_equal({ + \ 'windows': [1002, 1001], + \ }, event) + + " increase window width, three windows will be reported + call term_sendkeys(buf, "\<C-W>>") + call TermWait(buf) + call term_sendkeys(buf, ":echo g:resized\<CR>") + call WaitForAssert({-> assert_match('^2$', term_getline(buf, 10))}, 1000) + + let event = readfile('XresizeEvent')[0]->json_decode() + call assert_equal({ + \ 'windows': [1002, 1001, 1000], + \ }, event) + + call delete('XresizeEvent') + call StopVimInTerminal(buf) +endfunc + +func Test_WinScrolled() + CheckRunVimInTerminal + + let lines =<< trim END + set nowrap scrolloff=0 + for ii in range(1, 18) + call setline(ii, repeat(nr2char(96 + ii), ii * 2)) + endfor + let win_id = win_getid() + let g:matched = v:false + func WriteScrollEvent() + call writefile([json_encode(v:event)], 'XscrollEvent') + endfunc + execute 'au WinScrolled' win_id 'let g:matched = v:true' + let g:scrolled = 0 + au WinScrolled * let g:scrolled += 1 + au WinScrolled * let g:amatch = str2nr(expand('<amatch>')) + au WinScrolled * let g:afile = str2nr(expand('<afile>')) + au WinScrolled * call WriteScrollEvent() + END + call writefile(lines, 'Xtest_winscrolled', 'D') + let buf = RunVimInTerminal('-S Xtest_winscrolled', {'rows': 6}) + + call term_sendkeys(buf, ":echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^0 ', term_getline(buf, 6))}, 1000) + + " Scroll left/right in Normal mode. + call term_sendkeys(buf, "zlzh:echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^2 ', term_getline(buf, 6))}, 1000) + + let event = readfile('XscrollEvent')[0]->json_decode() + call assert_equal({ + \ 'all': {'leftcol': 1, 'topline': 0, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1000': {'leftcol': -1, 'topline': 0, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0} + \ }, event) + + " Scroll up/down in Normal mode. + call term_sendkeys(buf, "\<c-e>\<c-y>:echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^4 ', term_getline(buf, 6))}, 1000) + + let event = readfile('XscrollEvent')[0]->json_decode() + call assert_equal({ + \ 'all': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1000': {'leftcol': 0, 'topline': -1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0} + \ }, event) + + " Scroll up/down in Insert mode. + call term_sendkeys(buf, "Mi\<c-x>\<c-e>\<Esc>i\<c-x>\<c-y>\<Esc>") + call term_sendkeys(buf, ":echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^6 ', term_getline(buf, 6))}, 1000) + + let event = readfile('XscrollEvent')[0]->json_decode() + call assert_equal({ + \ 'all': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1000': {'leftcol': 0, 'topline': -1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0} + \ }, event) + + " Scroll the window horizontally to focus the last letter of the third line + " containing only six characters. Moving to the previous and shorter lines + " should trigger another autocommand as Vim has to make them visible. + call term_sendkeys(buf, "5zl2k") + call term_sendkeys(buf, ":echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^8 ', term_getline(buf, 6))}, 1000) + + let event = readfile('XscrollEvent')[0]->json_decode() + call assert_equal({ + \ 'all': {'leftcol': 5, 'topline': 0, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1000': {'leftcol': -5, 'topline': 0, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0} + \ }, event) + + " Ensure the command was triggered for the specified window ID. + call term_sendkeys(buf, ":echo g:matched\<CR>") + call WaitForAssert({-> assert_match('^v:true ', term_getline(buf, 6))}, 1000) + + " Ensure the expansion of <amatch> and <afile> matches the window ID. + call term_sendkeys(buf, ":echo g:amatch == win_id && g:afile == win_id\<CR>") + call WaitForAssert({-> assert_match('^v:true ', term_getline(buf, 6))}, 1000) + + call delete('XscrollEvent') + call StopVimInTerminal(buf) +endfunc + +func Test_WinScrolled_mouse() + CheckRunVimInTerminal + + let lines =<< trim END + set nowrap scrolloff=0 + set mouse=a term=xterm ttymouse=sgr mousetime=200 clipboard= + call setline(1, ['foo']->repeat(32)) + split + let g:scrolled = 0 + au WinScrolled * let g:scrolled += 1 + END + call writefile(lines, 'Xtest_winscrolled_mouse', 'D') + let buf = RunVimInTerminal('-S Xtest_winscrolled_mouse', {'rows': 10}) + + " With the upper split focused, send a scroll-down event to the unfocused one. + call test_setmouse(7, 1) + call term_sendkeys(buf, "\<ScrollWheelDown>") + call TermWait(buf) + call term_sendkeys(buf, ":echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^1', term_getline(buf, 10))}, 1000) + + " Again, but this time while we're in insert mode. + call term_sendkeys(buf, "i\<ScrollWheelDown>\<Esc>") + call TermWait(buf) + call term_sendkeys(buf, ":echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^2', term_getline(buf, 10))}, 1000) + + call StopVimInTerminal(buf) +endfunc + +func Test_WinScrolled_close_curwin() + CheckRunVimInTerminal + + let lines =<< trim END + set nowrap scrolloff=0 + call setline(1, ['aaa', 'bbb']) + vsplit + au WinScrolled * close + au VimLeave * call writefile(['123456'], 'Xtestout') + END + call writefile(lines, 'Xtest_winscrolled_close_curwin', 'D') + let buf = RunVimInTerminal('-S Xtest_winscrolled_close_curwin', {'rows': 6}) + + " This was using freed memory + call term_sendkeys(buf, "\<C-E>") + call TermWait(buf) + call StopVimInTerminal(buf) + + " check the startup script finished to the end + call assert_equal(['123456'], readfile('Xtestout')) + call delete('Xtestout') +endfunc + +func Test_WinScrolled_once_only() + CheckRunVimInTerminal + + let lines =<< trim END + set cmdheight=2 + call setline(1, ['aaa', 'bbb']) + let trigger_count = 0 + func ShowInfo(id) + echo g:trigger_count g:winid winlayout() + endfunc + + vsplit + split + " use a timer to show the info after a redraw + au WinScrolled * let trigger_count += 1 | let winid = expand('<amatch>') | call timer_start(100, 'ShowInfo') + wincmd j + wincmd l + END + call writefile(lines, 'Xtest_winscrolled_once', 'D') + let buf = RunVimInTerminal('-S Xtest_winscrolled_once', #{rows: 10, cols: 60, statusoff: 2}) + + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_winscrolled_once_only_1', {}) + + call StopVimInTerminal(buf) +endfunc + +" Check that WinScrolled is not triggered immediately when defined and there +" are split windows. +func Test_WinScrolled_not_when_defined() + CheckRunVimInTerminal + + let lines =<< trim END + call setline(1, ['aaa', 'bbb']) + echo 'nothing happened' + func ShowTriggered(id) + echo 'triggered' + endfunc + END + call writefile(lines, 'Xtest_winscrolled_not', 'D') + let buf = RunVimInTerminal('-S Xtest_winscrolled_not', #{rows: 10, cols: 60, statusoff: 2}) + call term_sendkeys(buf, ":split\<CR>") + call TermWait(buf) + " use a timer to show the message after redrawing + call term_sendkeys(buf, ":au WinScrolled * call timer_start(100, 'ShowTriggered')\<CR>") + call VerifyScreenDump(buf, 'Test_winscrolled_not_when_defined_1', {}) + + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_winscrolled_not_when_defined_2', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_WinScrolled_long_wrapped() + CheckRunVimInTerminal + + let lines =<< trim END + set scrolloff=0 + let height = winheight(0) + let width = winwidth(0) + let g:scrolled = 0 + au WinScrolled * let g:scrolled += 1 + call setline(1, repeat('foo', height * width)) + call cursor(1, height * width) + END + call writefile(lines, 'Xtest_winscrolled_long_wrapped', 'D') + let buf = RunVimInTerminal('-S Xtest_winscrolled_long_wrapped', {'rows': 6}) + + call term_sendkeys(buf, ":echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^0 ', term_getline(buf, 6))}, 1000) + + call term_sendkeys(buf, 'gj') + call term_sendkeys(buf, ":echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^1 ', term_getline(buf, 6))}, 1000) + + call term_sendkeys(buf, '0') + call term_sendkeys(buf, ":echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^2 ', term_getline(buf, 6))}, 1000) + + call term_sendkeys(buf, '$') + call term_sendkeys(buf, ":echo g:scrolled\<CR>") + call WaitForAssert({-> assert_match('^3 ', term_getline(buf, 6))}, 1000) + + call StopVimInTerminal(buf) +endfunc + +func Test_WinScrolled_diff() + CheckRunVimInTerminal + + let lines =<< trim END + set diffopt+=foldcolumn:0 + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + vnew + call setline(1, ['d', 'e', 'f', 'g', 'h', 'i']) + windo diffthis + func WriteScrollEvent() + call writefile([json_encode(v:event)], 'XscrollEvent') + endfunc + au WinScrolled * call WriteScrollEvent() + END + call writefile(lines, 'Xtest_winscrolled_diff', 'D') + let buf = RunVimInTerminal('-S Xtest_winscrolled_diff', {'rows': 8}) + + call term_sendkeys(buf, "\<C-E>") + call WaitForAssert({-> assert_match('^d', term_getline(buf, 3))}, 1000) + + let event = readfile('XscrollEvent')[0]->json_decode() + call assert_equal({ + \ 'all': {'leftcol': 0, 'topline': 1, 'topfill': 1, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1000': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1001': {'leftcol': 0, 'topline': 0, 'topfill': -1, 'width': 0, 'height': 0, 'skipcol': 0} + \ }, event) + + call term_sendkeys(buf, "2\<C-E>") + call WaitForAssert({-> assert_match('^f', term_getline(buf, 3))}, 1000) + + let event = readfile('XscrollEvent')[0]->json_decode() + call assert_equal({ + \ 'all': {'leftcol': 0, 'topline': 2, 'topfill': 2, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1000': {'leftcol': 0, 'topline': 2, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1001': {'leftcol': 0, 'topline': 0, 'topfill': -2, 'width': 0, 'height': 0, 'skipcol': 0} + \ }, event) + + call term_sendkeys(buf, "\<C-E>") + call WaitForAssert({-> assert_match('^g', term_getline(buf, 3))}, 1000) + + let event = readfile('XscrollEvent')[0]->json_decode() + call assert_equal({ + \ 'all': {'leftcol': 0, 'topline': 2, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1000': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1001': {'leftcol': 0, 'topline': 1, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0} + \ }, event) + + call term_sendkeys(buf, "2\<C-Y>") + call WaitForAssert({-> assert_match('^e', term_getline(buf, 3))}, 1000) + + let event = readfile('XscrollEvent')[0]->json_decode() + call assert_equal({ + \ 'all': {'leftcol': 0, 'topline': 3, 'topfill': 1, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1000': {'leftcol': 0, 'topline': -2, 'topfill': 0, 'width': 0, 'height': 0, 'skipcol': 0}, + \ '1001': {'leftcol': 0, 'topline': -1, 'topfill': 1, 'width': 0, 'height': 0, 'skipcol': 0} + \ }, event) + + call StopVimInTerminal(buf) + call delete('XscrollEvent') +endfunc + +func Test_WinClosed() + " Test that the pattern is matched against the closed window's ID, and both + " <amatch> and <afile> are set to it. + new + let winid = win_getid() + let g:matched = v:false + augroup test-WinClosed + autocmd! + execute 'autocmd WinClosed' winid 'let g:matched = v:true' + autocmd WinClosed * let g:amatch = str2nr(expand('<amatch>')) + autocmd WinClosed * let g:afile = str2nr(expand('<afile>')) + augroup END + close + call assert_true(g:matched) + call assert_equal(winid, g:amatch) + call assert_equal(winid, g:afile) + + " Test that WinClosed is non-recursive. + new + new + call assert_equal(3, winnr('$')) + let g:triggered = 0 + augroup test-WinClosed + autocmd! + autocmd WinClosed * let g:triggered += 1 + autocmd WinClosed * 2 wincmd c + augroup END + close + call assert_equal(1, winnr('$')) + call assert_equal(1, g:triggered) + + autocmd! test-WinClosed + augroup! test-WinClosed + unlet g:matched + unlet g:amatch + unlet g:afile + unlet g:triggered +endfunc + +func Test_WinClosed_throws() + vnew + let bnr = bufnr() + call assert_equal(1, bufloaded(bnr)) + augroup test-WinClosed + autocmd WinClosed * throw 'foo' + augroup END + try + close + catch /.*/ + endtry + call assert_equal(0, bufloaded(bnr)) + + autocmd! test-WinClosed + augroup! test-WinClosed +endfunc + +func Test_WinClosed_throws_with_tabs() + tabnew + let bnr = bufnr() + call assert_equal(1, bufloaded(bnr)) + augroup test-WinClosed + autocmd WinClosed * throw 'foo' + augroup END + try + close + catch /.*/ + endtry + call assert_equal(0, bufloaded(bnr)) + + autocmd! test-WinClosed + augroup! test-WinClosed +endfunc + +" This used to trigger WinClosed twice for the same window, and the window's +" buffer was NULL in the second autocommand. +func Test_WinClosed_switch_tab() + edit Xa + split Xb + split Xc + tab split + new + augroup test-WinClosed + autocmd WinClosed * tabprev | bwipe! + augroup END + close + " Check that the tabline has been fully removed + call assert_equal([1, 1], win_screenpos(0)) + + autocmd! test-WinClosed + augroup! test-WinClosed + %bwipe! +endfunc + +func s:AddAnAutocmd() + augroup vimBarTest + au BufReadCmd * echo 'hello' + augroup END + call assert_equal(3, len(split(execute('au vimBarTest'), "\n"))) +endfunc + +func Test_early_bar() + " test that a bar is recognized before the {event} + call s:AddAnAutocmd() + augroup vimBarTest | au! | let done = 77 | augroup END + call assert_equal(1, len(split(execute('au vimBarTest'), "\n"))) + call assert_equal(77, done) + + call s:AddAnAutocmd() + augroup vimBarTest| au!| let done = 88 | augroup END + call assert_equal(1, len(split(execute('au vimBarTest'), "\n"))) + call assert_equal(88, done) + + " test that a bar is recognized after the {event} + call s:AddAnAutocmd() + augroup vimBarTest| au!BufReadCmd| let done = 99 | augroup END + call assert_equal(1, len(split(execute('au vimBarTest'), "\n"))) + call assert_equal(99, done) + + " test that a bar is recognized after the {group} + call s:AddAnAutocmd() + au! vimBarTest|echo 'hello' + call assert_equal(1, len(split(execute('au vimBarTest'), "\n"))) +endfunc + +func RemoveGroup() + autocmd! StartOK + augroup! StartOK +endfunc + +func Test_augroup_warning() + augroup TheWarning + au VimEnter * echo 'entering' + augroup END + call assert_match("TheWarning.*VimEnter", execute('au VimEnter')) + redir => res + augroup! TheWarning + redir END + call assert_match("W19:", res) + call assert_match("-Deleted-.*VimEnter", execute('au VimEnter')) + + " check "Another" does not take the pace of the deleted entry + augroup Another + augroup END + call assert_match("-Deleted-.*VimEnter", execute('au VimEnter')) + augroup! Another + + " no warning for postpone aucmd delete + augroup StartOK + au VimEnter * call RemoveGroup() + augroup END + call assert_match("StartOK.*VimEnter", execute('au VimEnter')) + redir => res + doautocmd VimEnter + redir END + call assert_notmatch("W19:", res) + au! VimEnter + + call assert_fails('augroup!', 'E471:') +endfunc + +func Test_BufReadCmdHelp() + " This used to cause access to free memory + au BufReadCmd * e +h + help + + au! BufReadCmd +endfunc + +func Test_BufReadCmdHelpJump() + " This used to cause access to free memory + au BufReadCmd * e +h{ + " } to fix highlighting + call assert_fails('help', 'E434:') + + au! BufReadCmd +endfunc + +" BufReadCmd is triggered for a "nofile" buffer. Check all values. +func Test_BufReadCmdNofile() + for val in ['nofile', + \ 'nowrite', + \ 'acwrite', + \ 'quickfix', + \ 'help', + "\ 'terminal', + \ 'prompt', + "\ 'popup', + \ ] + new somefile + exe 'set buftype=' .. val + au BufReadCmd somefile call setline(1, 'triggered') + edit + call assert_equal('triggered', getline(1)) + + au! BufReadCmd + bwipe! + endfor +endfunc + +func Test_augroup_deleted() + " This caused a crash before E936 was introduced + augroup x + call assert_fails('augroup! x', 'E936:') + au VimEnter * echo + augroup end + augroup! x + call assert_match("-Deleted-.*VimEnter", execute('au VimEnter')) + au! VimEnter +endfunc + +" Tests for autocommands on :close command. +" This used to be in test13. +func Test_three_windows() + " Clean up buffers, because in some cases this function fails. + call s:cleanup_buffers() + + " Write three files and open them, each in a window. + " Then go to next window, with autocommand that deletes the previous one. + " Do this twice, writing the file. + e! Xtestje1 + call setline(1, 'testje1') + w + sp Xtestje2 + call setline(1, 'testje2') + w + sp Xtestje3 + call setline(1, 'testje3') + w + wincmd w + au WinLeave Xtestje2 bwipe + wincmd w + call assert_equal('Xtestje1', expand('%')) + + au WinLeave Xtestje1 bwipe Xtestje3 + close + call assert_equal('Xtestje1', expand('%')) + + " Test deleting the buffer on a Unload event. If this goes wrong there + " will be the ATTENTION prompt. + e Xtestje1 + au! + au! BufUnload Xtestje1 bwipe + call assert_fails('e Xtestje3', 'E937:') + call assert_equal('Xtestje3', expand('%')) + + e Xtestje2 + sp Xtestje1 + call assert_fails('e', 'E937:') + call assert_equal('Xtestje1', expand('%')) + + " Test changing buffers in a BufWipeout autocommand. If this goes wrong + " there are ml_line errors and/or a Crash. + au! + only + e Xanother + e Xtestje1 + bwipe Xtestje2 + bwipe Xtestje3 + au BufWipeout Xtestje1 buf Xtestje1 + bwipe + call assert_equal('Xanother', expand('%')) + + only + + help + wincmd w + 1quit + call assert_equal('Xanother', expand('%')) + + au! + enew + call delete('Xtestje1') + call delete('Xtestje2') + call delete('Xtestje3') +endfunc + +func Test_BufEnter() + au! BufEnter + au Bufenter * let val = val . '+' + let g:val = '' + split NewFile + call assert_equal('+', g:val) + bwipe! + call assert_equal('++', g:val) + + " Also get BufEnter when editing a directory + call mkdir('Xbufenterdir', 'D') + split Xbufenterdir + call assert_equal('+++', g:val) + + " On MS-Windows we can't edit the directory, make sure we wipe the right + " buffer. + bwipe! Xbufenterdir + au! BufEnter + + " Editing a "nofile" buffer doesn't read the file but does trigger BufEnter + " for historic reasons. Also test other 'buftype' values. + for val in ['nofile', + \ 'nowrite', + \ 'acwrite', + \ 'quickfix', + \ 'help', + "\ 'terminal', + \ 'prompt', + "\ 'popup', + \ ] + new somefile + exe 'set buftype=' .. val + au BufEnter somefile call setline(1, 'some text') + edit + call assert_equal('some text', getline(1)) + bwipe! + au! BufEnter + endfor +endfunc + +" Closing a window might cause an endless loop +" E814 for older Vims +func Test_autocmd_bufwipe_in_SessLoadPost() + edit Xtest + tabnew + file Xsomething + set noswapfile + mksession! + + let content =<< trim [CODE] + set nocp noswapfile + let v:swapchoice = "e" + augroup test_autocmd_sessionload + autocmd! + autocmd SessionLoadPost * exe bufnr("Xsomething") . "bw!" + augroup END + + func WriteErrors() + call writefile([execute("messages")], "XerrorsBwipe") + endfunc + au VimLeave * call WriteErrors() + [CODE] + + call writefile(content, 'Xvimrc', 'D') + call system(GetVimCommand('Xvimrc') .. ' --headless --noplugins -S Session.vim -c cq') + sleep 100m + let errors = join(readfile('XerrorsBwipe')) + call assert_match('E814:', errors) + + set swapfile + for file in ['Session.vim', 'XerrorsBwipe'] + call delete(file) + endfor +endfunc + +" Using :blast and :ball for many events caused a crash, because b_nwindows was +" not incremented correctly. +func Test_autocmd_blast_badd() + let content =<< trim [CODE] + au BufNew,BufAdd,BufWinEnter,BufEnter,BufLeave,BufWinLeave,BufUnload,VimEnter foo* blast + edit foo1 + au BufNew,BufAdd,BufWinEnter,BufEnter,BufLeave,BufWinLeave,BufUnload,VimEnter foo* ball + edit foo2 + call writefile(['OK'], 'XerrorsBlast') + qall + [CODE] + + call writefile(content, 'XblastBall', 'D') + call system(GetVimCommand() .. ' --clean -S XblastBall') + sleep 100m + call assert_match('OK', readfile('XerrorsBlast')->join()) + + call delete('XerrorsBlast') +endfunc + +" SEGV occurs in older versions. +func Test_autocmd_bufwipe_in_SessLoadPost2() + tabnew + set noswapfile + mksession! + + let content =<< trim [CODE] + set nocp noswapfile + function! DeleteInactiveBufs() + tabfirst + let tabblist = [] + for i in range(1, tabpagenr(''$'')) + call extend(tabblist, tabpagebuflist(i)) + endfor + for b in range(1, bufnr(''$'')) + if bufexists(b) && buflisted(b) && (index(tabblist, b) == -1 || bufname(b) =~# ''^$'') + exec ''bwipeout '' . b + endif + endfor + echomsg "SessionLoadPost DONE" + endfunction + au SessionLoadPost * call DeleteInactiveBufs() + + func WriteErrors() + call writefile([execute("messages")], "XerrorsPost") + endfunc + au VimLeave * call WriteErrors() + [CODE] + + call writefile(content, 'Xvimrc', 'D') + call system(GetVimCommand('Xvimrc') .. ' --headless --noplugins -S Session.vim -c cq') + sleep 100m + let errors = join(readfile('XerrorsPost')) + " This probably only ever matches on unix. + call assert_notmatch('Caught deadly signal SEGV', errors) + call assert_match('SessionLoadPost DONE', errors) + + set swapfile + for file in ['Session.vim', 'XerrorsPost'] + call delete(file) + endfor +endfunc + +func Test_empty_doau() + doau \| +endfunc + +func s:AutoCommandOptionSet(match) + let template = "Option: <%s>, OldVal: <%s>, OldValLocal: <%s>, OldValGlobal: <%s>, NewVal: <%s>, Scope: <%s>, Command: <%s>\n" + let item = remove(g:options, 0) + let expected = printf(template, item[0], item[1], item[2], item[3], item[4], item[5], item[6]) + let actual = printf(template, a:match, v:option_old, v:option_oldlocal, v:option_oldglobal, v:option_new, v:option_type, v:option_command) + let g:opt = [expected, actual] + "call assert_equal(expected, actual) +endfunc + +func Test_OptionSet() + CheckFunction test_override + CheckOption autochdir + + call test_override('starting', 1) + set nocp + au OptionSet * :call s:AutoCommandOptionSet(expand("<amatch>")) + + " 1: Setting number option" + let g:options = [['number', 0, 0, 0, 1, 'global', 'set']] + set nu + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 2: Setting local number option" + let g:options = [['number', 1, 1, '', 0, 'local', 'setlocal']] + setlocal nonu + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 3: Setting global number option" + let g:options = [['number', 1, '', 1, 0, 'global', 'setglobal']] + setglobal nonu + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 4: Setting local autoindent option" + let g:options = [['autoindent', 0, 0, '', 1, 'local', 'setlocal']] + setlocal ai + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 5: Setting global autoindent option" + let g:options = [['autoindent', 0, '', 0, 1, 'global', 'setglobal']] + setglobal ai + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 6: Setting global autoindent option" + let g:options = [['autoindent', 1, 1, 1, 0, 'global', 'set']] + set ai! + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 6a: Setting global autoindent option" + let g:options = [['autoindent', 1, 1, 0, 0, 'global', 'set']] + noa setlocal ai + noa setglobal noai + set ai! + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " Should not print anything, use :noa + " 7: don't trigger OptionSet" + let g:options = [['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid']] + noa set nonu + call assert_equal([['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid']], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 8: Setting several global list and number option" + let g:options = [['list', 0, 0, 0, 1, 'global', 'set'], ['number', 0, 0, 0, 1, 'global', 'set']] + set list nu + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 9: don't trigger OptionSet" + let g:options = [['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid'], ['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid']] + noa set nolist nonu + call assert_equal([['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid'], ['invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid']], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 10: Setting global acd" + let g:options = [['autochdir', 0, 0, '', 1, 'local', 'setlocal']] + setlocal acd + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 11: Setting global autoread (also sets local value)" + let g:options = [['autoread', 0, 0, 0, 1, 'global', 'set']] + set ar + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 12: Setting local autoread" + let g:options = [['autoread', 1, 1, '', 1, 'local', 'setlocal']] + setlocal ar + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 13: Setting global autoread" + let g:options = [['autoread', 1, '', 1, 0, 'global', 'setglobal']] + setglobal invar + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 14: Setting option backspace through :let" + let g:options = [['backspace', '', '', '', 'eol,indent,start', 'global', 'set']] + let &bs = "eol,indent,start" + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 15: Setting option backspace through setbufvar()" + let g:options = [['backup', 0, 0, '', 1, 'local', 'setlocal']] + " try twice, first time, shouldn't trigger because option name is invalid, + " second time, it should trigger + let bnum = bufnr('%') + call assert_fails("call setbufvar(bnum, '&l:bk', 1)", 'E355:') + " should trigger, use correct option name + call setbufvar(bnum, '&backup', 1) + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 16: Setting number option using setwinvar" + let g:options = [['number', 0, 0, '', 1, 'local', 'setlocal']] + call setwinvar(0, '&number', 1) + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 17: Setting key option, shouldn't trigger" + let g:options = [['key', 'invalid', 'invalid1', 'invalid2', 'invalid3', 'invalid4', 'invalid5']] + setlocal key=blah + setlocal key= + call assert_equal([['key', 'invalid', 'invalid1', 'invalid2', 'invalid3', 'invalid4', 'invalid5']], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 18a: Setting string global option" + let oldval = &backupext + let g:options = [['backupext', oldval, oldval, oldval, 'foo', 'global', 'set']] + set backupext=foo + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 18b: Resetting string global option" + let g:options = [['backupext', 'foo', 'foo', 'foo', oldval, 'global', 'set']] + set backupext& + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 18c: Setting global string global option" + let g:options = [['backupext', oldval, '', oldval, 'bar', 'global', 'setglobal']] + setglobal backupext=bar + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 18d: Setting local string global option" + " As this is a global option this sets the global value even though + " :setlocal is used! + noa set backupext& " Reset global and local value (without triggering autocmd) + let g:options = [['backupext', oldval, oldval, '', 'baz', 'local', 'setlocal']] + setlocal backupext=baz + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 18e: Setting again string global option" + noa setglobal backupext=ext_global " Reset global and local value (without triggering autocmd) + noa setlocal backupext=ext_local " Sets the global(!) value! + let g:options = [['backupext', 'ext_local', 'ext_local', 'ext_local', 'fuu', 'global', 'set']] + set backupext=fuu + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 19a: Setting string global-local (to buffer) option" + let oldval = &tags + let g:options = [['tags', oldval, oldval, oldval, 'tagpath', 'global', 'set']] + set tags=tagpath + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 19b: Resetting string global-local (to buffer) option" + let g:options = [['tags', 'tagpath', 'tagpath', 'tagpath', oldval, 'global', 'set']] + set tags& + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 19c: Setting global string global-local (to buffer) option " + let g:options = [['tags', oldval, '', oldval, 'tagpath1', 'global', 'setglobal']] + setglobal tags=tagpath1 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 19d: Setting local string global-local (to buffer) option" + let g:options = [['tags', 'tagpath1', 'tagpath1', '', 'tagpath2', 'local', 'setlocal']] + setlocal tags=tagpath2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 19e: Setting again string global-local (to buffer) option" + " Note: v:option_old is the old global value for global-local string options + " but the old local value for all other kinds of options. + noa setglobal tags=tag_global " Reset global and local value (without triggering autocmd) + noa setlocal tags=tag_local + let g:options = [['tags', 'tag_global', 'tag_local', 'tag_global', 'tagpath', 'global', 'set']] + set tags=tagpath + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 19f: Setting string global-local (to buffer) option to an empty string" + " Note: v:option_old is the old global value for global-local string options + " but the old local value for all other kinds of options. + noa set tags=tag_global " Reset global and local value (without triggering autocmd) + noa setlocal tags= " empty string + let g:options = [['tags', 'tag_global', '', 'tag_global', 'tagpath', 'global', 'set']] + set tags=tagpath + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 20a: Setting string local (to buffer) option" + let oldval = &spelllang + let g:options = [['spelllang', oldval, oldval, oldval, 'elvish,klingon', 'global', 'set']] + set spelllang=elvish,klingon + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 20b: Resetting string local (to buffer) option" + let g:options = [['spelllang', 'elvish,klingon', 'elvish,klingon', 'elvish,klingon', oldval, 'global', 'set']] + set spelllang& + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 20c: Setting global string local (to buffer) option" + let g:options = [['spelllang', oldval, '', oldval, 'elvish', 'global', 'setglobal']] + setglobal spelllang=elvish + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 20d: Setting local string local (to buffer) option" + noa set spelllang& " Reset global and local value (without triggering autocmd) + let g:options = [['spelllang', oldval, oldval, '', 'klingon', 'local', 'setlocal']] + setlocal spelllang=klingon + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 20e: Setting again string local (to buffer) option" + " Note: v:option_old is the old global value for global-local string options + " but the old local value for all other kinds of options. + noa setglobal spelllang=spellglobal " Reset global and local value (without triggering autocmd) + noa setlocal spelllang=spelllocal + let g:options = [['spelllang', 'spelllocal', 'spelllocal', 'spellglobal', 'foo', 'global', 'set']] + set spelllang=foo + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 21a: Setting string global-local (to window) option" + let oldval = &statusline + let g:options = [['statusline', oldval, oldval, oldval, 'foo', 'global', 'set']] + set statusline=foo + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 21b: Resetting string global-local (to window) option" + " Note: v:option_old is the old global value for global-local string options + " but the old local value for all other kinds of options. + let g:options = [['statusline', 'foo', 'foo', 'foo', oldval, 'global', 'set']] + set statusline& + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 21c: Setting global string global-local (to window) option" + let g:options = [['statusline', oldval, '', oldval, 'bar', 'global', 'setglobal']] + setglobal statusline=bar + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 21d: Setting local string global-local (to window) option" + noa set statusline& " Reset global and local value (without triggering autocmd) + let g:options = [['statusline', oldval, oldval, '', 'baz', 'local', 'setlocal']] + setlocal statusline=baz + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 21e: Setting again string global-local (to window) option" + " Note: v:option_old is the old global value for global-local string options + " but the old local value for all other kinds of options. + noa setglobal statusline=bar " Reset global and local value (without triggering autocmd) + noa setlocal statusline=baz + let g:options = [['statusline', 'bar', 'baz', 'bar', 'foo', 'global', 'set']] + set statusline=foo + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 22a: Setting string local (to window) option" + let oldval = &foldignore + let g:options = [['foldignore', oldval, oldval, oldval, 'fo', 'global', 'set']] + set foldignore=fo + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 22b: Resetting string local (to window) option" + let g:options = [['foldignore', 'fo', 'fo', 'fo', oldval, 'global', 'set']] + set foldignore& + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 22c: Setting global string local (to window) option" + let g:options = [['foldignore', oldval, '', oldval, 'bar', 'global', 'setglobal']] + setglobal foldignore=bar + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 22d: Setting local string local (to window) option" + noa set foldignore& " Reset global and local value (without triggering autocmd) + let g:options = [['foldignore', oldval, oldval, '', 'baz', 'local', 'setlocal']] + setlocal foldignore=baz + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 22e: Setting again string local (to window) option" + noa setglobal foldignore=glob " Reset global and local value (without triggering autocmd) + noa setlocal foldignore=loc + let g:options = [['foldignore', 'loc', 'loc', 'glob', 'fo', 'global', 'set']] + set foldignore=fo + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 23a: Setting global number global option" + noa setglobal cmdheight=8 " Reset global and local value (without triggering autocmd) + noa setlocal cmdheight=1 " Sets the global(!) value! + let g:options = [['cmdheight', '1', '', '1', '2', 'global', 'setglobal']] + setglobal cmdheight=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 23b: Setting local number global option" + noa setglobal cmdheight=8 " Reset global and local value (without triggering autocmd) + noa setlocal cmdheight=1 " Sets the global(!) value! + let g:options = [['cmdheight', '1', '1', '', '2', 'local', 'setlocal']] + setlocal cmdheight=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 23c: Setting again number global option" + noa setglobal cmdheight=8 " Reset global and local value (without triggering autocmd) + noa setlocal cmdheight=1 " Sets the global(!) value! + let g:options = [['cmdheight', '1', '1', '1', '2', 'global', 'set']] + set cmdheight=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 23d: Setting again number global option" + noa set cmdheight=8 " Reset global and local value (without triggering autocmd) + let g:options = [['cmdheight', '8', '8', '8', '2', 'global', 'set']] + set cmdheight=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 24a: Setting global number global-local (to buffer) option" + noa setglobal undolevels=8 " Reset global and local value (without triggering autocmd) + noa setlocal undolevels=1 + let g:options = [['undolevels', '8', '', '8', '2', 'global', 'setglobal']] + setglobal undolevels=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 24b: Setting local number global-local (to buffer) option" + noa setglobal undolevels=8 " Reset global and local value (without triggering autocmd) + noa setlocal undolevels=1 + let g:options = [['undolevels', '1', '1', '', '2', 'local', 'setlocal']] + setlocal undolevels=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 24c: Setting again number global-local (to buffer) option" + noa setglobal undolevels=8 " Reset global and local value (without triggering autocmd) + noa setlocal undolevels=1 + let g:options = [['undolevels', '1', '1', '8', '2', 'global', 'set']] + set undolevels=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 24d: Setting again global number global-local (to buffer) option" + noa set undolevels=8 " Reset global and local value (without triggering autocmd) + let g:options = [['undolevels', '8', '8', '8', '2', 'global', 'set']] + set undolevels=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 25a: Setting global number local (to buffer) option" + noa setglobal wrapmargin=8 " Reset global and local value (without triggering autocmd) + noa setlocal wrapmargin=1 + let g:options = [['wrapmargin', '8', '', '8', '2', 'global', 'setglobal']] + setglobal wrapmargin=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 25b: Setting local number local (to buffer) option" + noa setglobal wrapmargin=8 " Reset global and local value (without triggering autocmd) + noa setlocal wrapmargin=1 + let g:options = [['wrapmargin', '1', '1', '', '2', 'local', 'setlocal']] + setlocal wrapmargin=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 25c: Setting again number local (to buffer) option" + noa setglobal wrapmargin=8 " Reset global and local value (without triggering autocmd) + noa setlocal wrapmargin=1 + let g:options = [['wrapmargin', '1', '1', '8', '2', 'global', 'set']] + set wrapmargin=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 25d: Setting again global number local (to buffer) option" + noa set wrapmargin=8 " Reset global and local value (without triggering autocmd) + let g:options = [['wrapmargin', '8', '8', '8', '2', 'global', 'set']] + set wrapmargin=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 26: Setting number global-local (to window) option. + " Such option does currently not exist. + + + " 27a: Setting global number local (to window) option" + noa setglobal foldcolumn=8 " Reset global and local value (without triggering autocmd) + noa setlocal foldcolumn=1 + let g:options = [['foldcolumn', '8', '', '8', '2', 'global', 'setglobal']] + setglobal foldcolumn=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 27b: Setting local number local (to window) option" + noa setglobal foldcolumn=8 " Reset global and local value (without triggering autocmd) + noa setlocal foldcolumn=1 + let g:options = [['foldcolumn', '1', '1', '', '2', 'local', 'setlocal']] + setlocal foldcolumn=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 27c: Setting again number local (to window) option" + noa setglobal foldcolumn=8 " Reset global and local value (without triggering autocmd) + noa setlocal foldcolumn=1 + let g:options = [['foldcolumn', '1', '1', '8', '2', 'global', 'set']] + set foldcolumn=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 27d: Setting again global number local (to window) option" + noa set foldcolumn=8 " Reset global and local value (without triggering autocmd) + let g:options = [['foldcolumn', '8', '8', '8', '2', 'global', 'set']] + set foldcolumn=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 28a: Setting global boolean global option" + noa setglobal nowrapscan " Reset global and local value (without triggering autocmd) + noa setlocal wrapscan " Sets the global(!) value! + let g:options = [['wrapscan', '1', '', '1', '0', 'global', 'setglobal']] + setglobal nowrapscan + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 28b: Setting local boolean global option" + noa setglobal nowrapscan " Reset global and local value (without triggering autocmd) + noa setlocal wrapscan " Sets the global(!) value! + let g:options = [['wrapscan', '1', '1', '', '0', 'local', 'setlocal']] + setlocal nowrapscan + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 28c: Setting again boolean global option" + noa setglobal nowrapscan " Reset global and local value (without triggering autocmd) + noa setlocal wrapscan " Sets the global(!) value! + let g:options = [['wrapscan', '1', '1', '1', '0', 'global', 'set']] + set nowrapscan + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 28d: Setting again global boolean global option" + noa set nowrapscan " Reset global and local value (without triggering autocmd) + let g:options = [['wrapscan', '0', '0', '0', '1', 'global', 'set']] + set wrapscan + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 29a: Setting global boolean global-local (to buffer) option" + noa setglobal noautoread " Reset global and local value (without triggering autocmd) + noa setlocal autoread + let g:options = [['autoread', '0', '', '0', '1', 'global', 'setglobal']] + setglobal autoread + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 29b: Setting local boolean global-local (to buffer) option" + noa setglobal noautoread " Reset global and local value (without triggering autocmd) + noa setlocal autoread + let g:options = [['autoread', '1', '1', '', '0', 'local', 'setlocal']] + setlocal noautoread + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 29c: Setting again boolean global-local (to buffer) option" + noa setglobal noautoread " Reset global and local value (without triggering autocmd) + noa setlocal autoread + let g:options = [['autoread', '1', '1', '0', '1', 'global', 'set']] + set autoread + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 29d: Setting again global boolean global-local (to buffer) option" + noa set noautoread " Reset global and local value (without triggering autocmd) + let g:options = [['autoread', '0', '0', '0', '1', 'global', 'set']] + set autoread + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 30a: Setting global boolean local (to buffer) option" + noa setglobal nocindent " Reset global and local value (without triggering autocmd) + noa setlocal cindent + let g:options = [['cindent', '0', '', '0', '1', 'global', 'setglobal']] + setglobal cindent + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 30b: Setting local boolean local (to buffer) option" + noa setglobal nocindent " Reset global and local value (without triggering autocmd) + noa setlocal cindent + let g:options = [['cindent', '1', '1', '', '0', 'local', 'setlocal']] + setlocal nocindent + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 30c: Setting again boolean local (to buffer) option" + noa setglobal nocindent " Reset global and local value (without triggering autocmd) + noa setlocal cindent + let g:options = [['cindent', '1', '1', '0', '1', 'global', 'set']] + set cindent + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 30d: Setting again global boolean local (to buffer) option" + noa set nocindent " Reset global and local value (without triggering autocmd) + let g:options = [['cindent', '0', '0', '0', '1', 'global', 'set']] + set cindent + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 31: Setting boolean global-local (to window) option + " Currently no such option exists. + + + " 32a: Setting global boolean local (to window) option" + noa setglobal nocursorcolumn " Reset global and local value (without triggering autocmd) + noa setlocal cursorcolumn + let g:options = [['cursorcolumn', '0', '', '0', '1', 'global', 'setglobal']] + setglobal cursorcolumn + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 32b: Setting local boolean local (to window) option" + noa setglobal nocursorcolumn " Reset global and local value (without triggering autocmd) + noa setlocal cursorcolumn + let g:options = [['cursorcolumn', '1', '1', '', '0', 'local', 'setlocal']] + setlocal nocursorcolumn + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 32c: Setting again boolean local (to window) option" + noa setglobal nocursorcolumn " Reset global and local value (without triggering autocmd) + noa setlocal cursorcolumn + let g:options = [['cursorcolumn', '1', '1', '0', '1', 'global', 'set']] + set cursorcolumn + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + " 32d: Setting again global boolean local (to window) option" + noa set nocursorcolumn " Reset global and local value (without triggering autocmd) + let g:options = [['cursorcolumn', '0', '0', '0', '1', 'global', 'set']] + set cursorcolumn + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " 33: Test autocommands when an option value is converted internally. + noa set backspace=1 " Reset global and local value (without triggering autocmd) + let g:options = [['backspace', 'indent,eol', 'indent,eol', 'indent,eol', '2', 'global', 'set']] + set backspace=2 + call assert_equal([], g:options) + call assert_equal(g:opt[0], g:opt[1]) + + + " Cleanup + au! OptionSet + " set tags& + for opt in ['nu', 'ai', 'acd', 'ar', 'bs', 'backup', 'cul', 'cp', 'backupext', 'tags', 'spelllang', 'statusline', 'foldignore', 'cmdheight', 'undolevels', 'wrapmargin', 'foldcolumn', 'wrapscan', 'autoread', 'cindent', 'cursorcolumn'] + exe printf(":set %s&vim", opt) + endfor + call test_override('starting', 0) + delfunc! AutoCommandOptionSet +endfunc + +func Test_OptionSet_diffmode() + CheckFunction test_override + call test_override('starting', 1) + " 18: Changing an option when entering diff mode + new + au OptionSet diff :let &l:cul = v:option_new + + call setline(1, ['buffer 1', 'line2', 'line3', 'line4']) + call assert_equal(0, &l:cul) + diffthis + call assert_equal(1, &l:cul) + + vnew + call setline(1, ['buffer 2', 'line 2', 'line 3', 'line4']) + call assert_equal(0, &l:cul) + diffthis + call assert_equal(1, &l:cul) + + diffoff + call assert_equal(0, &l:cul) + call assert_equal(1, getwinvar(2, '&l:cul')) + bw! + + call assert_equal(1, &l:cul) + diffoff! + call assert_equal(0, &l:cul) + call assert_equal(0, getwinvar(1, '&l:cul')) + bw! + + " Cleanup + au! OptionSet + call test_override('starting', 0) +endfunc + +func Test_OptionSet_diffmode_close() + CheckFunction test_override + call test_override('starting', 1) + " 19: Try to close the current window when entering diff mode + " should not segfault + new + au OptionSet diff close + + call setline(1, ['buffer 1', 'line2', 'line3', 'line4']) + call assert_fails(':diffthis', 'E788') + call assert_equal(1, &diff) + vnew + call setline(1, ['buffer 2', 'line 2', 'line 3', 'line4']) + call assert_fails(':diffthis', 'E788') + call assert_equal(1, &diff) + set diffopt-=closeoff + bw! + call assert_fails(':diffoff!', 'E788') + bw! + + " Cleanup + au! OptionSet + call test_override('starting', 0) + "delfunc! AutoCommandOptionSet +endfunc + +" Test for Bufleave autocommand that deletes the buffer we are about to edit. +func Test_BufleaveWithDelete() + new | edit XbufLeave1 + + augroup test_bufleavewithdelete + autocmd! + autocmd BufLeave XbufLeave1 bwipe XbufLeave2 + augroup END + + call assert_fails('edit XbufLeave2', 'E143:') + call assert_equal('XbufLeave1', bufname('%')) + + autocmd! test_bufleavewithdelete BufLeave XbufLeave1 + augroup! test_bufleavewithdelete + + new + bwipe! XbufLeave1 +endfunc + +" Test for autocommand that changes the buffer list, when doing ":ball". +func Test_Acmd_BufAll() + enew! + %bwipe! + call writefile(['Test file Xxx1'], 'Xxx1', 'D') + call writefile(['Test file Xxx2'], 'Xxx2', 'D') + call writefile(['Test file Xxx3'], 'Xxx3', 'D') + + " Add three files to the buffer list + split Xxx1 + close + split Xxx2 + close + split Xxx3 + close + + " Wipe the buffer when the buffer is opened + au BufReadPost Xxx2 bwipe + + call append(0, 'Test file Xxx4') + ball + + call assert_equal(2, winnr('$')) + call assert_equal('Xxx1', bufname(winbufnr(winnr('$')))) + wincmd t + + au! BufReadPost + %bwipe! + enew! | only +endfunc + +" Test for autocommand that changes current buffer on BufEnter event. +" Check if modelines are interpreted for the correct buffer. +func Test_Acmd_BufEnter() + %bwipe! + call writefile(['start of test file Xxx1', + \ "\<Tab>this is a test", + \ 'end of test file Xxx1'], 'Xxx1', 'D') + call writefile(['start of test file Xxx2', + \ 'vim: set noai :', + \ "\<Tab>this is a test", + \ 'end of test file Xxx2'], 'Xxx2', 'D') + + au BufEnter Xxx2 brew + set ai modeline modelines=3 + edit Xxx1 + " edit Xxx2, autocmd will do :brew + edit Xxx2 + exe "normal G?this is a\<CR>" + " Append text with autoindent to this file + normal othis should be auto-indented + call assert_equal("\<Tab>this should be auto-indented", getline('.')) + call assert_equal(3, line('.')) + " Remove autocmd and edit Xxx2 again + au! BufEnter Xxx2 + buf! Xxx2 + exe "normal G?this is a\<CR>" + " append text without autoindent to Xxx + normal othis should be in column 1 + call assert_equal("this should be in column 1", getline('.')) + call assert_equal(4, line('.')) + + %bwipe! + set ai&vim modeline&vim modelines&vim +endfunc + +" Test for issue #57 +" do not move cursor on <c-o> when autoindent is set +func Test_ai_CTRL_O() + enew! + set ai + let save_fo = &fo + set fo+=r + exe "normal o# abcdef\<Esc>2hi\<CR>\<C-O>d0\<Esc>" + exe "normal o# abcdef\<Esc>2hi\<C-O>d0\<Esc>" + call assert_equal(['# abc', 'def', 'def'], getline(2, 4)) + + set ai&vim + let &fo = save_fo + enew! +endfunc + +" Test for autocommand that deletes the current buffer on BufLeave event. +" Also test deleting the last buffer, should give a new, empty buffer. +func Test_BufLeave_Wipe() + %bwipe! + let content = ['start of test file Xxx', + \ 'this is a test', + \ 'end of test file Xxx'] + call writefile(content, 'Xxx1', 'D') + call writefile(content, 'Xxx2', 'D') + + au BufLeave Xxx2 bwipe + edit Xxx1 + split Xxx2 + " delete buffer Xxx2, we should be back to Xxx1 + bwipe + call assert_equal('Xxx1', bufname('%')) + call assert_equal(1, winnr('$')) + + " Create an alternate buffer + %write! test.out + call assert_equal('test.out', bufname('#')) + " delete alternate buffer + bwipe test.out + call assert_equal('Xxx1', bufname('%')) + call assert_equal('', bufname('#')) + + au BufLeave Xxx1 bwipe + " delete current buffer, get an empty one + bwipe! + call assert_equal(1, line('$')) + call assert_equal('', bufname('%')) + let g:bufinfo = getbufinfo() + call assert_equal(1, len(g:bufinfo)) + + call delete('test.out') + %bwipe + au! BufLeave + + " check that bufinfo doesn't contain a pointer to freed memory + call test_garbagecollect_now() +endfunc + +func Test_QuitPre() + edit Xfoo + let winid = win_getid(winnr()) + split Xbar + au! QuitPre * let g:afile = expand('<afile>') + " Close the other window, <afile> should be correct. + exe win_id2win(winid) . 'q' + call assert_equal('Xfoo', g:afile) + + unlet g:afile + bwipe Xfoo + bwipe Xbar +endfunc + +func Test_Cmdline() + au! CmdlineChanged : let g:text = getcmdline() + let g:text = 0 + call feedkeys(":echom 'hello'\<CR>", 'xt') + call assert_equal("echom 'hello'", g:text) + au! CmdlineChanged + + au! CmdlineChanged : let g:entered = expand('<afile>') + let g:entered = 0 + call feedkeys(":echom 'hello'\<CR>", 'xt') + call assert_equal(':', g:entered) + au! CmdlineChanged + + autocmd CmdlineChanged : let g:log += [getcmdline()] + + let g:log = [] + cnoremap <F1> <Cmd>call setcmdline('ls')<CR> + call feedkeys(":\<F1>", 'xt') + call assert_equal(['ls'], g:log) + cunmap <F1> + + let g:log = [] + call feedkeys(":sign \<Tab>\<Tab>\<C-N>\<C-P>\<S-Tab>\<S-Tab>\<Esc>", 'xt') + call assert_equal([ + \ 's', + \ 'si', + \ 'sig', + \ 'sign', + \ 'sign ', + \ 'sign define', + \ 'sign jump', + \ 'sign list', + \ 'sign jump', + \ 'sign define', + \ 'sign ', + \ ], g:log) + let g:log = [] + set wildmenu wildoptions+=pum + call feedkeys(":sign \<S-Tab>\<PageUp>\<kPageUp>\<kPageDown>\<PageDown>\<Esc>", 'xt') + call assert_equal([ + \ 's', + \ 'si', + \ 'sig', + \ 'sign', + \ 'sign ', + \ 'sign unplace', + \ 'sign jump', + \ 'sign define', + \ 'sign undefine', + \ 'sign unplace', + \ ], g:log) + set wildmenu& wildoptions& + + let g:log = [] + let @r = 'abc' + call feedkeys(":0\<C-R>r1\<C-R>\<C-O>r2\<C-R>\<C-R>r3\<Esc>", 'xt') + call assert_equal([ + \ '0', + \ '0a', + \ '0ab', + \ '0abc', + \ '0abc1', + \ '0abc1abc', + \ '0abc1abc2', + \ '0abc1abc2abc', + \ '0abc1abc2abc3', + \ ], g:log) + + unlet g:log + au! CmdlineChanged + + au! CmdlineEnter : let g:entered = expand('<afile>') + au! CmdlineLeave : let g:left = expand('<afile>') + let g:entered = 0 + let g:left = 0 + call feedkeys(":echo 'hello'\<CR>", 'xt') + call assert_equal(':', g:entered) + call assert_equal(':', g:left) + au! CmdlineEnter + au! CmdlineLeave + + let save_shellslash = &shellslash + set noshellslash + au! CmdlineEnter / let g:entered = expand('<afile>') + au! CmdlineLeave / let g:left = expand('<afile>') + let g:entered = 0 + let g:left = 0 + new + call setline(1, 'hello') + call feedkeys("/hello\<CR>", 'xt') + call assert_equal('/', g:entered) + call assert_equal('/', g:left) + bwipe! + au! CmdlineEnter + au! CmdlineLeave + let &shellslash = save_shellslash +endfunc + +" Test for BufWritePre autocommand that deletes or unloads the buffer. +func Test_BufWritePre() + %bwipe + au BufWritePre Xxx1 bunload + au BufWritePre Xxx2 bwipe + + call writefile(['start of Xxx1', 'test', 'end of Xxx1'], 'Xxx1', 'D') + call writefile(['start of Xxx2', 'test', 'end of Xxx2'], 'Xxx2', 'D') + + edit Xtest + e! Xxx2 + bdel Xtest + e Xxx1 + " write it, will unload it and give an error msg + call assert_fails('w', 'E203:') + call assert_equal('Xxx2', bufname('%')) + edit Xtest + e! Xxx2 + bwipe Xtest + " write it, will delete the buffer and give an error msg + call assert_fails('w', 'E203:') + call assert_equal('Xxx1', bufname('%')) + au! BufWritePre +endfunc + +" Test for BufUnload autocommand that unloads all the other buffers +func Test_bufunload_all() + let g:test_is_flaky = 1 + call writefile(['Test file Xxx1'], 'Xxx1', 'D') + call writefile(['Test file Xxx2'], 'Xxx2', 'D') + + let content =<< trim [CODE] + func UnloadAllBufs() + let i = 1 + while i <= bufnr('$') + if i != bufnr('%') && bufloaded(i) + exe i . 'bunload' + endif + let i += 1 + endwhile + endfunc + au BufUnload * call UnloadAllBufs() + au VimLeave * call writefile(['Test Finished'], 'Xout') + set nohidden + edit Xxx1 + split Xxx2 + q + [CODE] + + call writefile(content, 'Xbunloadtest', 'D') + + call delete('Xout') + call system(GetVimCommandClean() .. ' -N --headless -S Xbunloadtest') + call assert_true(filereadable('Xout')) + + call delete('Xout') +endfunc + +" Some tests for buffer-local autocommands +func Test_buflocal_autocmd() + let g:bname = '' + edit xx + au BufLeave <buffer> let g:bname = expand("%") + " here, autocommand for xx should trigger. + " but autocommand shall not apply to buffer named <buffer>. + edit somefile + call assert_equal('xx', g:bname) + let g:bname = '' + " here, autocommand shall be auto-deleted + bwipe xx + " autocmd should not trigger + edit xx + call assert_equal('', g:bname) + " autocmd should not trigger + edit somefile + call assert_equal('', g:bname) + enew + unlet g:bname +endfunc + +" Test for "*Cmd" autocommands +func Test_Cmd_Autocmds() + call writefile(['start of Xxx', "\tabc2", 'end of Xxx'], 'Xxx', 'D') + + enew! + au BufReadCmd XtestA 0r Xxx|$del + edit XtestA " will read text of Xxd instead + call assert_equal('start of Xxx', getline(1)) + + au BufWriteCmd XtestA call append(line("$"), "write") + write " will append a line to the file + call assert_equal('write', getline('$')) + call assert_fails('read XtestA', 'E484') " should not read anything + call assert_equal('write', getline(4)) + + " now we have: + " 1 start of Xxx + " 2 abc2 + " 3 end of Xxx + " 4 write + + au FileReadCmd XtestB '[r Xxx + 2r XtestB " will read Xxx below line 2 instead + call assert_equal('start of Xxx', getline(3)) + + " now we have: + " 1 start of Xxx + " 2 abc2 + " 3 start of Xxx + " 4 abc2 + " 5 end of Xxx + " 6 end of Xxx + " 7 write + + au FileWriteCmd XtestC '[,']copy $ + normal 4GA1 + 4,5w XtestC " will copy lines 4 and 5 to the end + call assert_equal("\tabc21", getline(8)) + call assert_fails('r XtestC', 'E484') " should not read anything + call assert_equal("end of Xxx", getline(9)) + + " now we have: + " 1 start of Xxx + " 2 abc2 + " 3 start of Xxx + " 4 abc21 + " 5 end of Xxx + " 6 end of Xxx + " 7 write + " 8 abc21 + " 9 end of Xxx + + let g:lines = [] + au FileAppendCmd XtestD call extend(g:lines, getline(line("'["), line("']"))) + w >>XtestD " will add lines to 'lines' + call assert_equal(9, len(g:lines)) + call assert_fails('$r XtestD', 'E484') " should not read anything + call assert_equal(9, line('$')) + call assert_equal('end of Xxx', getline('$')) + + au BufReadCmd XtestE 0r Xxx|$del + sp XtestE " split window with test.out + call assert_equal('end of Xxx', getline(3)) + + let g:lines = [] + exe "normal 2Goasdf\<Esc>\<C-W>\<C-W>" + au BufWriteCmd XtestE call extend(g:lines, getline(0, '$')) + wall " will write other window to 'lines' + call assert_equal(4, len(g:lines), g:lines) + call assert_equal("asdf", g:lines[2]) + + au! BufReadCmd + au! BufWriteCmd + au! FileReadCmd + au! FileWriteCmd + au! FileAppendCmd + %bwipe! + enew! +endfunc + +func s:ReadFile() + setl noswapfile nomodified + let filename = resolve(expand("<afile>:p")) + execute 'read' fnameescape(filename) + 1d_ + exe 'file' fnameescape(filename) + setl buftype=acwrite +endfunc + +func s:WriteFile() + let filename = resolve(expand("<afile>:p")) + setl buftype= + noautocmd execute 'write' fnameescape(filename) + setl buftype=acwrite + setl nomodified +endfunc + +func Test_BufReadCmd() + autocmd BufReadCmd *.test call s:ReadFile() + autocmd BufWriteCmd *.test call s:WriteFile() + + call writefile(['one', 'two', 'three'], 'Xcmd.test', 'D') + edit Xcmd.test + call assert_match('Xcmd.test" line 1 of 3', execute('file')) + normal! Gofour + write + call assert_equal(['one', 'two', 'three', 'four'], readfile('Xcmd.test')) + + bwipe! + au! BufReadCmd + au! BufWriteCmd +endfunc + +func Test_BufWriteCmd() + autocmd BufWriteCmd Xbufwritecmd let g:written = 1 + new + file Xbufwritecmd + set buftype=acwrite + call mkdir('Xbufwritecmd', 'D') + write + " BufWriteCmd should be triggered even if a directory has the same name + call assert_equal(1, g:written) + unlet g:written + au! BufWriteCmd + bwipe! +endfunc + +func SetChangeMarks(start, end) + exe a:start .. 'mark [' + exe a:end .. 'mark ]' +endfunc + +" Verify the effects of autocmds on '[ and '] +func Test_change_mark_in_autocmds() + edit! Xtest + call feedkeys("ia\<CR>b\<CR>c\<CR>d\<C-g>u\<Esc>", 'xtn') + + call SetChangeMarks(2, 3) + write + call assert_equal([1, 4], [line("'["), line("']")]) + + call SetChangeMarks(2, 3) + au BufWritePre * call assert_equal([1, 4], [line("'["), line("']")]) + write + au! BufWritePre + + if has('unix') + write XtestFilter + write >> XtestFilter + + call SetChangeMarks(2, 3) + " Marks are set to the entire range of the write + au FilterWritePre * call assert_equal([1, 4], [line("'["), line("']")]) + " '[ is adjusted to just before the line that will receive the filtered + " data + au FilterReadPre * call assert_equal([4, 4], [line("'["), line("']")]) + " The filtered data is read into the buffer, and the source lines are + " still present, so the range is after the source lines + au FilterReadPost * call assert_equal([5, 12], [line("'["), line("']")]) + %!cat XtestFilter + " After the filtered data is read, the original lines are deleted + call assert_equal([1, 8], [line("'["), line("']")]) + au! FilterWritePre,FilterReadPre,FilterReadPost + undo + + call SetChangeMarks(1, 4) + au FilterWritePre * call assert_equal([2, 3], [line("'["), line("']")]) + au FilterReadPre * call assert_equal([3, 3], [line("'["), line("']")]) + au FilterReadPost * call assert_equal([4, 11], [line("'["), line("']")]) + 2,3!cat XtestFilter + call assert_equal([2, 9], [line("'["), line("']")]) + au! FilterWritePre,FilterReadPre,FilterReadPost + undo + + call delete('XtestFilter') + endif + + call SetChangeMarks(1, 4) + au FileWritePre * call assert_equal([2, 3], [line("'["), line("']")]) + 2,3write Xtest2 + au! FileWritePre + + call SetChangeMarks(2, 3) + au FileAppendPre * call assert_equal([1, 4], [line("'["), line("']")]) + write >> Xtest2 + au! FileAppendPre + + call SetChangeMarks(1, 4) + au FileAppendPre * call assert_equal([2, 3], [line("'["), line("']")]) + 2,3write >> Xtest2 + au! FileAppendPre + + call SetChangeMarks(1, 1) + au FileReadPre * call assert_equal([3, 1], [line("'["), line("']")]) + au FileReadPost * call assert_equal([4, 11], [line("'["), line("']")]) + 3read Xtest2 + au! FileReadPre,FileReadPost + undo + + call SetChangeMarks(4, 4) + " When the line is 0, it's adjusted to 1 + au FileReadPre * call assert_equal([1, 4], [line("'["), line("']")]) + au FileReadPost * call assert_equal([1, 8], [line("'["), line("']")]) + 0read Xtest2 + au! FileReadPre,FileReadPost + undo + + call SetChangeMarks(4, 4) + " When the line is 0, it's adjusted to 1 + au FileReadPre * call assert_equal([1, 4], [line("'["), line("']")]) + au FileReadPost * call assert_equal([2, 9], [line("'["), line("']")]) + 1read Xtest2 + au! FileReadPre,FileReadPost + undo + + bwipe! + call delete('Xtest') + call delete('Xtest2') +endfunc + +func Test_Filter_noshelltemp() + CheckExecutable cat + + enew! + call setline(1, ['a', 'b', 'c', 'd']) + + let shelltemp = &shelltemp + set shelltemp + + let g:filter_au = 0 + au FilterWritePre * let g:filter_au += 1 + au FilterReadPre * let g:filter_au += 1 + au FilterReadPost * let g:filter_au += 1 + %!cat + call assert_equal(3, g:filter_au) + + if has('filterpipe') + set noshelltemp + + let g:filter_au = 0 + au FilterWritePre * let g:filter_au += 1 + au FilterReadPre * let g:filter_au += 1 + au FilterReadPost * let g:filter_au += 1 + %!cat + call assert_equal(0, g:filter_au) + endif + + au! FilterWritePre,FilterReadPre,FilterReadPost + let &shelltemp = shelltemp + bwipe! +endfunc + +func Test_TextYankPost() + enew! + call setline(1, ['foo']) + + let g:event = [] + au TextYankPost * let g:event = copy(v:event) + + call assert_equal({}, v:event) + call assert_fails('let v:event = {}', 'E46:') + call assert_fails('let v:event.mykey = 0', 'E742:') + + norm "ayiw + call assert_equal( + \{'regcontents': ['foo'], 'inclusive': v:true, 'regname': 'a', 'operator': 'y', 'visual': v:false, 'regtype': 'v'}, + \g:event) + norm y_ + call assert_equal( + \{'regcontents': ['foo'], 'inclusive': v:false, 'regname': '', 'operator': 'y', 'visual': v:false, 'regtype': 'V'}, + \g:event) + norm Vy + call assert_equal( + \{'regcontents': ['foo'], 'inclusive': v:true, 'regname': '', 'operator': 'y', 'visual': v:true, 'regtype': 'V'}, + \g:event) + call feedkeys("\<C-V>y", 'x') + call assert_equal( + \{'regcontents': ['f'], 'inclusive': v:true, 'regname': '', 'operator': 'y', 'visual': v:true, 'regtype': "\x161"}, + \g:event) + norm "xciwbar + call assert_equal( + \{'regcontents': ['foo'], 'inclusive': v:true, 'regname': 'x', 'operator': 'c', 'visual': v:false, 'regtype': 'v'}, + \g:event) + norm "bdiw + call assert_equal( + \{'regcontents': ['bar'], 'inclusive': v:true, 'regname': 'b', 'operator': 'd', 'visual': v:false, 'regtype': 'v'}, + \g:event) + + call assert_equal({}, v:event) + + au! TextYankPost + unlet g:event + bwipe! +endfunc + +func Test_autocommand_all_events() + call assert_fails('au * * bwipe', 'E1155:') + call assert_fails('au * x bwipe', 'E1155:') + call assert_fails('au! * x bwipe', 'E1155:') +endfunc + +func Test_autocmd_user() + au User MyEvent let s:res = [expand("<afile>"), expand("<amatch>")] + doautocmd User MyEvent + call assert_equal(['MyEvent', 'MyEvent'], s:res) + au! User + unlet s:res +endfunc + +function s:Before_test_dirchanged() + augroup test_dirchanged + autocmd! + augroup END + let s:li = [] + let s:dir_this = getcwd() + let s:dir_foo = s:dir_this . '/Xfoo' + call mkdir(s:dir_foo) + let s:dir_bar = s:dir_this . '/Xbar' + call mkdir(s:dir_bar) +endfunc + +function s:After_test_dirchanged() + call chdir(s:dir_this) + call delete(s:dir_foo, 'd') + call delete(s:dir_bar, 'd') + augroup test_dirchanged + autocmd! + augroup END +endfunc + +function Test_dirchanged_global() + call s:Before_test_dirchanged() + autocmd test_dirchanged DirChangedPre global call add(s:li, expand("<amatch>") .. " pre cd " .. v:event.directory) + autocmd test_dirchanged DirChanged global call add(s:li, "cd:") + autocmd test_dirchanged DirChanged global call add(s:li, expand("<afile>")) + call chdir(s:dir_foo) + let expected = ["global pre cd " .. s:dir_foo, "cd:", s:dir_foo] + call assert_equal(expected, s:li) + call chdir(s:dir_foo) + call assert_equal(expected, s:li) + exe 'lcd ' .. fnameescape(s:dir_bar) + call assert_equal(expected, s:li) + + exe 'cd ' .. s:dir_foo + exe 'cd ' .. s:dir_bar + autocmd! test_dirchanged DirChanged global let g:result = expand("<afile>") + cd - + call assert_equal(s:dir_foo, substitute(g:result, '\\', '/', 'g')) + + call s:After_test_dirchanged() +endfunc + +function Test_dirchanged_local() + call s:Before_test_dirchanged() + autocmd test_dirchanged DirChanged window call add(s:li, "lcd:") + autocmd test_dirchanged DirChanged window call add(s:li, expand("<afile>")) + call chdir(s:dir_foo) + call assert_equal([], s:li) + exe 'lcd ' .. fnameescape(s:dir_bar) + call assert_equal(["lcd:", s:dir_bar], s:li) + exe 'lcd ' .. fnameescape(s:dir_bar) + call assert_equal(["lcd:", s:dir_bar], s:li) + call s:After_test_dirchanged() +endfunc + +function Test_dirchanged_auto() + CheckFunction test_autochdir + CheckOption autochdir + call s:Before_test_dirchanged() + call test_autochdir() + autocmd test_dirchanged DirChangedPre auto call add(s:li, "pre cd " .. v:event.directory) + autocmd test_dirchanged DirChanged auto call add(s:li, "auto:") + autocmd test_dirchanged DirChanged auto call add(s:li, expand("<afile>")) + set acd + cd .. + call assert_equal([], s:li) + exe 'edit ' . s:dir_foo . '/Xautofile' + call assert_equal(s:dir_foo, getcwd()) + let expected = ["pre cd " .. s:dir_foo, "auto:", s:dir_foo] + call assert_equal(expected, s:li) + set noacd + bwipe! + call s:After_test_dirchanged() +endfunc + +" Test TextChangedI and TextChangedP +func Test_ChangedP() + throw 'Skipped: use test/functional/autocmd/textchanged_spec.lua' + new + call setline(1, ['foo', 'bar', 'foobar']) + call test_override("char_avail", 1) + set complete=. completeopt=menuone + + func! TextChangedAutocmd(char) + let g:autocmd .= a:char + endfunc + + " TextChanged will not be triggered, only check that it isn't. + au! TextChanged <buffer> :call TextChangedAutocmd('N') + au! TextChangedI <buffer> :call TextChangedAutocmd('I') + au! TextChangedP <buffer> :call TextChangedAutocmd('P') + + call cursor(3, 1) + let g:autocmd = '' + call feedkeys("o\<esc>", 'tnix') + call assert_equal('I', g:autocmd) + + let g:autocmd = '' + call feedkeys("Sf", 'tnix') + call assert_equal('II', g:autocmd) + + let g:autocmd = '' + call feedkeys("Sf\<C-N>", 'tnix') + call assert_equal('IIP', g:autocmd) + + let g:autocmd = '' + call feedkeys("Sf\<C-N>\<C-N>", 'tnix') + call assert_equal('IIPP', g:autocmd) + + let g:autocmd = '' + call feedkeys("Sf\<C-N>\<C-N>\<C-N>", 'tnix') + call assert_equal('IIPPP', g:autocmd) + + let g:autocmd = '' + call feedkeys("Sf\<C-N>\<C-N>\<C-N>\<C-N>", 'tnix') + call assert_equal('IIPPPP', g:autocmd) + + call assert_equal(['foo', 'bar', 'foobar', 'foo'], getline(1, '$')) + " TODO: how should it handle completeopt=noinsert,noselect? + + " CleanUp + call test_override("char_avail", 0) + au! TextChanged + au! TextChangedI + au! TextChangedP + delfu TextChangedAutocmd + unlet! g:autocmd + set complete&vim completeopt&vim + + bw! +endfunc + +let g:setline_handled = v:false +func SetLineOne() + if !g:setline_handled + call setline(1, "(x)") + let g:setline_handled = v:true + endif +endfunc + +func Test_TextChangedI_with_setline() + throw 'Skipped: use test/functional/autocmd/textchanged_spec.lua' + new + call test_override('char_avail', 1) + autocmd TextChangedI <buffer> call SetLineOne() + call feedkeys("i(\<CR>\<Esc>", 'tx') + call assert_equal('(', getline(1)) + call assert_equal('x)', getline(2)) + undo + call assert_equal('', getline(1)) + call assert_equal('', getline(2)) + + call test_override('starting', 0) + bwipe! +endfunc + +func Test_Changed_FirstTime() + CheckFeature terminal + CheckNotGui + " Starting a terminal to run Vim is always considered flaky. + let g:test_is_flaky = 1 + + " Prepare file for TextChanged event. + call writefile([''], 'Xchanged.txt', 'D') + let buf = term_start([GetVimProg(), '--clean', '-c', 'set noswapfile'], {'term_rows': 3}) + call assert_equal('running', term_getstatus(buf)) + " Wait for the ruler (in the status line) to be shown. + " In ConPTY, there is additional character which is drawn up to the width of + " the screen. + if has('conpty') + call WaitForAssert({-> assert_match('\<All.*$', term_getline(buf, 3))}) + else + call WaitForAssert({-> assert_match('\<All$', term_getline(buf, 3))}) + endif + " It's only adding autocmd, so that no event occurs. + call term_sendkeys(buf, ":au! TextChanged <buffer> call writefile(['No'], 'Xchanged.txt')\<cr>") + call term_sendkeys(buf, "\<C-\\>\<C-N>:qa!\<cr>") + call WaitForAssert({-> assert_equal('finished', term_getstatus(buf))}) + call assert_equal([''], readfile('Xchanged.txt')) + + " clean up + bwipe! +endfunc + +func Test_autocmd_nested() + let g:did_nested = 0 + augroup Testing + au WinNew * edit somefile + au BufNew * let g:did_nested = 1 + augroup END + split + call assert_equal(0, g:did_nested) + close + bwipe! somefile + + " old nested argument still works + augroup Testing + au! + au WinNew * nested edit somefile + au BufNew * let g:did_nested = 1 + augroup END + split + call assert_equal(1, g:did_nested) + close + bwipe! somefile + + " New ++nested argument works + augroup Testing + au! + au WinNew * ++nested edit somefile + au BufNew * let g:did_nested = 1 + augroup END + split + call assert_equal(1, g:did_nested) + close + bwipe! somefile + + augroup Testing + au! + augroup END + + call assert_fails('au WinNew * ++nested ++nested echo bad', 'E983:') + call assert_fails('au WinNew * nested nested echo bad', 'E983:') +endfunc + +func Test_autocmd_nested_cursor_invalid() + set laststatus=0 + copen + cclose + call setline(1, ['foo', 'bar', 'baz']) + 3 + augroup nested_inv + autocmd User foo ++nested copen + autocmd BufAdd * let &laststatus = 2 - &laststatus + augroup END + doautocmd User foo + + augroup nested_inv + au! + augroup END + set laststatus& + cclose + bwipe! +endfunc + +func Test_autocmd_nested_keeps_cursor_pos() + enew + call setline(1, 'foo') + autocmd User foo ++nested normal! $a + autocmd InsertLeave * : + doautocmd User foo + call assert_equal([0, 1, 3, 0], getpos('.')) + + bwipe! +endfunc + +func Test_autocmd_nested_switch_window() + " run this in a separate Vim so that SafeState works + CheckRunVimInTerminal + + let lines =<< trim END + vim9script + ['()']->writefile('Xautofile') + autocmd VimEnter * ++nested edit Xautofile | split + autocmd BufReadPost * autocmd SafeState * ++once foldclosed('.') + autocmd WinEnter * matchadd('ErrorMsg', 'pat') + END + call writefile(lines, 'Xautoscript', 'D') + let buf = RunVimInTerminal('-S Xautoscript', {'rows': 10}) + call VerifyScreenDump(buf, 'Test_autocmd_nested_switch', {}) + + call StopVimInTerminal(buf) + call delete('Xautofile') +endfunc + +func Test_autocmd_once() + " Without ++once WinNew triggers twice + let g:did_split = 0 + augroup Testing + au WinNew * let g:did_split += 1 + augroup END + split + split + call assert_equal(2, g:did_split) + call assert_true(exists('#WinNew')) + close + close + + " With ++once WinNew triggers once + let g:did_split = 0 + augroup Testing + au! + au WinNew * ++once let g:did_split += 1 + augroup END + split + split + call assert_equal(1, g:did_split) + call assert_false(exists('#WinNew')) + close + close + + call assert_fails('au WinNew * ++once ++once echo bad', 'E983:') +endfunc + +func Test_autocmd_bufreadpre() + new + let b:bufreadpre = 1 + call append(0, range(100)) + w! XAutocmdBufReadPre.txt + autocmd BufReadPre <buffer> :let b:bufreadpre += 1 + norm! 50gg + sp + norm! 100gg + wincmd p + let g:wsv1 = winsaveview() + wincmd p + let g:wsv2 = winsaveview() + " triggers BufReadPre, should not move the cursor in either window + " The topline may change one line in a large window. + edit + call assert_inrange(g:wsv2.topline - 1, g:wsv2.topline + 1, winsaveview().topline) + call assert_equal(g:wsv2.lnum, winsaveview().lnum) + call assert_equal(2, b:bufreadpre) + wincmd p + call assert_equal(g:wsv1.topline, winsaveview().topline) + call assert_equal(g:wsv1.lnum, winsaveview().lnum) + call assert_equal(2, b:bufreadpre) + " Now set the cursor position in an BufReadPre autocommand + " (even though the position will be invalid, this should make Vim reset the + " cursor position in the other window. + wincmd p + 1 " set cpo+=g + " won't do anything, but try to set the cursor on an invalid lnum + autocmd BufReadPre <buffer> :norm! 70gg + " triggers BufReadPre, should not move the cursor in either window + e + call assert_equal(1, winsaveview().topline) + call assert_equal(1, winsaveview().lnum) + call assert_equal(3, b:bufreadpre) + wincmd p + call assert_equal(g:wsv1.topline, winsaveview().topline) + call assert_equal(g:wsv1.lnum, winsaveview().lnum) + call assert_equal(3, b:bufreadpre) + close + close + call delete('XAutocmdBufReadPre.txt') + set cpo-=g +endfunc + +" FileChangedShell tested in test_filechanged.vim + +" Tests for the following autocommands: +" - FileWritePre writing a compressed file +" - FileReadPost reading a compressed file +" - BufNewFile reading a file template +" - BufReadPre decompressing the file to be read +" - FilterReadPre substituting characters in the temp file +" - FilterReadPost substituting characters after filtering +" - FileReadPre set options for decompression +" - FileReadPost decompress the file +func Test_ReadWrite_Autocmds() + " Run this test only on Unix-like systems and if gzip is available + if !has('unix') || !executable("gzip") + return + endif + + " Make $GZIP empty, "-v" would cause trouble. + let $GZIP = "" + + " Use a FileChangedShell autocommand to avoid a prompt for 'Xtestfile.gz' + " being modified outside of Vim (noticed on Solaris). + au FileChangedShell * echo 'caught FileChangedShell' + + " Test for the FileReadPost, FileWritePre and FileWritePost autocmds + augroup Test1 + au! + au FileWritePre *.gz '[,']!gzip + au FileWritePost *.gz undo + au FileReadPost *.gz '[,']!gzip -d + augroup END + + new + set bin + call append(0, [ + \ 'line 2 Abcdefghijklmnopqrstuvwxyz', + \ 'line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 4 Abcdefghijklmnopqrstuvwxyz', + \ 'line 5 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 6 Abcdefghijklmnopqrstuvwxyz', + \ 'line 7 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 8 Abcdefghijklmnopqrstuvwxyz', + \ 'line 9 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 10 Abcdefghijklmnopqrstuvwxyz' + \ ]) + 1,9write! Xtestfile.gz + enew! | close + + new + " Read and decompress the testfile + 0read Xtestfile.gz + call assert_equal([ + \ 'line 2 Abcdefghijklmnopqrstuvwxyz', + \ 'line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 4 Abcdefghijklmnopqrstuvwxyz', + \ 'line 5 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 6 Abcdefghijklmnopqrstuvwxyz', + \ 'line 7 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 8 Abcdefghijklmnopqrstuvwxyz', + \ 'line 9 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 10 Abcdefghijklmnopqrstuvwxyz' + \ ], getline(1, 9)) + enew! | close + + augroup Test1 + au! + augroup END + + " Test for the FileAppendPre and FileAppendPost autocmds + augroup Test2 + au! + au BufNewFile *.c read Xtest.c + au FileAppendPre *.out '[,']s/new/NEW/ + au FileAppendPost *.out !cat Xtest.c >> test.out + augroup END + + call writefile(['/*', ' * Here is a new .c file', ' */'], 'Xtest.c', 'D') + new foo.c " should load Xtest.c + call assert_equal(['/*', ' * Here is a new .c file', ' */'], getline(2, 4)) + w! >> test.out " append it to the output file + + let contents = readfile('test.out') + call assert_equal(' * Here is a NEW .c file', contents[2]) + call assert_equal(' * Here is a new .c file', contents[5]) + + call delete('test.out') + enew! | close + augroup Test2 + au! + augroup END + + " Test for the BufReadPre and BufReadPost autocmds + augroup Test3 + au! + " setup autocommands to decompress before reading and re-compress + " afterwards + au BufReadPre *.gz exe '!gzip -d ' . shellescape(expand("<afile>")) + au BufReadPre *.gz call rename(expand("<afile>:r"), expand("<afile>")) + au BufReadPost *.gz call rename(expand("<afile>"), expand("<afile>:r")) + au BufReadPost *.gz exe '!gzip ' . shellescape(expand("<afile>:r")) + augroup END + + e! Xtestfile.gz " Edit compressed file + call assert_equal([ + \ 'line 2 Abcdefghijklmnopqrstuvwxyz', + \ 'line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 4 Abcdefghijklmnopqrstuvwxyz', + \ 'line 5 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 6 Abcdefghijklmnopqrstuvwxyz', + \ 'line 7 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 8 Abcdefghijklmnopqrstuvwxyz', + \ 'line 9 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 10 Abcdefghijklmnopqrstuvwxyz' + \ ], getline(1, 9)) + + w! >> test.out " Append it to the output file + + augroup Test3 + au! + augroup END + + " Test for the FilterReadPre and FilterReadPost autocmds. + set shelltemp " need temp files here + augroup Test4 + au! + au FilterReadPre *.out call rename(expand("<afile>"), expand("<afile>") . ".t") + au FilterReadPre *.out exe 'silent !sed s/e/E/ ' . shellescape(expand("<afile>")) . ".t >" . shellescape(expand("<afile>")) + au FilterReadPre *.out exe 'silent !rm ' . shellescape(expand("<afile>")) . '.t' + au FilterReadPost *.out '[,']s/x/X/g + augroup END + + e! test.out " Edit the output file + 1,$!cat + call assert_equal([ + \ 'linE 2 AbcdefghijklmnopqrstuvwXyz', + \ 'linE 3 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + \ 'linE 4 AbcdefghijklmnopqrstuvwXyz', + \ 'linE 5 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + \ 'linE 6 AbcdefghijklmnopqrstuvwXyz', + \ 'linE 7 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + \ 'linE 8 AbcdefghijklmnopqrstuvwXyz', + \ 'linE 9 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', + \ 'linE 10 AbcdefghijklmnopqrstuvwXyz' + \ ], getline(1, 9)) + call assert_equal([ + \ 'line 2 Abcdefghijklmnopqrstuvwxyz', + \ 'line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 4 Abcdefghijklmnopqrstuvwxyz', + \ 'line 5 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 6 Abcdefghijklmnopqrstuvwxyz', + \ 'line 7 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 8 Abcdefghijklmnopqrstuvwxyz', + \ 'line 9 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 10 Abcdefghijklmnopqrstuvwxyz' + \ ], readfile('test.out')) + + augroup Test4 + au! + augroup END + set shelltemp&vim + + " Test for the FileReadPre and FileReadPost autocmds. + augroup Test5 + au! + au FileReadPre *.gz exe 'silent !gzip -d ' . shellescape(expand("<afile>")) + au FileReadPre *.gz call rename(expand("<afile>:r"), expand("<afile>")) + au FileReadPost *.gz '[,']s/l/L/ + augroup END + + new + 0r Xtestfile.gz " Read compressed file + call assert_equal([ + \ 'Line 2 Abcdefghijklmnopqrstuvwxyz', + \ 'Line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'Line 4 Abcdefghijklmnopqrstuvwxyz', + \ 'Line 5 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'Line 6 Abcdefghijklmnopqrstuvwxyz', + \ 'Line 7 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'Line 8 Abcdefghijklmnopqrstuvwxyz', + \ 'Line 9 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'Line 10 Abcdefghijklmnopqrstuvwxyz' + \ ], getline(1, 9)) + call assert_equal([ + \ 'line 2 Abcdefghijklmnopqrstuvwxyz', + \ 'line 3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 4 Abcdefghijklmnopqrstuvwxyz', + \ 'line 5 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 6 Abcdefghijklmnopqrstuvwxyz', + \ 'line 7 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 8 Abcdefghijklmnopqrstuvwxyz', + \ 'line 9 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', + \ 'line 10 Abcdefghijklmnopqrstuvwxyz' + \ ], readfile('Xtestfile.gz')) + + augroup Test5 + au! + augroup END + + au! FileChangedShell + call delete('Xtestfile.gz') + call delete('test.out') +endfunc + +func Test_throw_in_BufWritePre() + new + call setline(1, ['one', 'two', 'three']) + call assert_false(filereadable('Xthefile')) + augroup throwing + au BufWritePre X* throw 'do not write' + augroup END + try + w Xthefile + catch + let caught = 1 + endtry + call assert_equal(1, caught) + call assert_false(filereadable('Xthefile')) + + bwipe! + au! throwing +endfunc + +func Test_autocmd_in_try_block() + call mkdir('Xintrydir', 'R') + au BufEnter * let g:fname = expand('%') + try + edit Xintrydir/ + endtry + call assert_match('Xintrydir', g:fname) + + unlet g:fname + au! BufEnter +endfunc + +func Test_autocmd_SafeState() + CheckRunVimInTerminal + + let lines =<< trim END + let g:safe = 0 + let g:again = '' + au SafeState * let g:safe += 1 + au SafeStateAgain * let g:again ..= 'x' + func CallTimer() + call timer_start(10, {id -> execute('let g:again ..= "t"')}) + endfunc + END + call writefile(lines, 'XSafeState', 'D') + let buf = RunVimInTerminal('-S XSafeState', #{rows: 6}) + + " Sometimes we loop to handle a K_IGNORE, SafeState may be triggered once or + " more often. + call term_sendkeys(buf, ":echo g:safe\<CR>") + call WaitForAssert({-> assert_match('^\d ', term_getline(buf, 6))}, 1000) + + " SafeStateAgain should be invoked at least three times + call term_sendkeys(buf, ":echo g:again\<CR>") + call WaitForAssert({-> assert_match('^xxx', term_getline(buf, 6))}, 1000) + + call term_sendkeys(buf, ":let g:again = ''\<CR>:call CallTimer()\<CR>") + call TermWait(buf, 50) + call term_sendkeys(buf, ":\<CR>") + call TermWait(buf, 50) + call term_sendkeys(buf, ":echo g:again\<CR>") + call WaitForAssert({-> assert_match('xtx', term_getline(buf, 6))}, 1000) + + call StopVimInTerminal(buf) +endfunc + +func Test_autocmd_CmdWinEnter() + CheckRunVimInTerminal + " There is not cmdwin switch, so + " test for cmdline_hist + " (both are available with small builds) + CheckFeature cmdline_hist + let lines =<< trim END + let b:dummy_var = 'This is a dummy' + autocmd CmdWinEnter * quit + let winnr = winnr('$') + END + let filename = 'XCmdWinEnter' + call writefile(lines, filename) + let buf = RunVimInTerminal('-S '.filename, #{rows: 6}) + + call term_sendkeys(buf, "q:") + call TermWait(buf) + call term_sendkeys(buf, ":echo b:dummy_var\<cr>") + call WaitForAssert({-> assert_match('^This is a dummy', term_getline(buf, 6))}, 2000) + call term_sendkeys(buf, ":echo &buftype\<cr>") + call WaitForAssert({-> assert_notmatch('^nofile', term_getline(buf, 6))}, 1000) + call term_sendkeys(buf, ":echo winnr\<cr>") + call WaitForAssert({-> assert_match('^1', term_getline(buf, 6))}, 1000) + + " clean up + call StopVimInTerminal(buf) + call delete(filename) +endfunc + +func Test_autocmd_was_using_freed_memory() + CheckFeature quickfix + + pedit xx + n x + augroup winenter + au WinEnter * if winnr('$') > 2 | quit | endif + augroup END + " Nvim needs large 'winwidth' and 'nowinfixwidth' to crash + set winwidth=99999 nowinfixwidth + split + + augroup winenter + au! WinEnter + augroup END + + set winwidth& winfixwidth& + bwipe xx + bwipe x + pclose +endfunc + +func Test_BufWrite_lockmarks() + let g:test_is_flaky = 1 + edit! Xtest + call setline(1, ['a', 'b', 'c', 'd']) + + " :lockmarks preserves the marks + call SetChangeMarks(2, 3) + lockmarks write + call assert_equal([2, 3], [line("'["), line("']")]) + + " *WritePre autocmds get the correct line range, but lockmarks preserves the + " original values for the user + augroup lockmarks + au! + au BufWritePre,FilterWritePre * call assert_equal([1, 4], [line("'["), line("']")]) + au FileWritePre * call assert_equal([3, 4], [line("'["), line("']")]) + augroup END + + lockmarks write + call assert_equal([2, 3], [line("'["), line("']")]) + + if executable('cat') + lockmarks %!cat + call assert_equal([2, 3], [line("'["), line("']")]) + endif + + lockmarks 3,4write Xtest2 + call assert_equal([2, 3], [line("'["), line("']")]) + + au! lockmarks + augroup! lockmarks + call delete('Xtest') + call delete('Xtest2') +endfunc + +func Test_FileType_spell() + if !isdirectory('/tmp') + throw "Skipped: requires /tmp directory" + endif + + " this was crashing with an invalid free() + setglobal spellfile=/tmp/en.utf-8.add + augroup crash + autocmd! + autocmd BufNewFile,BufReadPost crashfile setf somefiletype + autocmd BufNewFile,BufReadPost crashfile set ft=anotherfiletype + autocmd FileType anotherfiletype setlocal spell + augroup END + func! NoCrash() abort + edit /tmp/crashfile + endfunc + call NoCrash() + + au! crash + setglobal spellfile= +endfunc + +" this was wiping out the current buffer and using freed memory +func Test_SpellFileMissing_bwipe() + next 0 + au SpellFileMissing 0 bwipe + call assert_fails('set spell spelllang=0', 'E937:') + + au! SpellFileMissing + set nospell spelllang=en + bwipe +endfunc + +" Test closing a window or editing another buffer from a FileChangedRO handler +" in a readonly buffer +func Test_FileChangedRO_winclose() + augroup FileChangedROTest + au! + autocmd FileChangedRO * quit + augroup END + new + set readonly + call assert_fails('normal i', 'E788:') + close + augroup! FileChangedROTest + + augroup FileChangedROTest + au! + autocmd FileChangedRO * edit Xrofile + augroup END + new + set readonly + call assert_fails('normal i', 'E788:') + close + augroup! FileChangedROTest +endfunc + +func LogACmd() + call add(g:logged, line('$')) +endfunc + +func Test_TermChanged() + throw 'skipped: Nvim does not support TermChanged event' + CheckNotGui + + enew! + tabnew + call setline(1, ['a', 'b', 'c', 'd']) + $ + au TermChanged * call LogACmd() + let g:logged = [] + let term_save = &term + set term=xterm + call assert_equal([1, 4], g:logged) + + au! TermChanged + let &term = term_save + bwipe! +endfunc + +" Test for FileReadCmd autocmd +func Test_autocmd_FileReadCmd() + func ReadFileCmd() + call append(line('$'), "v:cmdarg = " .. v:cmdarg) + endfunc + augroup FileReadCmdTest + au! + au FileReadCmd Xtest call ReadFileCmd() + augroup END + + new + read ++bin Xtest + read ++nobin Xtest + read ++edit Xtest + read ++bad=keep Xtest + read ++bad=drop Xtest + read ++bad=- Xtest + read ++ff=unix Xtest + read ++ff=dos Xtest + read ++ff=mac Xtest + read ++enc=utf-8 Xtest + + call assert_equal(['', + \ 'v:cmdarg = ++bin', + \ 'v:cmdarg = ++nobin', + \ 'v:cmdarg = ++edit', + \ 'v:cmdarg = ++bad=keep', + \ 'v:cmdarg = ++bad=drop', + \ 'v:cmdarg = ++bad=-', + \ 'v:cmdarg = ++ff=unix', + \ 'v:cmdarg = ++ff=dos', + \ 'v:cmdarg = ++ff=mac', + \ 'v:cmdarg = ++enc=utf-8'], getline(1, '$')) + + bwipe! + augroup FileReadCmdTest + au! + augroup END + delfunc ReadFileCmd +endfunc + +" Test for passing invalid arguments to autocmd +func Test_autocmd_invalid_args() + " Additional character after * for event + call assert_fails('autocmd *a Xinvfile set ff=unix', 'E215:') + augroup Test + augroup END + " Invalid autocmd event + call assert_fails('autocmd Bufabc Xinvfile set ft=vim', 'E216:') + " Invalid autocmd event in a autocmd group + call assert_fails('autocmd Test Bufabc Xinvfile set ft=vim', 'E216:') + augroup! Test + " Execute all autocmds + call assert_fails('doautocmd * BufEnter', 'E217:') + call assert_fails('augroup! x1a2b3', 'E367:') + call assert_fails('autocmd BufNew <buffer=999> pwd', 'E680:') + call assert_fails('autocmd BufNew \) set ff=unix', 'E55:') +endfunc + +" Test for deep nesting of autocmds +func Test_autocmd_deep_nesting() + autocmd BufEnter Xdeepfile doautocmd BufEnter Xdeepfile + call assert_fails('doautocmd BufEnter Xdeepfile', 'E218:') + autocmd! BufEnter Xdeepfile +endfunc + +" Tests for SigUSR1 autocmd event, which is only available on posix systems. +func Test_autocmd_sigusr1() + CheckUnix + + let g:sigusr1_passed = 0 + au Signal SIGUSR1 let g:sigusr1_passed = 1 + call system('kill -s usr1 ' . getpid()) + call WaitForAssert({-> assert_true(g:sigusr1_passed)}) + + au! Signal + unlet g:sigusr1_passed +endfunc + +" Test for BufReadPre autocmd deleting the file +func Test_BufReadPre_delfile() + augroup TestAuCmd + au! + autocmd BufReadPre XbufreadPre call delete('XbufreadPre') + augroup END + call writefile([], 'XbufreadPre', 'D') + call assert_fails('new XbufreadPre', 'E200:') + call assert_equal('XbufreadPre', @%) + call assert_equal(1, &readonly) + + augroup TestAuCmd + au! + augroup END + close! +endfunc + +" Test for BufReadPre autocmd changing the current buffer +func Test_BufReadPre_changebuf() + augroup TestAuCmd + au! + autocmd BufReadPre Xchangebuf edit Xsomeotherfile + augroup END + call writefile([], 'Xchangebuf', 'D') + call assert_fails('new Xchangebuf', 'E201:') + call assert_equal('Xsomeotherfile', @%) + call assert_equal(1, &readonly) + + augroup TestAuCmd + au! + augroup END + close! +endfunc + +" Test for BufWipeouti autocmd changing the current buffer when reading a file +" in an empty buffer with 'f' flag in 'cpo' +func Test_BufDelete_changebuf() + new + augroup TestAuCmd + au! + autocmd BufWipeout * let bufnr = bufadd('somefile') | exe "b " .. bufnr + augroup END + let save_cpo = &cpo + set cpo+=f + call assert_fails('r Xfile', ['E812:', 'E484:']) + call assert_equal('somefile', @%) + let &cpo = save_cpo + augroup TestAuCmd + au! + augroup END + close! +endfunc + +" Test for the temporary internal window used to execute autocmds +func Test_autocmd_window() + %bw! + edit one.txt + tabnew two.txt + vnew three.txt + tabnew four.txt + tabprevious + let g:blist = [] + augroup aucmd_win_test1 + au! + au BufEnter * call add(g:blist, [expand('<afile>'), + \ win_gettype(bufwinnr(expand('<afile>')))]) + augroup END + + doautoall BufEnter + call assert_equal([ + \ ['one.txt', 'autocmd'], + \ ['two.txt', ''], + \ ['four.txt', 'autocmd'], + \ ['three.txt', ''], + \ ], g:blist) + + augroup aucmd_win_test1 + au! + augroup END + augroup! aucmd_win_test1 + %bw! +endfunc + +" Test for trying to close the temporary window used for executing an autocmd +func Test_close_autocmd_window() + %bw! + edit one.txt + tabnew two.txt + augroup aucmd_win_test2 + au! + " Nvim makes aucmd_win the last window + " au BufEnter * if expand('<afile>') == 'one.txt' | 1close | endif + au BufEnter * if expand('<afile>') == 'one.txt' | close | endif + augroup END + + call assert_fails('doautoall BufEnter', 'E813:') + + augroup aucmd_win_test2 + au! + augroup END + augroup! aucmd_win_test2 + %bw! +endfunc + +" Test for trying to close the tab that has the temporary window for exeucing +" an autocmd. +func Test_close_autocmd_tab() + edit one.txt + tabnew two.txt + augroup aucmd_win_test + au! + au BufEnter * if expand('<afile>') == 'one.txt' | tabfirst | tabonly | endif + augroup END + + call assert_fails('doautoall BufEnter', 'E813:') + + tabonly + augroup aucmd_win_test + au! + augroup END + augroup! aucmd_win_test + %bwipe! +endfunc + +func Test_Visual_doautoall_redraw() + call setline(1, ['a', 'b']) + new + wincmd p + call feedkeys("G\<C-V>", 'txn') + autocmd User Explode ++once redraw + doautoall User Explode + %bwipe! +endfunc + +" This was using freed memory. +func Test_BufNew_arglocal() + arglocal + au BufNew * arglocal + call assert_fails('drop xx', 'E1156:') + + au! BufNew +endfunc + +func Test_autocmd_closes_window() + au BufNew,BufWinLeave * e %e + file yyy + au BufNew,BufWinLeave * ball + n xxx + + %bwipe + au! BufNew + au! BufWinLeave +endfunc + +func Test_autocmd_quit_psearch() + sn aa bb + augroup aucmd_win_test + au! + au BufEnter,BufLeave,BufNew,WinEnter,WinLeave,WinNew * if winnr('$') > 1 | q | endif + augroup END + ps / + + augroup aucmd_win_test + au! + augroup END + new + pclose +endfunc + +" Fuzzer found some strange combination that caused a crash. +func Test_autocmd_normal_mess() + " For unknown reason this hangs on MS-Windows + CheckNotMSWindows + + augroup aucmd_normal_test + au BufLeave,BufWinLeave,BufHidden,BufUnload,BufDelete,BufWipeout * norm 7q/qc + augroup END + " Nvim has removed :open + " call assert_fails('o4', 'E1159') + call assert_fails('e4', 'E1159') + silent! H + call assert_fails('e xx', 'E1159') + normal G + + augroup aucmd_normal_test + au! + augroup END +endfunc + +func Test_autocmd_closing_cmdwin() + " For unknown reason this hangs on MS-Windows + CheckNotMSWindows + + au BufWinLeave * nested q + call assert_fails("norm 7q?\n", 'E855:') + + au! BufWinLeave + new + only +endfunc + +func Test_autocmd_vimgrep() + augroup aucmd_vimgrep + au QuickfixCmdPre,BufNew,BufReadCmd * sb + " Nvim makes aucmd_win the last window + " au QuickfixCmdPre,BufNew,BufReadCmd * q9 + au QuickfixCmdPre,BufNew,BufReadCmd * exe 'q' .. (winnr('$') - (win_gettype(winnr('$')) == 'autocmd')) + augroup END + call assert_fails('lv ?a? foo', 'E926:') + + augroup aucmd_vimgrep + au! + augroup END +endfunc + +" Test TextChangedI and TextChanged +func Test_Changed_ChangedI() + throw 'Skipped: use test/functional/autocmd/textchanged_spec.lua' + new + call test_override("char_avail", 1) + let [g:autocmd_i, g:autocmd_n] = ['',''] + + func! TextChangedAutocmdI(char) + let g:autocmd_{tolower(a:char)} = a:char .. b:changedtick + endfunc + + augroup Test_TextChanged + au! + au TextChanged <buffer> :call TextChangedAutocmdI('N') + au TextChangedI <buffer> :call TextChangedAutocmdI('I') + augroup END + + call feedkeys("ifoo\<esc>", 'tnix') + " TODO: Test test does not seem to trigger TextChanged autocommand, this + " requires running Vim in a terminal window. + " call assert_equal('N3', g:autocmd_n) + call assert_equal('I3', g:autocmd_i) + + call feedkeys("yyp", 'tnix') + " TODO: Test test does not seem to trigger TextChanged autocommand. + " call assert_equal('N4', g:autocmd_n) + call assert_equal('I3', g:autocmd_i) + + " TextChangedI should only trigger if change was done in Insert mode + let g:autocmd_i = '' + call feedkeys("yypi\<esc>", 'tnix') + call assert_equal('', g:autocmd_i) + + " TextChanged should only trigger if change was done in Normal mode + let g:autocmd_n = '' + call feedkeys("ibar\<esc>", 'tnix') + call assert_equal('', g:autocmd_n) + + " If change is a mix of Normal and Insert modes, TextChangedI should trigger + func s:validate_mixed_textchangedi(keys) + call feedkeys("ifoo\<esc>", 'tnix') + let g:autocmd_i = '' + let g:autocmd_n = '' + call feedkeys(a:keys, 'tnix') + call assert_notequal('', g:autocmd_i) + call assert_equal('', g:autocmd_n) + endfunc + + call s:validate_mixed_textchangedi("o\<esc>") + call s:validate_mixed_textchangedi("O\<esc>") + call s:validate_mixed_textchangedi("ciw\<esc>") + call s:validate_mixed_textchangedi("cc\<esc>") + call s:validate_mixed_textchangedi("C\<esc>") + call s:validate_mixed_textchangedi("s\<esc>") + call s:validate_mixed_textchangedi("S\<esc>") + + + " CleanUp + call test_override("char_avail", 0) + au! TextChanged <buffer> + au! TextChangedI <buffer> + augroup! Test_TextChanged + delfu TextChangedAutocmdI + unlet! g:autocmd_i g:autocmd_n + + bw! +endfunc + +func Test_closing_autocmd_window() + let lines =<< trim END + edit Xa.txt + tabnew Xb.txt + autocmd BufEnter Xa.txt unhide 1 + doautoall BufEnter + END + call CheckScriptFailure(lines, 'E814:') + au! BufEnter + bwipe Xa.txt + bwipe Xb.txt +endfunc + +func Test_switch_window_in_autocmd_window() + edit Xa.txt + tabnew Xb.txt + autocmd BufEnter Xa.txt wincmd w + doautoall BufEnter + au! BufEnter + bwipe Xa.txt + call assert_false(bufexists('Xa.txt')) + bwipe Xb.txt + call assert_false(bufexists('Xb.txt')) +endfunc + +func Test_bufwipeout_changes_window() + " This should not crash, but we don't have any expectations about what + " happens, changing window in BufWipeout has unpredictable results. + tabedit + let g:window_id = win_getid() + topleft new + setlocal bufhidden=wipe + autocmd BufWipeout <buffer> call win_gotoid(g:window_id) + tabprevious + +tabclose + + unlet g:window_id + au! BufWipeout + %bwipe! +endfunc + +func Test_v_event_readonly() + autocmd CompleteChanged * let v:event.width = 0 + call assert_fails("normal! i\<C-X>\<C-V>", 'E46:') + au! CompleteChanged + + autocmd DirChangedPre * let v:event.directory = '' + call assert_fails('cd .', 'E46:') + au! DirChangedPre + + autocmd ModeChanged * let v:event.new_mode = '' + call assert_fails('normal! cc', 'E46:') + au! ModeChanged + + autocmd TextYankPost * let v:event.operator = '' + call assert_fails('normal! yy', 'E46:') + au! TextYankPost +endfunc + +" Test for ModeChanged pattern +func Test_mode_changes() + let g:index = 0 + let g:mode_seq = ['n', 'i', 'n', 'v', 'V', 'i', 'ix', 'i', 'ic', 'i', 'n', 'no', 'noV', 'n', 'V', 'v', 's', 'n'] + func! TestMode() + call assert_equal(g:mode_seq[g:index], get(v:event, "old_mode")) + call assert_equal(g:mode_seq[g:index + 1], get(v:event, "new_mode")) + call assert_equal(mode(1), get(v:event, "new_mode")) + let g:index += 1 + endfunc + + au ModeChanged * :call TestMode() + let g:n_to_any = 0 + au ModeChanged n:* let g:n_to_any += 1 + call feedkeys("i\<esc>vVca\<CR>\<C-X>\<C-L>\<esc>ggdV\<MouseMove>G", 'tnix') + + let g:V_to_v = 0 + au ModeChanged V:v let g:V_to_v += 1 + call feedkeys("Vv\<C-G>\<esc>", 'tnix') + call assert_equal(len(filter(g:mode_seq[1:], {idx, val -> val == 'n'})), g:n_to_any) + call assert_equal(1, g:V_to_v) + call assert_equal(len(g:mode_seq) - 1, g:index) + + let g:n_to_i = 0 + au ModeChanged n:i let g:n_to_i += 1 + let g:n_to_niI = 0 + au ModeChanged i:niI let g:n_to_niI += 1 + let g:niI_to_i = 0 + au ModeChanged niI:i let g:niI_to_i += 1 + let g:nany_to_i = 0 + au ModeChanged n*:i let g:nany_to_i += 1 + let g:i_to_n = 0 + au ModeChanged i:n let g:i_to_n += 1 + let g:nori_to_any = 0 + au ModeChanged [ni]:* let g:nori_to_any += 1 + let g:i_to_any = 0 + au ModeChanged i:* let g:i_to_any += 1 + let g:index = 0 + let g:mode_seq = ['n', 'i', 'niI', 'i', 'n'] + call feedkeys("a\<C-O>l\<esc>", 'tnix') + call assert_equal(len(g:mode_seq) - 1, g:index) + call assert_equal(1, g:n_to_i) + call assert_equal(1, g:n_to_niI) + call assert_equal(1, g:niI_to_i) + call assert_equal(2, g:nany_to_i) + call assert_equal(1, g:i_to_n) + call assert_equal(2, g:i_to_any) + call assert_equal(3, g:nori_to_any) + + if has('terminal') + let g:mode_seq += ['c', 'n', 't', 'nt', 'c', 'nt', 'n'] + call feedkeys(":term\<CR>\<C-W>N:bd!\<CR>", 'tnix') + call assert_equal(len(g:mode_seq) - 1, g:index) + call assert_equal(1, g:n_to_i) + call assert_equal(1, g:n_to_niI) + call assert_equal(1, g:niI_to_i) + call assert_equal(2, g:nany_to_i) + call assert_equal(1, g:i_to_n) + call assert_equal(2, g:i_to_any) + call assert_equal(5, g:nori_to_any) + endif + + let g:n_to_c = 0 + au ModeChanged n:c let g:n_to_c += 1 + let g:c_to_n = 0 + au ModeChanged c:n let g:c_to_n += 1 + let g:mode_seq += ['c', 'n', 'c', 'n'] + call feedkeys("q:\<C-C>\<Esc>", 'tnix') + call assert_equal(len(g:mode_seq) - 1, g:index) + call assert_equal(2, g:n_to_c) + call assert_equal(2, g:c_to_n) + + let g:n_to_v = 0 + au ModeChanged n:v let g:n_to_v += 1 + let g:v_to_n = 0 + au ModeChanged v:n let g:v_to_n += 1 + let g:mode_seq += ['v', 'n'] + call feedkeys("v\<C-C>", 'tnix') + call assert_equal(len(g:mode_seq) - 1, g:index) + call assert_equal(1, g:n_to_v) + call assert_equal(1, g:v_to_n) + + let g:mode_seq += ['c', 'cr', 'c', 'cr', 'n'] + call feedkeys(":\<Insert>\<Insert>\<Insert>\<CR>", 'tnix') + call assert_equal(len(g:mode_seq) - 1, g:index) + + au! ModeChanged + delfunc TestMode + unlet! g:mode_seq + unlet! g:index + unlet! g:n_to_any + unlet! g:V_to_v + unlet! g:n_to_i + unlet! g:n_to_niI + unlet! g:niI_to_i + unlet! g:nany_to_i + unlet! g:i_to_n + unlet! g:nori_to_any + unlet! g:i_to_any + unlet! g:n_to_c + unlet! g:c_to_n + unlet! g:n_to_v + unlet! g:v_to_n +endfunc + +func Test_recursive_ModeChanged() + au! ModeChanged * norm 0u + sil! norm + au! ModeChanged +endfunc + +func Test_ModeChanged_starts_visual() + " This was triggering ModeChanged before setting VIsual, causing a crash. + au! ModeChanged * norm 0u + sil! norm + + au! ModeChanged +endfunc + +func Test_noname_autocmd() + augroup test_noname_autocmd_group + autocmd! + autocmd BufEnter * call add(s:li, ["BufEnter", expand("<afile>")]) + autocmd BufDelete * call add(s:li, ["BufDelete", expand("<afile>")]) + autocmd BufLeave * call add(s:li, ["BufLeave", expand("<afile>")]) + autocmd BufUnload * call add(s:li, ["BufUnload", expand("<afile>")]) + autocmd BufWipeout * call add(s:li, ["BufWipeout", expand("<afile>")]) + augroup END + + let s:li = [] + edit foo + call assert_equal([['BufUnload', ''], ['BufDelete', ''], ['BufWipeout', ''], ['BufEnter', 'foo']], s:li) + + au! test_noname_autocmd_group + augroup! test_noname_autocmd_group +endfunc + +func Test_autocmd_split_dummy() + " Autocommand trying to split a window containing a dummy buffer. + auto BufReadPre * exe "sbuf " .. expand("<abuf>") + " Avoid the "W11" prompt + au FileChangedShell * let v:fcs_choice = 'reload' + func Xautocmd_changelist() + cal writefile(['Xtestfile2:4:4'], 'Xerr') + edit Xerr + lex 'Xtestfile2:4:4' + endfunc + call Xautocmd_changelist() + " Should get E86, but it doesn't always happen (timing?) + silent! call Xautocmd_changelist() + + au! BufReadPre + au! FileChangedShell + delfunc Xautocmd_changelist + bwipe! Xerr + call delete('Xerr') +endfunc + +" This was crashing because there was only one window to execute autocommands +" in. +func Test_autocmd_nested_setbufvar() + CheckFeature python3 + + set hidden + edit Xaaa + edit Xbbb + call setline(1, 'bar') + enew + au BufWriteCmd Xbbb ++nested call setbufvar('Xaaa', '&ft', 'foo') | bw! Xaaa + au FileType foo call py3eval('vim.current.buffer.options["cindent"]') + wall + + au! BufWriteCmd + au! FileType foo + set nohidden + call delete('Xaaa') + call delete('Xbbb') + %bwipe! +endfunc + +func SetupVimTest_shm() + let g:bwe = [] + let g:brp = [] + set shortmess-=l + messages clear + + let dirname='XVimTestSHM' + call mkdir(dirname, 'R') + call writefile(['test'], dirname .. '/1') + call writefile(['test'], dirname .. '/2') + call writefile(['test'], dirname .. '/3') + + augroup test + autocmd! + autocmd BufWinEnter * call add(g:bwe, $'BufWinEnter: {expand('<amatch>')}') + autocmd BufReadPost * call add(g:brp, $'BufReadPost: {expand('<amatch>')}') + augroup END + + call setqflist([ + \ {'filename': dirname .. '/1', 'lnum': 1, 'col': 1, 'text': 'test', 'vcol': 0}, + \ {'filename': dirname .. '/2', 'lnum': 1, 'col': 1, 'text': 'test', 'vcol': 0}, + \ {'filename': dirname .. '/3', 'lnum': 1, 'col': 1, 'text': 'test', 'vcol': 0} + \ ]) + cdo! substitute/test/TEST + + " clean up + noa enew! + set shortmess&vim + augroup test + autocmd! + augroup END + augroup! test +endfunc + +func Test_autocmd_shortmess() + CheckNotMSWindows + + call SetupVimTest_shm() + let output = execute(':mess')->split('\n') + + let info = copy(output)->filter({idx, val -> val =~# '\d of 3'} ) + let bytes = copy(output)->filter({idx, val -> val =~# 'bytes'} ) + + " We test the following here: + " BufReadPost should have been triggered 3 times, once per file + " BufWinEnter should have been triggered 3 times, once per file + " FileInfoMessage should have been shown 3 times, regardless of shm option + " "(x of 3)" message from :cnext has been shown 3 times + + call assert_equal(3, g:brp->len()) + call assert_equal(3, g:bwe->len()) + call assert_equal(3, info->len()) + call assert_equal(3, bytes->len()) + + delfunc SetupVimTest_shm +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_autoload.vim b/test/old/testdir/test_autoload.vim new file mode 100644 index 0000000000..e89fe3943b --- /dev/null +++ b/test/old/testdir/test_autoload.vim @@ -0,0 +1,25 @@ +" 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 diff --git a/test/old/testdir/test_backspace_opt.vim b/test/old/testdir/test_backspace_opt.vim new file mode 100644 index 0000000000..78c51cb874 --- /dev/null +++ b/test/old/testdir/test_backspace_opt.vim @@ -0,0 +1,141 @@ +" 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 diff --git a/test/old/testdir/test_backup.vim b/test/old/testdir/test_backup.vim new file mode 100644 index 0000000000..862ec2e4a1 --- /dev/null +++ b/test/old/testdir/test_backup.vim @@ -0,0 +1,89 @@ +" 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'], 'Xbackupdir', 'D') + new Xbackupdir + call assert_fails('write', 'E510:') + + set backupdir&vim backupskip&vim +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_blob.vim b/test/old/testdir/test_blob.vim new file mode 100644 index 0000000000..25b3c00dfc --- /dev/null +++ b/test/old/testdir/test_blob.vim @@ -0,0 +1,867 @@ +" 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)) + call assert_equal(0z, copy(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:']) + + call assert_fails('let b = readblob("a1b2c3")', 'E484:') +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) + call assert_true(0z != 0z10) + call assert_true(0z10 != 0z) + 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 + LET b[0] = 0x33 + call assert_equal(0z331122, 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:') + + let lines =<< trim END + VAR b = 0z00010203 + LET b[0 : -1] = 0z33 + END + call CheckLegacyAndVim9Failure(lines, 'E979:') + + let lines =<< trim END + VAR b = 0z00010203 + LET b[3 : 4] = 0z3344 + 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:') + + let lines =<< trim END + let b = 0zDEADBEEF + lockvar b + call add(b, 0) + unlockvar b + END + call CheckScriptFailure(lines, 'E741:') +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, -10) + 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:') + + call assert_fails('echo remove(0z1020, [])', 'E745:') + call assert_fails('echo remove(0z1020, 0, [])', 'E745:') +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) + call assert_fails('echo filter(0z10, "a10")', 'E121:') +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:') + call assert_fails('echo map(0z10, "a10")', 'E121:') +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 diff --git a/test/old/testdir/test_blockedit.vim b/test/old/testdir/test_blockedit.vim new file mode 100644 index 0000000000..e0cfe11af0 --- /dev/null +++ b/test/old/testdir/test_blockedit.vim @@ -0,0 +1,135 @@ +" 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 + vim9script + 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! 3Gf)\<c-v>2jA: asdf\<esc>" + let expected =<< trim END + vim9script + var d = { + a: (): asdf => 0, + b: (): asdf => 0, + c: (): asdf => 0, + } + END + call assert_equal(expected, getline(1, 6)) + + " insert on the next column should do exactly the same + :%dele + call setline(1, lines) + exe "norm! 3Gf)l\<c-v>2jI: asdf\<esc>" + call assert_equal(expected, getline(1, 6)) + + :%dele + call setline(1, lines) + setlocal sw=8 noet + exe "norm! 3Gf)\<c-v>2jA: asdf\<esc>" + let expected =<< trim END + vim9script + var d = { + a: (): asdf => 0, + b: (): asdf => 0, + c: (): asdf => 0, + } + END + call assert_equal(expected, getline(1, 6)) + + " insert on the next column should do exactly the same + :%dele + call setline(1, lines) + exe "norm! 3Gf)l\<c-v>2jI: asdf\<esc>" + call assert_equal(expected, getline(1, 6)) + + 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 diff --git a/test/old/testdir/test_breakindent.vim b/test/old/testdir/test_breakindent.vim new file mode 100644 index 0000000000..301e2d0e40 --- /dev/null +++ b/test/old/testdir/test_breakindent.vim @@ -0,0 +1,1107 @@ +" Test for breakindent +" +" Note: if you get strange failures when adding new tests, it might be that +" while the test is run, the breakindent caching gets in its way. +" It helps to change the tabstop setting and force a redraw (e.g. see +" Test_breakindent08()) +source check.vim +CheckOption breakindent + +source view_util.vim +source screendump.vim + +func SetUp() + let s:input ="\tabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP" +endfunc + +func s:screen_lines(lnum, width) abort + return ScreenLines([a:lnum, a:lnum + 2], a:width) +endfunc + +func s:screen_lines2(lnums, lnume, width) abort + return ScreenLines([a:lnums, a:lnume], a:width) +endfunc + +func s:compare_lines(expect, actual) + call assert_equal(join(a:expect, "\n"), join(a:actual, "\n")) +endfunc + +func s:test_windows(...) + call NewWindow(10, 20) + setl ts=4 sw=4 sts=4 breakindent + put =s:input + exe get(a:000, 0, '') +endfunc + +func s:close_windows(...) + call CloseWindow() + exe get(a:000, 0, '') +endfunc + +func Test_breakindent01() + " simple breakindent test + call s:test_windows('setl briopt=min:0') + let lines = s:screen_lines(line('.'),8) + let expect = [ + \ " abcd", + \ " qrst", + \ " GHIJ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_breakindent01_vartabs() + " like 01 but with vartabs feature + if !has("vartabs") + return + endif + call s:test_windows('setl briopt=min:0 vts=4') + let lines = s:screen_lines(line('.'),8) + let expect = [ + \ " abcd", + \ " qrst", + \ " GHIJ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set vts&') +endfunc + +func Test_breakindent02() + " simple breakindent test with showbreak set + set sbr=>> + call s:test_windows('setl briopt=min:0 sbr=') + let lines = s:screen_lines(line('.'),8) + let expect = [ + \ " abcd", + \ " >>qr", + \ " >>EF", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr=') +endfunc + +func Test_breakindent02_vartabs() + if !has("vartabs") + return + endif + " simple breakindent test with showbreak set + call s:test_windows('setl briopt=min:0 sbr=>> vts=4') + let lines = s:screen_lines(line('.'), 8) + let expect = [ + \ " abcd", + \ " >>qr", + \ " >>EF", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr= vts&') +endfunc + +func Test_breakindent03() + " simple breakindent test with showbreak set and briopt including sbr + call s:test_windows('setl briopt=sbr,min:0 sbr=++') + let lines = s:screen_lines(line('.'), 8) + let expect=[ +\ " abcd", +\ "++ qrst", +\ "++ GHIJ", +\ ] + call s:compare_lines(expect, lines) + " clean up + call s:close_windows('set sbr=') +endfunc + +func Test_breakindent03_vartabs() + " simple breakindent test with showbreak set and briopt including sbr + if !has("vartabs") + return + endif + call s:test_windows('setl briopt=sbr,min:0 sbr=++ vts=4') + let lines = s:screen_lines(line('.'), 8) + let expect = [ + \ " abcd", + \ "++ qrst", + \ "++ GHIJ", + \ ] + call s:compare_lines(expect, lines) + " clean up + call s:close_windows('set sbr= vts&') +endfunc + +func Test_breakindent04() + " breakindent set with min width 18 + set sbr=<<< + call s:test_windows('setl sbr=NONE briopt=min:18') + let lines = s:screen_lines(line('.'), 8) + let expect = [ + \ " abcd", + \ " qrstuv", + \ " IJKLMN", + \ ] + call s:compare_lines(expect, lines) + " clean up + call s:close_windows('set sbr=') + set sbr= +endfunc + +func Test_breakindent04_vartabs() + " breakindent set with min width 18 + if !has("vartabs") + return + endif + call s:test_windows('setl sbr= briopt=min:18 vts=4') + let lines = s:screen_lines(line('.'), 8) + let expect = [ + \ " abcd", + \ " qrstuv", + \ " IJKLMN", + \ ] + call s:compare_lines(expect, lines) + " clean up + call s:close_windows('set sbr= vts&') +endfunc + +func Test_breakindent05() + " breakindent set and shift by 2 + call s:test_windows('setl briopt=shift:2,min:0') + let lines = s:screen_lines(line('.'),8) + let expect = [ + \ " abcd", + \ " qr", + \ " EF", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_breakindent05_vartabs() + " breakindent set and shift by 2 + if !has("vartabs") + return + endif + call s:test_windows('setl briopt=shift:2,min:0 vts=4') + let lines = s:screen_lines(line('.'),8) + let expect = [ + \ " abcd", + \ " qr", + \ " EF", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set vts&') +endfunc + +func Test_breakindent06() + " breakindent set and shift by -1 + call s:test_windows('setl briopt=shift:-1,min:0') + let lines = s:screen_lines(line('.'),8) + let expect = [ + \ " abcd", + \ " qrstu", + \ " HIJKL", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_breakindent06_vartabs() + " breakindent set and shift by -1 + if !has("vartabs") + return + endif + call s:test_windows('setl briopt=shift:-1,min:0 vts=4') + let lines = s:screen_lines(line('.'),8) + let expect = [ + \ " abcd", + \ " qrstu", + \ " HIJKL", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set vts&') +endfunc + +func Test_breakindent07() + " breakindent set and shift by 1, Number set sbr=? and briopt:sbr + call s:test_windows('setl briopt=shift:1,sbr,min:0 nu sbr=? nuw=4 cpo+=n') + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ab", + \ "? m", + \ "? x", + \ ] + call s:compare_lines(expect, lines) + " clean up + call s:close_windows('set sbr= cpo-=n') +endfunc + +func Test_breakindent07_vartabs() + if !has("vartabs") + return + endif + " breakindent set and shift by 1, Number set sbr=? and briopt:sbr + call s:test_windows('setl briopt=shift:1,sbr,min:0 nu sbr=? nuw=4 cpo+=n vts=4') + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ab", + \ "? m", + \ "? x", + \ ] + call s:compare_lines(expect, lines) + " clean up + call s:close_windows('set sbr= cpo-=n vts&') +endfunc + +func Test_breakindent07a() + " breakindent set and shift by 1, Number set sbr=? and briopt:sbr + call s:test_windows('setl briopt=shift:1,sbr,min:0 nu sbr=? nuw=4') + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ab", + \ " ? m", + \ " ? x", + \ ] + call s:compare_lines(expect, lines) + " clean up + call s:close_windows('set sbr=') +endfunc + +func Test_breakindent07a_vartabs() + if !has("vartabs") + return + endif + " breakindent set and shift by 1, Number set sbr=? and briopt:sbr + call s:test_windows('setl briopt=shift:1,sbr,min:0 nu sbr=? nuw=4 vts=4') + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ab", + \ " ? m", + \ " ? x", + \ ] + call s:compare_lines(expect, lines) + " clean up + call s:close_windows('set sbr= vts&') +endfunc + +func Test_breakindent08() + " breakindent set and shift by 1, Number and list set sbr=# and briopt:sbr + call s:test_windows('setl briopt=shift:1,sbr,min:0 nu nuw=4 sbr=# list cpo+=n ts=4') + " make sure, cache is invalidated! + set ts=8 + redraw! + set ts=4 + redraw! + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ^Iabcd", + \ "# opq", + \ "# BCD", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr= cpo-=n') +endfunc + +func Test_breakindent08_vartabs() + if !has("vartabs") + return + endif + " breakindent set and shift by 1, Number and list set sbr=# and briopt:sbr + call s:test_windows('setl briopt=shift:1,sbr,min:0 nu nuw=4 sbr=# list cpo+=n ts=4 vts=4') + " make sure, cache is invalidated! + set ts=8 + redraw! + set ts=4 + redraw! + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ^Iabcd", + \ "# opq", + \ "# BCD", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr= cpo-=n vts&') +endfunc + +func Test_breakindent08a() + " breakindent set and shift by 1, Number and list set sbr=# and briopt:sbr + call s:test_windows('setl briopt=shift:1,sbr,min:0 nu nuw=4 sbr=# list') + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ^Iabcd", + \ " # opq", + \ " # BCD", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr=') +endfunc + +func Test_breakindent08a_vartabs() + if !has("vartabs") + return + endif + " breakindent set and shift by 1, Number and list set sbr=# and briopt:sbr + call s:test_windows('setl briopt=shift:1,sbr,min:0 nu nuw=4 sbr=# list vts=4') + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ^Iabcd", + \ " # opq", + \ " # BCD", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr= vts&') +endfunc + +func Test_breakindent09() + " breakindent set and shift by 1, Number and list set sbr=# + call s:test_windows('setl briopt=shift:1,min:0 nu nuw=4 sbr=# list') + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ^Iabcd", + \ " #op", + \ " #AB", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr=') +endfunc + +func Test_breakindent09_vartabs() + if !has("vartabs") + return + endif + " breakindent set and shift by 1, Number and list set sbr=# + call s:test_windows('setl briopt=shift:1,min:0 nu nuw=4 sbr=# list vts=4') + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ^Iabcd", + \ " #op", + \ " #AB", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr= vts&') +endfunc + +func Test_breakindent10() + " breakindent set, Number set sbr=~ + call s:test_windows('setl cpo+=n sbr=~ nu nuw=4 nolist briopt=sbr,min:0') + " make sure, cache is invalidated! + set ts=8 + redraw! + set ts=4 + redraw! + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ab", + \ "~ mn", + \ "~ yz", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr= cpo-=n') +endfunc + +func Test_breakindent10_vartabs() + if !has("vartabs") + return + endif + " breakindent set, Number set sbr=~ + call s:test_windows('setl cpo+=n sbr=~ nu nuw=4 nolist briopt=sbr,min:0 vts=4') + " make sure, cache is invalidated! + set ts=8 + redraw! + set ts=4 + redraw! + let lines = s:screen_lines(line('.'),10) + let expect = [ + \ " 2 ab", + \ "~ mn", + \ "~ yz", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set sbr= cpo-=n vts&') +endfunc + +func Test_breakindent11() + " test strdisplaywidth() + call s:test_windows('setl cpo-=n sbr=>> nu nuw=4 nolist briopt= ts=4') + let text = getline(2) + let width = strlen(text[1:]) + indent(2) + strlen(&sbr) * 3 " text wraps 3 times + call assert_equal(width, strdisplaywidth(text)) + call s:close_windows('set sbr=') + call assert_equal(4, strdisplaywidth("\t", 4)) +endfunc + +func Test_breakindent11_vartabs() + if !has("vartabs") + return + endif + " test strdisplaywidth() + call s:test_windows('setl cpo-=n sbr=>> nu nuw=4 nolist briopt= ts=4 vts=4') + let text = getline(2) + let width = strlen(text[1:]) + 2->indent() + strlen(&sbr) * 3 " text wraps 3 times + call assert_equal(width, text->strdisplaywidth()) + call s:close_windows('set sbr= vts&') +endfunc + +func Test_breakindent12() + " test breakindent with long indent + let s:input="\t\t\t\t\t{" + call s:test_windows('setl breakindent linebreak briopt=min:10 nu numberwidth=3 ts=4 list listchars=tab:>-') + let lines = s:screen_lines(2,16) + let expect = [ + \ " 2 >--->--->--->", + \ " ---{ ", + \ "~ ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set nuw=4 listchars=') +endfunc + +func Test_breakindent12_vartabs() + if !has("vartabs") + return + endif + " test breakindent with long indent + let s:input = "\t\t\t\t\t{" + call s:test_windows('setl breakindent linebreak briopt=min:10 nu numberwidth=3 ts=4 list listchars=tab:>- vts=4') + let lines = s:screen_lines(2,16) + let expect = [ + \ " 2 >--->--->--->", + \ " ---{ ", + \ "~ ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set nuw=4 listchars= vts&') +endfunc + +func Test_breakindent13() + let s:input = "" + call s:test_windows('setl breakindent briopt=min:10 ts=8') + vert resize 20 + call setline(1, [" a\tb\tc\td\te", " z y x w v"]) + 1 + norm! fbgj"ayl + 2 + norm! fygj"byl + call assert_equal('d', @a) + call assert_equal('w', @b) + call s:close_windows() +endfunc + +func Test_breakindent13_vartabs() + if !has("vartabs") + return + endif + let s:input = "" + call s:test_windows('setl breakindent briopt=min:10 ts=8 vts=8') + vert resize 20 + call setline(1, [" a\tb\tc\td\te", " z y x w v"]) + 1 + norm! fbgj"ayl + 2 + norm! fygj"byl + call assert_equal('d', @a) + call assert_equal('w', @b) + call s:close_windows('set vts&') +endfunc + +func Test_breakindent14() + let s:input = "" + call s:test_windows('setl breakindent briopt= ts=8') + vert resize 30 + norm! 3a1234567890 + norm! a abcde + exec "norm! 0\<C-V>tex" + let lines = s:screen_lines(line('.'),8) + let expect = [ + \ "e ", + \ "~ ", + \ "~ ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_breakindent14_vartabs() + if !has("vartabs") + return + endif + let s:input = "" + call s:test_windows('setl breakindent briopt= ts=8 vts=8') + vert resize 30 + norm! 3a1234567890 + norm! a abcde + exec "norm! 0\<C-V>tex" + let lines = s:screen_lines(line('.'),8) + let expect = [ + \ "e ", + \ "~ ", + \ "~ ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set vts&') +endfunc + +func Test_breakindent15() + let s:input = "" + call s:test_windows('setl breakindent briopt= ts=8 sw=8') + vert resize 30 + norm! 4a1234567890 + exe "normal! >>\<C-V>3f0x" + let lines = s:screen_lines(line('.'),20) + let expect = [ + \ " 1234567890 ", + \ "~ ", + \ "~ ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_breakindent15_vartabs() + if !has("vartabs") + return + endif + let s:input = "" + call s:test_windows('setl breakindent briopt= ts=8 sw=8 vts=8') + vert resize 30 + norm! 4a1234567890 + exe "normal! >>\<C-V>3f0x" + let lines = s:screen_lines(line('.'),20) + let expect = [ + \ " 1234567890 ", + \ "~ ", + \ "~ ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set vts&') +endfunc + +func Test_breakindent16() + " Check that overlong lines are indented correctly. + let s:input = "" + call s:test_windows('setl breakindent briopt=min:0 ts=4') + call setline(1, "\t".repeat("1234567890", 10)) + resize 6 + norm! 1gg$ + redraw! + let lines = s:screen_lines(1,10) + let expect = [ + \ "<<< 789012", + \ " 345678", + \ " 901234", + \ ] + call s:compare_lines(expect, lines) + let lines = s:screen_lines(4,10) + let expect = [ + \ " 567890", + \ " 123456", + \ " 7890 ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_breakindent16_vartabs() + if !has("vartabs") + return + endif + " Check that overlong lines are indented correctly. + let s:input = "" + call s:test_windows('setl breakindent briopt=min:0 ts=4 vts=4') + call setline(1, "\t".repeat("1234567890", 10)) + resize 6 + norm! 1gg$ + redraw! + let lines = s:screen_lines(1,10) + let expect = [ + \ "<<< 789012", + \ " 345678", + \ " 901234", + \ ] + call s:compare_lines(expect, lines) + let lines = s:screen_lines(4,10) + let expect = [ + \ " 567890", + \ " 123456", + \ " 7890 ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set vts&') +endfunc + +func Test_breakindent17_vartabs() + if !has("vartabs") + return + endif + let s:input = "" + call s:test_windows('setl breakindent list listchars=tab:<-> showbreak=+++') + call setline(1, "\t" . repeat('a', 63)) + vert resize 30 + norm! 1gg$ + redraw! + let lines = s:screen_lines(1, 30) + let expect = [ + \ "<-->aaaaaaaaaaaaaaaaaaaaaaaaaa", + \ " +++aaaaaaaaaaaaaaaaaaaaaaa", + \ " +++aaaaaaaaaaaaaa ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set breakindent& list& listchars& showbreak&') +endfunc + +func Test_breakindent18_vartabs() + if !has("vartabs") + return + endif + let s:input = "" + call s:test_windows('setl breakindent list listchars=tab:<->') + call setline(1, "\t" . repeat('a', 63)) + vert resize 30 + norm! 1gg$ + redraw! + let lines = s:screen_lines(1, 30) + let expect = [ + \ "<-->aaaaaaaaaaaaaaaaaaaaaaaaaa", + \ " aaaaaaaaaaaaaaaaaaaaaaaaaa", + \ " aaaaaaaaaaa ", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set breakindent& list& listchars&') +endfunc + +func Test_breakindent19_sbr_nextpage() + let s:input = "" + call s:test_windows('setl breakindent briopt=shift:2,sbr,min:18 sbr=>') + call setline(1, repeat('a', 200)) + norm! 1gg + redraw! + let lines = s:screen_lines(1, 20) + let expect = [ + \ "aaaaaaaaaaaaaaaaaaaa", + \ "> aaaaaaaaaaaaaaaaaa", + \ "> aaaaaaaaaaaaaaaaaa", + \ ] + call s:compare_lines(expect, lines) + " Scroll down one screen line + setl scrolloff=5 + norm! 5gj + let lines = s:screen_lines(1, 20) + let expect = [ + \ "aaaaaaaaaaaaaaaaaaaa", + \ "> aaaaaaaaaaaaaaaaaa", + \ "> aaaaaaaaaaaaaaaaaa", + \ ] + call s:compare_lines(expect, lines) + redraw! + " moving the cursor doesn't change the text offset + norm! l + redraw! + let lines = s:screen_lines(1, 20) + call s:compare_lines(expect, lines) + + setl breakindent briopt=min:18 sbr=> + norm! 5gj + let lines = s:screen_lines(1, 20) + let expect = [ + \ ">aaaaaaaaaaaaaaaaaaa", + \ ">aaaaaaaaaaaaaaaaaaa", + \ ">aaaaaaaaaaaaaaaaaaa", + \ ] + call s:compare_lines(expect, lines) + call s:close_windows('set breakindent& briopt& sbr&') +endfunc + +func Test_breakindent20_cpo_n_nextpage() + let s:input = "" + call s:test_windows('setl breakindent briopt=min:14 cpo+=n number') + call setline(1, repeat('abcdefghijklmnopqrst', 10)) + norm! 1gg + redraw! + let lines = s:screen_lines(1, 20) + let expect = [ + \ " 1 abcdefghijklmnop", + \ " qrstabcdefghijkl", + \ " mnopqrstabcdefgh", + \ ] + call s:compare_lines(expect, lines) + " Scroll down one screen line + setl scrolloff=5 + norm! 6gj + redraw! + let lines = s:screen_lines(1, 20) + let expect = [ + \ "<<< qrstabcdefghijkl", + \ " mnopqrstabcdefgh", + \ " ijklmnopqrstabcd", + \ ] + call s:compare_lines(expect, lines) + + setl briopt+=shift:2 + norm! 1gg + let lines = s:screen_lines(1, 20) + let expect = [ + \ " 1 abcdefghijklmnop", + \ " qrstabcdefghij", + \ " klmnopqrstabcd", + \ ] + call s:compare_lines(expect, lines) + " Scroll down one screen line + norm! 6gj + let lines = s:screen_lines(1, 20) + let expect = [ + \ "<<< qrstabcdefghij", + \ " klmnopqrstabcd", + \ " efghijklmnopqr", + \ ] + call s:compare_lines(expect, lines) + + call s:close_windows('set breakindent& briopt& cpo& number&') +endfunc + +func Test_breakindent20_list() + call s:test_windows('setl breakindent breakindentopt= linebreak') + " default: + call setline(1, [' 1. Congress shall make no law', + \ ' 2.) Congress shall make no law', + \ ' 3.] Congress shall make no law']) + norm! 1gg + redraw! + let lines = s:screen_lines2(1, 6, 20) + let expect = [ + \ " 1. Congress ", + \ "shall make no law ", + \ " 2.) Congress ", + \ "shall make no law ", + \ " 3.] Congress ", + \ "shall make no law ", + \ ] + call s:compare_lines(expect, lines) + " set minimum indent + setl briopt=min:5 + redraw! + let lines = s:screen_lines2(1, 6, 20) + let expect = [ + \ " 1. Congress ", + \ " shall make no law ", + \ " 2.) Congress ", + \ " shall make no law ", + \ " 3.] Congress ", + \ " shall make no law ", + \ ] + call s:compare_lines(expect, lines) + " set additional handing indent + setl briopt+=list:4 + redraw! + let expect = [ + \ " 1. Congress ", + \ " shall make no ", + \ " law ", + \ " 2.) Congress ", + \ " shall make no ", + \ " law ", + \ " 3.] Congress ", + \ " shall make no ", + \ " law ", + \ ] + let lines = s:screen_lines2(1, 9, 20) + call s:compare_lines(expect, lines) + + " reset linebreak option + " Note: it indents by one additional + " space, because of the leading space. + setl linebreak&vim list listchars=eol:$,space:_ + redraw! + let expect = [ + \ "__1.__Congress_shall", + \ " _make_no_law$ ", + \ "__2.)_Congress_shall", + \ " _make_no_law$ ", + \ "__3.]_Congress_shall", + \ " _make_no_law$ ", + \ ] + let lines = s:screen_lines2(1, 6, 20) + call s:compare_lines(expect, lines) + + " check formatlistpat indent + setl briopt=min:5,list:-1 + setl linebreak list&vim listchars&vim + let &l:flp = '^\s*\d\+\.\?[\]:)}\t ]\s*' + redraw! + let expect = [ + \ " 1. Congress ", + \ " shall make no ", + \ " law ", + \ " 2.) Congress ", + \ " shall make no ", + \ " law ", + \ " 3.] Congress ", + \ " shall make no ", + \ " law ", + \ ] + let lines = s:screen_lines2(1, 9, 20) + call s:compare_lines(expect, lines) + " check formatlistpat indent with different list levels + let &l:flp = '^\s*\*\+\s\+' + %delete _ + call setline(1, ['* Congress shall make no law', + \ '*** Congress shall make no law', + \ '**** Congress shall make no law']) + norm! 1gg + redraw! + let expect = [ + \ "* Congress shall ", + \ " make no law ", + \ "*** Congress shall ", + \ " make no law ", + \ "**** Congress shall ", + \ " make no law ", + \ ] + let lines = s:screen_lines2(1, 6, 20) + call s:compare_lines(expect, lines) + + " check formatlistpat indent with different list level + " showbreak and sbr + setl briopt=min:5,sbr,list:-1 + setl showbreak=> + redraw! + let expect = [ + \ "* Congress shall ", + \ "> make no law ", + \ "*** Congress shall ", + \ "> make no law ", + \ "**** Congress shall ", + \ "> make no law ", + \ ] + let lines = s:screen_lines2(1, 6, 20) + call s:compare_lines(expect, lines) + + " check formatlistpat indent with different list level + " showbreak sbr and shift + setl briopt=min:5,sbr,list:-1,shift:2 + setl showbreak=> + redraw! + let expect = [ + \ "* Congress shall ", + \ "> make no law ", + \ "*** Congress shall ", + \ "> make no law ", + \ "**** Congress shall ", + \ "> make no law ", + \ ] + let lines = s:screen_lines2(1, 6, 20) + call s:compare_lines(expect, lines) + + " check breakindent works if breakindentopt=list:-1 + " for a non list content + %delete _ + call setline(1, [' Congress shall make no law', + \ ' Congress shall make no law', + \ ' Congress shall make no law']) + norm! 1gg + setl briopt=min:5,list:-1 + setl showbreak= + redraw! + let expect = [ + \ " Congress shall ", + \ " make no law ", + \ " Congress shall ", + \ " make no law ", + \ " Congress shall ", + \ " make no law ", + \ ] + let lines = s:screen_lines2(1, 6, 20) + call s:compare_lines(expect, lines) + + call s:close_windows('set breakindent& briopt& linebreak& list& listchars& showbreak&') +endfunc + +" The following used to crash Vim. This is fixed by 8.2.3391. +" This is a regression introduced by 8.2.2903. +func Test_window_resize_with_linebreak() + new + 53vnew + setl linebreak + setl showbreak=>> + setl breakindent + setl breakindentopt=shift:4 + call setline(1, "\naaaaaaaaa\n\na\naaaaa\n¯aaaaaaaaaa\naaaaaaaaaaaa\naaa\n\"a:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - aaaaaaaa\"\naaaaaaaa\n\"a") + redraw! + call assert_equal([" >>aa^@\"a: "], ScreenLines(2, 14)) + vertical resize 52 + redraw! + call assert_equal([" >>aaa^@\"a:"], ScreenLines(2, 14)) + set linebreak& showbreak& breakindent& breakindentopt& + %bw! +endfunc + +func Test_cursor_position_with_showbreak() + CheckScreendump + + let lines =<< trim END + vim9script + &signcolumn = 'yes' + &showbreak = '++' + &breakindentopt = 'shift:2' + var leftcol: number = win_getid()->getwininfo()->get(0, {})->get('textoff') + repeat('x', &columns - leftcol - 1)->setline(1) + 'second line'->setline(2) + END + call writefile(lines, 'XscriptShowbreak', 'D') + let buf = RunVimInTerminal('-S XscriptShowbreak', #{rows: 6}) + + call term_sendkeys(buf, "AX") + call VerifyScreenDump(buf, 'Test_cursor_position_with_showbreak_1', {}) + " No line wraps, so changing 'showbreak' should lead to the same screen. + call term_sendkeys(buf, "\<C-\>\<C-O>:setlocal showbreak=+\<CR>") + call VerifyScreenDump(buf, 'Test_cursor_position_with_showbreak_1', {}) + " No line wraps, so setting 'breakindent' should lead to the same screen. + call term_sendkeys(buf, "\<C-\>\<C-O>:setlocal breakindent\<CR>") + call VerifyScreenDump(buf, 'Test_cursor_position_with_showbreak_1', {}) + " The first line now wraps because of "eol" in 'listchars'. + call term_sendkeys(buf, "\<C-\>\<C-O>:setlocal list\<CR>") + call VerifyScreenDump(buf, 'Test_cursor_position_with_showbreak_2', {}) + call term_sendkeys(buf, "\<C-\>\<C-O>:setlocal nobreakindent\<CR>") + call VerifyScreenDump(buf, 'Test_cursor_position_with_showbreak_3', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_no_spurious_match() + let s:input = printf('- y %s y %s', repeat('x', 50), repeat('x', 50)) + call s:test_windows('setl breakindent breakindentopt=list:-1 formatlistpat=^- hls') + let @/ = '\%>3v[y]' + redraw! + call searchcount().total->assert_equal(1) + + " cleanup + set hls&vim + bwipeout! +endfunc + +func Test_no_extra_indent() + call s:test_windows('setl breakindent breakindentopt=list:-1,min:10') + %d + let &l:formatlistpat='^\s*\d\+\.\s\+' + let text = 'word ' + let len = text->strcharlen() + let line1 = text->repeat((winwidth(0) / len) * 2) + let line2 = repeat(' ', 2) .. '1. ' .. line1 + call setline(1, [line2]) + redraw! + " 1) matches formatlist pattern, so indent + let expect = [ + \ " 1. word word word ", + \ " word word word ", + \ " word word ", + \ "~ ", + \ ] + let lines = s:screen_lines2(1, 4, 20) + call s:compare_lines(expect, lines) + " 2) change formatlist pattern + " -> indent adjusted + let &l:formatlistpat='^\s*\d\+\.' + let expect = [ + \ " 1. word word word ", + \ " word word word ", + \ " word word ", + \ "~ ", + \ ] + let lines = s:screen_lines2(1, 4, 20) + " 3) no local formatlist pattern, + " so use global one -> indent + let g_flp = &g:flp + let &g:formatlistpat='^\s*\d\+\.\s\+' + let &l:formatlistpat='' + let expect = [ + \ " 1. word word word ", + \ " word word word ", + \ " word word ", + \ "~ ", + \ ] + let lines = s:screen_lines2(1, 4, 20) + call s:compare_lines(expect, lines) + let &g:flp = g_flp + let &l:formatlistpat='^\s*\d\+\.' + " 4) add something in front, no additional indent + norm! gg0 + exe ":norm! 5iword \<esc>" + redraw! + let expect = [ + \ "word word word word ", + \ "word 1. word word ", + \ "word word word word ", + \ "word word ", + \ "~ ", + \ ] + let lines = s:screen_lines2(1, 5, 20) + call s:compare_lines(expect, lines) + bwipeout! +endfunc + +func Test_breakindent_column() + call s:test_windows('setl breakindent breakindentopt=column:10') + redraw! + " 1) default: does not indent, too wide :( + let expect = [ + \ " ", + \ " abcdefghijklmnop", + \ "qrstuvwxyzABCDEFGHIJ", + \ "KLMNOP " + \ ] + let lines = s:screen_lines2(1, 4, 20) + call s:compare_lines(expect, lines) + " 2) lower min value, so that breakindent works + setl breakindentopt+=min:5 + redraw! + let expect = [ + \ " ", + \ " abcdefghijklmnop", + \ " qrstuvwxyz", + \ " ABCDEFGHIJ", + \ " KLMNOP " + \ ] + let lines = s:screen_lines2(1, 5, 20) + " 3) set shift option -> no influence + setl breakindentopt+=shift:5 + redraw! + let expect = [ + \ " ", + \ " abcdefghijklmnop", + \ " qrstuvwxyz", + \ " ABCDEFGHIJ", + \ " KLMNOP " + \ ] + let lines = s:screen_lines2(1, 5, 20) + call s:compare_lines(expect, lines) + " 4) add showbreak value + setl showbreak=++ + redraw! + let expect = [ + \ " ", + \ " abcdefghijklmnop", + \ " ++qrstuvwx", + \ " ++yzABCDEF", + \ " ++GHIJKLMN", + \ " ++OP " + \ ] + let lines = s:screen_lines2(1, 6, 20) + call s:compare_lines(expect, lines) + bwipeout! +endfunc + +func Test_linebreak_list() + " This was setting wlv.c_extra to NUL while wlv.p_extra is NULL + filetype plugin on + syntax enable + edit! $VIMRUNTIME/doc/index.txt + /v_P + + setlocal list + setlocal listchars=tab:>- + setlocal linebreak + setlocal nowrap + setlocal filetype=help + redraw! + + bwipe! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_buffer.vim b/test/old/testdir/test_buffer.vim new file mode 100644 index 0000000000..b0b9f4f24b --- /dev/null +++ b/test/old/testdir/test_buffer.vim @@ -0,0 +1,515 @@ +" Tests for Vim buffer + +source check.vim + +" Test for the :bunload command with an offset +func Test_bunload_with_offset() + %bwipe! + call writefile(['B1'], 'Xb1', 'D') + call writefile(['B2'], 'Xb2', 'D') + call writefile(['B3'], 'Xb3', 'D') + call writefile(['B4'], 'Xb4', 'D') + + " Load four buffers. Unload the second and third buffers and then + " execute .+3bunload to unload the last buffer. + edit Xb1 + new Xb2 + new Xb3 + new Xb4 + + bunload Xb2 + bunload Xb3 + exe bufwinnr('Xb1') . 'wincmd w' + .+3bunload + call assert_equal(0, getbufinfo('Xb4')[0].loaded) + call assert_equal('Xb1', + \ 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 Xb3 + bunload Xb4 + exe bufwinnr('Xb1') . 'wincmd w' + .+3bunload + call assert_equal(0, getbufinfo('Xb2')[0].loaded) + call assert_equal('Xb1', + \ 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 Xb2 + bunload Xb3 + exe bufwinnr('Xb4') . 'wincmd w' + .-3bunload + call assert_equal(0, getbufinfo('Xb1')[0].loaded) + call assert_equal('Xb4', + \ 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 Xb1 + bunload Xb2 + exe bufwinnr('Xb4') . 'wincmd w' + .-3bunload + call assert_equal(0, getbufinfo('Xb3')[0].loaded) + call assert_equal('Xb4', + \ fnamemodify(getbufinfo({'bufloaded' : 1})[0].name, ':t')) + + %bwipe! + + 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'], 'Xbrowse1', 'D') + call writefile(['bar1', 'bar2', 'bar3', 'bar4'], 'Xbrowse2', 'D') + call writefile(['baz1', 'baz2', 'baz3', 'baz4'], 'Xbrowse3', 'D') + edit Xbrowse1 + let b1 = bufnr() + edit Xbrowse2 + let b2 = bufnr() + edit +/baz4 Xbrowse3 + 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:') + + %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 Xbdelfile1 + 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([], 'XsplitCleanup', 'D') + " first open the file in a buffer + new XsplitCleanup + let bnr = bufnr() + close + " create the swap file + call writefile([], '.XsplitCleanup.swp', 'D') + " Remove the catch-all that runtest.vim adds + au! SwapExists + augroup BufTest + au! + autocmd SwapExists XsplitCleanup let v:swapchoice='q' + augroup END + exe 'sbuf ' . bnr + call assert_equal(1, winnr('$')) + call assert_equal(0, getbufinfo('XsplitCleanup')[0].loaded) + + " test for :sball + sball + call assert_equal(1, winnr('$')) + call assert_equal(0, getbufinfo('XsplitCleanup')[0].loaded) + + %bw! + set shortmess+=F + let v:statusmsg = '' + edit XsplitCleanup + call assert_equal('', v:statusmsg) + call assert_equal(1, winnr('$')) + call assert_equal(0, getbufinfo('XsplitCleanup')[0].loaded) + set shortmess& + + 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 XgotoConf + enew + call setline(1, 'test') + call assert_fails('b XgotoConf', 'E37:') + call feedkeys('c', 'L') + call assert_fails('confirm b XgotoConf', 'E37:') + call assert_equal(1, &modified) + call assert_equal('', @%) + call feedkeys('y', 'L') + call assert_fails('confirm b XgotoConf', ['', 'E37:']) + call assert_equal(1, &modified) + call assert_equal('', @%) + call feedkeys('n', 'L') + confirm b XgotoConf + call assert_equal('XgotoConf', @%) + close! +endfunc + +" Test for splitting buffer with 'switchbuf' +func Test_buffer_switchbuf() + new Xswitchbuf + wincmd w + set switchbuf=useopen + sbuf Xswitchbuf + call assert_equal(1, winnr()) + call assert_equal(2, winnr('$')) + set switchbuf=usetab + tabnew + sbuf Xswitchbuf + 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 Xbwipe %bw! + augroup END + edit Xbwipe + call assert_equal('', @%) + call assert_equal(0, bufexists('Xbwipe')) + 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 Xlockfile1 + edit Xlockfile2 + 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), 'Xaltfile1', 'D') + call writefile(repeat(['five six'], 50), 'Xaltfile2', 'D') + set nosol + edit Xaltfile1 + call cursor(25, 5) + edit Xaltfile2 + 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 Xaltfile1 + call assert_equal([0, 25, 5, 0], getpos('.')) + buf Xaltfile2 + call assert_equal([0, 30, 4, 0], getpos('.')) + set sol& +endfunc + +" Test for running the :sball command with a maximum window count and a +" modified buffer +func Test_sball_with_count() + %bw! + edit Xcountfile1 + call setline(1, ['abc']) + new Xcountfile2 + new Xcountfile3 + new Xcountfile4 + 2sball + call assert_equal(bufnr('Xcountfile4'), winbufnr(1)) + call assert_equal(bufnr('Xcountfile1'), winbufnr(2)) + call assert_equal(0, getbufinfo('Xcountfile2')[0].loaded) + call assert_equal(0, getbufinfo('Xcountfile3')[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 noswapfile + 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& + set swapfile& +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 XallocFail1 + call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0) + call assert_fails('edit XallocFail2', '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 XallocFail2 + call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0) + call assert_fails('next XallocFail3', '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 XallocFail4 + call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0) + call assert_fails('%bw!', 'E342:') + + " test for :checktime loading the buffer + call writefile(['one'], 'XallocFail5', 'D') + if has('unix') + edit XallocFail5 + " sleep for some time to make sure the timestamp is different + sleep 200m + call writefile(['two'], 'XallocFail5') + 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 XallocFail5', 'E342:') + + " test for quickfix command loading a buffer + call test_alloc_fail(GetAllocId('newbuf_bvars'), 0, 0) + call assert_fails('cexpr "XallocFail6:10:Line10"', 'E342:') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_bufline.vim b/test/old/testdir/test_bufline.vim new file mode 100644 index 0000000000..29ec46a606 --- /dev/null +++ b/test/old/testdir/test_bufline.vim @@ -0,0 +1,299 @@ +" 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(0, setbufline(b, 5, [])) + call assert_equal(0, 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', 'D') + call system(cmd) + sleep 50m + call assert_equal(['Hello'], readfile('Xtest')) + + call assert_equal(0, setline(1, [])) + call assert_equal(0, setline(1, v:_null_list)) + call assert_equal(0, setline(5, [])) + call assert_equal(0, setline(6, v:_null_list)) + + 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(0, appendbufline(b, 4, [])) + call assert_equal(0, 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(0, appendbufline(b, 3, [])) + call assert_equal(0, 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', 'D') + let buf = RunVimInTerminal('-S XscriptMatchCommon', #{rows: 10}) + call VerifyScreenDump(buf, 'Test_appendbufline_1', {}) + + call StopVimInTerminal(buf) +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 diff --git a/test/old/testdir/test_bufwintabinfo.vim b/test/old/testdir/test_bufwintabinfo.vim new file mode 100644 index 0000000000..57492e07c9 --- /dev/null +++ b/test/old/testdir/test_bufwintabinfo.vim @@ -0,0 +1,191 @@ +" Tests for the getbufinfo(), getwininfo() and gettabinfo() functions +source check.vim + +func Test_getbufwintabinfo() + CheckFeature quickfix + + 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 + call assert_notequal([], getbufinfo(v:_null_dict)) + + 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 +endfunc + +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 diff --git a/test/old/testdir/test_cd.vim b/test/old/testdir/test_cd.vim new file mode 100644 index 0000000000..cffba99451 --- /dev/null +++ b/test/old/testdir/test_cd.vim @@ -0,0 +1,257 @@ +" 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) + call assert_equal('', chdir([])) + + 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 diff --git a/test/old/testdir/test_cdo.vim b/test/old/testdir/test_cdo.vim new file mode 100644 index 0000000000..dbed7df4ac --- /dev/null +++ b/test/old/testdir/test_cdo.vim @@ -0,0 +1,216 @@ +" 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 diff --git a/test/old/testdir/test_changedtick.vim b/test/old/testdir/test_changedtick.vim new file mode 100644 index 0000000000..c789cdc1bc --- /dev/null +++ b/test/old/testdir/test_changedtick.vim @@ -0,0 +1,95 @@ +" 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 diff --git a/test/old/testdir/test_changelist.vim b/test/old/testdir/test_changelist.vim new file mode 100644 index 0000000000..0d435590a9 --- /dev/null +++ b/test/old/testdir/test_changelist.vim @@ -0,0 +1,107 @@ +" 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 Xgclfile1.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 Xgclfile2.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('Xgclfile1.txt') + call delete('Xgclfile2.txt') +endfunc + +func Test_getchangelist() + bwipe! + enew + call assert_equal([], 10->getchangelist()) + call assert_equal([[], 0], getchangelist()) + + call writefile(['line1', 'line2', 'line3'], 'Xclistfile1.txt') + call writefile(['line1', 'line2', 'line3'], 'Xclistfile2.txt') + + edit Xclistfile1.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 Xclistfile2.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('Xclistfile1.txt') + call delete('Xclistfile2.txt') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_charsearch.vim b/test/old/testdir/test_charsearch.vim new file mode 100644 index 0000000000..084d4f0a22 --- /dev/null +++ b/test/old/testdir/test_charsearch.vim @@ -0,0 +1,101 @@ +" 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_beeps('normal ;') + call assert_beeps('normal ,') + + call assert_fails("call setcharsearch([])", 'E1206:') + 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 diff --git a/test/old/testdir/test_charsearch_utf8.vim b/test/old/testdir/test_charsearch_utf8.vim new file mode 100644 index 0000000000..843edbb514 --- /dev/null +++ b/test/old/testdir/test_charsearch_utf8.vim @@ -0,0 +1,26 @@ +" 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('.')) + call assert_equal('最', getcharsearch().char) + call setcharsearch({'char' : ''}) + call assert_equal('', getcharsearch().char) + call assert_beeps('normal ;') + call assert_equal([0, 1, 28, 0], getpos('.')) + call assert_beeps('normal ,') + call assert_equal([0, 1, 28, 0], getpos('.')) + bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_checkpath.vim b/test/old/testdir/test_checkpath.vim new file mode 100644 index 0000000000..f6a3bbce08 --- /dev/null +++ b/test/old/testdir/test_checkpath.vim @@ -0,0 +1,121 @@ +" 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 diff --git a/test/old/testdir/test_cindent.vim b/test/old/testdir/test_cindent.vim new file mode 100644 index 0000000000..d9702f57d2 --- /dev/null +++ b/test/old/testdir/test_cindent.vim @@ -0,0 +1,5452 @@ +" Test for cinoptions and cindent +" + +func Test_cino_hash() + " Test that curbuf->b_ind_hash_comment is correctly reset + new + setlocal cindent cinoptions=#1 + setlocal cinoptions= + call setline(1, ["#include <iostream>"]) + call cursor(1, 1) + norm! o#include + "call feedkeys("o#include\<esc>", 't') + call assert_equal(["#include <iostream>", "#include"], getline(1,2)) + bwipe! +endfunc + +func Test_cino_extern_c() + " Test for cino-E + + let without_ind =<< trim [CODE] + #ifdef __cplusplus + extern "C" { + #endif + int func_a(void); + #ifdef __cplusplus + } + #endif + [CODE] + + let with_ind =<< trim [CODE] + #ifdef __cplusplus + extern "C" { + #endif + int func_a(void); + #ifdef __cplusplus + } + #endif + [CODE] + new + setlocal cindent cinoptions=E0 + call setline(1, without_ind) + call feedkeys("gg=G", 'tx') + call assert_equal(with_ind, getline(1, '$')) + + setlocal cinoptions=E-s + call setline(1, with_ind) + call feedkeys("gg=G", 'tx') + call assert_equal(without_ind, getline(1, '$')) + + setlocal cinoptions=Es + let tests = [ + \ ['recognized', ['extern "C" {'], "\t\t;"], + \ ['recognized', ['extern "C++" {'], "\t\t;"], + \ ['recognized', ['extern /* com */ "C"{'], "\t\t;"], + \ ['recognized', ['extern"C"{'], "\t\t;"], + \ ['recognized', ['extern "C"', '{'], "\t\t;"], + \ ['not recognized', ['extern {'], "\t;"], + \ ['not recognized', ['extern /*"C"*/{'], "\t;"], + \ ['not recognized', ['extern "C" //{'], ";"], + \ ['not recognized', ['extern "C" /*{*/'], ";"], + \ ] + + for pair in tests + let lines = pair[1] + call setline(1, lines) + call feedkeys(len(lines) . "Go;", 'tx') + call assert_equal(pair[2], getline(len(lines) + 1), 'Failed for "' . string(lines) . '"') + endfor + + bwipe! +endfunc + +func Test_cindent_rawstring() + new + setl cindent + call feedkeys("i" . + \ "int main() {\<CR>" . + \ "R\"(\<CR>" . + \ ")\";\<CR>" . + \ "statement;\<Esc>", "x") + call assert_equal("\tstatement;", getline(line('.'))) + bw! +endfunc + +func Test_cindent_expr() + new + func! MyIndentFunction() + return v:lnum == 1 ? shiftwidth() : 0 + endfunc + setl expandtab sw=8 indentkeys+=; indentexpr=MyIndentFunction() + let testinput =<< trim [CODE] + var_a = something() + b = something() + [CODE] + call setline(1, testinput) + call cursor(1, 1) + call feedkeys("^\<c-v>j$A;\<esc>", 'tnix') + let expected =<< [CODE] + var_a = something(); +b = something(); +[CODE] + call assert_equal(expected, getline(1, '$')) + + %d + let testinput =<< [CODE] + var_a = something() + b = something() +[CODE] + call setline(1, testinput) + call cursor(1, 1) + call feedkeys("^\<c-v>j$A;\<esc>", 'tnix') + let expected =<< [CODE] + var_a = something(); + b = something() +[CODE] + call assert_equal(expected, getline(1, '$')) + bw! +endfunc + +func Test_cindent_func() + new + setlocal cindent + call setline(1, ['int main(void)', '{', 'return 0;', '}']) + call assert_equal(-1, cindent(0)) + call assert_equal(&sw, 3->cindent()) + call assert_equal(-1, cindent(line('$')+1)) + bwipe! +endfunc + +func Test_cindent_1() + new + setl cindent ts=4 sw=4 + setl cino& sts& + + let code =<< trim [CODE] + /* start of AUTO matically checked vim: set ts=4 : */ + { + if (test) + cmd1; + cmd2; + } + + { + if (test) + cmd1; + else + cmd2; + } + + { + if (test) + { + cmd1; + cmd2; + } + } + + { + if (test) + { + cmd1; + else + } + } + + { + while (this) + if (test) + cmd1; + cmd2; + } + + { + while (this) + if (test) + cmd1; + else + cmd2; + } + + { + if (test) + { + cmd; + } + + if (test) + cmd; + } + + { + if (test) { + cmd; + } + + if (test) cmd; + } + + { + cmd1; + for (blah) + while (this) + if (test) + cmd2; + cmd3; + } + + { + cmd1; + for (blah) + while (this) + if (test) + cmd2; + cmd3; + + if (test) + { + cmd1; + cmd2; + cmd3; + } + } + + + /* Test for 'cindent' do/while mixed with if/else: */ + + { + do + if (asdf) + asdfasd; + while (cond); + + do + if (asdf) + while (asdf) + asdf; + while (asdf); + } + + /* Test for 'cindent' with two ) on a continuation line */ + { + if (asdfasdf;asldkfj asdlkfj as;ldkfj sal;d + aal;sdkjf ( ;asldfkja;sldfk + al;sdjfka ;slkdf ) sa;ldkjfsa dlk;) + line up here; + } + + + /* C++ tests: */ + + // foo() these three lines should remain in column 0 + // { + // } + + /* Test for continuation and unterminated lines: */ + { + i = 99 + 14325 + + 21345 + + 21345 + + 21345 + ( 21345 + + 21345) + + 2345 + + 1234; + c = 1; + } + + /* + testje for indent with empty line + + here */ + + { + if (testing && + not a joke || + line up here) + hay; + if (testing && + (not a joke || testing + )line up here) + hay; + if (testing && + (not a joke || testing + line up here)) + hay; + } + + + { + switch (c) + { + case xx: + do + if (asdf) + do + asdfasdf; + while (asdf); + else + asdfasdf; + while (cond); + case yy: + case xx: + case zz: + testing; + } + } + + { + if (cond) { + foo; + } + else + { + bar; + } + } + + { + if (alskdfj ;alsdkfjal;skdjf (;sadlkfsa ;dlkf j;alksdfj ;alskdjf + alsdkfj (asldk;fj + awith cino=(0 ;lf this one goes to below the paren with == + ;laksjfd ;lsakdjf ;alskdf asd) + asdfasdf;))) + asdfasdf; + } + + int + func(a, b) + int a; + int c; + { + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3) + ) + } + + { + while (asd) + { + if (asdf) + if (test) + if (that) + { + if (asdf) + do + cdasd; + while (as + df); + } + else + if (asdf) + asdf; + else + asdf; + asdf; + } + } + + { + s = "/*"; b = ';' + s = "/*"; b = ';'; + a = b; + } + + { + switch (a) + { + case a: + switch (t) + { + case 1: + cmd; + break; + case 2: + cmd; + break; + } + cmd; + break; + case b: + { + int i; + cmd; + } + break; + case c: { + int i; + cmd; + } + case d: if (cond && + test) { /* this line doesn't work right */ + int i; + cmd; + } + break; + } + } + + { + if (!(vim_strchr(p_cpo, CPO_BUFOPTGLOB) != NULL && entering) && + (bp_to->b_p_initialized || + (!entering && vim_strchr(p_cpo, CPO_BUFOPT) != NULL))) + return; + label : + asdf = asdf ? + asdf : asdf; + asdf = asdf ? + asdf: asdf; + } + + /* Special Comments : This function has the added complexity (compared */ + /* : to addtolist) of having to check for a detail */ + /* : texture and add that to the list first. */ + + char *(array[100]) = { + "testje", + "foo", + "bar", + } + + enum soppie + { + yes = 0, + no, + maybe + }; + + typedef enum soppie + { + yes = 0, + no, + maybe + }; + + static enum + { + yes = 0, + no, + maybe + } soppie; + + public static enum + { + yes = 0, + no, + maybe + } soppie; + + static private enum + { + yes = 0, + no, + maybe + } soppie; + + { + int a, + b; + } + + { + struct Type + { + int i; + char *str; + } var[] = + { + 0, "zero", + 1, "one", + 2, "two", + 3, "three" + }; + + float matrix[3][3] = + { + { + 0, + 1, + 2 + }, + { + 3, + 4, + 5 + }, + { + 6, + 7, + 8 + } + }; + } + + { + /* blah ( blah */ + /* where does this go? */ + + /* blah ( blah */ + cmd; + + func(arg1, + /* comment */ + arg2); + a; + { + b; + { + c; /* Hey, NOW it indents?! */ + } + } + + { + func(arg1, + arg2, + arg3); + /* Hey, what am I doing here? Is this coz of the ","? */ + } + } + + main () + { + if (cond) + { + a = b; + } + if (cond) { + a = c; + } + if (cond) + a = d; + return; + } + + { + case 2: if (asdf && + asdfasdf) + aasdf; + a = 9; + case 3: if (asdf) + aasdf; + a = 9; + case 4: x = 1; + y = 2; + + label: if (asdf) + here; + + label: if (asdf && + asdfasdf) + { + } + + label: if (asdf && + asdfasdf) { + there; + } + + label: if (asdf && + asdfasdf) + there; + } + + { + /* + hello with ":set comments= cino=c5" + */ + + /* + hello with ":set comments= cino=" + */ + } + + + { + if (a < b) { + a = a + 1; + } else + a = a + 2; + + if (a) + do { + testing; + } while (asdfasdf); + a = b + 1; + asdfasdf + } + + { + for ( int i = 0; + i < 10; i++ ) + { + } + i = 0; + } + + class bob + { + int foo() {return 1;} + int bar; + } + + main() + { + while(1) + if (foo) + { + bar; + } + else { + asdf; + } + misplacedline; + } + + { + if (clipboard.state == SELECT_DONE + && ((row == clipboard.start.lnum + && col >= clipboard.start.col) + || row > clipboard.start.lnum)) + } + + { + if (1) {i += 4;} + where_am_i; + return 0; + } + + { + { + } // sdf(asdf + if (asdf) + asd; + } + + { + label1: + label2: + } + + { + int fooRet = foo(pBar1, false /*fKB*/, + true /*fPTB*/, 3 /*nT*/, false /*fDF*/); + f() { + for ( i = 0; + i < m; + /* c */ i++ ) { + a = b; + } + } + } + + { + f1(/*comment*/); + f2(); + } + + { + do { + if (foo) { + } else + ; + } while (foo); + foo(); // was wrong + } + + int x; // no extra indent because of the ; + void func() + { + } + + char *tab[] = {"aaa", + "};", /* }; */ NULL} + int indented; + {} + + char *a[] = {"aaa", "bbb", + "ccc", NULL}; + // here + + char *tab[] = {"aaa", + "xx", /* xx */}; /* asdf */ + int not_indented; + + { + do { + switch (bla) + { + case 1: if (foo) + bar; + } + } while (boo); + wrong; + } + + int foo, + bar; + int foo; + + #if defined(foo) \ + && defined(bar) + char * xx = "asdf\ + foo\ + bor"; + int x; + + char *foo = "asdf\ + asdf\ + asdf", + *bar; + + void f() + { + #if defined(foo) \ + && defined(bar) + char *foo = "asdf\ + asdf\ + asdf", + *bar; + { + int i; + char *foo = "asdf\ + asdf\ + asdf", + *bar; + } + #endif + } + #endif + + int y; // comment + // comment + + // comment + + { + Constructor(int a, + int b ) : BaseClass(a) + { + } + } + + void foo() + { + char one, + two; + struct bla piet, + jan; + enum foo kees, + jannie; + static unsigned sdf, + krap; + unsigned int piet, + jan; + int + kees, + jan; + } + + { + t(int f, + int d); // ) + d(); + } + + Constructor::Constructor(int a, + int b + ) : + BaseClass(a, + b, + c), + mMember(b), + { + } + + Constructor::Constructor(int a, + int b ) : + BaseClass(a) + { + } + + Constructor::Constructor(int a, + int b ) /*x*/ : /*x*/ BaseClass(a), + member(b) + { + } + + A::A(int a, int b) + : aa(a), + bb(b), + cc(c) + { + } + + class CAbc : + public BaseClass1, + protected BaseClass2 + { + int Test() { return FALSE; } + int Test1() { return TRUE; } + + CAbc(int a, int b ) : + BaseClass(a) + { + switch(xxx) + { + case abc: + asdf(); + break; + + case 999: + baer(); + break; + } + } + + public: // <-- this was incorrectly indented before!! + void testfall(); + protected: + void testfall(); + }; + + class CAbc : public BaseClass1, + protected BaseClass2 + { + }; + + static struct + { + int a; + int b; + } variable[COUNT] = + { + { + 123, + 456 + }, + { + 123, + 456 + } + }; + + static struct + { + int a; + int b; + } variable[COUNT] = + { + { 123, 456 }, + { 123, 456 } + }; + + void asdf() /* ind_maxparen may cause trouble here */ + { + if ((0 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1)) break; + } + + foo() + { + a = cond ? foo() : asdf + + asdf; + + a = cond ? + foo() : asdf + + asdf; + } + + int main(void) + { + if (a) + if (b) + 2; + else 3; + next_line_of_code(); + } + + barry() + { + Foo::Foo (int one, + int two) + : something(4) + {} + } + + barry() + { + Foo::Foo (int one, int two) + : something(4) + {} + } + + Constructor::Constructor(int a, + int b + ) : + BaseClass(a, + b, + c), + mMember(b) + { + } + int main () + { + if (lala) + do + ++(*lolo); + while (lili + && lele); + lulu; + } + + int main () + { + switch (c) + { + case 'c': if (cond) + { + } + } + } + + main() + { + (void) MyFancyFuasdfadsfnction( + argument); + } + + main() + { + char foo[] = "/*"; + /* as + df */ + hello + } + + /* valid namespaces with normal indent */ + namespace + { + { + 111111111111; + } + } + namespace /* test */ + { + 11111111111111111; + } + namespace // test + { + 111111111111111111; + } + namespace + { + 111111111111111111; + } + namespace test + { + 111111111111111111; + } + namespace{ + 111111111111111111; + } + namespace test{ + 111111111111111111; + } + namespace { + 111111111111111111; + } + namespace test { + 111111111111111111; + namespace test2 { + 22222222222222222; + } + } + inline namespace { + 111111111111111111; + } + inline /* test */ namespace { + 111111111111111111; + } + inline/* test */namespace { + 111111111111111111; + } + + /* invalid namespaces use block indent */ + namespace test test2 { + 111111111111111111111; + } + namespace11111111111 { + 111111111111; + } + namespace() { + 1111111111111; + } + namespace() + { + 111111111111111111; + } + namespace test test2 + { + 1111111111111111111; + } + namespace111111111 + { + 111111111111111111; + } + inlinenamespace { + 111111111111111111; + } + + void getstring() { + /* Raw strings */ + const char* s = R"( + test { + # comment + field: 123 + } + )"; + } + + void getstring() { + const char* s = R"foo( + test { + # comment + field: 123 + } + )foo"; + } + + { + int a[4] = { + [0] = 0, + [1] = 1, + [2] = 2, + [3] = 3, + }; + } + + { + a = b[2] + + 3; + } + + { + if (1) + /* aaaaa + * bbbbb + */ + a = 1; + } + + void func() + { + switch (foo) + { + case (bar): + if (baz()) + quux(); + break; + case (shmoo): + if (!bar) + { + } + case (foo1): + switch (bar) + { + case baz: + baz_f(); + break; + } + break; + default: + baz(); + baz(); + break; + } + } + + /* end of AUTO */ + [CODE] + + call append(0, code) + normal gg + call search('start of AUTO') + exe "normal =/end of AUTO\<CR>" + + let expected =<< trim [CODE] + /* start of AUTO matically checked vim: set ts=4 : */ + { + if (test) + cmd1; + cmd2; + } + + { + if (test) + cmd1; + else + cmd2; + } + + { + if (test) + { + cmd1; + cmd2; + } + } + + { + if (test) + { + cmd1; + else + } + } + + { + while (this) + if (test) + cmd1; + cmd2; + } + + { + while (this) + if (test) + cmd1; + else + cmd2; + } + + { + if (test) + { + cmd; + } + + if (test) + cmd; + } + + { + if (test) { + cmd; + } + + if (test) cmd; + } + + { + cmd1; + for (blah) + while (this) + if (test) + cmd2; + cmd3; + } + + { + cmd1; + for (blah) + while (this) + if (test) + cmd2; + cmd3; + + if (test) + { + cmd1; + cmd2; + cmd3; + } + } + + + /* Test for 'cindent' do/while mixed with if/else: */ + + { + do + if (asdf) + asdfasd; + while (cond); + + do + if (asdf) + while (asdf) + asdf; + while (asdf); + } + + /* Test for 'cindent' with two ) on a continuation line */ + { + if (asdfasdf;asldkfj asdlkfj as;ldkfj sal;d + aal;sdkjf ( ;asldfkja;sldfk + al;sdjfka ;slkdf ) sa;ldkjfsa dlk;) + line up here; + } + + + /* C++ tests: */ + + // foo() these three lines should remain in column 0 + // { + // } + + /* Test for continuation and unterminated lines: */ + { + i = 99 + 14325 + + 21345 + + 21345 + + 21345 + ( 21345 + + 21345) + + 2345 + + 1234; + c = 1; + } + + /* + testje for indent with empty line + + here */ + + { + if (testing && + not a joke || + line up here) + hay; + if (testing && + (not a joke || testing + )line up here) + hay; + if (testing && + (not a joke || testing + line up here)) + hay; + } + + + { + switch (c) + { + case xx: + do + if (asdf) + do + asdfasdf; + while (asdf); + else + asdfasdf; + while (cond); + case yy: + case xx: + case zz: + testing; + } + } + + { + if (cond) { + foo; + } + else + { + bar; + } + } + + { + if (alskdfj ;alsdkfjal;skdjf (;sadlkfsa ;dlkf j;alksdfj ;alskdjf + alsdkfj (asldk;fj + awith cino=(0 ;lf this one goes to below the paren with == + ;laksjfd ;lsakdjf ;alskdf asd) + asdfasdf;))) + asdfasdf; + } + + int + func(a, b) + int a; + int c; + { + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3) + ) + } + + { + while (asd) + { + if (asdf) + if (test) + if (that) + { + if (asdf) + do + cdasd; + while (as + df); + } + else + if (asdf) + asdf; + else + asdf; + asdf; + } + } + + { + s = "/*"; b = ';' + s = "/*"; b = ';'; + a = b; + } + + { + switch (a) + { + case a: + switch (t) + { + case 1: + cmd; + break; + case 2: + cmd; + break; + } + cmd; + break; + case b: + { + int i; + cmd; + } + break; + case c: { + int i; + cmd; + } + case d: if (cond && + test) { /* this line doesn't work right */ + int i; + cmd; + } + break; + } + } + + { + if (!(vim_strchr(p_cpo, CPO_BUFOPTGLOB) != NULL && entering) && + (bp_to->b_p_initialized || + (!entering && vim_strchr(p_cpo, CPO_BUFOPT) != NULL))) + return; + label : + asdf = asdf ? + asdf : asdf; + asdf = asdf ? + asdf: asdf; + } + + /* Special Comments : This function has the added complexity (compared */ + /* : to addtolist) of having to check for a detail */ + /* : texture and add that to the list first. */ + + char *(array[100]) = { + "testje", + "foo", + "bar", + } + + enum soppie + { + yes = 0, + no, + maybe + }; + + typedef enum soppie + { + yes = 0, + no, + maybe + }; + + static enum + { + yes = 0, + no, + maybe + } soppie; + + public static enum + { + yes = 0, + no, + maybe + } soppie; + + static private enum + { + yes = 0, + no, + maybe + } soppie; + + { + int a, + b; + } + + { + struct Type + { + int i; + char *str; + } var[] = + { + 0, "zero", + 1, "one", + 2, "two", + 3, "three" + }; + + float matrix[3][3] = + { + { + 0, + 1, + 2 + }, + { + 3, + 4, + 5 + }, + { + 6, + 7, + 8 + } + }; + } + + { + /* blah ( blah */ + /* where does this go? */ + + /* blah ( blah */ + cmd; + + func(arg1, + /* comment */ + arg2); + a; + { + b; + { + c; /* Hey, NOW it indents?! */ + } + } + + { + func(arg1, + arg2, + arg3); + /* Hey, what am I doing here? Is this coz of the ","? */ + } + } + + main () + { + if (cond) + { + a = b; + } + if (cond) { + a = c; + } + if (cond) + a = d; + return; + } + + { + case 2: if (asdf && + asdfasdf) + aasdf; + a = 9; + case 3: if (asdf) + aasdf; + a = 9; + case 4: x = 1; + y = 2; + + label: if (asdf) + here; + + label: if (asdf && + asdfasdf) + { + } + + label: if (asdf && + asdfasdf) { + there; + } + + label: if (asdf && + asdfasdf) + there; + } + + { + /* + hello with ":set comments= cino=c5" + */ + + /* + hello with ":set comments= cino=" + */ + } + + + { + if (a < b) { + a = a + 1; + } else + a = a + 2; + + if (a) + do { + testing; + } while (asdfasdf); + a = b + 1; + asdfasdf + } + + { + for ( int i = 0; + i < 10; i++ ) + { + } + i = 0; + } + + class bob + { + int foo() {return 1;} + int bar; + } + + main() + { + while(1) + if (foo) + { + bar; + } + else { + asdf; + } + misplacedline; + } + + { + if (clipboard.state == SELECT_DONE + && ((row == clipboard.start.lnum + && col >= clipboard.start.col) + || row > clipboard.start.lnum)) + } + + { + if (1) {i += 4;} + where_am_i; + return 0; + } + + { + { + } // sdf(asdf + if (asdf) + asd; + } + + { + label1: + label2: + } + + { + int fooRet = foo(pBar1, false /*fKB*/, + true /*fPTB*/, 3 /*nT*/, false /*fDF*/); + f() { + for ( i = 0; + i < m; + /* c */ i++ ) { + a = b; + } + } + } + + { + f1(/*comment*/); + f2(); + } + + { + do { + if (foo) { + } else + ; + } while (foo); + foo(); // was wrong + } + + int x; // no extra indent because of the ; + void func() + { + } + + char *tab[] = {"aaa", + "};", /* }; */ NULL} + int indented; + {} + + char *a[] = {"aaa", "bbb", + "ccc", NULL}; + // here + + char *tab[] = {"aaa", + "xx", /* xx */}; /* asdf */ + int not_indented; + + { + do { + switch (bla) + { + case 1: if (foo) + bar; + } + } while (boo); + wrong; + } + + int foo, + bar; + int foo; + + #if defined(foo) \ + && defined(bar) + char * xx = "asdf\ + foo\ + bor"; + int x; + + char *foo = "asdf\ + asdf\ + asdf", + *bar; + + void f() + { + #if defined(foo) \ + && defined(bar) + char *foo = "asdf\ + asdf\ + asdf", + *bar; + { + int i; + char *foo = "asdf\ + asdf\ + asdf", + *bar; + } + #endif + } + #endif + + int y; // comment + // comment + + // comment + + { + Constructor(int a, + int b ) : BaseClass(a) + { + } + } + + void foo() + { + char one, + two; + struct bla piet, + jan; + enum foo kees, + jannie; + static unsigned sdf, + krap; + unsigned int piet, + jan; + int + kees, + jan; + } + + { + t(int f, + int d); // ) + d(); + } + + Constructor::Constructor(int a, + int b + ) : + BaseClass(a, + b, + c), + mMember(b), + { + } + + Constructor::Constructor(int a, + int b ) : + BaseClass(a) + { + } + + Constructor::Constructor(int a, + int b ) /*x*/ : /*x*/ BaseClass(a), + member(b) + { + } + + A::A(int a, int b) + : aa(a), + bb(b), + cc(c) + { + } + + class CAbc : + public BaseClass1, + protected BaseClass2 + { + int Test() { return FALSE; } + int Test1() { return TRUE; } + + CAbc(int a, int b ) : + BaseClass(a) + { + switch(xxx) + { + case abc: + asdf(); + break; + + case 999: + baer(); + break; + } + } + + public: // <-- this was incorrectly indented before!! + void testfall(); + protected: + void testfall(); + }; + + class CAbc : public BaseClass1, + protected BaseClass2 + { + }; + + static struct + { + int a; + int b; + } variable[COUNT] = + { + { + 123, + 456 + }, + { + 123, + 456 + } + }; + + static struct + { + int a; + int b; + } variable[COUNT] = + { + { 123, 456 }, + { 123, 456 } + }; + + void asdf() /* ind_maxparen may cause trouble here */ + { + if ((0 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1 + && 1)) break; + } + + foo() + { + a = cond ? foo() : asdf + + asdf; + + a = cond ? + foo() : asdf + + asdf; + } + + int main(void) + { + if (a) + if (b) + 2; + else 3; + next_line_of_code(); + } + + barry() + { + Foo::Foo (int one, + int two) + : something(4) + {} + } + + barry() + { + Foo::Foo (int one, int two) + : something(4) + {} + } + + Constructor::Constructor(int a, + int b + ) : + BaseClass(a, + b, + c), + mMember(b) + { + } + int main () + { + if (lala) + do + ++(*lolo); + while (lili + && lele); + lulu; + } + + int main () + { + switch (c) + { + case 'c': if (cond) + { + } + } + } + + main() + { + (void) MyFancyFuasdfadsfnction( + argument); + } + + main() + { + char foo[] = "/*"; + /* as + df */ + hello + } + + /* valid namespaces with normal indent */ + namespace + { + { + 111111111111; + } + } + namespace /* test */ + { + 11111111111111111; + } + namespace // test + { + 111111111111111111; + } + namespace + { + 111111111111111111; + } + namespace test + { + 111111111111111111; + } + namespace{ + 111111111111111111; + } + namespace test{ + 111111111111111111; + } + namespace { + 111111111111111111; + } + namespace test { + 111111111111111111; + namespace test2 { + 22222222222222222; + } + } + inline namespace { + 111111111111111111; + } + inline /* test */ namespace { + 111111111111111111; + } + inline/* test */namespace { + 111111111111111111; + } + + /* invalid namespaces use block indent */ + namespace test test2 { + 111111111111111111111; + } + namespace11111111111 { + 111111111111; + } + namespace() { + 1111111111111; + } + namespace() + { + 111111111111111111; + } + namespace test test2 + { + 1111111111111111111; + } + namespace111111111 + { + 111111111111111111; + } + inlinenamespace { + 111111111111111111; + } + + void getstring() { + /* Raw strings */ + const char* s = R"( + test { + # comment + field: 123 + } + )"; + } + + void getstring() { + const char* s = R"foo( + test { + # comment + field: 123 + } + )foo"; + } + + { + int a[4] = { + [0] = 0, + [1] = 1, + [2] = 2, + [3] = 3, + }; + } + + { + a = b[2] + + 3; + } + + { + if (1) + /* aaaaa + * bbbbb + */ + a = 1; + } + + void func() + { + switch (foo) + { + case (bar): + if (baz()) + quux(); + break; + case (shmoo): + if (!bar) + { + } + case (foo1): + switch (bar) + { + case baz: + baz_f(); + break; + } + break; + default: + baz(); + baz(); + break; + } + } + + /* end of AUTO */ + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_2() + new + setl cindent ts=4 sw=4 + setl tw=0 noai fo=croq + let &wm = &columns - 20 + + let code =<< trim [CODE] + { + + /* this is + * a real serious important big + * comment + */ + /* insert " about life, the universe, and the rest" after "serious" */ + } + [CODE] + + call append(0, code) + normal gg + call search('serious', 'e') + normal a about life, the universe, and the rest + + let expected =<< trim [CODE] + { + + /* this is + * a real serious + * about life, the + * universe, and the + * rest important big + * comment + */ + /* insert " about life, the universe, and the rest" after "serious" */ + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + set wm& + enew! | close +endfunc + +func Test_cindent_3() + new + setl nocindent ts=4 sw=4 + + let code =<< trim [CODE] + { + /* + * Testing for comments, without 'cin' set + */ + + /* + * what happens here? + */ + + /* + the end of the comment, try inserting a line below */ + + /* how about + this one */ + } + [CODE] + + call append(0, code) + normal gg + call search('comments') + normal joabout life + call search('happens') + normal jothere + call search('below') + normal oline + call search('this') + normal Ohello + + let expected =<< trim [CODE] + { + /* + * Testing for comments, without 'cin' set + */ + about life + + /* + * what happens here? + */ + there + + /* + the end of the comment, try inserting a line below */ + line + + /* how about + hello + this one */ + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_4() + new + setl cindent ts=4 sw=4 + + let code =<< trim [CODE] + { + var = this + that + vec[0] * vec[0] + + vec[1] * vec[1] + + vec2[2] * vec[2]; + } + [CODE] + + call append(0, code) + normal gg + call search('vec2') + normal == + + let expected =<< trim [CODE] + { + var = this + that + vec[0] * vec[0] + + vec[1] * vec[1] + + vec2[2] * vec[2]; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_5() + new + setl cindent ts=4 sw=4 + setl cino=}4 + + let code =<< trim [CODE] + { + asdf asdflkajds f; + if (tes & ting) { + asdf asdf asdf ; + asdfa sdf asdf; + } + testing1; + if (tes & ting) + { + asdf asdf asdf ; + asdfa sdf asdf; + } + testing2; + } + [CODE] + + call append(0, code) + normal gg + call search('testing1') + exe "normal k2==/testing2\<CR>" + normal k2== + + let expected =<< trim [CODE] + { + asdf asdflkajds f; + if (tes & ting) { + asdf asdf asdf ; + asdfa sdf asdf; + } + testing1; + if (tes & ting) + { + asdf asdf asdf ; + asdfa sdf asdf; + } + testing2; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_6() + new + setl cindent ts=4 sw=4 + setl cino=(0,)20 + + let code =<< trim [CODE] + main ( int first_par, /* + * Comment for + * first par + */ + int second_par /* + * Comment for + * second par + */ + ) + { + func( first_par, /* + * Comment for + * first par + */ + second_par /* + * Comment for + * second par + */ + ); + + } + [CODE] + + call append(0, code) + normal gg + call search('main') + normal =][ + + let expected =<< trim [CODE] + main ( int first_par, /* + * Comment for + * first par + */ + int second_par /* + * Comment for + * second par + */ + ) + { + func( first_par, /* + * Comment for + * first par + */ + second_par /* + * Comment for + * second par + */ + ); + + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_7() + new + setl cindent ts=4 sw=4 + setl cino=es,n0s + + let code =<< trim [CODE] + main(void) + { + /* Make sure that cino=X0s is not parsed like cino=Xs. */ + if (cond) + foo(); + else + { + bar(); + } + } + [CODE] + + call append(0, code) + normal gg + call search('main') + normal =][ + + let expected =<< trim [CODE] + main(void) + { + /* Make sure that cino=X0s is not parsed like cino=Xs. */ + if (cond) + foo(); + else + { + bar(); + } + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_8() + new + setl cindent ts=4 sw=4 + setl cino= + + let code =<< trim [CODE] + + { + do + { + if () + { + if () + asdf; + else + asdf; + } + } while (); + cmd; /* this should go under the } */ + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + + { + do + { + if () + { + if () + asdf; + else + asdf; + } + } while (); + cmd; /* this should go under the } */ + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_9() + new + setl cindent ts=4 sw=4 + + let code =<< trim [CODE] + + void f() + { + if ( k() ) { + l(); + + } else { /* Start (two words) end */ + m(); + } + + n(); + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + + void f() + { + if ( k() ) { + l(); + + } else { /* Start (two words) end */ + m(); + } + + n(); + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_10() + new + setl cindent ts=4 sw=4 + setl cino={s,e-s + + let code =<< trim [CODE] + + void f() + { + if ( k() ) + { + l(); + } else { /* Start (two words) end */ + m(); + } + n(); /* should be under the if () */ + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + + void f() + { + if ( k() ) + { + l(); + } else { /* Start (two words) end */ + m(); + } + n(); /* should be under the if () */ + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_11() + new + setl cindent ts=4 sw=4 + setl cino={s,fs + + let code =<< trim [CODE] + void bar(void) + { + static array[2][2] = + { + { 1, 2 }, + { 3, 4 }, + } + + while (a) + { + foo(&a); + } + + { + int a; + { + a = a + 1; + } + } + b = a; + } + + void func(void) + { + a = 1; + { + b = 2; + } + c = 3; + d = 4; + } + /* foo */ + [CODE] + + call append(0, code) + normal gg + exe "normal ]]=/ foo\<CR>" + + let expected =<< trim [CODE] + void bar(void) + { + static array[2][2] = + { + { 1, 2 }, + { 3, 4 }, + } + + while (a) + { + foo(&a); + } + + { + int a; + { + a = a + 1; + } + } + b = a; + } + + void func(void) + { + a = 1; + { + b = 2; + } + c = 3; + d = 4; + } + /* foo */ + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_12() + new + setl cindent ts=4 sw=4 + setl cino= + + let code =<< trim [CODE] + a() + { + do { + a = a + + a; + } while ( a ); /* add text under this line */ + if ( a ) + a; + } + [CODE] + + call append(0, code) + normal gg + call search('while') + normal ohere + + let expected =<< trim [CODE] + a() + { + do { + a = a + + a; + } while ( a ); /* add text under this line */ + here + if ( a ) + a; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_13() + new + setl cindent ts=4 sw=4 + setl cino= com= + + let code =<< trim [CODE] + a() + { + label1: + /* hmm */ + // comment + } + [CODE] + + call append(0, code) + normal gg + call search('comment') + exe "normal olabel2: b();\rlabel3 /* post */:\r/* pre */ label4:\r" . + \ "f(/*com*/);\rif (/*com*/)\rcmd();" + + let expected =<< trim [CODE] + a() + { + label1: + /* hmm */ + // comment + label2: b(); + label3 /* post */: + /* pre */ label4: + f(/*com*/); + if (/*com*/) + cmd(); + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_14() + new + setl cindent ts=4 sw=4 + setl comments& comments^=s:/*,m:**,ex:*/ + + let code =<< trim [CODE] + /* + * A simple comment + */ + + /* + ** A different comment + */ + [CODE] + + call append(0, code) + normal gg + call search('simple') + normal =5j + + let expected =<< trim [CODE] + /* + * A simple comment + */ + + /* + ** A different comment + */ + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_15() + new + setl cindent ts=4 sw=4 + setl cino=c0 + setl comments& comments-=s1:/* comments^=s0:/* + + let code =<< trim [CODE] + void f() + { + + /********* + A comment. + *********/ + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + + /********* + A comment. + *********/ + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_16() + new + setl cindent ts=4 sw=4 + setl cino=c0,C1 + setl comments& comments-=s1:/* comments^=s0:/* + + let code =<< trim [CODE] + void f() + { + + /********* + A comment. + *********/ + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + + /********* + A comment. + *********/ + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_17() + new + setl cindent ts=4 sw=4 + setl cino= + + let code =<< trim [CODE] + void f() + { + c = c1 && + ( + c2 || + c3 + ) && c4; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + c = c1 && + ( + c2 || + c3 + ) && c4; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_18() + new + setl cindent ts=4 sw=4 + setl cino=(s + + let code =<< trim [CODE] + void f() + { + c = c1 && + ( + c2 || + c3 + ) && c4; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + c = c1 && + ( + c2 || + c3 + ) && c4; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_19() + new + setl cindent ts=4 sw=4 + set cino=(s,U1 + + let code =<< trim [CODE] + void f() + { + c = c1 && + ( + c2 || + c3 + ) && c4; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + c = c1 && + ( + c2 || + c3 + ) && c4; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_20() + new + setl cindent ts=4 sw=4 + setl cino=(0 + + let code =<< trim [CODE] + void f() + { + if ( c1 + && ( c2 + || c3)) + foo; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + if ( c1 + && ( c2 + || c3)) + foo; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_21() + new + setl cindent ts=4 sw=4 + setl cino=(0,w1 + + let code =<< trim [CODE] + void f() + { + if ( c1 + && ( c2 + || c3)) + foo; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + if ( c1 + && ( c2 + || c3)) + foo; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_22() + new + setl cindent ts=4 sw=4 + setl cino=(s + + let code =<< trim [CODE] + void f() + { + c = c1 && ( + c2 || + c3 + ) && c4; + if ( + c1 && c2 + ) + foo; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + c = c1 && ( + c2 || + c3 + ) && c4; + if ( + c1 && c2 + ) + foo; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_23() + new + setl cindent ts=4 sw=4 + setl cino=(s,m1 + + let code =<< trim [CODE] + void f() + { + c = c1 && ( + c2 || + c3 + ) && c4; + if ( + c1 && c2 + ) + foo; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + c = c1 && ( + c2 || + c3 + ) && c4; + if ( + c1 && c2 + ) + foo; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_24() + new + setl cindent ts=4 sw=4 + setl cino=b1 + + let code =<< trim [CODE] + void f() + { + switch (x) + { + case 1: + a = b; + break; + default: + a = 0; + break; + } + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + switch (x) + { + case 1: + a = b; + break; + default: + a = 0; + break; + } + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_25() + new + setl cindent ts=4 sw=4 + setl cino=(0,W5 + + let code =<< trim [CODE] + void f() + { + invokeme( + argu, + ment); + invokeme( + argu, + ment + ); + invokeme(argu, + ment + ); + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + invokeme( + argu, + ment); + invokeme( + argu, + ment + ); + invokeme(argu, + ment + ); + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_26() + new + setl cindent ts=4 sw=4 + setl cino=/6 + + let code =<< trim [CODE] + void f() + { + statement; + // comment 1 + // comment 2 + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void f() + { + statement; + // comment 1 + // comment 2 + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_27() + new + setl cindent ts=4 sw=4 + setl cino= + + let code =<< trim [CODE] + void f() + { + statement; + // comment 1 + // comment 2 + } + [CODE] + + call append(0, code) + normal gg + exe "normal ]]/comment 1/+1\<CR>==" + + let expected =<< trim [CODE] + void f() + { + statement; + // comment 1 + // comment 2 + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_28() + new + setl cindent ts=4 sw=4 + setl cino=g0 + + let code =<< trim [CODE] + class CAbc + { + int Test() { return FALSE; } + + public: // comment + void testfall(); + protected: + void testfall(); + }; + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + class CAbc + { + int Test() { return FALSE; } + + public: // comment + void testfall(); + protected: + void testfall(); + }; + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_29() + new + setl cindent ts=4 sw=4 + setl cino=(0,gs,hs + + let code =<< trim [CODE] + class Foo : public Bar + { + public: + virtual void method1(void) = 0; + virtual void method2(int arg1, + int arg2, + int arg3) = 0; + }; + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + class Foo : public Bar + { + public: + virtual void method1(void) = 0; + virtual void method2(int arg1, + int arg2, + int arg3) = 0; + }; + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_30() + new + setl cindent ts=4 sw=4 + setl cino=+20 + + let code =<< [CODE] + void +foo() +{ + if (a) + { + } else + asdf; +} +[CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< [CODE] + void +foo() +{ + if (a) + { + } else + asdf; +} + +[CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_31() + new + setl cindent ts=4 sw=4 + setl cino=(0,W2s + + let code =<< trim [CODE] + + { + averylongfunctionnamelongfunctionnameaverylongfunctionname()->asd( + asdasdf, + func(asdf, + asdfadsf), + asdfasdf + ); + + /* those are ugly, but consequent */ + + func()->asd(asdasdf, + averylongfunctionname( + abc, + dec)->averylongfunctionname( + asdfadsf, + asdfasdf, + asdfasdf, + ), + func(asdfadf, + asdfasdf + ), + asdasdf + ); + + averylongfunctionnameaverylongfunctionnameavery()->asd(fasdf( + abc, + dec)->asdfasdfasdf( + asdfadsf, + asdfasdf, + asdfasdf, + ), + func(asdfadf, + asdfasdf), + asdasdf + ); + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + + { + averylongfunctionnamelongfunctionnameaverylongfunctionname()->asd( + asdasdf, + func(asdf, + asdfadsf), + asdfasdf + ); + + /* those are ugly, but consequent */ + + func()->asd(asdasdf, + averylongfunctionname( + abc, + dec)->averylongfunctionname( + asdfadsf, + asdfasdf, + asdfasdf, + ), + func(asdfadf, + asdfasdf + ), + asdasdf + ); + + averylongfunctionnameaverylongfunctionnameavery()->asd(fasdf( + abc, + dec)->asdfasdfasdf( + asdfadsf, + asdfasdf, + asdfasdf, + ), + func(asdfadf, + asdfasdf), + asdasdf + ); + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_32() + new + setl cindent ts=4 sw=4 + setl cino=M1 + + let code =<< trim [CODE] + int main () + { + if (cond1 && + cond2 + ) + foo; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + int main () + { + if (cond1 && + cond2 + ) + foo; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_33() + new + setl cindent ts=4 sw=4 + setl cino=(0,ts + + let code =<< trim [CODE] + void func(int a + #if defined(FOO) + , int b + , int c + #endif + ) + { + } + [CODE] + + call append(0, code) + normal gg + normal 2j=][ + + let expected =<< trim [CODE] + void func(int a + #if defined(FOO) + , int b + , int c + #endif + ) + { + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_34() + new + setl cindent ts=4 sw=4 + setl cino=(0 + + let code =<< trim [CODE] + + void + func(int a + #if defined(FOO) + , int b + , int c + #endif + ) + { + } + [CODE] + + call append(0, code) + normal gg + normal =][ + + let expected =<< trim [CODE] + + void + func(int a + #if defined(FOO) + , int b + , int c + #endif + ) + { + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_35() + new + setl cindent ts=4 sw=4 + setl cino& + + let code =<< trim [CODE] + void func(void) + { + if(x==y) + if(y==z) + foo=1; + else { bar=1; + baz=2; + } + printf("Foo!\n"); + } + + void func1(void) + { + char* tab[] = {"foo", "bar", + "baz", "quux", + "this line used", "to be indented incorrectly"}; + foo(); + } + + void func2(void) + { + int tab[] = + {1, 2, + 3, 4, + 5, 6}; + + printf("This line used to be indented incorrectly.\n"); + } + + int foo[] + #ifdef BAR + + = { 1, 2, 3, + 4, 5, 6 } + + #endif + ; + int baz; + + void func3(void) + { + int tab[] = { + 1, 2, + 3, 4, + 5, 6}; + + printf("Don't you dare indent this line incorrectly!\n"); + } + + void + func4(a, b, + c) + int a; + int b; + int c; + { + } + + void + func5( + int a, + int b) + { + } + + void + func6( + int a) + { + } + [CODE] + + call append(0, code) + normal gg + normal ]]=7][ + + let expected =<< trim [CODE] + void func(void) + { + if(x==y) + if(y==z) + foo=1; + else { bar=1; + baz=2; + } + printf("Foo!\n"); + } + + void func1(void) + { + char* tab[] = {"foo", "bar", + "baz", "quux", + "this line used", "to be indented incorrectly"}; + foo(); + } + + void func2(void) + { + int tab[] = + {1, 2, + 3, 4, + 5, 6}; + + printf("This line used to be indented incorrectly.\n"); + } + + int foo[] + #ifdef BAR + + = { 1, 2, 3, + 4, 5, 6 } + + #endif + ; + int baz; + + void func3(void) + { + int tab[] = { + 1, 2, + 3, 4, + 5, 6}; + + printf("Don't you dare indent this line incorrectly!\n"); + } + + void + func4(a, b, + c) + int a; + int b; + int c; + { + } + + void + func5( + int a, + int b) + { + } + + void + func6( + int a) + { + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_36() + new + setl cindent ts=4 sw=4 + setl cino& + setl cino+=l1 + + let code =<< trim [CODE] + void func(void) + { + int tab[] = + { + 1, 2, 3, + 4, 5, 6}; + + printf("Indent this line correctly!\n"); + + switch (foo) + { + case bar: + printf("bar"); + break; + case baz: { + printf("baz"); + break; + } + case quux: + printf("But don't break the indentation of this instruction\n"); + break; + } + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + int tab[] = + { + 1, 2, 3, + 4, 5, 6}; + + printf("Indent this line correctly!\n"); + + switch (foo) + { + case bar: + printf("bar"); + break; + case baz: { + printf("baz"); + break; + } + case quux: + printf("But don't break the indentation of this instruction\n"); + break; + } + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_37() + new + setl cindent ts=4 sw=4 + setl cino& + + let code =<< trim [CODE] + void func(void) + { + cout << "a" + << "b" + << ") :" + << "c"; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + cout << "a" + << "b" + << ") :" + << "c"; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_38() + new + setl cindent ts=4 sw=4 + setl com=s1:/*,m:*,ex:*/ + + let code =<< trim [CODE] + void func(void) + { + /* + * This is a comment. + */ + } + [CODE] + + call append(0, code) + normal gg + normal ]]3jofoo(); + + let expected =<< trim [CODE] + void func(void) + { + /* + * This is a comment. + */ + foo(); + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_39() + new + setl cindent ts=4 sw=4 + setl cino& + + let code =<< trim [CODE] + void func(void) + { + for (int i = 0; i < 10; ++i) + if (i & 1) { + foo(1); + } else + foo(0); + baz(); + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + for (int i = 0; i < 10; ++i) + if (i & 1) { + foo(1); + } else + foo(0); + baz(); + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_40() + new + setl cindent ts=4 sw=4 + setl cino=k2s,(0 + + let code =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + + if ( c1 + && ( c2 + || c3)) + foo; + func( c1 + && ( c2 + || c3)) + foo; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + + if ( c1 + && ( c2 + || c3)) + foo; + func( c1 + && ( c2 + || c3)) + foo; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_41() + new + setl cindent ts=4 sw=4 + setl cino=k2s,(s + + let code =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + + if ( c1 + && ( c2 + || c3)) + foo; + func( c1 + && ( c2 + || c3)) + foo; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + + if ( c1 + && ( c2 + || c3)) + foo; + func( c1 + && ( c2 + || c3)) + foo; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_42() + new + setl cindent ts=4 sw=4 + setl cino=k2s,(s,U1 + + let code =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + if (c123456789 + && (c22345 + || c3)) + printf("foo\n"); + + c = c1 && + ( + c2 || + c3 + ) && c4; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + if (c123456789 + && (c22345 + || c3)) + printf("foo\n"); + + c = c1 && + ( + c2 || + c3 + ) && c4; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_43() + new + setl cindent ts=4 sw=4 + setl cino=k2s,(0,W4 + + let code =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + if (c123456789 + && (c22345 + || c3)) + printf("foo\n"); + + if ( c1 + && ( c2 + || c3)) + foo; + + a_long_line( + argument, + argument); + a_short_line(argument, + argument); + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + if (c123456789 + && (c22345 + || c3)) + printf("foo\n"); + + if ( c1 + && ( c2 + || c3)) + foo; + + a_long_line( + argument, + argument); + a_short_line(argument, + argument); + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_44() + new + setl cindent ts=4 sw=4 + setl cino=k2s,u2 + + let code =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + if (c123456789 + && (c22345 + || c3)) + printf("foo\n"); + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + if (c123456789 + && (c22345 + || c3)) + printf("foo\n"); + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_45() + new + setl cindent ts=4 sw=4 + setl cino=k2s,(0,w1 + + let code =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + if (c123456789 + && (c22345 + || c3)) + printf("foo\n"); + + if ( c1 + && ( c2 + || c3)) + foo; + func( c1 + && ( c2 + || c3)) + foo; + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + if (c123456789 + && (c22345 + || c3)) + printf("foo\n"); + + if ( c1 + && ( c2 + || c3)) + foo; + func( c1 + && ( c2 + || c3)) + foo; + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_46() + new + setl cindent ts=4 sw=4 + setl cino=k2,(s + + let code =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + } + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + void func(void) + { + if (condition1 + && condition2) + action(); + function(argument1 + && argument2); + + if (c1 && (c2 || + c3)) + foo; + if (c1 && + (c2 || c3)) + { + } + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_47() + new + setl cindent ts=4 sw=4 + setl cino=N-s + + let code =<< trim [CODE] + NAMESPACESTART + /* valid namespaces with normal indent */ + namespace + { + { + 111111111111; + } + } + namespace /* test */ + { + 11111111111111111; + } + namespace // test + { + 111111111111111111; + } + namespace + { + 111111111111111111; + } + namespace test + { + 111111111111111111; + } + namespace test::cpp17 + { + 111111111111111111; + } + namespace ::incorrectcpp17 + { + 111111111111111111; + } + namespace test::incorrectcpp17:: + { + 111111111111111111; + } + namespace test:incorrectcpp17 + { + 111111111111111111; + } + namespace test:::incorrectcpp17 + { + 111111111111111111; + } + namespace{ + 111111111111111111; + } + namespace test{ + 111111111111111111; + } + namespace { + 111111111111111111; + } + namespace test { + 111111111111111111; + namespace test2 { + 22222222222222222; + } + } + inline namespace { + 111111111111111111; + } + inline /* test */ namespace { + 111111111111111111; + } + inline/* test */namespace { + 111111111111111111; + } + export namespace { + 111111111111111111; + } + export inline namespace { + 111111111111111111; + } + export/* test */inline namespace { + 111111111111111111; + } + inline export namespace { + 111111111111111111; + } + + /* invalid namespaces use block indent */ + namespace test test2 { + 111111111111111111111; + } + namespace11111111111 { + 111111111111; + } + namespace() { + 1111111111111; + } + namespace() + { + 111111111111111111; + } + namespace test test2 + { + 1111111111111111111; + } + namespace111111111 + { + 111111111111111111; + } + inlinenamespace { + 111111111111111111; + } + NAMESPACEEND + [CODE] + + call append(0, code) + normal gg + call search('^NAMESPACESTART') + exe "normal =/^NAMESPACEEND\n" + + let expected =<< trim [CODE] + NAMESPACESTART + /* valid namespaces with normal indent */ + namespace + { + { + 111111111111; + } + } + namespace /* test */ + { + 11111111111111111; + } + namespace // test + { + 111111111111111111; + } + namespace + { + 111111111111111111; + } + namespace test + { + 111111111111111111; + } + namespace test::cpp17 + { + 111111111111111111; + } + namespace ::incorrectcpp17 + { + 111111111111111111; + } + namespace test::incorrectcpp17:: + { + 111111111111111111; + } + namespace test:incorrectcpp17 + { + 111111111111111111; + } + namespace test:::incorrectcpp17 + { + 111111111111111111; + } + namespace{ + 111111111111111111; + } + namespace test{ + 111111111111111111; + } + namespace { + 111111111111111111; + } + namespace test { + 111111111111111111; + namespace test2 { + 22222222222222222; + } + } + inline namespace { + 111111111111111111; + } + inline /* test */ namespace { + 111111111111111111; + } + inline/* test */namespace { + 111111111111111111; + } + export namespace { + 111111111111111111; + } + export inline namespace { + 111111111111111111; + } + export/* test */inline namespace { + 111111111111111111; + } + inline export namespace { + 111111111111111111; + } + + /* invalid namespaces use block indent */ + namespace test test2 { + 111111111111111111111; + } + namespace11111111111 { + 111111111111; + } + namespace() { + 1111111111111; + } + namespace() + { + 111111111111111111; + } + namespace test test2 + { + 1111111111111111111; + } + namespace111111111 + { + 111111111111111111; + } + inlinenamespace { + 111111111111111111; + } + NAMESPACEEND + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_48() + new + setl cindent ts=4 sw=4 + setl cino=j1,J1 + + let code =<< trim [CODE] + JSSTART + var bar = { + foo: { + that: this, + some: ok, + }, + "bar":{ + a : 2, + b: "123abc", + x: 4, + "y": 5 + } + } + JSEND + [CODE] + + call append(0, code) + normal gg + call search('^JSSTART') + exe "normal =/^JSEND\n" + + let expected =<< trim [CODE] + JSSTART + var bar = { + foo: { + that: this, + some: ok, + }, + "bar":{ + a : 2, + b: "123abc", + x: 4, + "y": 5 + } + } + JSEND + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_49() + new + setl cindent ts=4 sw=4 + setl cino=j1,J1 + + let code =<< trim [CODE] + JSSTART + var foo = [ + 1, + 2, + 3 + ]; + JSEND + [CODE] + + call append(0, code) + normal gg + call search('^JSSTART') + exe "normal =/^JSEND\n" + + let expected =<< trim [CODE] + JSSTART + var foo = [ + 1, + 2, + 3 + ]; + JSEND + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_50() + new + setl cindent ts=4 sw=4 + setl cino=j1,J1 + + let code =<< trim [CODE] + JSSTART + function bar() { + var foo = [ + 1, + 2, + 3 + ]; + } + JSEND + [CODE] + + call append(0, code) + normal gg + call search('^JSSTART') + exe "normal =/^JSEND\n" + + let expected =<< trim [CODE] + JSSTART + function bar() { + var foo = [ + 1, + 2, + 3 + ]; + } + JSEND + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_51() + new + setl cindent ts=4 sw=4 + setl cino=j1,J1 + + let code =<< trim [CODE] + JSSTART + (function($){ + + if (cond && + cond) { + stmt; + } + window.something.left = + (width - 50 + offset) + "px"; + var class_name='myclass'; + + function private_method() { + } + + var public_method={ + method: function(options,args){ + private_method(); + } + } + + function init(options) { + + $(this).data(class_name+'_public',$.extend({},{ + foo: 'bar', + bar: 2, + foobar: [ + 1, + 2, + 3 + ], + callback: function(){ + return true; + } + }, options||{})); + } + + $.fn[class_name]=function() { + + var _arguments=arguments; + return this.each(function(){ + + var options=$(this).data(class_name+'_public'); + if (!options) { + init.apply(this,_arguments); + + } else { + var method=public_method[_arguments[0]]; + + if (typeof(method)!='function') { + console.log(class_name+' has no method "'+_arguments[0]+'"'); + return false; + } + _arguments[0]=options; + method.apply(this,_arguments); + } + }); + } + + })(jQuery); + JSEND + [CODE] + + call append(0, code) + normal gg + call search('^JSSTART') + exe "normal =/^JSEND\n" + + let expected =<< trim [CODE] + JSSTART + (function($){ + + if (cond && + cond) { + stmt; + } + window.something.left = + (width - 50 + offset) + "px"; + var class_name='myclass'; + + function private_method() { + } + + var public_method={ + method: function(options,args){ + private_method(); + } + } + + function init(options) { + + $(this).data(class_name+'_public',$.extend({},{ + foo: 'bar', + bar: 2, + foobar: [ + 1, + 2, + 3 + ], + callback: function(){ + return true; + } + }, options||{})); + } + + $.fn[class_name]=function() { + + var _arguments=arguments; + return this.each(function(){ + + var options=$(this).data(class_name+'_public'); + if (!options) { + init.apply(this,_arguments); + + } else { + var method=public_method[_arguments[0]]; + + if (typeof(method)!='function') { + console.log(class_name+' has no method "'+_arguments[0]+'"'); + return false; + } + _arguments[0]=options; + method.apply(this,_arguments); + } + }); + } + + })(jQuery); + JSEND + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_52() + new + setl cindent ts=4 sw=4 + setl cino=j1,J1 + + let code =<< trim [CODE] + JSSTART + function init(options) { + $(this).data(class_name+'_public',$.extend({},{ + foo: 'bar', + bar: 2, + foobar: [ + 1, + 2, + 3 + ], + callback: function(){ + return true; + } + }, options||{})); + } + JSEND + [CODE] + + call append(0, code) + normal gg + call search('^JSSTART') + exe "normal =/^JSEND\n" + + let expected =<< trim [CODE] + JSSTART + function init(options) { + $(this).data(class_name+'_public',$.extend({},{ + foo: 'bar', + bar: 2, + foobar: [ + 1, + 2, + 3 + ], + callback: function(){ + return true; + } + }, options||{})); + } + JSEND + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_53() + new + setl cindent ts=4 sw=4 + setl cino=j1,J1 + + let code =<< trim [CODE] + JSSTART + (function($){ + function init(options) { + $(this).data(class_name+'_public',$.extend({},{ + foo: 'bar', + bar: 2, + foobar: [ + 1, + 2, + 3 + ], + callback: function(){ + return true; + } + }, options||{})); + } + })(jQuery); + JSEND + [CODE] + + call append(0, code) + normal gg + call search('^JSSTART') + exe "normal =/^JSEND\n" + + let expected =<< trim [CODE] + JSSTART + (function($){ + function init(options) { + $(this).data(class_name+'_public',$.extend({},{ + foo: 'bar', + bar: 2, + foobar: [ + 1, + 2, + 3 + ], + callback: function(){ + return true; + } + }, options||{})); + } + })(jQuery); + JSEND + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_54() + new + setl cindent ts=4 sw=4 + setl cino=j1,J1,+2 + + let code =<< trim [CODE] + JSSTART + // Results of JavaScript indent + // 1 + (function(){ + var a = [ + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i' + ]; + }()) + + // 2 + (function(){ + var a = [ + 0 + + 5 * + 9 * + 'a', + 'b', + 0 + + 5 * + 9 * + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i' + ]; + }()) + + // 3 + (function(){ + var a = [ + 0 + + // comment 1 + 5 * + /* comment 2 */ + 9 * + 'a', + 'b', + 0 + + 5 * + 9 * + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i' + ]; + }()) + + // 4 + { + var a = [ + 0, + 1 + ]; + var b; + var c; + } + + // 5 + { + var a = [ + [ + 0 + ], + 2, + 3 + ]; + } + + // 6 + { + var a = [ + [ + 0, + 1 + ], + 2, + 3 + ]; + } + + // 7 + { + var a = [ + // [ + 0, + // 1 + // ], + 2, + 3 + ]; + } + + // 8 + var x = [ + (function(){ + var a, + b, + c, + d, + e, + f, + g, + h, + i; + }) + ]; + + // 9 + var a = [ + 0 + + 5 * + 9 * + 'a', + 'b', + 0 + + 5 * + 9 * + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i' + ]; + + // 10 + var a, + b, + c, + d, + e, + f, + g, + h, + i; + JSEND + [CODE] + + call append(0, code) + normal gg + call search('^JSSTART') + exe "normal =/^JSEND\n" + + let expected =<< trim [CODE] + JSSTART + // Results of JavaScript indent + // 1 + (function(){ + var a = [ + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i' + ]; + }()) + + // 2 + (function(){ + var a = [ + 0 + + 5 * + 9 * + 'a', + 'b', + 0 + + 5 * + 9 * + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i' + ]; + }()) + + // 3 + (function(){ + var a = [ + 0 + + // comment 1 + 5 * + /* comment 2 */ + 9 * + 'a', + 'b', + 0 + + 5 * + 9 * + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i' + ]; + }()) + + // 4 + { + var a = [ + 0, + 1 + ]; + var b; + var c; + } + + // 5 + { + var a = [ + [ + 0 + ], + 2, + 3 + ]; + } + + // 6 + { + var a = [ + [ + 0, + 1 + ], + 2, + 3 + ]; + } + + // 7 + { + var a = [ + // [ + 0, + // 1 + // ], + 2, + 3 + ]; + } + + // 8 + var x = [ + (function(){ + var a, + b, + c, + d, + e, + f, + g, + h, + i; + }) + ]; + + // 9 + var a = [ + 0 + + 5 * + 9 * + 'a', + 'b', + 0 + + 5 * + 9 * + 'c', + 'd', + 'e', + 'f', + 'g', + 'h', + 'i' + ]; + + // 10 + var a, + b, + c, + d, + e, + f, + g, + h, + i; + JSEND + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_55() + new + setl cindent ts=4 sw=4 + setl cino& + + let code =<< trim [CODE] + /* start of define */ + { + } + #define AAA \ + BBB\ + CCC + + #define CNT \ + 1 + \ + 2 + \ + 4 + /* end of define */ + [CODE] + + call append(0, code) + normal gg + call search('start of define') + exe "normal =/end of define\n" + + let expected =<< trim [CODE] + /* start of define */ + { + } + #define AAA \ + BBB\ + CCC + + #define CNT \ + 1 + \ + 2 + \ + 4 + /* end of define */ + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_56() + new + setl cindent ts=4 sw=4 + setl cino& + + let code =<< trim [CODE] + { + a = second/*bug*/*line; + } + [CODE] + + call append(0, code) + normal gg + call search('a = second') + normal ox + + let expected =<< trim [CODE] + { + a = second/*bug*/*line; + x + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +" this was going beyond the end of the line. +func Test_cindent_case() + new + call setline(1, 'case x: // x') + set cindent + norm! f:a: + call assert_equal('case x:: // x', getline(1)) + set cindent& + bwipe! +endfunc + +" Test for changing multiple lines (using c) with cindent +func Test_cindent_change_multline() + new + setlocal cindent + call setline(1, ['if (a)', '{', ' i = 1;', '}']) + normal! jc3jm = 2; + call assert_equal("\tm = 2;", getline(2)) + close! +endfunc + +" This was reading past the end of the line +func Test_cindent_check_funcdecl() + new + sil norm o0('\0=L + bwipe! +endfunc + +func Test_cindent_scopedecls() + new + setl cindent ts=4 sw=4 + setl cino=g0 + setl cinsd+=public\ slots,signals + + let code =<< trim [CODE] + class Foo + { + public: + virtual void foo() = 0; + public slots: + void onBar(); + signals: + void baz(); + private: + int x; + }; + [CODE] + + call append(0, code) + normal gg + normal ]]=][ + + let expected =<< trim [CODE] + class Foo + { + public: + virtual void foo() = 0; + public slots: + void onBar(); + signals: + void baz(); + private: + int x; + }; + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_cindent_pragma() + new + setl cindent ts=4 sw=4 + setl cino=Ps + + let code =<< trim [CODE] + { + #pragma omp parallel + { + #pragma omp task + foo(); + # pragma omp taskwait + } + } + [CODE] + + call append(0, code) + normal gg + normal =G + + let expected =<< trim [CODE] + { + #pragma omp parallel + { + #pragma omp task + foo(); + # pragma omp taskwait + } + } + + [CODE] + + call assert_equal(expected, getline(1, '$')) + enew! | close +endfunc + +func Test_backslash_at_end_of_line() + new + exe "norm v>O'\\\<C-m>-" + exe "norm \<C-q>=" + bwipe! +endfunc + +func Test_find_brace_backwards() + " this was looking beyond the end of the line + new + norm R/* + norm o0{ + norm o// + norm V{= + call assert_equal(['/*', ' 0{', '//'], getline(1, 3)) + bwipe! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_cjk_linebreak.vim b/test/old/testdir/test_cjk_linebreak.vim new file mode 100644 index 0000000000..dfaa8fa1af --- /dev/null +++ b/test/old/testdir/test_cjk_linebreak.vim @@ -0,0 +1,97 @@ +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 diff --git a/test/old/testdir/test_clientserver.vim b/test/old/testdir/test_clientserver.vim new file mode 100644 index 0000000000..1c4b4732fe --- /dev/null +++ b/test/old/testdir/test_clientserver.vim @@ -0,0 +1,196 @@ +" 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 g:test_is_flaky = 1 + let cmd = GetVimCommand() + if cmd == '' + throw 'GetVimCommand() failed' + 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 Xclientfile<CR>"') + call assert_equal('2', remote_expr(name, 'winnr("$")')) + call assert_equal('Xclientfile', 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 Xclientfile1 Xclientfile2 Xclientfile3') + call assert_match(".*Xclientfile1\n.*Xclientfile2\n.*Xclientfile3\n", remote_expr(name, 'argv()')) + eval name->remote_send(":%bw!\<CR>") + + " Edit files in separate tab pages + call system(cmd .. ' --remote-tab Xclientfile1 Xclientfile2 Xclientfile3') + call WaitForAssert({-> assert_equal('3', remote_expr(name, 'tabpagenr("$")'))}) + call assert_match('.*\<Xclientfile2', 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 Xclientfile1') + call assert_match('.*\<Xclientfile1', remote_expr(name, 'bufname("#")')) + eval name->remote_send(":%bw!\<CR>") + + " Edit files using --remote-tab-wait + call system(cmd .. ' --remote-tabwait +tabonly\|enew Xclientfile1 Xclientfile2') + 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 diff --git a/test/old/testdir/test_close_count.vim b/test/old/testdir/test_close_count.vim new file mode 100644 index 0000000000..1f9adba32d --- /dev/null +++ b/test/old/testdir/test_close_count.vim @@ -0,0 +1,174 @@ + +" 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 diff --git a/test/old/testdir/test_cmdline.vim b/test/old/testdir/test_cmdline.vim new file mode 100644 index 0000000000..3f13218c5b --- /dev/null +++ b/test/old/testdir/test_cmdline.vim @@ -0,0 +1,3914 @@ +" Tests for editing the command line. + +source check.vim +source screendump.vim +source view_util.vim +source shared.vim + +func SetUp() + func SaveLastScreenLine() + let g:Sline = Screenline(&lines - 1) + return '' + endfunc + cnoremap <expr> <F4> SaveLastScreenLine() +endfunc + +func TearDown() + delfunc SaveLastScreenLine + cunmap <F4> +endfunc + +func Test_complete_tab() + call writefile(['testfile'], 'Xtestfile') + call feedkeys(":e Xtest\t\r", "tx") + call assert_equal('testfile', getline(1)) + + " Pressing <Tab> after '%' completes the current file, also on MS-Windows + call feedkeys(":e %\t\r", "tx") + call assert_equal('e Xtestfile', @:) + call delete('Xtestfile') +endfunc + +func Test_complete_list() + " We can't see the output, but at least we check the code runs properly. + call feedkeys(":e test\<C-D>\r", "tx") + call assert_equal('test', expand('%:t')) + + " If a command doesn't support completion, then CTRL-D should be literally + " used. + call feedkeys(":chistory \<C-D>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"chistory \<C-D>", @:) + + " Test for displaying the tail of the completion matches + set wildmode=longest,full + call mkdir('Xtest') + call writefile([], 'Xtest/a.c') + call writefile([], 'Xtest/a.h') + let g:Sline = '' + call feedkeys(":e Xtest/\<C-D>\<F4>\<C-B>\"\<CR>", 'xt') + call assert_equal('a.c a.h', g:Sline) + call assert_equal('"e Xtest/', @:) + if has('win32') + " Test for 'completeslash' + set completeslash=backslash + call feedkeys(":e Xtest\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xtest\', @:) + call feedkeys(":e Xtest/\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xtest\a.', @:) + set completeslash=slash + call feedkeys(":e Xtest\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xtest/', @:) + call feedkeys(":e Xtest\\\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xtest/a.', @:) + set completeslash& + endif + + " Test for displaying the tail with wildcards + let g:Sline = '' + call feedkeys(":e Xtes?/\<C-D>\<F4>\<C-B>\"\<CR>", 'xt') + call assert_equal('Xtest/a.c Xtest/a.h', g:Sline) + call assert_equal('"e Xtes?/', @:) + let g:Sline = '' + call feedkeys(":e Xtes*/\<C-D>\<F4>\<C-B>\"\<CR>", 'xt') + call assert_equal('Xtest/a.c Xtest/a.h', g:Sline) + call assert_equal('"e Xtes*/', @:) + let g:Sline = '' + call feedkeys(":e Xtes[/\<C-D>\<F4>\<C-B>\"\<CR>", 'xt') + call assert_equal(':e Xtes[/', g:Sline) + call assert_equal('"e Xtes[/', @:) + + call delete('Xtest', 'rf') + set wildmode& +endfunc + +func Test_complete_wildmenu() + call mkdir('Xwilddir1/Xdir2', 'pR') + call writefile(['testfile1'], 'Xwilddir1/Xtestfile1') + call writefile(['testfile2'], 'Xwilddir1/Xtestfile2') + call writefile(['testfile3'], 'Xwilddir1/Xdir2/Xtestfile3') + call writefile(['testfile3'], 'Xwilddir1/Xdir2/Xtestfile4') + set wildmenu + + " Pressing <Tab> completes, and moves to next files when pressing again. + call feedkeys(":e Xwilddir1/\<Tab>\<Tab>\<CR>", 'tx') + call assert_equal('testfile1', getline(1)) + call feedkeys(":e Xwilddir1/\<Tab>\<Tab>\<Tab>\<CR>", 'tx') + call assert_equal('testfile2', getline(1)) + + " <S-Tab> is like <Tab> but begin with the last match and then go to + " previous. + call feedkeys(":e Xwilddir1/Xtest\<S-Tab>\<CR>", 'tx') + call assert_equal('testfile2', getline(1)) + call feedkeys(":e Xwilddir1/Xtest\<S-Tab>\<S-Tab>\<CR>", 'tx') + call assert_equal('testfile1', getline(1)) + + " <Left>/<Right> to move to previous/next file. + call feedkeys(":e Xwilddir1/\<Tab>\<Right>\<CR>", 'tx') + call assert_equal('testfile1', getline(1)) + call feedkeys(":e Xwilddir1/\<Tab>\<Right>\<Right>\<CR>", 'tx') + call assert_equal('testfile2', getline(1)) + call feedkeys(":e Xwilddir1/\<Tab>\<Right>\<Right>\<Left>\<CR>", 'tx') + call assert_equal('testfile1', getline(1)) + + " <Up>/<Down> to go up/down directories. + call feedkeys(":e Xwilddir1/\<Tab>\<Down>\<CR>", 'tx') + call assert_equal('testfile3', getline(1)) + call feedkeys(":e Xwilddir1/\<Tab>\<Down>\<Up>\<Right>\<CR>", 'tx') + call assert_equal('testfile1', getline(1)) + + " this fails in some Unix GUIs, not sure why + if !has('unix') || !has('gui_running') + " <C-J>/<C-K> mappings to go up/down directories when 'wildcharm' is + " different than 'wildchar'. + set wildcharm=<C-Z> + cnoremap <C-J> <Down><C-Z> + cnoremap <C-K> <Up><C-Z> + call feedkeys(":e Xwilddir1/\<Tab>\<C-J>\<CR>", 'tx') + call assert_equal('testfile3', getline(1)) + call feedkeys(":e Xwilddir1/\<Tab>\<C-J>\<C-K>\<CR>", 'tx') + call assert_equal('testfile1', getline(1)) + set wildcharm=0 + cunmap <C-J> + cunmap <C-K> + endif + + " Test for canceling the wild menu by adding a character + redrawstatus + call feedkeys(":e Xwilddir1/\<Tab>x\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xwilddir1/Xdir2/x', @:) + + " Completion using a relative path + cd Xwilddir1/Xdir2 + call feedkeys(":e ../\<Tab>\<Right>\<Down>\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"e Xtestfile3 Xtestfile4', @:) + cd - + + " test for wildmenumode() + cnoremap <expr> <F2> wildmenumode() + call feedkeys(":cd Xwilddir\<Tab>\<F2>\<C-B>\"\<CR>", 'tx') + call assert_equal('"cd Xwilddir1/0', @:) + call feedkeys(":e Xwilddir1/\<Tab>\<F2>\<C-B>\"\<CR>", 'tx') + call assert_equal('"e Xwilddir1/Xdir2/1', @:) + cunmap <F2> + + " Test for canceling the wild menu by pressing <PageDown> or <PageUp>. + " After this pressing <Left> or <Right> should not change the selection. + call feedkeys(":sign \<Tab>\<PageDown>\<Left>\<Right>\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign define', @:) + call histadd('cmd', 'TestWildMenu') + call feedkeys(":sign \<Tab>\<PageUp>\<Left>\<Right>\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"TestWildMenu', @:) + + " Test for Ctrl-E/Ctrl-Y being able to cancel / accept a match + call feedkeys(":sign un zz\<Left>\<Left>\<Left>\<Tab>\<C-E> yy\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign un yy zz', @:) + + call feedkeys(":sign un zz\<Left>\<Left>\<Left>\<Tab>\<Tab>\<C-Y> yy\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign unplace yy zz', @:) + + " cleanup + %bwipe + set nowildmenu +endfunc + +func Test_wildmenu_screendump() + CheckScreendump + + let lines =<< trim [SCRIPT] + set wildmenu hlsearch + [SCRIPT] + call writefile(lines, 'XTest_wildmenu', 'D') + + " Test simple wildmenu + let buf = RunVimInTerminal('-S XTest_wildmenu', {'rows': 8}) + call term_sendkeys(buf, ":vim\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_1', {}) + + call term_sendkeys(buf, "\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_2', {}) + + call term_sendkeys(buf, "\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_3', {}) + + " Looped back to the original value + call term_sendkeys(buf, "\<Tab>\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_4', {}) + + " Test that the wild menu is cleared properly + call term_sendkeys(buf, " ") + call VerifyScreenDump(buf, 'Test_wildmenu_5', {}) + + " Test that a different wildchar still works + call term_sendkeys(buf, "\<Esc>:set wildchar=<Esc>\<CR>") + call term_sendkeys(buf, ":vim\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_1', {}) + + " Double-<Esc> is a hard-coded method to escape while wildchar=<Esc>. Make + " sure clean up is properly done in edge case like this. + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_6', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_redraw_in_autocmd() + CheckScreendump + + let lines =<< trim END + set cmdheight=2 + autocmd CmdlineChanged * redraw + END + call writefile(lines, 'XTest_redraw', 'D') + + let buf = RunVimInTerminal('-S XTest_redraw', {'rows': 8}) + call term_sendkeys(buf, ":for i in range(3)\<CR>") + call VerifyScreenDump(buf, 'Test_redraw_in_autocmd_1', {}) + + call term_sendkeys(buf, "let i =") + call VerifyScreenDump(buf, 'Test_redraw_in_autocmd_2', {}) + + " clean up + call term_sendkeys(buf, "\<CR>") + call StopVimInTerminal(buf) +endfunc + +func Test_redrawstatus_in_autocmd() + CheckScreendump + + let lines =<< trim END + set laststatus=2 + set statusline=%=:%{getcmdline()} + autocmd CmdlineChanged * redrawstatus + END + call writefile(lines, 'XTest_redrawstatus', 'D') + + let buf = RunVimInTerminal('-S XTest_redrawstatus', {'rows': 8}) + " :redrawstatus is postponed if messages have scrolled + call term_sendkeys(buf, ":echo \"one\\ntwo\\nthree\\nfour\"\<CR>") + call term_sendkeys(buf, ":foobar") + call VerifyScreenDump(buf, 'Test_redrawstatus_in_autocmd_1', {}) + " it is not postponed if messages have not scrolled + call term_sendkeys(buf, "\<Esc>:for in in range(3)") + call VerifyScreenDump(buf, 'Test_redrawstatus_in_autocmd_2', {}) + " with cmdheight=1 messages have scrolled when typing :endfor + call term_sendkeys(buf, "\<CR>:endfor") + call VerifyScreenDump(buf, 'Test_redrawstatus_in_autocmd_3', {}) + call term_sendkeys(buf, "\<CR>:set cmdheight=2\<CR>") + " with cmdheight=2 messages haven't scrolled when typing :for or :endfor + call term_sendkeys(buf, ":for in in range(3)") + call VerifyScreenDump(buf, 'Test_redrawstatus_in_autocmd_4', {}) + call term_sendkeys(buf, "\<CR>:endfor") + call VerifyScreenDump(buf, 'Test_redrawstatus_in_autocmd_5', {}) + + " clean up + call term_sendkeys(buf, "\<CR>") + call StopVimInTerminal(buf) +endfunc + +func Test_changing_cmdheight() + CheckScreendump + + let lines =<< trim END + set cmdheight=1 laststatus=2 + func EchoTwo() + set laststatus=2 + set cmdheight=5 + echo 'foo' + echo 'bar' + set cmdheight=1 + endfunc + END + call writefile(lines, 'XTest_cmdheight', 'D') + + let buf = RunVimInTerminal('-S XTest_cmdheight', {'rows': 8}) + call term_sendkeys(buf, ":resize -3\<CR>") + call VerifyScreenDump(buf, 'Test_changing_cmdheight_1', {}) + + " using the space available doesn't change the status line + call term_sendkeys(buf, ":set cmdheight+=3\<CR>") + call VerifyScreenDump(buf, 'Test_changing_cmdheight_2', {}) + + " using more space moves the status line up + call term_sendkeys(buf, ":set cmdheight+=1\<CR>") + call VerifyScreenDump(buf, 'Test_changing_cmdheight_3', {}) + + " reducing cmdheight moves status line down + call term_sendkeys(buf, ":set cmdheight-=2\<CR>") + call VerifyScreenDump(buf, 'Test_changing_cmdheight_4', {}) + + " reducing window size and then setting cmdheight + call term_sendkeys(buf, ":resize -1\<CR>") + call term_sendkeys(buf, ":set cmdheight=1\<CR>") + call VerifyScreenDump(buf, 'Test_changing_cmdheight_5', {}) + + " setting 'cmdheight' works after outputting two messages + call term_sendkeys(buf, ":call EchoTwo()\<CR>") + call VerifyScreenDump(buf, 'Test_changing_cmdheight_6', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_cmdheight_tabline() + CheckScreendump + + let buf = RunVimInTerminal('-c "set ls=2" -c "set stal=2" -c "set cmdheight=1"', {'rows': 6}) + call VerifyScreenDump(buf, 'Test_cmdheight_tabline_1', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_map_completion() + call feedkeys(":map <unique> <si\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <unique> <silent>', getreg(':')) + call feedkeys(":map <script> <un\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <script> <unique>', getreg(':')) + call feedkeys(":map <expr> <sc\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <expr> <script>', getreg(':')) + call feedkeys(":map <buffer> <e\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <buffer> <expr>', getreg(':')) + call feedkeys(":map <nowait> <b\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <nowait> <buffer>', getreg(':')) + call feedkeys(":map <special> <no\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <special> <nowait>', getreg(':')) + call feedkeys(":map <silent> <sp\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <silent> <special>', getreg(':')) + + map <Middle>x middle + + map ,f commaf + map ,g commaf + map <Left> left + map <A-Left>x shiftleft + call feedkeys(":map ,\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map ,f', getreg(':')) + call feedkeys(":map ,\<Tab>\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map ,g', getreg(':')) + call feedkeys(":map <L\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <Left>', getreg(':')) + call feedkeys(":map <A-Left>\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal("\"map <A-Left>\<Tab>", getreg(':')) + call feedkeys(":map <M-Left>\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal("\"map <M-Left>x", getreg(':')) + unmap ,f + unmap ,g + unmap <Left> + unmap <A-Left>x + + set cpo-=< cpo-=k + map <Left> left + call feedkeys(":map <L\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <Left>', getreg(':')) + call feedkeys(":map <M\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal("\"map <M\<Tab>", getreg(':')) + call feedkeys(":map \<C-V>\<C-V><M\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal("\"map \<C-V><Middle>x", getreg(':')) + unmap <Left> + + " set cpo+=< + map <Left> left + exe "set t_k6=\<Esc>[17~" + call feedkeys(":map \<Esc>[17~x f6x\<CR>", 'xt') + call feedkeys(":map <L\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <Left>', getreg(':')) + if !has('gui_running') + call feedkeys(":map \<Esc>[17~\<Tab>\<Home>\"\<CR>", 'xt') + " call assert_equal("\"map <F6>x", getreg(':')) + endif + unmap <Left> + call feedkeys(":unmap \<Esc>[17~x\<CR>", 'xt') + set cpo-=< + + set cpo+=B + map <Left> left + call feedkeys(":map <L\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <Left>', getreg(':')) + unmap <Left> + set cpo-=B + + " set cpo+=k + map <Left> left + call feedkeys(":map <L\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"map <Left>', getreg(':')) + unmap <Left> + set cpo-=k + + call assert_fails('call feedkeys(":map \\\\%(\<Tab>\<Home>\"\<CR>", "xt")', 'E53:') + + unmap <Middle>x + set cpo&vim +endfunc + +func Test_match_completion() + hi Aardig ctermfg=green + " call feedkeys(":match \<Tab>\<Home>\"\<CR>", 'xt') + call feedkeys(":match A\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"match Aardig', @:) + call feedkeys(":match \<S-Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"match none', @:) + call feedkeys(":match | chist\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"match | chistory', @:) +endfunc + +func Test_highlight_completion() + hi Aardig ctermfg=green + " call feedkeys(":hi \<Tab>\<Home>\"\<CR>", 'xt') + call feedkeys(":hi A\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"hi Aardig', getreg(':')) + " call feedkeys(":hi default \<Tab>\<Home>\"\<CR>", 'xt') + call feedkeys(":hi default A\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"hi default Aardig', getreg(':')) + call feedkeys(":hi clear Aa\<Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"hi clear Aardig', getreg(':')) + call feedkeys(":hi li\<S-Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"hi link', getreg(':')) + call feedkeys(":hi d\<S-Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"hi default', getreg(':')) + call feedkeys(":hi c\<S-Tab>\<Home>\"\<CR>", 'xt') + call assert_equal('"hi clear', getreg(':')) + + " A cleared group does not show up in completions. + hi Anders ctermfg=green + call assert_equal(['Aardig', 'Anders'], getcompletion('A', 'highlight')) + hi clear Aardig + call assert_equal(['Anders'], getcompletion('A', 'highlight')) + hi clear Anders + call assert_equal([], getcompletion('A', 'highlight')) +endfunc + +func Test_getcompletion() + let groupcount = len(getcompletion('', 'event')) + call assert_true(groupcount > 0) + let matchcount = len('File'->getcompletion('event')) + call assert_true(matchcount > 0) + call assert_true(groupcount > matchcount) + + if has('menu') + source $VIMRUNTIME/menu.vim + let matchcount = len(getcompletion('', 'menu')) + call assert_true(matchcount > 0) + call assert_equal(['File.'], getcompletion('File', 'menu')) + call assert_true(matchcount > 0) + let matchcount = len(getcompletion('File.', 'menu')) + call assert_true(matchcount > 0) + source $VIMRUNTIME/delmenu.vim + endif + + let l = getcompletion('v:n', 'var') + call assert_true(index(l, 'v:null') >= 0) + let l = getcompletion('v:notexists', 'var') + call assert_equal([], l) + + args a.c b.c + let l = getcompletion('', 'arglist') + call assert_equal(['a.c', 'b.c'], l) + let l = getcompletion('a.', 'buffer') + call assert_equal(['a.c'], l) + %argdelete + + let l = getcompletion('', 'augroup') + call assert_true(index(l, 'END') >= 0) + let l = getcompletion('blahblah', 'augroup') + call assert_equal([], l) + + " let l = getcompletion('', 'behave') + " call assert_true(index(l, 'mswin') >= 0) + " let l = getcompletion('not', 'behave') + " call assert_equal([], l) + + let l = getcompletion('', 'color') + call assert_true(index(l, 'default') >= 0) + let l = getcompletion('dirty', 'color') + call assert_equal([], l) + + let l = getcompletion('', 'command') + call assert_true(index(l, 'sleep') >= 0) + let l = getcompletion('awake', 'command') + call assert_equal([], l) + + let l = getcompletion('', 'dir') + call assert_true(index(l, 'sautest/') >= 0) + let l = getcompletion('NoMatch', 'dir') + call assert_equal([], l) + + if glob('~/*') !=# '' + let l = getcompletion('~/', 'dir') + call assert_true(l[0][0] ==# '~') + endif + + let l = getcompletion('exe', 'expression') + call assert_true(index(l, 'executable(') >= 0) + let l = getcompletion('kill', 'expression') + call assert_equal([], l) + + let l = getcompletion('tag', 'function') + call assert_true(index(l, 'taglist(') >= 0) + let l = getcompletion('paint', 'function') + call assert_equal([], l) + + let Flambda = {-> 'hello'} + let l = getcompletion('', 'function') + let l = filter(l, {i, v -> v =~ 'lambda'}) + call assert_equal(0, len(l)) + + let l = getcompletion('run', 'file') + call assert_true(index(l, 'runtest.vim') >= 0) + let l = getcompletion('walk', 'file') + call assert_equal([], l) + set wildignore=*.vim + let l = getcompletion('run', 'file', 1) + call assert_true(index(l, 'runtest.vim') < 0) + set wildignore& + " Directory name with space character + call mkdir('Xdir with space') + call assert_equal(['Xdir with space/'], getcompletion('Xdir\ w', 'shellcmd')) + call assert_equal(['./Xdir with space/'], getcompletion('./Xdir', 'shellcmd')) + call delete('Xdir with space', 'd') + + let l = getcompletion('ha', 'filetype') + call assert_true(index(l, 'hamster') >= 0) + let l = getcompletion('horse', 'filetype') + call assert_equal([], l) + + let l = getcompletion('z', 'syntax') + call assert_true(index(l, 'zimbu') >= 0) + let l = getcompletion('emacs', 'syntax') + call assert_equal([], l) + + let l = getcompletion('jikes', 'compiler') + call assert_true(index(l, 'jikes') >= 0) + let l = getcompletion('break', 'compiler') + call assert_equal([], l) + + let l = getcompletion('last', 'help') + call assert_true(index(l, ':tablast') >= 0) + let l = getcompletion('giveup', 'help') + call assert_equal([], l) + + let l = getcompletion('time', 'option') + call assert_true(index(l, 'timeoutlen') >= 0) + let l = getcompletion('space', 'option') + call assert_equal([], l) + + let l = getcompletion('er', 'highlight') + call assert_true(index(l, 'ErrorMsg') >= 0) + let l = getcompletion('dark', 'highlight') + call assert_equal([], l) + + let l = getcompletion('', 'messages') + call assert_true(index(l, 'clear') >= 0) + let l = getcompletion('not', 'messages') + call assert_equal([], l) + + let l = getcompletion('', 'mapclear') + call assert_true(index(l, '<buffer>') >= 0) + let l = getcompletion('not', 'mapclear') + call assert_equal([], l) + + let l = getcompletion('.', 'shellcmd') + call assert_equal(['./', '../'], filter(l, 'v:val =~ "\\./"')) + call assert_equal(-1, match(l[2:], '^\.\.\?/$')) + let root = has('win32') ? 'C:\\' : '/' + let l = getcompletion(root, 'shellcmd') + let expected = map(filter(glob(root . '*', 0, 1), + \ 'isdirectory(v:val) || executable(v:val)'), 'isdirectory(v:val) ? v:val . ''/'' : v:val') + call assert_equal(expected, l) + + if has('cscope') + let l = getcompletion('', 'cscope') + let cmds = ['add', 'find', 'help', 'kill', 'reset', 'show'] + call assert_equal(cmds, l) + " using cmdline completion must not change the result + call feedkeys(":cscope find \<c-d>\<c-c>", 'xt') + let l = getcompletion('', 'cscope') + call assert_equal(cmds, l) + let keys = ['a', 'c', 'd', 'e', 'f', 'g', 'i', 's', 't'] + let l = getcompletion('find ', 'cscope') + call assert_equal(keys, l) + endif + + if has('signs') + sign define Testing linehl=Comment + let l = getcompletion('', 'sign') + let cmds = ['define', 'jump', 'list', 'place', 'undefine', 'unplace'] + call assert_equal(cmds, l) + " using cmdline completion must not change the result + call feedkeys(":sign list \<c-d>\<c-c>", 'xt') + let l = getcompletion('', 'sign') + call assert_equal(cmds, l) + let l = getcompletion('list ', 'sign') + call assert_equal(['Testing'], l) + let l = getcompletion('de*', 'sign') + call assert_equal(['define'], l) + let l = getcompletion('p?', 'sign') + call assert_equal(['place'], l) + let l = getcompletion('j.', 'sign') + call assert_equal(['jump'], l) + endif + + " Command line completion tests + let l = getcompletion('cd ', 'cmdline') + call assert_true(index(l, 'samples/') >= 0) + let l = getcompletion('cd NoMatch', 'cmdline') + call assert_equal([], l) + let l = getcompletion('let v:n', 'cmdline') + call assert_true(index(l, 'v:null') >= 0) + let l = getcompletion('let v:notexists', 'cmdline') + call assert_equal([], l) + let l = getcompletion('call tag', 'cmdline') + call assert_true(index(l, 'taglist(') >= 0) + let l = getcompletion('call paint', 'cmdline') + call assert_equal([], l) + let l = getcompletion('autocmd BufEnter * map <bu', 'cmdline') + call assert_equal(['<buffer>'], l) + + func T(a, c, p) + let g:cmdline_compl_params = [a:a, a:c, a:p] + return "oneA\noneB\noneC" + endfunc + command -nargs=1 -complete=custom,T MyCmd + let l = getcompletion('MyCmd ', 'cmdline') + call assert_equal(['oneA', 'oneB', 'oneC'], l) + call assert_equal(['', 'MyCmd ', 6], g:cmdline_compl_params) + + delcommand MyCmd + delfunc T + unlet g:cmdline_compl_params + + " For others test if the name is recognized. + let names = ['buffer', 'environment', 'file_in_path', 'mapping', 'tag', 'tag_listfiles', 'user'] + if has('cmdline_hist') + call add(names, 'history') + endif + if has('gettext') + call add(names, 'locale') + endif + if has('profile') + call add(names, 'syntime') + endif + + set tags=Xtags + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", "word\tfile\tcmd"], 'Xtags') + + for name in names + let matchcount = len(getcompletion('', name)) + call assert_true(matchcount >= 0, 'No matches for ' . name) + endfor + + call delete('Xtags') + set tags& + + edit a~b + enew + call assert_equal(['a~b'], getcompletion('a~', 'buffer')) + bw a~b + + if has('unix') + edit Xtest\ + enew + call assert_equal(['Xtest\'], getcompletion('Xtest\', 'buffer')) + bw Xtest\ + endif + + call assert_fails("call getcompletion('\\\\@!\\\\@=', 'buffer')", 'E871:') + call assert_fails('call getcompletion("", "burp")', 'E475:') + call assert_fails('call getcompletion("abc", [])', 'E1174:') +endfunc + +" Test for getcompletion() with "fuzzy" in 'wildoptions' +func Test_getcompletion_wildoptions() + let save_wildoptions = &wildoptions + set wildoptions& + let l = getcompletion('space', 'option') + call assert_equal([], l) + let l = getcompletion('ier', 'command') + call assert_equal([], l) + set wildoptions=fuzzy + let l = getcompletion('space', 'option') + call assert_true(index(l, 'backspace') >= 0) + let l = getcompletion('ier', 'command') + call assert_true(index(l, 'compiler') >= 0) + let &wildoptions = save_wildoptions +endfunc + +func Test_fullcommand() + let tests = { + \ '': '', + \ ':': '', + \ ':::': '', + \ ':::5': '', + \ 'not_a_cmd': '', + \ 'Check': '', + \ 'syntax': 'syntax', + \ ':syntax': 'syntax', + \ '::::syntax': 'syntax', + \ 'sy': 'syntax', + \ 'syn': 'syntax', + \ 'synt': 'syntax', + \ ':sy': 'syntax', + \ '::::sy': 'syntax', + \ 'match': 'match', + \ '2match': 'match', + \ '3match': 'match', + \ 'aboveleft': 'aboveleft', + \ 'abo': 'aboveleft', + \ 's': 'substitute', + \ '5s': 'substitute', + \ ':5s': 'substitute', + \ "'<,'>s": 'substitute', + \ ":'<,'>s": 'substitute', + \ 'CheckUni': 'CheckUnix', + \ 'CheckUnix': 'CheckUnix', + \ } + + for [in, want] in items(tests) + call assert_equal(want, fullcommand(in)) + endfor + call assert_equal('', fullcommand(v:_null_string)) + + call assert_equal('syntax', 'syn'->fullcommand()) + + command -buffer BufferLocalCommand : + command GlobalCommand : + call assert_equal('GlobalCommand', fullcommand('GlobalCom')) + call assert_equal('BufferLocalCommand', fullcommand('BufferL')) + delcommand BufferLocalCommand + delcommand GlobalCommand +endfunc + +func Test_shellcmd_completion() + let save_path = $PATH + + call mkdir('Xpathdir/Xpathsubdir', 'pR') + call writefile([''], 'Xpathdir/Xfile.exe') + call setfperm('Xpathdir/Xfile.exe', 'rwx------') + + " Set PATH to example directory without trailing slash. + let $PATH = getcwd() . '/Xpathdir' + + " Test for the ":!<TAB>" case. Previously, this would include subdirs of + " dirs in the PATH, even though they won't be executed. We check that only + " subdirs of the PWD and executables from the PATH are included in the + " suggestions. + let actual = getcompletion('X', 'shellcmd') + let expected = map(filter(glob('*', 0, 1), 'isdirectory(v:val) && v:val[0] == "X"'), 'v:val . "/"') + call insert(expected, 'Xfile.exe') + call assert_equal(expected, actual) + + let $PATH = save_path +endfunc + +func Test_expand_star_star() + call mkdir('a/b/c', 'pR') + call writefile(['asdfasdf'], 'a/b/c/fileXname') + call feedkeys(":find a/**/fileXname\<Tab>\<CR>", 'xt') + call assert_equal('find a/b/c/fileXname', @:) + bwipe! +endfunc + +func Test_cmdline_paste() + let @a = "def" + call feedkeys(":abc \<C-R>a ghi\<C-B>\"\<CR>", 'tx') + call assert_equal('"abc def ghi', @:) + + new + call setline(1, 'asdf.x /tmp/some verylongword a;b-c*d ') + + call feedkeys(":aaa \<C-R>\<C-W> bbb\<C-B>\"\<CR>", 'tx') + call assert_equal('"aaa asdf bbb', @:) + + call feedkeys("ft:aaa \<C-R>\<C-F> bbb\<C-B>\"\<CR>", 'tx') + call assert_equal('"aaa /tmp/some bbb', @:) + + call feedkeys(":aaa \<C-R>\<C-L> bbb\<C-B>\"\<CR>", 'tx') + call assert_equal('"aaa '.getline(1).' bbb', @:) + + set incsearch + call feedkeys("fy:aaa veryl\<C-R>\<C-W> bbb\<C-B>\"\<CR>", 'tx') + call assert_equal('"aaa verylongword bbb', @:) + + call feedkeys("f;:aaa \<C-R>\<C-A> bbb\<C-B>\"\<CR>", 'tx') + call assert_equal('"aaa a;b-c*d bbb', @:) + + call feedkeys(":\<C-\>etoupper(getline(1))\<CR>\<C-B>\"\<CR>", 'tx') + call assert_equal('"ASDF.X /TMP/SOME VERYLONGWORD A;B-C*D ', @:) + bwipe! + + " Error while typing a command used to cause that it was not executed + " in the end. + new + try + call feedkeys(":file \<C-R>%Xtestfile\<CR>", 'tx') + catch /^Vim\%((\a\+)\)\=:E32/ + " ignore error E32 + endtry + call assert_equal("Xtestfile", bufname("%")) + + " Try to paste an invalid register using <C-R> + call feedkeys(":\"one\<C-R>\<C-X>two\<CR>", 'xt') + call assert_equal('"onetwo', @:) + + " Test for pasting register containing CTRL-H using CTRL-R and CTRL-R CTRL-R + let @a = "xy\<C-H>z" + call feedkeys(":\"\<C-R>a\<CR>", 'xt') + call assert_equal('"xz', @:) + call feedkeys(":\"\<C-R>\<C-R>a\<CR>", 'xt') + call assert_equal("\"xy\<C-H>z", @:) + call feedkeys(":\"\<C-R>\<C-O>a\<CR>", 'xt') + call assert_equal("\"xy\<C-H>z", @:) + + " Test for pasting register containing CTRL-V using CTRL-R and CTRL-R CTRL-R + let @a = "xy\<C-V>z" + call feedkeys(":\"\<C-R>=@a\<CR>\<cr>", 'xt') + call assert_equal('"xyz', @:) + call feedkeys(":\"\<C-R>\<C-R>=@a\<CR>\<cr>", 'xt') + call assert_equal("\"xy\<C-V>z", @:) + + call assert_beeps('call feedkeys(":\<C-R>=\<C-R>=\<Esc>", "xt")') + + bwipe! +endfunc + +func Test_cmdline_remove_char() + let encoding_save = &encoding + + " for e in ['utf8', 'latin1'] + for e in ['utf8'] + exe 'set encoding=' . e + + call feedkeys(":abc def\<S-Left>\<Del>\<C-B>\"\<CR>", 'tx') + call assert_equal('"abc ef', @:, e) + + call feedkeys(":abc def\<S-Left>\<BS>\<C-B>\"\<CR>", 'tx') + call assert_equal('"abcdef', @:) + + call feedkeys(":abc def ghi\<S-Left>\<C-W>\<C-B>\"\<CR>", 'tx') + call assert_equal('"abc ghi', @:, e) + + call feedkeys(":abc def\<S-Left>\<C-U>\<C-B>\"\<CR>", 'tx') + call assert_equal('"def', @:, e) + + " This was going before the start in latin1. + call feedkeys(": \<C-W>\<CR>", 'tx') + endfor + + let &encoding = encoding_save +endfunc + +func Test_cmdline_keymap_ctrl_hat() + if !has('keymap') + return + endif + + set keymap=esperanto + call feedkeys(":\"Jxauxdo \<C-^>Jxauxdo \<C-^>Jxauxdo\<CR>", 'tx') + call assert_equal('"Jxauxdo Ĵaŭdo Jxauxdo', @:) + set keymap= +endfunc + +func Test_illegal_address1() + new + 2;'( + 2;') + quit +endfunc + +func Test_illegal_address2() + call writefile(['c', 'x', ' x', '.', '1;y'], 'Xtest.vim') + new + source Xtest.vim + " Trigger calling validate_cursor() + diffsp Xtest.vim + quit! + bwipe! + call delete('Xtest.vim') +endfunc + +func Test_mark_from_line_zero() + " this was reading past the end of the first (empty) line + new + norm oxxxx + call assert_fails("0;'(", 'E20:') + bwipe! +endfunc + +func Test_cmdline_complete_wildoptions() + help + call feedkeys(":tag /\<c-a>\<c-b>\"\<cr>", 'tx') + let a = join(sort(split(@:)),' ') + set wildoptions=tagfile + call feedkeys(":tag /\<c-a>\<c-b>\"\<cr>", 'tx') + let b = join(sort(split(@:)),' ') + call assert_equal(a, b) + bw! +endfunc + +func Test_cmdline_complete_user_cmd() + command! -complete=color -nargs=1 Foo : + call feedkeys(":Foo \<Tab>\<Home>\"\<cr>", 'tx') + call assert_equal('"Foo blue', @:) + call feedkeys(":Foo b\<Tab>\<Home>\"\<cr>", 'tx') + call assert_equal('"Foo blue', @:) + call feedkeys(":Foo a b\<Tab>\<Home>\"\<cr>", 'tx') + call assert_equal('"Foo a blue', @:) + call feedkeys(":Foo b\\\<Tab>\<Home>\"\<cr>", 'tx') + call assert_equal('"Foo b\', @:) + call feedkeys(":Foo b\\x\<Tab>\<Home>\"\<cr>", 'tx') + call assert_equal('"Foo b\x', @:) + delcommand Foo + + redraw + call assert_equal('~', Screenline(&lines - 1)) + command! FooOne : + command! FooTwo : + + set nowildmenu + call feedkeys(":Foo\<Tab>\<Home>\"\<cr>", 'tx') + call assert_equal('"FooOne', @:) + call assert_equal('~', Screenline(&lines - 1)) + + call feedkeys(":Foo\<S-Tab>\<Home>\"\<cr>", 'tx') + call assert_equal('"FooTwo', @:) + call assert_equal('~', Screenline(&lines - 1)) + + delcommand FooOne + delcommand FooTwo + set wildmenu& +endfunc + +func Test_complete_user_cmd() + command FooBar echo 'global' + command -buffer FooBar echo 'local' + call feedkeys(":Foo\<C-A>\<Home>\"\<CR>", 'tx') + call assert_equal('"FooBar', @:) + + delcommand -buffer FooBar + delcommand FooBar +endfunc + +func s:ScriptLocalFunction() + echo 'yes' +endfunc + +func Test_cmdline_complete_user_func() + call feedkeys(":func Test_cmdline_complete_user\<Tab>\<Home>\"\<cr>", 'tx') + call assert_match('"func Test_cmdline_complete_user_', @:) + call feedkeys(":func s:ScriptL\<Tab>\<Home>\"\<cr>", 'tx') + call assert_match('"func <SNR>\d\+_ScriptLocalFunction', @:) + + " g: prefix also works + call feedkeys(":echo g:Test_cmdline_complete_user_f\<Tab>\<Home>\"\<cr>", 'tx') + call assert_match('"echo g:Test_cmdline_complete_user_func', @:) + + " using g: prefix does not result in just "g:" matches from a lambda + let Fx = { a -> a } + call feedkeys(":echo g:\<Tab>\<Home>\"\<cr>", 'tx') + call assert_match('"echo g:[A-Z]', @:) + + " existence of script-local dict function does not break user function name + " completion + function s:a_dict_func() dict + endfunction + call feedkeys(":call Test_cmdline_complete_user\<Tab>\<Home>\"\<cr>", 'tx') + call assert_match('"call Test_cmdline_complete_user_', @:) + delfunction s:a_dict_func +endfunc + +func Test_cmdline_complete_user_names() + if has('unix') && executable('whoami') + let whoami = systemlist('whoami')[0] + let first_letter = whoami[0] + if len(first_letter) > 0 + " Trying completion of :e ~x where x is the first letter of + " the user name should complete to at least the user name. + call feedkeys(':e ~' . first_letter . "\<c-a>\<c-B>\"\<cr>", 'tx') + call assert_match('^"e \~.*\<' . whoami . '\>', @:) + endif + endif + if has('win32') + " Just in case: check that the system has an Administrator account. + let names = system('net user') + if names =~ 'Administrator' + " Trying completion of :e ~A should complete to Administrator. + " There could be other names starting with "A" before Administrator. + call feedkeys(':e ~A' . "\<c-a>\<c-B>\"\<cr>", 'tx') + call assert_match('^"e \~.*Administrator', @:) + endif + endif +endfunc + +func Test_cmdline_complete_bang() + if executable('whoami') + call feedkeys(":!whoam\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_match('^".*\<whoami\>', @:) + endif +endfunc + +func Test_cmdline_complete_languages() + let lang = substitute(execute('language time'), '.*"\(.*\)"$', '\1', '') + call assert_equal(lang, v:lc_time) + + let lang = substitute(execute('language ctype'), '.*"\(.*\)"$', '\1', '') + call assert_equal(lang, v:ctype) + + let lang = substitute(execute('language collate'), '.*"\(.*\)"$', '\1', '') + call assert_equal(lang, v:collate) + + let lang = substitute(execute('language messages'), '.*"\(.*\)"$', '\1', '') + call assert_equal(lang, v:lang) + + call feedkeys(":language \<c-a>\<c-b>\"\<cr>", 'tx') + call assert_match('^"language .*\<collate\>.*\<ctype\>.*\<messages\>.*\<time\>', @:) + + if has('unix') + " TODO: these tests don't work on Windows. lang appears to be 'C' + " but C does not appear in the completion. Why? + call assert_match('^"language .*\<' . lang . '\>', @:) + + call feedkeys(":language messages \<c-a>\<c-b>\"\<cr>", 'tx') + call assert_match('^"language .*\<' . lang . '\>', @:) + + call feedkeys(":language ctype \<c-a>\<c-b>\"\<cr>", 'tx') + call assert_match('^"language .*\<' . lang . '\>', @:) + + call feedkeys(":language time \<c-a>\<c-b>\"\<cr>", 'tx') + call assert_match('^"language .*\<' . lang . '\>', @:) + + call feedkeys(":language collate \<c-a>\<c-b>\"\<cr>", 'tx') + call assert_match('^"language .*\<' . lang . '\>', @:) + endif +endfunc + +func Test_cmdline_complete_env_variable() + let $X_VIM_TEST_COMPLETE_ENV = 'foo' + call feedkeys(":edit $X_VIM_TEST_COMPLETE_E\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_match('"edit $X_VIM_TEST_COMPLETE_ENV', @:) + unlet $X_VIM_TEST_COMPLETE_ENV +endfunc + +func Test_cmdline_complete_expression() + let g:SomeVar = 'blah' + for cmd in ['exe', 'echo', 'echon', 'echomsg'] + call feedkeys(":" .. cmd .. " SomeV\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"' .. cmd .. ' SomeVar', @:) + call feedkeys(":" .. cmd .. " foo SomeV\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"' .. cmd .. ' foo SomeVar', @:) + endfor + unlet g:SomeVar +endfunc + +func Test_cmdline_complete_argopt() + " completion for ++opt=arg for file commands + call assert_equal('fileformat=', getcompletion('edit ++', 'cmdline')[0]) + call assert_equal('encoding=', getcompletion('read ++e', 'cmdline')[0]) + call assert_equal('edit', getcompletion('read ++bin ++edi', 'cmdline')[0]) + + call assert_equal(['fileformat='], getcompletion('edit ++ff', 'cmdline')) + " Test ++ff in the middle of the cmdline + call feedkeys(":edit ++ff zz\<Left>\<Left>\<Left>\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"edit ++fileformat= zz", @:) + + call assert_equal('dos', getcompletion('write ++ff=d', 'cmdline')[0]) + call assert_equal('mac', getcompletion('args ++fileformat=m', 'cmdline')[0]) + call assert_equal('utf-8', getcompletion('split ++enc=ut*-8', 'cmdline')[0]) + call assert_equal('latin1', getcompletion('tabedit ++encoding=lati', 'cmdline')[0]) + call assert_equal('keep', getcompletion('edit ++bad=k', 'cmdline')[0]) + + call assert_equal([], getcompletion('edit ++bogus=', 'cmdline')) + + " completion should skip the ++opt and continue + call writefile([], 'Xaaaaa.txt', 'D') + call feedkeys(":split ++enc=latin1 Xaaa\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"split ++enc=latin1 Xaaaaa.txt', @:) + + if has('terminal') + " completion for terminal's [options] + call assert_equal('close', getcompletion('terminal ++cl*e', 'cmdline')[0]) + call assert_equal('hidden', getcompletion('terminal ++open ++hidd', 'cmdline')[0]) + call assert_equal('term', getcompletion('terminal ++kill=ter', 'cmdline')[0]) + + call assert_equal([], getcompletion('terminal ++bogus=', 'cmdline')) + + " :terminal completion should skip the ++opt when considering what is the + " first option, which is a list of shell commands, unlike second option + " onwards. + let first_param = getcompletion('terminal ', 'cmdline') + let second_param = getcompletion('terminal foo ', 'cmdline') + let skipped_opt_param = getcompletion('terminal ++close ', 'cmdline') + call assert_equal(first_param, skipped_opt_param) + call assert_notequal(first_param, second_param) + endif +endfunc + +" Unique function name for completion below +func s:WeirdFunc() + echo 'weird' +endfunc + +" Test for various command-line completion +func Test_cmdline_complete_various() + " completion for a command starting with a comment + call feedkeys(": :|\"\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\" :|\"\<C-A>", @:) + + " completion for a range followed by a comment + call feedkeys(":1,2\"\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"1,2\"\<C-A>", @:) + + " completion for :k command + call feedkeys(":ka\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"ka\<C-A>", @:) + + " completion for short version of the :s command + call feedkeys(":sI \<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"sI \<C-A>", @:) + + " completion for :write command + call mkdir('Xcwdir') + call writefile(['one'], 'Xcwdir/Xfile1') + let save_cwd = getcwd() + cd Xcwdir + call feedkeys(":w >> \<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"w >> Xfile1", @:) + call chdir(save_cwd) + call delete('Xcwdir', 'rf') + + " completion for :w ! and :r ! commands + call feedkeys(":w !invalid_xyz_cmd\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"w !invalid_xyz_cmd", @:) + call feedkeys(":r !invalid_xyz_cmd\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"r !invalid_xyz_cmd", @:) + + " completion for :>> and :<< commands + call feedkeys(":>>>\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\">>>\<C-A>", @:) + call feedkeys(":<<<\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"<<<\<C-A>", @:) + + " completion for command with +cmd argument + call feedkeys(":buffer +/pat Xabc\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"buffer +/pat Xabc", @:) + call feedkeys(":buffer +/pat\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"buffer +/pat\<C-A>", @:) + + " completion for a command with a trailing comment + call feedkeys(":ls \" comment\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"ls \" comment\<C-A>", @:) + + " completion for a command with a trailing command + call feedkeys(":ls | ls\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"ls | ls", @:) + + " completion for a command with an CTRL-V escaped argument + call feedkeys(":ls \<C-V>\<C-V>a\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"ls \<C-V>a\<C-A>", @:) + + " completion for a command that doesn't take additional arguments + call feedkeys(":all abc\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"all abc\<C-A>", @:) + + " completion for :wincmd with :horizontal modifier + call feedkeys(":horizontal wincm\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"horizontal wincmd", @:) + + " completion for a command with a command modifier + call feedkeys(":topleft new\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"topleft new", @:) + + " completion for the :match command + call feedkeys(":match Search /pat/\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"match Search /pat/\<C-A>", @:) + + " completion for the :doautocmd command + call feedkeys(":doautocmd User MyCmd a.c\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"doautocmd User MyCmd a.c\<C-A>", @:) + + " completion of autocmd group after comma + call feedkeys(":doautocmd BufNew,BufEn\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"doautocmd BufNew,BufEnter", @:) + + " completion of file name in :doautocmd + call writefile([], 'Xvarfile1') + call writefile([], 'Xvarfile2') + call feedkeys(":doautocmd BufEnter Xvarfi\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"doautocmd BufEnter Xvarfile1 Xvarfile2", @:) + call delete('Xvarfile1') + call delete('Xvarfile2') + + " completion for the :augroup command + augroup XTest.test + augroup END + call feedkeys(":augroup X\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"augroup XTest.test", @:) + call feedkeys(":au X\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"au XTest.test", @:) + augroup! XTest.test + + " completion for the :unlet command + call feedkeys(":unlet one two\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"unlet one two", @:) + + " completion for the :buffer command with curlies + " FIXME: what should happen on MS-Windows? + if !has('win32') + edit \{someFile} + call feedkeys(":buf someFile\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"buf {someFile}", @:) + bwipe {someFile} + endif + + " completion for the :bdelete command + call feedkeys(":bdel a b c\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"bdel a b c", @:) + + " completion for the :mapclear command + call feedkeys(":mapclear \<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"mapclear <buffer>", @:) + + " completion for user defined commands with menu names + menu Test.foo :ls<CR> + com -nargs=* -complete=menu MyCmd + call feedkeys(":MyCmd Te\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"MyCmd Test.', @:) + delcom MyCmd + unmenu Test + + " completion for user defined commands with mappings + mapclear + map <F3> :ls<CR> + com -nargs=* -complete=mapping MyCmd + call feedkeys(":MyCmd <F\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"MyCmd <F3> <F4>', @:) + mapclear + delcom MyCmd + + " Prepare for path completion + call mkdir('Xa b c', 'D') + defer delete('Xcomma,foobar.txt') + call writefile([], 'Xcomma,foobar.txt') + + " completion for :set path= with multiple backslashes + call feedkeys(':set path=Xa\\\ b' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set path=Xa\\\ b\\\ c/', @:) + set path& + + " completion for :set dir= with a backslash + call feedkeys(':set dir=Xa\ b' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set dir=Xa\ b\ c/', @:) + set dir& + + " completion for :set tags= / set dictionary= with escaped commas + if has('win32') + " In Windows backslashes are rounded up, so both '\,' and '\\,' escape to + " '\,' + call feedkeys(':set dictionary=Xcomma\,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set dictionary=Xcomma\,foobar.txt', @:) + + call feedkeys(':set tags=Xcomma\\,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set tags=Xcomma\,foobar.txt', @:) + + call feedkeys(':set tags=Xcomma\\\,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set tags=Xcomma\\\,foo', @:) " Didn't find a match + + " completion for :set dictionary= with escaped commas (same behavior, but + " different internal code path from 'set tags=' for escaping the output) + call feedkeys(':set tags=Xcomma\\,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set tags=Xcomma\,foobar.txt', @:) + else + " In other platforms, backslashes are rounded down (since '\,' itself will + " be escaped into ','). As a result '\\,' and '\\\,' escape to '\,'. + call feedkeys(':set tags=Xcomma\,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set tags=Xcomma\,foo', @:) " Didn't find a match + + call feedkeys(':set tags=Xcomma\\,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set tags=Xcomma\\,foobar.txt', @:) + + call feedkeys(':set dictionary=Xcomma\\\,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set dictionary=Xcomma\\,foobar.txt', @:) + + " completion for :set dictionary= with escaped commas (same behavior, but + " different internal code path from 'set tags=' for escaping the output) + call feedkeys(':set dictionary=Xcomma\\,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set dictionary=Xcomma\\,foobar.txt', @:) + endif + set tags& + set dictionary& + + " completion for :set makeprg= with no escaped commas + call feedkeys(':set makeprg=Xcomma,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set makeprg=Xcomma,foobar.txt', @:) + + if !has('win32') + " Cannot create file with backslash in file name in Windows, so only test + " this elsewhere. + defer delete('Xcomma\,fooslash.txt') + call writefile([], 'Xcomma\,fooslash.txt') + call feedkeys(':set makeprg=Xcomma\\,foo' .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set makeprg=Xcomma\\,fooslash.txt', @:) + endif + set makeprg& + + " completion for the :py3 commands + call feedkeys(":py3\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"py3 py3do py3file', @:) + + " redir @" is not the start of a comment. So complete after that + call feedkeys(":redir @\" | cwin\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"redir @" | cwindow', @:) + + " completion after a backtick + call feedkeys(":e `a1b2c\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"e `a1b2c', @:) + + " completion for :language command with an invalid argument + call feedkeys(":language dummy \t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"language dummy \t", @:) + + " completion for commands after a :global command + call feedkeys(":g/a\\xb/clearj\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"g/a\xb/clearjumps', @:) + + " completion with ambiguous user defined commands + com TCmd1 echo 'TCmd1' + com TCmd2 echo 'TCmd2' + call feedkeys(":TCmd \t\<C-B>\"\<CR>", 'xt') + call assert_equal('"TCmd ', @:) + delcom TCmd1 + delcom TCmd2 + + " completion after a range followed by a pipe (|) character + call feedkeys(":1,10 | chist\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"1,10 | chistory', @:) + + " completion after a :global command + call feedkeys(":g/a/chist\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"g/a/chistory', @:) + call feedkeys(":g/a\\/chist\t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"g/a\\/chist\t", @:) + + " use <Esc> as the 'wildchar' for completion + set wildchar=<Esc> + call feedkeys(":g/a\\xb/clearj\<Esc>\<C-B>\"\<CR>", 'xt') + call assert_equal('"g/a\xb/clearjumps', @:) + " pressing <esc> twice should cancel the command + call feedkeys(":chist\<Esc>\<Esc>", 'xt') + call assert_equal('"g/a\xb/clearjumps', @:) + set wildchar& + + if has('unix') + " should be able to complete a file name that starts with a '~'. + call writefile([], '~Xtest') + call feedkeys(":e \\~X\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e \~Xtest', @:) + call delete('~Xtest') + + " should be able to complete a file name that has a '*' + call writefile([], 'Xx*Yy') + call feedkeys(":e Xx\*\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xx\*Yy', @:) + call delete('Xx*Yy') + + " use a literal star + call feedkeys(":e \\*\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e \*', @:) + endif + + call feedkeys(":py3f\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"py3file', @:) +endfunc + +" Test that expanding a pattern doesn't interfere with cmdline completion. +func Test_expand_during_cmdline_completion() + func ExpandStuff() + badd <script>:p:h/README.* + call assert_equal(expand('<script>:p:h') .. '/README.txt', bufname('$')) + $bwipe + call assert_equal('README.txt', expand('README.*')) + call assert_equal(['README.txt'], getcompletion('README.*', 'file')) + endfunc + augroup test_CmdlineChanged + autocmd! + autocmd CmdlineChanged * call ExpandStuff() + augroup END + + call feedkeys(":sign \<Tab>\<Tab>\<Tab>\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"sign place', @:) + + augroup test_CmdlineChanged + au! + augroup END + augroup! test_CmdlineChanged + delfunc ExpandStuff +endfunc + +" Test for 'wildignorecase' +func Test_cmdline_wildignorecase() + CheckUnix + call writefile([], 'XTEST') + set wildignorecase + call feedkeys(":e xt\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e XTEST', @:) + call assert_equal(['XTEST'], getcompletion('xt', 'file')) + let g:Sline = '' + call feedkeys(":e xt\<C-d>\<F4>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e xt', @:) + call assert_equal('XTEST', g:Sline) + set wildignorecase& + call delete('XTEST') +endfunc + +func Test_cmdline_write_alternatefile() + new + call setline('.', ['one', 'two']) + f foo.txt + new + f #-A + call assert_equal('foo.txt-A', expand('%')) + f #<-B.txt + call assert_equal('foo-B.txt', expand('%')) + f %< + call assert_equal('foo-B', expand('%')) + new + call assert_fails('f #<', 'E95') + bw! + f foo-B.txt + f %<-A + call assert_equal('foo-B-A', expand('%')) + bw! + bw! +endfunc + +func Test_cmdline_expand_cur_alt_file() + enew + file http://some.com/file.txt + call feedkeys(":e %\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e http://some.com/file.txt', @:) + edit another + call feedkeys(":e #\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e http://some.com/file.txt', @:) + bwipe + bwipe http://some.com/file.txt +endfunc + +" using a leading backslash here +set cpo+=C + +func Test_cmdline_search_range() + new + call setline(1, ['a', 'b', 'c', 'd']) + /d + 1,\/s/b/B/ + call assert_equal('B', getline(2)) + + /a + $ + \?,4s/c/C/ + call assert_equal('C', getline(3)) + + call setline(1, ['a', 'b', 'c', 'd']) + %s/c/c/ + 1,\&s/b/B/ + call assert_equal('B', getline(2)) + + let @/ = 'apple' + call assert_fails('\/print', ['E486:.*apple']) + + bwipe! +endfunc + +" Test for the tick mark (') in an excmd range +func Test_tick_mark_in_range() + " If only the tick is passed as a range and no command is specified, there + " should not be an error + call feedkeys(":'\<CR>", 'xt') + call assert_equal("'", @:) + call assert_fails("',print", 'E78:') +endfunc + +" Test for using a line number followed by a search pattern as range +func Test_lnum_and_pattern_as_range() + new + call setline(1, ['foo 1', 'foo 2', 'foo 3']) + let @" = '' + 2/foo/yank + call assert_equal("foo 3\n", @") + call assert_equal(1, line('.')) + close! +endfunc + +" Tests for getcmdline(), getcmdpos() and getcmdtype() +func Check_cmdline(cmdtype) + call assert_equal('MyCmd a', getcmdline()) + call assert_equal(8, getcmdpos()) + call assert_equal(a:cmdtype, getcmdtype()) + return '' +endfunc + +set cpo& + +func Test_getcmdtype() + call feedkeys(":MyCmd a\<C-R>=Check_cmdline(':')\<CR>\<Esc>", "xt") + + let cmdtype = '' + debuggreedy + call feedkeys(":debug echo 'test'\<CR>", "t") + call feedkeys("let cmdtype = \<C-R>=string(getcmdtype())\<CR>\<CR>", "t") + call feedkeys("cont\<CR>", "xt") + 0debuggreedy + call assert_equal('>', cmdtype) + + call feedkeys("/MyCmd a\<C-R>=Check_cmdline('/')\<CR>\<Esc>", "xt") + call feedkeys("?MyCmd a\<C-R>=Check_cmdline('?')\<CR>\<Esc>", "xt") + + call feedkeys(":call input('Answer?')\<CR>", "t") + call feedkeys("MyCmd a\<C-R>=Check_cmdline('@')\<CR>\<C-C>", "xt") + + call feedkeys(":insert\<CR>MyCmd a\<C-R>=Check_cmdline('-')\<CR>\<Esc>", "xt") + + cnoremap <expr> <F6> Check_cmdline('=') + call feedkeys("a\<C-R>=MyCmd a\<F6>\<Esc>\<Esc>", "xt") + cunmap <F6> + + call assert_equal('', getcmdline()) +endfunc + +func Test_getcmdwintype() + call feedkeys("q/:let a = getcmdwintype()\<CR>:q\<CR>", 'x!') + call assert_equal('/', a) + + call feedkeys("q?:let a = getcmdwintype()\<CR>:q\<CR>", 'x!') + call assert_equal('?', a) + + call feedkeys("q::let a = getcmdwintype()\<CR>:q\<CR>", 'x!') + call assert_equal(':', a) + + call feedkeys(":\<C-F>:let a = getcmdwintype()\<CR>:q\<CR>", 'x!') + call assert_equal(':', a) + + call assert_equal('', getcmdwintype()) +endfunc + +func Test_getcmdwin_autocmd() + let s:seq = [] + augroup CmdWin + au WinEnter * call add(s:seq, 'WinEnter ' .. win_getid()) + au WinLeave * call add(s:seq, 'WinLeave ' .. win_getid()) + au BufEnter * call add(s:seq, 'BufEnter ' .. bufnr()) + au BufLeave * call add(s:seq, 'BufLeave ' .. bufnr()) + au CmdWinEnter * call add(s:seq, 'CmdWinEnter ' .. win_getid()) + au CmdWinLeave * call add(s:seq, 'CmdWinLeave ' .. win_getid()) + + let org_winid = win_getid() + let org_bufnr = bufnr() + call feedkeys("q::let a = getcmdwintype()\<CR>:let s:cmd_winid = win_getid()\<CR>:let s:cmd_bufnr = bufnr()\<CR>:q\<CR>", 'x!') + call assert_equal(':', a) + call assert_equal([ + \ 'WinLeave ' .. org_winid, + \ 'WinEnter ' .. s:cmd_winid, + \ 'BufLeave ' .. org_bufnr, + \ 'BufEnter ' .. s:cmd_bufnr, + \ 'CmdWinEnter ' .. s:cmd_winid, + \ 'CmdWinLeave ' .. s:cmd_winid, + \ 'BufLeave ' .. s:cmd_bufnr, + \ 'WinLeave ' .. s:cmd_winid, + \ 'WinEnter ' .. org_winid, + \ 'BufEnter ' .. org_bufnr, + \ ], s:seq) + + au! + augroup END +endfunc + +func Test_verbosefile() + set verbosefile=Xlog + echomsg 'foo' + echomsg 'bar' + set verbosefile= + let log = readfile('Xlog') + call assert_match("foo\nbar", join(log, "\n")) + call delete('Xlog') + call mkdir('Xdir') + if !has('win32') " FIXME: no error on Windows, libuv bug? + call assert_fails('set verbosefile=Xdir', ['E484:.*Xdir', 'E474:']) + endif + call delete('Xdir', 'd') +endfunc + +func Test_verbose_option() + " See test/functional/legacy/cmdline_spec.lua + CheckScreendump + + let lines =<< trim [SCRIPT] + command DoSomething echo 'hello' |set ts=4 |let v = '123' |echo v + call feedkeys("\r", 't') " for the hit-enter prompt + set verbose=20 + [SCRIPT] + call writefile(lines, 'XTest_verbose') + + let buf = RunVimInTerminal('-S XTest_verbose', {'rows': 12}) + call TermWait(buf, 50) + call term_sendkeys(buf, ":DoSomething\<CR>") + call VerifyScreenDump(buf, 'Test_verbose_option_1', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XTest_verbose') +endfunc + +func Test_setcmdpos() + func InsertTextAtPos(text, pos) + call assert_equal(0, setcmdpos(a:pos)) + return a:text + endfunc + + " setcmdpos() with position in the middle of the command line. + call feedkeys(":\"12\<C-R>=InsertTextAtPos('a', 3)\<CR>b\<CR>", 'xt') + call assert_equal('"1ab2', @:) + + call feedkeys(":\"12\<C-R>\<C-R>=InsertTextAtPos('a', 3)\<CR>b\<CR>", 'xt') + call assert_equal('"1b2a', @:) + + " setcmdpos() with position beyond the end of the command line. + call feedkeys(":\"12\<C-B>\<C-R>=InsertTextAtPos('a', 10)\<CR>b\<CR>", 'xt') + call assert_equal('"12ab', @:) + + " setcmdpos() returns 1 when not editing the command line. + call assert_equal(1, 3->setcmdpos()) +endfunc + +func Test_cmdline_overstrike() + " Nvim: only utf8 is supported. + let encodings = ['utf8'] + let encoding_save = &encoding + + for e in encodings + exe 'set encoding=' . e + + " Test overstrike in the middle of the command line. + call feedkeys(":\"01234\<home>\<right>\<right>ab\<right>\<insert>cd\<enter>", 'xt') + call assert_equal('"0ab1cd4', @:, e) + + " Test overstrike going beyond end of command line. + call feedkeys(":\"01234\<home>\<right>\<right>ab\<right>\<insert>cdefgh\<enter>", 'xt') + call assert_equal('"0ab1cdefgh', @:, e) + + " Test toggling insert/overstrike a few times. + call feedkeys(":\"01234\<home>\<right>ab\<right>\<insert>cd\<right>\<insert>ef\<enter>", 'xt') + call assert_equal('"ab0cd3ef4', @:, e) + endfor + + " Test overstrike with multi-byte characters. + call feedkeys(":\"テキストエディタ\<home>\<right>\<right>ab\<right>\<insert>cd\<enter>", 'xt') + call assert_equal('"テabキcdエディタ', @:, e) + + let &encoding = encoding_save +endfunc + +func Test_cmdwin_bug() + let winid = win_getid() + sp + try + call feedkeys("q::call win_gotoid(" .. winid .. ")\<CR>:q\<CR>", 'x!') + catch /^Vim\%((\a\+)\)\=:E11/ + endtry + bw! +endfunc + +func Test_cmdwin_restore() + CheckScreendump + + let lines =<< trim [SCRIPT] + call setline(1, range(30)) + 2split + [SCRIPT] + call writefile(lines, 'XTest_restore') + + let buf = RunVimInTerminal('-S XTest_restore', {'rows': 12}) + call TermWait(buf, 50) + call term_sendkeys(buf, "q:") + call VerifyScreenDump(buf, 'Test_cmdwin_restore_1', {}) + + " normal restore + call term_sendkeys(buf, ":q\<CR>") + call VerifyScreenDump(buf, 'Test_cmdwin_restore_2', {}) + + " restore after setting 'lines' with one window + call term_sendkeys(buf, ":close\<CR>") + call term_sendkeys(buf, "q:") + call term_sendkeys(buf, ":set lines=18\<CR>") + call term_sendkeys(buf, ":q\<CR>") + call VerifyScreenDump(buf, 'Test_cmdwin_restore_3', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XTest_restore') +endfunc + +func Test_cmdwin_no_terminal() + CheckFeature cmdwin + CheckFeature terminal + CheckNotMSWindows + + let buf = RunVimInTerminal('', {'rows': 12}) + call TermWait(buf, 50) + call term_sendkeys(buf, ":set cmdheight=2\<CR>") + call term_sendkeys(buf, "q:") + call term_sendkeys(buf, ":let buf = term_start(['/bin/echo'], #{hidden: 1})\<CR>") + call VerifyScreenDump(buf, 'Test_cmdwin_no_terminal', {}) + call term_sendkeys(buf, ":q\<CR>") + call StopVimInTerminal(buf) +endfunc + +func Test_buffers_lastused() + " check that buffers are sorted by time when wildmode has lastused + edit bufc " oldest + + sleep 1200m + enew + edit bufa " middle + + sleep 1200m + enew + edit bufb " newest + + enew + + call assert_equal(['bufc', 'bufa', 'bufb'], + \ getcompletion('', 'buffer')) + + let save_wildmode = &wildmode + set wildmode=full:lastused + + let cap = "\<c-r>=execute('let X=getcmdline()')\<cr>" + call feedkeys(":b \<tab>" .. cap .. "\<esc>", 'xt') + call assert_equal('b bufb', X) + call feedkeys(":b \<tab>\<tab>" .. cap .. "\<esc>", 'xt') + call assert_equal('b bufa', X) + call feedkeys(":b \<tab>\<tab>\<tab>" .. cap .. "\<esc>", 'xt') + call assert_equal('b bufc', X) + enew + + sleep 1200m + edit other + call feedkeys(":b \<tab>" .. cap .. "\<esc>", 'xt') + call assert_equal('b bufb', X) + call feedkeys(":b \<tab>\<tab>" .. cap .. "\<esc>", 'xt') + call assert_equal('b bufa', X) + call feedkeys(":b \<tab>\<tab>\<tab>" .. cap .. "\<esc>", 'xt') + call assert_equal('b bufc', X) + enew + + let &wildmode = save_wildmode + + bwipeout bufa + bwipeout bufb + bwipeout bufc +endfunc + +func Test_cmdwin_feedkeys() + " This should not generate E488 + call feedkeys("q:\<CR>", 'x') + " Using feedkeys with q: only should automatically close the cmd window + call feedkeys('q:', 'xt') + call assert_equal(1, winnr('$')) + call assert_equal('', getcmdwintype()) +endfunc + +" Tests for the issues fixed in 7.4.441. +" When 'cedit' is set to Ctrl-C, opening the command window hangs Vim +func Test_cmdwin_cedit() + exe "set cedit=\<C-c>" + normal! : + call assert_equal(1, winnr('$')) + + let g:cmd_wintype = '' + func CmdWinType() + let g:cmd_wintype = getcmdwintype() + let g:wintype = win_gettype() + return '' + endfunc + + call feedkeys("\<C-c>a\<C-R>=CmdWinType()\<CR>\<CR>") + echo input('') + call assert_equal('@', g:cmd_wintype) + call assert_equal('command', g:wintype) + + set cedit&vim + delfunc CmdWinType +endfunc + +" Test for CmdwinEnter autocmd +func Test_cmdwin_autocmd() + CheckFeature cmdwin + + augroup CmdWin + au! + autocmd BufLeave * if &buftype == '' | update | endif + autocmd CmdwinEnter * startinsert + augroup END + + call assert_fails('call feedkeys("q:xyz\<CR>", "xt")', 'E492:') + call assert_equal('xyz', @:) + + augroup CmdWin + au! + augroup END + augroup! CmdWin +endfunc + +func Test_cmdlineclear_tabenter() + " See test/functional/legacy/cmdline_spec.lua + CheckScreendump + + let lines =<< trim [SCRIPT] + call setline(1, range(30)) + [SCRIPT] + + call writefile(lines, 'XtestCmdlineClearTabenter') + let buf = RunVimInTerminal('-S XtestCmdlineClearTabenter', #{rows: 10}) + call TermWait(buf, 25) + " in one tab make the command line higher with CTRL-W - + call term_sendkeys(buf, ":tabnew\<cr>\<C-w>-\<C-w>-gtgt") + call VerifyScreenDump(buf, 'Test_cmdlineclear_tabenter', {}) + + call StopVimInTerminal(buf) + call delete('XtestCmdlineClearTabenter') +endfunc + +" Test for expanding special keywords in cmdline +func Test_cmdline_expand_special() + new + %bwipe! + call assert_fails('e #', 'E194:') + call assert_fails('e <afile>', 'E495:') + call assert_fails('e <abuf>', 'E496:') + call assert_fails('e <amatch>', 'E497:') + + call writefile([], 'Xfile.cpp') + call writefile([], 'Xfile.java') + new Xfile.cpp + call feedkeys(":e %:r\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xfile.cpp Xfile.java', @:) + close + call delete('Xfile.cpp') + call delete('Xfile.java') +endfunc + +func Test_cmdwin_jump_to_win() + call assert_fails('call feedkeys("q:\<C-W>\<C-W>\<CR>", "xt")', 'E11:') + new + set modified + call assert_fails('call feedkeys("q/:qall\<CR>", "xt")', ['E37:', 'E162:']) + close! + call feedkeys("q/:close\<CR>", "xt") + call assert_equal(1, winnr('$')) + call feedkeys("q/:exit\<CR>", "xt") + call assert_equal(1, winnr('$')) + + " opening command window twice should fail + call assert_beeps('call feedkeys("q:q:\<CR>\<CR>", "xt")') + call assert_equal(1, winnr('$')) +endfunc + +func Test_cmdwin_tabpage() + tabedit + call assert_fails("silent norm q/g :I\<Esc>", 'E11:') + tabclose! +endfunc + +func Test_cmdwin_interrupted() + CheckScreendump + + " aborting the :smile output caused the cmdline window to use the current + " buffer. + let lines =<< trim [SCRIPT] + au WinNew * smile + [SCRIPT] + call writefile(lines, 'XTest_cmdwin') + + let buf = RunVimInTerminal('-S XTest_cmdwin', {'rows': 18}) + " open cmdwin + call term_sendkeys(buf, "q:") + call WaitForAssert({-> assert_match('-- More --', term_getline(buf, 18))}) + " quit more prompt for :smile command + call term_sendkeys(buf, "q") + call WaitForAssert({-> assert_match('^$', term_getline(buf, 18))}) + " execute a simple command + call term_sendkeys(buf, "aecho 'done'\<CR>") + call VerifyScreenDump(buf, 'Test_cmdwin_interrupted', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XTest_cmdwin') +endfunc + +" Test for backtick expression in the command line +func Test_cmd_backtick() + CheckNotMSWindows " FIXME: see #19297 + %argd + argadd `=['a', 'b', 'c']` + call assert_equal(['a', 'b', 'c'], argv()) + %argd + + argadd `echo abc def` + call assert_equal(['abc def'], argv()) + %argd +endfunc + +" Test for the :! command +func Test_cmd_bang() + CheckUnix + + let lines =<< trim [SCRIPT] + " Test for no previous command + call assert_fails('!!', 'E34:') + set nomore + " Test for cmdline expansion with :! + call setline(1, 'foo!') + silent !echo <cWORD> > Xfile.out + call assert_equal(['foo!'], readfile('Xfile.out')) + " Test for using previous command + silent !echo \! ! + call assert_equal(['! echo foo!'], readfile('Xfile.out')) + call writefile(v:errors, 'Xresult') + call delete('Xfile.out') + 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 error: "E135: *Filter* Autocommands must not change current buffer" +func Test_cmd_bang_E135() + new + call setline(1, ['a', 'b', 'c', 'd']) + augroup test_cmd_filter_E135 + au! + autocmd FilterReadPost * help + augroup END + call assert_fails('2,3!echo "x"', 'E135:') + + augroup test_cmd_filter_E135 + au! + augroup END + augroup! test_cmd_filter_E135 + %bwipe! +endfunc + +func Test_cmd_bang_args() + new + :.! + call assert_equal(0, v:shell_error) + + " Note that below there is one space char after the '!'. This caused a + " shell error in the past, see https://github.com/vim/vim/issues/11495. + :.! + call assert_equal(0, v:shell_error) + bwipe! + + CheckUnix + :.!pwd + call assert_equal(0, v:shell_error) + :.! pwd + call assert_equal(0, v:shell_error) + + " Note there is one space after 'pwd'. + :.! pwd + call assert_equal(0, v:shell_error) + + " Note there are two spaces after 'pwd'. + :.! pwd + call assert_equal(0, v:shell_error) + :.!ls ~ + call assert_equal(0, v:shell_error) + + " Note there is one space char after '~'. + :.!ls ~ + call assert_equal(0, v:shell_error) + + " Note there are two spaces after '~'. + :.!ls ~ + call assert_equal(0, v:shell_error) + + :.!echo "foo" + call assert_equal(getline('.'), "foo") + :.!echo "foo " + call assert_equal(getline('.'), "foo ") + :.!echo " foo " + call assert_equal(getline('.'), " foo ") + :.!echo " foo " + call assert_equal(getline('.'), " foo ") + + %bwipe! +endfunc + +" Test for using ~ for home directory in cmdline completion matches +func Test_cmdline_expand_home() + call mkdir('Xexpdir') + call writefile([], 'Xexpdir/Xfile1') + call writefile([], 'Xexpdir/Xfile2') + cd Xexpdir + let save_HOME = $HOME + let $HOME = getcwd() + call feedkeys(":e ~/\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e ~/Xfile1 ~/Xfile2', @:) + let $HOME = save_HOME + cd .. + call delete('Xexpdir', 'rf') +endfunc + +" Test for using CTRL-\ CTRL-G in the command line to go back to normal mode +" or insert mode (when 'insertmode' is set) +func Test_cmdline_ctrl_g() + new + call setline(1, 'abc') + call cursor(1, 3) + " If command line is entered from insert mode, using C-\ C-G should back to + " insert mode + call feedkeys("i\<C-O>:\<C-\>\<C-G>xy", 'xt') + call assert_equal('abxyc', getline(1)) + call assert_equal(4, col('.')) + + " If command line is entered in 'insertmode', using C-\ C-G should back to + " 'insertmode' + " call feedkeys(":set im\<cr>\<C-L>:\<C-\>\<C-G>12\<C-L>:set noim\<cr>", 'xt') + " call assert_equal('ab12xyc', getline(1)) + close! +endfunc + +" Test for 'wildmode' +func Wildmode_tests() + func T(a, c, p) + return "oneA\noneB\noneC" + endfunc + command -nargs=1 -complete=custom,T MyCmd + + set nowildmenu + set wildmode=full,list + let g:Sline = '' + call feedkeys(":MyCmd \t\t\<F4>\<C-B>\"\<CR>", 'xt') + call assert_equal('oneA oneB oneC', g:Sline) + call assert_equal('"MyCmd oneA', @:) + + set wildmode=longest,full + call feedkeys(":MyCmd o\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"MyCmd one', @:) + call feedkeys(":MyCmd o\t\t\t\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"MyCmd oneC', @:) + + set wildmode=longest + call feedkeys(":MyCmd one\t\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"MyCmd one', @:) + + set wildmode=list:longest + let g:Sline = '' + call feedkeys(":MyCmd \t\<F4>\<C-B>\"\<CR>", 'xt') + call assert_equal('oneA oneB oneC', g:Sline) + call assert_equal('"MyCmd one', @:) + + set wildmode="" + call feedkeys(":MyCmd \t\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"MyCmd oneA', @:) + + " Test for wildmode=longest with 'fileignorecase' set + set wildmode=longest + set fileignorecase + argadd AAA AAAA AAAAA + call feedkeys(":buffer a\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"buffer AAA', @:) + set fileignorecase& + + " Test for listing files with wildmode=list + set wildmode=list + let g:Sline = '' + call feedkeys(":b A\t\t\<F4>\<C-B>\"\<CR>", 'xt') + call assert_equal('AAA AAAA AAAAA', g:Sline) + call assert_equal('"b A', @:) + + " when using longest completion match, matches shorter than the argument + " should be ignored (happens with :help) + set wildmode=longest,full + set wildmenu + call feedkeys(":help a*\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"help a', @:) + " non existing file + call feedkeys(":e a1b2y3z4\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"e a1b2y3z4', @:) + set wildmenu& + + " Test for longest file name completion with 'fileignorecase' + " On MS-Windows, file names are case insensitive. + if has('unix') + call writefile([], 'XTESTfoo') + call writefile([], 'Xtestbar') + set nofileignorecase + call feedkeys(":e XT\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e XTESTfoo', @:) + call feedkeys(":e Xt\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xtestbar', @:) + set fileignorecase + call feedkeys(":e XT\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xtest', @:) + call feedkeys(":e Xt\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xtest', @:) + set fileignorecase& + call delete('XTESTfoo') + call delete('Xtestbar') + endif + + %argdelete + delcommand MyCmd + delfunc T + set wildmode& + %bwipe! +endfunc + +func Test_wildmode() + " Test with utf-8 encoding + call Wildmode_tests() + + " Test with latin1 encoding + let save_encoding = &encoding + " set encoding=latin1 + " call Wildmode_tests() + let &encoding = save_encoding +endfunc + +func Test_custom_complete_autoload() + call mkdir('Xcustdir/autoload', 'p') + let save_rtp = &rtp + exe 'set rtp=' .. getcwd() .. '/Xcustdir' + let lines =<< trim END + func vim8#Complete(a, c, p) + return "oneA\noneB\noneC" + endfunc + END + call writefile(lines, 'Xcustdir/autoload/vim8.vim') + + command -nargs=1 -complete=custom,vim8#Complete MyCmd + set nowildmenu + set wildmode=full,list + call feedkeys(":MyCmd \<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"MyCmd oneA oneB oneC', @:) + + let &rtp = save_rtp + set wildmode& wildmenu& + delcommand MyCmd + call delete('Xcustdir', 'rf') +endfunc + +" Test for interrupting the command-line completion +func Test_interrupt_compl() + func F(lead, cmdl, p) + if a:lead =~ 'tw' + call interrupt() + return + endif + return "one\ntwo\nthree" + endfunc + command -nargs=1 -complete=custom,F Tcmd + + set nowildmenu + set wildmode=full + let interrupted = 0 + try + call feedkeys(":Tcmd tw\<Tab>\<C-B>\"\<CR>", 'xt') + catch /^Vim:Interrupt$/ + let interrupted = 1 + endtry + call assert_equal(1, interrupted) + + let interrupted = 0 + try + call feedkeys(":Tcmd tw\<C-d>\<C-B>\"\<CR>", 'xt') + catch /^Vim:Interrupt$/ + let interrupted = 1 + endtry + call assert_equal(1, interrupted) + + delcommand Tcmd + delfunc F + set wildmode& +endfunc + +" Test for moving the cursor on the : command line +func Test_cmdline_edit() + let str = ":one two\<C-U>" + let str ..= "one two\<C-W>\<C-W>" + let str ..= "four\<BS>\<C-H>\<Del>\<kDel>" + let str ..= "\<Left>five\<Right>" + let str ..= "\<Home>two " + let str ..= "\<C-Left>one " + let str ..= "\<C-Right> three" + let str ..= "\<End>\<S-Left>four " + let str ..= "\<S-Right> six" + let str ..= "\<C-B>\"\<C-E> seven\<CR>" + call feedkeys(str, 'xt') + call assert_equal("\"one two three four five six seven", @:) +endfunc + +" Test for moving the cursor on the / command line in 'rightleft' mode +func Test_cmdline_edit_rightleft() + CheckFeature rightleft + set rightleft + set rightleftcmd=search + let str = "/one two\<C-U>" + let str ..= "one two\<C-W>\<C-W>" + let str ..= "four\<BS>\<C-H>\<Del>\<kDel>" + let str ..= "\<Right>five\<Left>" + let str ..= "\<Home>two " + let str ..= "\<C-Right>one " + let str ..= "\<C-Left> three" + let str ..= "\<End>\<S-Right>four " + let str ..= "\<S-Left> six" + let str ..= "\<C-B>\"\<C-E> seven\<CR>" + call assert_fails("call feedkeys(str, 'xt')", 'E486:') + call assert_equal("\"one two three four five six seven", @/) + set rightleftcmd& + set rightleft& +endfunc + +" Test for using <C-\>e in the command line to evaluate an expression +func Test_cmdline_expr() + " Evaluate an expression from the beginning of a command line + call feedkeys(":abc\<C-B>\<C-\>e\"\\\"hello\"\<CR>\<CR>", 'xt') + call assert_equal('"hello', @:) + + " Use an invalid expression for <C-\>e + call assert_beeps('call feedkeys(":\<C-\>einvalid\<CR>", "tx")') + + " Insert literal <CTRL-\> in the command line + call feedkeys(":\"e \<C-\>\<C-Y>\<CR>", 'xt') + call assert_equal("\"e \<C-\>\<C-Y>", @:) +endfunc + +" This was making the insert position negative +func Test_cmdline_expr_register() + exe "sil! norm! ?\<C-\>e0\<C-R>0\<Esc>?\<C-\>e0\<CR>" +endfunc + +" Test for 'imcmdline' and 'imsearch' +" This test doesn't actually test the input method functionality. +func Test_cmdline_inputmethod() + new + call setline(1, ['', 'abc', '']) + set imcmdline + + call feedkeys(":\"abc\<CR>", 'xt') + call assert_equal("\"abc", @:) + call feedkeys(":\"\<C-^>abc\<C-^>\<CR>", 'xt') + call assert_equal("\"abc", @:) + call feedkeys("/abc\<CR>", 'xt') + call assert_equal([2, 1], [line('.'), col('.')]) + call feedkeys("/\<C-^>abc\<C-^>\<CR>", 'xt') + call assert_equal([2, 1], [line('.'), col('.')]) + + " set imsearch=2 + call cursor(1, 1) + call feedkeys("/abc\<CR>", 'xt') + call assert_equal([2, 1], [line('.'), col('.')]) + call cursor(1, 1) + call feedkeys("/\<C-^>abc\<C-^>\<CR>", 'xt') + call assert_equal([2, 1], [line('.'), col('.')]) + set imdisable + call feedkeys("/\<C-^>abc\<C-^>\<CR>", 'xt') + call assert_equal([2, 1], [line('.'), col('.')]) + set imdisable& + set imsearch& + + set imcmdline& + %bwipe! +endfunc + +" Test for recursively getting multiple command line inputs +func Test_cmdwin_multi_input() + call feedkeys(":\<C-R>=input('P: ')\<CR>\"cyan\<CR>\<CR>", 'xt') + call assert_equal('"cyan', @:) +endfunc + +" Test for using CTRL-_ in the command line with 'allowrevins' +func Test_cmdline_revins() + CheckNotMSWindows + CheckFeature rightleft + call feedkeys(":\"abc\<c-_>\<cr>", 'xt') + call assert_equal("\"abc\<c-_>", @:) + set allowrevins + call feedkeys(":\"abc\<c-_>xyz\<c-_>\<CR>", 'xt') + " call assert_equal('"abcñèæ', @:) + call assert_equal('"abcxyz', @:) + set allowrevins& +endfunc + +" Test for typing UTF-8 composing characters in the command line +func Test_cmdline_composing_chars() + call feedkeys(":\"\<C-V>u3046\<C-V>u3099\<CR>", 'xt') + call assert_equal('"ゔ', @:) +endfunc + +" Test for normal mode commands not supported in the cmd window +func Test_cmdwin_blocked_commands() + call assert_fails('call feedkeys("q:\<C-T>\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-]>\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-^>\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:Q\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:Z\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<F1>\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>s\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>v\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>^\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>n\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>z\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>o\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>w\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>j\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>k\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>h\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>l\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>T\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>x\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>r\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>R\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>K\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>}\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>]\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>f\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>d\<CR>", "xt")', 'E11:') + call assert_fails('call feedkeys("q:\<C-W>g\<CR>", "xt")', 'E11:') +endfunc + +" Close the Cmd-line window in insert mode using CTRL-C +func Test_cmdwin_insert_mode_close() + %bw! + let s = '' + exe "normal q:a\<C-C>let s='Hello'\<CR>" + call assert_equal('Hello', s) + call assert_equal(1, winnr('$')) +endfunc + +" test that ";" works to find a match at the start of the first line +func Test_zero_line_search() + new + call setline(1, ["1, pattern", "2, ", "3, pattern"]) + call cursor(1,1) + 0;/pattern/d + call assert_equal(["2, ", "3, pattern"], getline(1,'$')) + q! +endfunc + +func Test_read_shellcmd() + CheckUnix + if executable('ls') + " There should be ls in the $PATH + call feedkeys(":r! l\<c-a>\<c-b>\"\<cr>", 'tx') + call assert_match('^"r! .*\<ls\>', @:) + endif + + if executable('rm') + call feedkeys(":r! ++enc=utf-8 r\<c-a>\<c-b>\"\<cr>", 'tx') + call assert_notmatch('^"r!.*\<runtest.vim\>', @:) + call assert_match('^"r!.*\<rm\>', @:) + + call feedkeys(":r ++enc=utf-8 !rm\<c-a>\<c-b>\"\<cr>", 'tx') + call assert_notmatch('^"r.*\<runtest.vim\>', @:) + call assert_match('^"r ++enc\S\+ !.*\<rm\>', @:) + endif +endfunc + +" Test for going up and down the directory tree using 'wildmenu' +func Test_wildmenu_dirstack() + CheckUnix + %bw! + call mkdir('Xdir1/dir2/dir3/dir4', 'p') + call writefile([], 'Xdir1/file1_1.txt') + call writefile([], 'Xdir1/file1_2.txt') + call writefile([], 'Xdir1/dir2/file2_1.txt') + call writefile([], 'Xdir1/dir2/file2_2.txt') + call writefile([], 'Xdir1/dir2/dir3/file3_1.txt') + call writefile([], 'Xdir1/dir2/dir3/file3_2.txt') + call writefile([], 'Xdir1/dir2/dir3/dir4/file4_1.txt') + call writefile([], 'Xdir1/dir2/dir3/dir4/file4_2.txt') + set wildmenu + + cd Xdir1/dir2/dir3/dir4 + call feedkeys(":e \<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e file4_1.txt', @:) + call feedkeys(":e \<Tab>\<Up>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e ../dir4/', @:) + call feedkeys(":e \<Tab>\<Up>\<Up>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e ../../dir3/', @:) + call feedkeys(":e \<Tab>\<Up>\<Up>\<Up>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e ../../../dir2/', @:) + call feedkeys(":e \<Tab>\<Up>\<Up>\<Down>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e ../../dir3/dir4/', @:) + call feedkeys(":e \<Tab>\<Up>\<Up>\<Down>\<Down>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e ../../dir3/dir4/file4_1.txt', @:) + cd - + call feedkeys(":e Xdir1/\<Tab>\<Down>\<Down>\<Down>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xdir1/dir2/dir3/dir4/file4_1.txt', @:) + + call delete('Xdir1', 'rf') + set wildmenu& +endfunc + +" Test for recalling newer or older cmdline from history with <Up>, <Down>, +" <S-Up>, <S-Down>, <PageUp>, <PageDown>, <kPageUp>, <kPageDown>, <C-p>, or +" <C-n>. +func Test_recalling_cmdline() + CheckFeature cmdline_hist + + let g:cmdlines = [] + cnoremap <Plug>(save-cmdline) <Cmd>let g:cmdlines += [getcmdline()]<CR> + + let histories = [ + \ #{name: 'cmd', enter: ':', exit: "\<Esc>"}, + \ #{name: 'search', enter: '/', exit: "\<Esc>"}, + \ #{name: 'expr', enter: ":\<C-r>=", exit: "\<Esc>\<Esc>"}, + \ #{name: 'input', enter: ":call input('')\<CR>", exit: "\<CR>"}, + "\ TODO: {'name': 'debug', ...} + \] + let keypairs = [ + \ #{older: "\<Up>", newer: "\<Down>", prefixmatch: v:true}, + \ #{older: "\<S-Up>", newer: "\<S-Down>", prefixmatch: v:false}, + \ #{older: "\<PageUp>", newer: "\<PageDown>", prefixmatch: v:false}, + \ #{older: "\<kPageUp>", newer: "\<kPageDown>", prefixmatch: v:false}, + \ #{older: "\<C-p>", newer: "\<C-n>", prefixmatch: v:false}, + \] + let prefix = 'vi' + for h in histories + call histadd(h.name, 'vim') + call histadd(h.name, 'virtue') + call histadd(h.name, 'Virgo') + call histadd(h.name, 'vogue') + call histadd(h.name, 'emacs') + for k in keypairs + let g:cmdlines = [] + let keyseqs = h.enter + \ .. prefix + \ .. repeat(k.older .. "\<Plug>(save-cmdline)", 2) + \ .. repeat(k.newer .. "\<Plug>(save-cmdline)", 2) + \ .. h.exit + call feedkeys(keyseqs, 'xt') + call histdel(h.name, -1) " delete the history added by feedkeys above + let expect = k.prefixmatch + \ ? ['virtue', 'vim', 'virtue', prefix] + \ : ['emacs', 'vogue', 'emacs', prefix] + call assert_equal(expect, g:cmdlines) + endfor + endfor + + unlet g:cmdlines + cunmap <Plug>(save-cmdline) +endfunc + +func Test_cmd_map_cmdlineChanged() + let g:log = [] + cnoremap <F1> l<Cmd><CR>s + augroup test_CmdlineChanged + autocmd! + autocmd CmdlineChanged : let g:log += [getcmdline()] + augroup END + + call feedkeys(":\<F1>\<CR>", 'xt') + call assert_equal(['l', 'ls'], g:log) + + let @b = 'b' + cnoremap <F1> a<C-R>b + let g:log = [] + call feedkeys(":\<F1>\<CR>", 'xt') + call assert_equal(['a', 'ab'], g:log) + + unlet g:log + cunmap <F1> + augroup test_CmdlineChanged + autocmd! + augroup END + augroup! test_CmdlineChanged +endfunc + +" Test for the 'suffixes' option +func Test_suffixes_opt() + call writefile([], 'Xsuffile') + call writefile([], 'Xsuffile.c') + call writefile([], 'Xsuffile.o') + set suffixes= + call feedkeys(":e Xsuffi*\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xsuffile Xsuffile.c Xsuffile.o', @:) + call feedkeys(":e Xsuffi*\<Tab>\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xsuffile.c', @:) + set suffixes=.c + call feedkeys(":e Xsuffi*\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xsuffile Xsuffile.o Xsuffile.c', @:) + call feedkeys(":e Xsuffi*\<Tab>\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xsuffile.o', @:) + set suffixes=,, + call feedkeys(":e Xsuffi*\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xsuffile.c Xsuffile.o Xsuffile', @:) + call feedkeys(":e Xsuffi*\<Tab>\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"e Xsuffile.o', @:) + set suffixes& + " Test for getcompletion() with different patterns + call assert_equal(['Xsuffile', 'Xsuffile.c', 'Xsuffile.o'], getcompletion('Xsuffile', 'file')) + call assert_equal(['Xsuffile'], getcompletion('Xsuffile$', 'file')) + call delete('Xsuffile') + call delete('Xsuffile.c') + call delete('Xsuffile.o') +endfunc + +" Test for using a popup menu for the command line completion matches +" (wildoptions=pum) +func Test_wildmenu_pum() + CheckRunVimInTerminal + + let commands =<< trim [CODE] + set wildmenu + set wildoptions=pum + set shm+=I + set noruler + set noshowcmd + + func CmdCompl(a, b, c) + return repeat(['aaaa'], 120) + endfunc + command -nargs=* -complete=customlist,CmdCompl Tcmd + + func MyStatusLine() abort + return 'status' + endfunc + func SetupStatusline() + set statusline=%!MyStatusLine() + set laststatus=2 + endfunc + + func MyTabLine() + return 'my tab line' + endfunc + func SetupTabline() + set statusline= + set tabline=%!MyTabLine() + set showtabline=2 + endfunc + + func DoFeedKeys() + let &wildcharm = char2nr("\t") + call feedkeys(":edit $VIMRUNTIME/\<Tab>\<Left>\<C-U>ab\<Tab>") + endfunc + [CODE] + call writefile(commands, 'Xtest', 'D') + + let buf = RunVimInTerminal('-S Xtest', #{rows: 10}) + + call term_sendkeys(buf, ":sign \<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_01', {}) + + " going down the popup menu using <Down> + call term_sendkeys(buf, "\<Down>\<Down>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_02', {}) + + " going down the popup menu using <C-N> + call term_sendkeys(buf, "\<C-N>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_03', {}) + + " going up the popup menu using <C-P> + call term_sendkeys(buf, "\<C-P>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_04', {}) + + " going up the popup menu using <Up> + call term_sendkeys(buf, "\<Up>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_05', {}) + + " pressing <C-E> should end completion and go back to the original match + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_06', {}) + + " pressing <C-Y> should select the current match and end completion + call term_sendkeys(buf, "\<Tab>\<C-P>\<C-P>\<C-Y>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_07', {}) + + " With 'wildmode' set to 'longest,full', completing a match should display + " the longest match, the wildmenu should not be displayed. + call term_sendkeys(buf, ":\<C-U>set wildmode=longest,full\<CR>") + call TermWait(buf) + call term_sendkeys(buf, ":sign u\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_08', {}) + + " pressing <Tab> should display the wildmenu + call term_sendkeys(buf, "\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_09', {}) + + " pressing <Tab> second time should select the next entry in the menu + call term_sendkeys(buf, "\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_10', {}) + + call term_sendkeys(buf, ":\<C-U>set wildmode=full\<CR>") + " showing popup menu in different columns in the cmdline + call term_sendkeys(buf, ":sign define \<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_11', {}) + + call term_sendkeys(buf, " \<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_12', {}) + + call term_sendkeys(buf, " \<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_13', {}) + + " Directory name completion + call mkdir('Xnamedir/XdirA/XdirB', 'pR') + call writefile([], 'Xnamedir/XfileA') + call writefile([], 'Xnamedir/XdirA/XfileB') + call writefile([], 'Xnamedir/XdirA/XdirB/XfileC') + + call term_sendkeys(buf, "\<C-U>e Xnamedi\<Tab>\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_14', {}) + + " Pressing <Right> on a directory name should go into that directory + call term_sendkeys(buf, "\<Right>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_15', {}) + + " Pressing <Left> on a directory name should go to the parent directory + call term_sendkeys(buf, "\<Left>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_16', {}) + + " Pressing <C-A> when the popup menu is displayed should list all the + " matches but the popup menu should still remain + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<C-A>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_17', {}) + + " Pressing <C-D> when the popup menu is displayed should remove the popup + " menu + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<C-D>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_18', {}) + + " Pressing <S-Tab> should open the popup menu with the last entry selected + call term_sendkeys(buf, "\<C-U>\<CR>:sign \<S-Tab>\<C-P>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_19', {}) + + " Pressing <Esc> should close the popup menu and cancel the cmd line + call term_sendkeys(buf, "\<C-U>\<CR>:sign \<Tab>\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_20', {}) + + " Typing a character when the popup is open, should close the popup + call term_sendkeys(buf, ":sign \<Tab>x") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_21', {}) + + " When the popup is open, entering the cmdline window should close the popup + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<C-F>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_22', {}) + call term_sendkeys(buf, ":q\<CR>") + + " After the last popup menu item, <C-N> should show the original string + call term_sendkeys(buf, ":sign u\<Tab>\<C-N>\<C-N>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_23', {}) + + " Use the popup menu for the command name + call term_sendkeys(buf, "\<C-U>bu\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_24', {}) + + " Pressing the left arrow should remove the popup menu + call term_sendkeys(buf, "\<Left>\<Left>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_25', {}) + + " Pressing <BS> should remove the popup menu and erase the last character + call term_sendkeys(buf, "\<C-E>\<C-U>sign \<Tab>\<BS>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_26', {}) + + " Pressing <C-W> should remove the popup menu and erase the previous word + call term_sendkeys(buf, "\<C-E>\<C-U>sign \<Tab>\<C-W>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_27', {}) + + " Pressing <C-U> should remove the popup menu and erase the entire line + call term_sendkeys(buf, "\<C-E>\<C-U>sign \<Tab>\<C-U>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_28', {}) + + " Using <C-E> to cancel the popup menu and then pressing <Up> should recall + " the cmdline from history + call term_sendkeys(buf, "sign xyz\<Esc>:sign \<Tab>\<C-E>\<Up>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_29', {}) + + " Check "list" still works + call term_sendkeys(buf, "\<C-U>set wildmode=longest,list\<CR>") + call term_sendkeys(buf, ":cn\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_30', {}) + call term_sendkeys(buf, "s") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_31', {}) + + " Tests a directory name contained full-width characters. + call mkdir('Xnamedir/あいう', 'p') + call writefile([], 'Xnamedir/あいう/abc') + call writefile([], 'Xnamedir/あいう/xyz') + call writefile([], 'Xnamedir/あいう/123') + + call term_sendkeys(buf, "\<C-U>set wildmode&\<CR>") + call term_sendkeys(buf, ":\<C-U>e Xnamedir/あいう/\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_32', {}) + + " Pressing <C-A> when the popup menu is displayed should list all the + " matches and pressing a key after that should remove the popup menu + call term_sendkeys(buf, "\<C-U>set wildmode=full\<CR>") + call term_sendkeys(buf, ":sign \<Tab>\<C-A>x") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_33', {}) + + " Pressing <C-A> when the popup menu is displayed should list all the + " matches and pressing <Left> after that should move the cursor + call term_sendkeys(buf, "\<C-U>abc\<Esc>") + call term_sendkeys(buf, ":sign \<Tab>\<C-A>\<Left>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_34', {}) + + " When <C-A> displays a lot of matches (screen scrolls), all the matches + " should be displayed correctly on the screen. + call term_sendkeys(buf, "\<End>\<C-U>Tcmd \<Tab>\<C-A>\<Left>\<Left>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_35', {}) + + " After using <C-A> to expand all the filename matches, pressing <Up> + " should not open the popup menu again. + call term_sendkeys(buf, "\<C-E>\<C-U>:cd Xnamedir/XdirA\<CR>") + call term_sendkeys(buf, ":e \<Tab>\<C-A>\<Up>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_36', {}) + call term_sendkeys(buf, "\<C-E>\<C-U>:cd -\<CR>") + + " After using <C-A> to expand all the matches, pressing <S-Tab> used to + " crash Vim + call term_sendkeys(buf, ":sign \<Tab>\<C-A>\<S-Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_37', {}) + + " After removing the pum the command line is redrawn + call term_sendkeys(buf, ":edit foo\<CR>") + call term_sendkeys(buf, ":edit bar\<CR>") + call term_sendkeys(buf, ":ls\<CR>") + call term_sendkeys(buf, ":com\<Tab> ") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_38', {}) + call term_sendkeys(buf, "\<C-U>\<CR>") + + " Esc still works to abort the command when 'statusline' is set + call term_sendkeys(buf, ":call SetupStatusline()\<CR>") + call term_sendkeys(buf, ":si\<Tab>") + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_39', {}) + + " Esc still works to abort the command when 'tabline' is set + call term_sendkeys(buf, ":call SetupTabline()\<CR>") + call term_sendkeys(buf, ":si\<Tab>") + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_40', {}) + + " popup is cleared also when 'lazyredraw' is set + call term_sendkeys(buf, ":set showtabline=1 laststatus=1 lazyredraw\<CR>") + call term_sendkeys(buf, ":call DoFeedKeys()\<CR>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_41', {}) + call term_sendkeys(buf, "\<Esc>") + + " Pressing <PageDown> should scroll the menu downward + call term_sendkeys(buf, ":sign \<Tab>\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_42', {}) + call term_sendkeys(buf, "\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_43', {}) + call term_sendkeys(buf, "\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_44', {}) + call term_sendkeys(buf, "\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_45', {}) + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<Down>\<Down>\<PageDown>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_46', {}) + + " Pressing <PageUp> should scroll the menu upward + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<PageUp>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_47', {}) + call term_sendkeys(buf, "\<PageUp>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_48', {}) + call term_sendkeys(buf, "\<PageUp>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_49', {}) + call term_sendkeys(buf, "\<PageUp>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_50', {}) + + " pressing <C-E> to end completion should work in middle of the line too + call term_sendkeys(buf, "\<Esc>:set wildchazz\<Left>\<Left>\<Tab>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_51', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_52', {}) + + " pressing <C-Y> should select the current match and end completion + call term_sendkeys(buf, "\<Esc>:set wildchazz\<Left>\<Left>\<Tab>\<C-Y>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_53', {}) + + call term_sendkeys(buf, "\<C-U>\<CR>") + call StopVimInTerminal(buf) +endfunc + +" Test for wildmenumode() with the cmdline popup menu +func Test_wildmenumode_with_pum() + set wildmenu + set wildoptions=pum + cnoremap <expr> <F2> wildmenumode() + call feedkeys(":sign \<Tab>\<F2>\<F2>\<C-B>\"\<CR>", 'xt') + call assert_equal('"sign define10', @:) + call feedkeys(":sign \<Tab>\<C-A>\<F2>\<C-B>\"\<CR>", 'xt') + call assert_equal('"sign define jump list place undefine unplace0', @:) + call feedkeys(":sign \<Tab>\<C-E>\<F2>\<C-B>\"\<CR>", 'xt') + call assert_equal('"sign 0', @:) + call feedkeys(":sign \<Tab>\<C-Y>\<F2>\<C-B>\"\<CR>", 'xt') + call assert_equal('"sign define0', @:) + set nowildmenu wildoptions& + cunmap <F2> +endfunc + +" Test for opening the cmdline completion popup menu from the terminal window. +" The popup menu should be positioned correctly over the status line of the +" bottom-most window. +func Test_wildmenu_pum_from_terminal() + CheckRunVimInTerminal + let python = PythonProg() + call CheckPython(python) + + %bw! + let cmds = ['set wildmenu wildoptions=pum'] + let pcmd = python .. ' -c "import sys; sys.stdout.write(sys.stdin.read())"' + call add(cmds, "call term_start('" .. pcmd .. "')") + call writefile(cmds, 'Xtest', 'D') + let buf = RunVimInTerminal('-S Xtest', #{rows: 10}) + call term_sendkeys(buf, "\r\r\r") + call term_wait(buf) + call term_sendkeys(buf, "\<C-W>:sign \<Tab>") + call term_wait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_term_01', {}) + call term_wait(buf) + call StopVimInTerminal(buf) +endfunc + +func Test_wildmenu_pum_odd_wildchar() + CheckRunVimInTerminal + + " Test odd wildchar interactions with pum. Make sure they behave properly + " and don't lead to memory corruption due to improperly cleaned up memory. + let lines =<< trim END + set wildoptions=pum + set wildchar=<C-E> + END + call writefile(lines, 'XwildmenuTest', 'D') + let buf = RunVimInTerminal('-S XwildmenuTest', #{rows: 10}) + + call term_sendkeys(buf, ":\<C-E>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_odd_wildchar_1', {}) + + " <C-E> being a wildchar takes priority over its original functionality + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_odd_wildchar_2', {}) + + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_odd_wildchar_3', {}) + + " Escape key can be wildchar too. Double-<Esc> is hard-coded to escape + " command-line, and we need to make sure to clean up properly. + call term_sendkeys(buf, ":set wildchar=<Esc>\<CR>") + call term_sendkeys(buf, ":\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_odd_wildchar_1', {}) + + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_odd_wildchar_3', {}) + + " <C-\> can also be wildchar. <C-\><C-N> however will still escape cmdline + " and we again need to make sure we clean up properly. + call term_sendkeys(buf, ":set wildchar=<C-\\>\<CR>") + call term_sendkeys(buf, ":\<C-\>\<C-\>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_odd_wildchar_1', {}) + + call term_sendkeys(buf, "\<C-N>") + call VerifyScreenDump(buf, 'Test_wildmenu_pum_odd_wildchar_3', {}) + + call StopVimInTerminal(buf) +endfunc + +" Test for completion after a :substitute command followed by a pipe (|) +" character +func Test_cmdline_complete_substitute() + call feedkeys(":s | \t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"s | \t", @:) + call feedkeys(":s/ | \t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"s/ | \t", @:) + call feedkeys(":s/one | \t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"s/one | \t", @:) + call feedkeys(":s/one/ | \t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"s/one/ | \t", @:) + call feedkeys(":s/one/two | \t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"s/one/two | \t", @:) + call feedkeys(":s/one/two/ | chist\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"s/one/two/ | chistory', @:) + call feedkeys(":s/one/two/g \t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"s/one/two/g \t", @:) + call feedkeys(":s/one/two/g | chist\t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"s/one/two/g | chistory", @:) + call feedkeys(":s/one/t\\/ | \t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"s/one/t\\/ | \t", @:) + call feedkeys(":s/one/t\"o/ | chist\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"s/one/t"o/ | chistory', @:) + call feedkeys(":s/one/t|o/ | chist\t\<C-B>\"\<CR>", 'xt') + call assert_equal('"s/one/t|o/ | chistory', @:) + call feedkeys(":&\t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"&\t", @:) +endfunc + +" Test for the :dlist command completion +func Test_cmdline_complete_dlist() + call feedkeys(":dlist 10 /pat/ a\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"dlist 10 /pat/ a\<C-A>", @:) + call feedkeys(":dlist 10 /pat/ \t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"dlist 10 /pat/ \t", @:) + call feedkeys(":dlist 10 /pa\\t/\t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"dlist 10 /pa\\t/\t", @:) + call feedkeys(":dlist 10 /pat\\\t\<C-B>\"\<CR>", 'xt') + call assert_equal("\"dlist 10 /pat\\\t", @:) + call feedkeys(":dlist 10 /pat/ | chist\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"dlist 10 /pat/ | chistory", @:) +endfunc + +" argument list (only for :argdel) fuzzy completion +func Test_fuzzy_completion_arglist() + argadd change.py count.py charge.py + set wildoptions& + call feedkeys(":argdel cge\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"argdel cge', @:) + set wildoptions=fuzzy + call feedkeys(":argdel cge\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"argdel change.py charge.py', @:) + %argdelete + set wildoptions& +endfunc + +" autocmd group name fuzzy completion +func Test_fuzzy_completion_autocmd() + set wildoptions& + augroup MyFuzzyGroup + augroup END + call feedkeys(":augroup mfg\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"augroup mfg', @:) + call feedkeys(":augroup My*p\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"augroup MyFuzzyGroup', @:) + set wildoptions=fuzzy + call feedkeys(":augroup mfg\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"augroup MyFuzzyGroup', @:) + call feedkeys(":augroup My*p\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"augroup My*p', @:) + augroup! MyFuzzyGroup + set wildoptions& +endfunc + +" buffer name fuzzy completion +func Test_fuzzy_completion_bufname() + set wildoptions& + " Use a long name to reduce the risk of matching a random directory name + edit SomeRandomFileWithLetters.txt + enew + call feedkeys(":b SRFWL\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"b SRFWL', @:) + call feedkeys(":b S*FileWithLetters.txt\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"b SomeRandomFileWithLetters.txt', @:) + set wildoptions=fuzzy + call feedkeys(":b SRFWL\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"b SomeRandomFileWithLetters.txt', @:) + call feedkeys(":b S*FileWithLetters.txt\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"b S*FileWithLetters.txt', @:) + %bw! + set wildoptions& +endfunc + +" buffer name (full path) fuzzy completion +func Test_fuzzy_completion_bufname_fullpath() + CheckUnix + set wildoptions& + call mkdir('Xcmd/Xstate/Xfile.js', 'p') + edit Xcmd/Xstate/Xfile.js + cd Xcmd/Xstate + enew + call feedkeys(":b CmdStateFile\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"b CmdStateFile', @:) + set wildoptions=fuzzy + call feedkeys(":b CmdStateFile\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('Xcmd/Xstate/Xfile.js$', @:) + cd - + call delete('Xcmd', 'rf') + set wildoptions& +endfunc + +" :behave suboptions fuzzy completion +func Test_fuzzy_completion_behave() + throw 'Skipped: Nvim removed :behave' + set wildoptions& + call feedkeys(":behave xm\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"behave xm', @:) + call feedkeys(":behave xt*m\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"behave xterm', @:) + set wildoptions=fuzzy + call feedkeys(":behave xm\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"behave xterm', @:) + call feedkeys(":behave xt*m\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"behave xt*m', @:) + let g:Sline = '' + call feedkeys(":behave win\<C-D>\<F4>\<C-B>\"\<CR>", 'tx') + call assert_equal('mswin', g:Sline) + call assert_equal('"behave win', @:) + set wildoptions& +endfunc + +" " colorscheme name fuzzy completion - NOT supported +" func Test_fuzzy_completion_colorscheme() +" endfunc + +" built-in command name fuzzy completion +func Test_fuzzy_completion_cmdname() + set wildoptions& + call feedkeys(":sbwin\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sbwin', @:) + call feedkeys(":sbr*d\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sbrewind', @:) + set wildoptions=fuzzy + call feedkeys(":sbwin\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sbrewind', @:) + call feedkeys(":sbr*d\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sbr*d', @:) + set wildoptions& +endfunc + +" " compiler name fuzzy completion - NOT supported +" func Test_fuzzy_completion_compiler() +" endfunc + +" :cscope suboptions fuzzy completion +func Test_fuzzy_completion_cscope() + CheckFeature cscope + set wildoptions& + call feedkeys(":cscope ret\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"cscope ret', @:) + call feedkeys(":cscope re*t\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"cscope reset', @:) + set wildoptions=fuzzy + call feedkeys(":cscope ret\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"cscope reset', @:) + call feedkeys(":cscope re*t\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"cscope re*t', @:) + set wildoptions& +endfunc + +" :diffget/:diffput buffer name fuzzy completion +func Test_fuzzy_completion_diff() + new SomeBuffer + diffthis + new OtherBuffer + diffthis + set wildoptions& + call feedkeys(":diffget sbuf\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffget sbuf', @:) + call feedkeys(":diffput sbuf\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffput sbuf', @:) + set wildoptions=fuzzy + call feedkeys(":diffget sbuf\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffget SomeBuffer', @:) + call feedkeys(":diffput sbuf\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffput SomeBuffer', @:) + %bw! + set wildoptions& +endfunc + +" " directory name fuzzy completion - NOT supported +" func Test_fuzzy_completion_dirname() +" endfunc + +" environment variable name fuzzy completion +func Test_fuzzy_completion_env() + set wildoptions& + call feedkeys(":echo $VUT\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"echo $VUT', @:) + set wildoptions=fuzzy + call feedkeys(":echo $VUT\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"echo $VIMRUNTIME', @:) + set wildoptions& +endfunc + +" autocmd event fuzzy completion +func Test_fuzzy_completion_autocmd_event() + set wildoptions& + call feedkeys(":autocmd BWout\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"autocmd BWout', @:) + set wildoptions=fuzzy + call feedkeys(":autocmd BWout\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"autocmd BufWipeout', @:) + set wildoptions& +endfunc + +" vim expression fuzzy completion +func Test_fuzzy_completion_expr() + let g:PerPlaceCount = 10 + set wildoptions& + call feedkeys(":let c = ppc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"let c = ppc', @:) + set wildoptions=fuzzy + call feedkeys(":let c = ppc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"let c = PerPlaceCount', @:) + set wildoptions& +endfunc + +" " file name fuzzy completion - NOT supported +" func Test_fuzzy_completion_filename() +" endfunc + +" " files in path fuzzy completion - NOT supported +" func Test_fuzzy_completion_filesinpath() +" endfunc + +" " filetype name fuzzy completion - NOT supported +" func Test_fuzzy_completion_filetype() +" endfunc + +" user defined function name completion +func Test_fuzzy_completion_userdefined_func() + set wildoptions& + call feedkeys(":call Test_f_u_f\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"call Test_f_u_f', @:) + set wildoptions=fuzzy + call feedkeys(":call Test_f_u_f\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"call Test_fuzzy_completion_userdefined_func()', @:) + set wildoptions& +endfunc + +" <SNR> functions should be sorted to the end +func Test_fuzzy_completion_userdefined_snr_func() + func s:Sendmail() + endfunc + func SendSomemail() + endfunc + func S1e2n3dmail() + endfunc + set wildoptions=fuzzy + call feedkeys(":call sendmail\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"call SendSomemail() S1e2n3dmail() ' + \ .. expand("<SID>") .. 'Sendmail()', @:) + set wildoptions& + delfunc s:Sendmail + delfunc SendSomemail + delfunc S1e2n3dmail +endfunc + +" user defined command name completion +func Test_fuzzy_completion_userdefined_cmd() + set wildoptions& + call feedkeys(":MsFeat\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"MsFeat', @:) + set wildoptions=fuzzy + call feedkeys(":MsFeat\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"MissingFeature', @:) + set wildoptions& +endfunc + +" " :help tag fuzzy completion - NOT supported +" func Test_fuzzy_completion_helptag() +" endfunc + +" highlight group name fuzzy completion +func Test_fuzzy_completion_hlgroup() + set wildoptions& + call feedkeys(":highlight SKey\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"highlight SKey', @:) + call feedkeys(":highlight Sp*Key\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"highlight SpecialKey', @:) + set wildoptions=fuzzy + call feedkeys(":highlight SKey\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"highlight SpecialKey', @:) + call feedkeys(":highlight Sp*Key\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"highlight Sp*Key', @:) + set wildoptions& +endfunc + +" :history suboptions fuzzy completion +func Test_fuzzy_completion_history() + set wildoptions& + call feedkeys(":history dg\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"history dg', @:) + call feedkeys(":history se*h\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"history search', @:) + set wildoptions=fuzzy + call feedkeys(":history dg\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"history debug', @:) + call feedkeys(":history se*h\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"history se*h', @:) + set wildoptions& +endfunc + +" :language locale name fuzzy completion +func Test_fuzzy_completion_lang() + CheckUnix + set wildoptions& + call feedkeys(":lang psx\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"lang psx', @:) + set wildoptions=fuzzy + call feedkeys(":lang psx\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"lang POSIX', @:) + set wildoptions& +endfunc + +" :mapclear buffer argument fuzzy completion +func Test_fuzzy_completion_mapclear() + set wildoptions& + call feedkeys(":mapclear buf\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"mapclear buf', @:) + set wildoptions=fuzzy + call feedkeys(":mapclear buf\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"mapclear <buffer>', @:) + set wildoptions& +endfunc + +" map name fuzzy completion +func Test_fuzzy_completion_mapname() + " test regex completion works + set wildoptions=fuzzy + call feedkeys(":cnoremap <ex\<Tab> <esc> \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"cnoremap <expr> <esc> \<Tab>", @:) + nmap <plug>MyLongMap :p<CR> + call feedkeys(":nmap MLM\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"nmap <Plug>MyLongMap", @:) + call feedkeys(":nmap MLM \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"nmap MLM \t", @:) + call feedkeys(":nmap <F2> one two \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"nmap <F2> one two \t", @:) + " duplicate entries should be removed + vmap <plug>MyLongMap :<C-U>#<CR> + call feedkeys(":nmap MLM\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"nmap <Plug>MyLongMap", @:) + nunmap <plug>MyLongMap + vunmap <plug>MyLongMap + call feedkeys(":nmap ABC\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"nmap ABC\t", @:) + " results should be sorted by best match + nmap <Plug>format : + nmap <Plug>goformat : + nmap <Plug>TestFOrmat : + nmap <Plug>fendoff : + nmap <Plug>state : + nmap <Plug>FendingOff : + call feedkeys(":nmap <Plug>fo\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"nmap <Plug>format <Plug>TestFOrmat <Plug>FendingOff <Plug>goformat <Plug>fendoff", @:) + nunmap <Plug>format + nunmap <Plug>goformat + nunmap <Plug>TestFOrmat + nunmap <Plug>fendoff + nunmap <Plug>state + nunmap <Plug>FendingOff + set wildoptions& +endfunc + +" abbreviation fuzzy completion +func Test_fuzzy_completion_abbr() + set wildoptions=fuzzy + call feedkeys(":iabbr wait\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"iabbr <nowait>", @:) + iabbr WaitForCompletion WFC + call feedkeys(":iabbr fcl\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"iabbr WaitForCompletion", @:) + call feedkeys(":iabbr a1z\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"iabbr a1z\t", @:) + + iunabbrev WaitForCompletion + set wildoptions& +endfunc + +" menu name fuzzy completion +func Test_fuzzy_completion_menu() + CheckFeature menu + + source $VIMRUNTIME/menu.vim + set wildoptions& + call feedkeys(":menu pup\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"menu pup', @:) + set wildoptions=fuzzy + call feedkeys(":menu pup\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"menu PopUp.', @:) + + set wildoptions& + source $VIMRUNTIME/delmenu.vim +endfunc + +" :messages suboptions fuzzy completion +func Test_fuzzy_completion_messages() + set wildoptions& + call feedkeys(":messages clr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"messages clr', @:) + set wildoptions=fuzzy + call feedkeys(":messages clr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"messages clear', @:) + set wildoptions& +endfunc + +" :set option name fuzzy completion +func Test_fuzzy_completion_option() + set wildoptions& + call feedkeys(":set brkopt\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set brkopt', @:) + set wildoptions=fuzzy + call feedkeys(":set brkopt\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set breakindentopt', @:) + set wildoptions& + call feedkeys(":set fixeol\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set fixendofline', @:) + set wildoptions=fuzzy + call feedkeys(":set fixeol\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set fixendofline', @:) + set wildoptions& +endfunc + +" :set <term_option> +func Test_fuzzy_completion_term_option() + throw 'Skipped: Nvim does not support term options' + set wildoptions& + call feedkeys(":set t_E\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set t_EC', @:) + call feedkeys(":set <t_E\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set <t_EC>', @:) + set wildoptions=fuzzy + call feedkeys(":set t_E\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set t_EC', @:) + call feedkeys(":set <t_E\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set <t_EC>', @:) + set wildoptions& +endfunc + +" " :packadd directory name fuzzy completion - NOT supported +" func Test_fuzzy_completion_packadd() +" endfunc + +" " shell command name fuzzy completion - NOT supported +" func Test_fuzzy_completion_shellcmd() +" endfunc + +" :sign suboptions fuzzy completion +func Test_fuzzy_completion_sign() + set wildoptions& + call feedkeys(":sign ufe\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign ufe', @:) + set wildoptions=fuzzy + call feedkeys(":sign ufe\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign undefine', @:) + set wildoptions& +endfunc + +" :syntax suboptions fuzzy completion +func Test_fuzzy_completion_syntax_cmd() + set wildoptions& + call feedkeys(":syntax kwd\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syntax kwd', @:) + set wildoptions=fuzzy + call feedkeys(":syntax kwd\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syntax keyword', @:) + set wildoptions& +endfunc + +" syntax group name fuzzy completion +func Test_fuzzy_completion_syntax_group() + set wildoptions& + call feedkeys(":syntax list mpar\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syntax list mpar', @:) + set wildoptions=fuzzy + call feedkeys(":syntax list mpar\<Tab>\<C-B>\"\<CR>", 'tx') + " Fuzzy match prefers NvimParenthesis over MatchParen + " call assert_equal('"syntax list MatchParen', @:) + call assert_equal('"syntax list NvimParenthesis', @:) + set wildoptions& +endfunc + +" :syntime suboptions fuzzy completion +func Test_fuzzy_completion_syntime() + CheckFeature profile + set wildoptions& + call feedkeys(":syntime clr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syntime clr', @:) + set wildoptions=fuzzy + call feedkeys(":syntime clr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syntime clear', @:) + set wildoptions& +endfunc + +" " tag name fuzzy completion - NOT supported +" func Test_fuzzy_completion_tagname() +" endfunc + +" " tag name and file fuzzy completion - NOT supported +" func Test_fuzzy_completion_tagfile() +" endfunc + +" " user names fuzzy completion - how to test this functionality? +" func Test_fuzzy_completion_username() +" endfunc + +" user defined variable name fuzzy completion +func Test_fuzzy_completion_userdefined_var() + let g:SomeVariable=10 + set wildoptions& + call feedkeys(":let SVar\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"let SVar', @:) + set wildoptions=fuzzy + call feedkeys(":let SVar\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"let SomeVariable', @:) + set wildoptions& +endfunc + +" Test for sorting the results by the best match +func Test_fuzzy_completion_cmd_sort_results() + %bw! + command T123format : + command T123goformat : + command T123TestFOrmat : + command T123fendoff : + command T123state : + command T123FendingOff : + set wildoptions=fuzzy + call feedkeys(":T123fo\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"T123format T123TestFOrmat T123FendingOff T123goformat T123fendoff', @:) + delcommand T123format + delcommand T123goformat + delcommand T123TestFOrmat + delcommand T123fendoff + delcommand T123state + delcommand T123FendingOff + %bw + set wildoptions& +endfunc + +" Test for fuzzy completion of a command with lower case letters and a number +func Test_fuzzy_completion_cmd_alnum() + command Foo2Bar : + set wildoptions=fuzzy + call feedkeys(":foo2\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"Foo2Bar', @:) + call feedkeys(":foo\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"Foo2Bar', @:) + call feedkeys(":bar\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"Foo2Bar', @:) + delcommand Foo2Bar + set wildoptions& +endfunc + +" Test for command completion for a command starting with 'k' +func Test_fuzzy_completion_cmd_k() + command KillKillKill : + set wildoptions& + call feedkeys(":killkill\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"killkill\<Tab>", @:) + set wildoptions=fuzzy + call feedkeys(":killkill\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"KillKillKill', @:) + delcom KillKillKill + set wildoptions& +endfunc + +" Test for fuzzy completion for user defined custom completion function +func Test_fuzzy_completion_custom_func() + func Tcompl(a, c, p) + return "format\ngoformat\nTestFOrmat\nfendoff\nstate" + endfunc + command -nargs=* -complete=custom,Tcompl Fuzzy : + set wildoptions& + call feedkeys(":Fuzzy fo\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"Fuzzy format", @:) + call feedkeys(":Fuzzy xy\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"Fuzzy xy", @:) + call feedkeys(":Fuzzy ttt\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"Fuzzy ttt", @:) + set wildoptions=fuzzy + call feedkeys(":Fuzzy \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"Fuzzy format goformat TestFOrmat fendoff state", @:) + call feedkeys(":Fuzzy fo\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"Fuzzy format TestFOrmat goformat fendoff", @:) + call feedkeys(":Fuzzy xy\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"Fuzzy xy", @:) + call feedkeys(":Fuzzy ttt\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"Fuzzy TestFOrmat", @:) + delcom Fuzzy + set wildoptions& +endfunc + +" Test for fuzzy completion in the middle of a cmdline instead of at the end +func Test_fuzzy_completion_in_middle() + set wildoptions=fuzzy + call feedkeys(":set ildar wrap\<Left>\<Left>\<Left>\<Left>\<Left>\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"set wildchar wildcharm wrap", @:) + + call feedkeys(":args ++odng zz\<Left>\<Left>\<Left>\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"args ++encoding= zz", @:) + set wildoptions& +endfunc + +" Test for :breakadd argument completion +func Test_cmdline_complete_breakadd() + call feedkeys(":breakadd \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr file func here", @:) + call feedkeys(":breakadd \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr", @:) + call feedkeys(":breakadd \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr", @:) + call feedkeys(":breakadd he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here", @:) + call feedkeys(":breakadd he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here", @:) + call feedkeys(":breakadd abc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd abc", @:) + call assert_equal(['expr', 'file', 'func', 'here'], getcompletion('', 'breakpoint')) + let l = getcompletion('not', 'breakpoint') + call assert_equal([], l) + + " Test for :breakadd file [lnum] <file> + call writefile([], 'Xscript') + call feedkeys(":breakadd file Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file Xscript", @:) + call feedkeys(":breakadd file Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file Xscript", @:) + call feedkeys(":breakadd file 20 Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20 Xscript", @:) + call feedkeys(":breakadd file 20 Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20 Xscript", @:) + call feedkeys(":breakadd file 20x Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20x Xsc\t", @:) + call feedkeys(":breakadd file 20\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20\t", @:) + call feedkeys(":breakadd file 20x\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file 20x\t", @:) + call feedkeys(":breakadd file Xscript \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file Xscript ", @:) + call feedkeys(":breakadd file X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd file X1B2C3", @:) + call delete('Xscript') + + " Test for :breakadd func [lnum] <function> + func Xbreak_func() + endfunc + call feedkeys(":breakadd func Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func Xbreak_func", @:) + call feedkeys(":breakadd func Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func Xbreak_func", @:) + call feedkeys(":breakadd func 20 Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20 Xbreak_func", @:) + call feedkeys(":breakadd func 20 Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20 Xbreak_func", @:) + call feedkeys(":breakadd func 20x Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20x Xbr\t", @:) + call feedkeys(":breakadd func 20\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20\t", @:) + call feedkeys(":breakadd func 20x\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func 20x\t", @:) + call feedkeys(":breakadd func Xbreak_func \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func Xbreak_func ", @:) + call feedkeys(":breakadd func X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd func X1B2C3", @:) + delfunc Xbreak_func + + " Test for :breakadd expr <expression> + let g:Xtest_var = 10 + call feedkeys(":breakadd expr Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr Xtest_var", @:) + call feedkeys(":breakadd expr Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr Xtest_var", @:) + call feedkeys(":breakadd expr Xtest_var \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr Xtest_var ", @:) + call feedkeys(":breakadd expr X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd expr X1B2C3", @:) + unlet g:Xtest_var + + " Test for :breakadd here + call feedkeys(":breakadd here Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here Xtest", @:) + call feedkeys(":breakadd here Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here Xtest", @:) + call feedkeys(":breakadd here \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakadd here ", @:) +endfunc + +" Test for :breakdel argument completion +func Test_cmdline_complete_breakdel() + call feedkeys(":breakdel \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file func here", @:) + call feedkeys(":breakdel \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file", @:) + call feedkeys(":breakdel \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file", @:) + call feedkeys(":breakdel he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here", @:) + call feedkeys(":breakdel he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here", @:) + call feedkeys(":breakdel abc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel abc", @:) + + " Test for :breakdel file [lnum] <file> + call writefile([], 'Xscript') + call feedkeys(":breakdel file Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file Xscript", @:) + call feedkeys(":breakdel file Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file Xscript", @:) + call feedkeys(":breakdel file 20 Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20 Xscript", @:) + call feedkeys(":breakdel file 20 Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20 Xscript", @:) + call feedkeys(":breakdel file 20x Xsc\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20x Xsc\t", @:) + call feedkeys(":breakdel file 20\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20\t", @:) + call feedkeys(":breakdel file 20x\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file 20x\t", @:) + call feedkeys(":breakdel file Xscript \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file Xscript ", @:) + call feedkeys(":breakdel file X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel file X1B2C3", @:) + call delete('Xscript') + + " Test for :breakdel func [lnum] <function> + func Xbreak_func() + endfunc + call feedkeys(":breakdel func Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func Xbreak_func", @:) + call feedkeys(":breakdel func Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func Xbreak_func", @:) + call feedkeys(":breakdel func 20 Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20 Xbreak_func", @:) + call feedkeys(":breakdel func 20 Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20 Xbreak_func", @:) + call feedkeys(":breakdel func 20x Xbr\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20x Xbr\t", @:) + call feedkeys(":breakdel func 20\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20\t", @:) + call feedkeys(":breakdel func 20x\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func 20x\t", @:) + call feedkeys(":breakdel func Xbreak_func \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func Xbreak_func ", @:) + call feedkeys(":breakdel func X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel func X1B2C3", @:) + delfunc Xbreak_func + + " Test for :breakdel here + call feedkeys(":breakdel here Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here Xtest", @:) + call feedkeys(":breakdel here Xtest\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here Xtest", @:) + call feedkeys(":breakdel here \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"breakdel here ", @:) +endfunc + +" Test for :scriptnames argument completion +func Test_cmdline_complete_scriptnames() + set wildmenu + call writefile(['let a = 1'], 'Xa1b2c3.vim') + source Xa1b2c3.vim + call feedkeys(":script \<Tab>\<Left>\<Left>\<C-B>\"\<CR>", 'tx') + call assert_match("\"script .*Xa1b2c3.vim$", @:) + call feedkeys(":script \<Tab>\<Left>\<Left>\<C-B>\"\<CR>", 'tx') + call assert_match("\"script .*Xa1b2c3.vim$", @:) + call feedkeys(":script b2c3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"script b2c3", @:) + call feedkeys(":script 2\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match("\"script 2\<Tab>$", @:) + call feedkeys(":script \<Tab>\<Left>\<Left> \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match("\"script .*Xa1b2c3.vim $", @:) + call feedkeys(":script \<Tab>\<Left>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"script ", @:) + call assert_match('Xa1b2c3.vim$', getcompletion('.*Xa1b2.*', 'scriptnames')[0]) + call assert_equal([], getcompletion('Xa1b2', 'scriptnames')) + new + call feedkeys(":script \<Tab>\<Left>\<Left>\<CR>", 'tx') + call assert_equal('Xa1b2c3.vim', fnamemodify(@%, ':t')) + bw! + call delete('Xa1b2c3.vim') + set wildmenu& +endfunc + +" this was going over the end of IObuff +func Test_report_error_with_composing() + let caught = 'no' + try + exe repeat('0', 987) .. "0\xdd\x80\xdd\x80\xdd\x80\xdd\x80" + catch /E492:/ + let caught = 'yes' + endtry + call assert_equal('yes', caught) +endfunc + +" Test for expanding 2-letter and 3-letter :substitute command arguments. +" These commands don't accept an argument. +func Test_cmdline_complete_substitute_short() + for cmd in ['sc', 'sce', 'scg', 'sci', 'scI', 'scn', 'scp', 'scl', + \ 'sgc', 'sge', 'sg', 'sgi', 'sgI', 'sgn', 'sgp', 'sgl', 'sgr', + \ 'sic', 'sie', 'si', 'siI', 'sin', 'sip', 'sir', + \ 'sIc', 'sIe', 'sIg', 'sIi', 'sI', 'sIn', 'sIp', 'sIl', 'sIr', + \ 'src', 'srg', 'sri', 'srI', 'srn', 'srp', 'srl', 'sr'] + call feedkeys(':' .. cmd .. " \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"' .. cmd .. " \<Tab>", @:) + endfor +endfunc + +" Test for :! shell command argument completion +func Test_cmdline_complete_bang_cmd_argument() + set wildoptions=fuzzy + call feedkeys(":!vim test_cmdline.\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"!vim test_cmdline.vim', @:) + set wildoptions& + call feedkeys(":!vim test_cmdline.\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"!vim test_cmdline.vim', @:) +endfunc + +func Call_cmd_funcs() + return string([getcmdpos(), getcmdscreenpos(), getcmdcompltype()]) +endfunc + +func Test_screenpos_and_completion() + call assert_equal(0, getcmdpos()) + call assert_equal(0, getcmdscreenpos()) + call assert_equal('', getcmdcompltype()) + + cnoremap <expr> <F2> string([getcmdpos(), getcmdscreenpos(), getcmdcompltype()]) + call feedkeys(":let a\<F2>\<C-B>\"\<CR>", "xt") + call assert_equal("\"let a[6, 7, 'var']", @:) + call feedkeys(":quit \<F2>\<C-B>\"\<CR>", "xt") + call assert_equal("\"quit [6, 7, '']", @:) + call feedkeys(":nosuchcommand \<F2>\<C-B>\"\<CR>", "xt") + call assert_equal("\"nosuchcommand [15, 16, '']", @:) + cunmap <F2> +endfunc + +func Test_recursive_register() + let @= = '' + silent! ?e/ + let caught = 'no' + try + normal // + catch /E169:/ + let caught = 'yes' + endtry + call assert_equal('yes', caught) +endfunc + +func Test_long_error_message() + " the error should be truncated, not overrun IObuff + silent! norm Q00000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 +endfunc + +func Test_cmdline_redraw_tabline() + CheckRunVimInTerminal + + let lines =<< trim END + set showtabline=2 + autocmd CmdlineEnter * set tabline=foo + END + call writefile(lines, 'Xcmdline_redraw_tabline') + let buf = RunVimInTerminal('-S Xcmdline_redraw_tabline', #{rows: 6}) + call term_sendkeys(buf, ':') + call WaitForAssert({-> assert_match('^foo', term_getline(buf, 1))}) + + call StopVimInTerminal(buf) + call delete('Xcmdline_redraw_tabline') +endfunc + +func Test_wildmenu_pum_disable_while_shown() + set wildoptions=pum + set wildmenu + cnoremap <F2> <Cmd>set nowildmenu<CR> + call feedkeys(":sign \<Tab>\<F2>\<Esc>", 'tx') + call assert_equal(0, pumvisible()) + cunmap <F2> + set wildoptions& wildmenu& +endfunc + +func Test_setcmdline() + func SetText(text, pos) + call assert_equal(0, setcmdline(v:_null_string)) + call assert_equal('', getcmdline()) + call assert_equal(1, getcmdpos()) + + call assert_equal(0, setcmdline(''[: -1])) + call assert_equal('', getcmdline()) + call assert_equal(1, getcmdpos()) + + autocmd CmdlineChanged * let g:cmdtype = expand('<afile>') + call assert_equal(0, setcmdline(a:text)) + call assert_equal(a:text, getcmdline()) + call assert_equal(len(a:text) + 1, getcmdpos()) + call assert_equal(getcmdtype(), g:cmdtype) + unlet g:cmdtype + autocmd! CmdlineChanged + + call assert_equal(0, setcmdline(a:text, a:pos)) + call assert_equal(a:text, getcmdline()) + call assert_equal(a:pos, getcmdpos()) + + call assert_fails('call setcmdline("' .. a:text .. '", -1)', 'E487:') + call assert_fails('call setcmdline({}, 0)', 'E1174:') + call assert_fails('call setcmdline("' .. a:text .. '", {})', 'E1210:') + + return '' + endfunc + + call feedkeys(":\<C-R>=SetText('set rtp?', 2)\<CR>\<CR>", 'xt') + call assert_equal('set rtp?', @:) + + call feedkeys(":let g:str = input('? ')\<CR>", 't') + call feedkeys("\<C-R>=SetText('foo', 4)\<CR>\<CR>", 'xt') + call assert_equal('foo', g:str) + unlet g:str + + delfunc SetText + + " setcmdline() returns 1 when not editing the command line. + call assert_equal(1, 'foo'->setcmdline()) + + " Called in custom function + func CustomComplete(A, L, P) + call assert_equal(0, setcmdline("DoCmd ")) + return "January\nFebruary\nMars\n" + endfunc + + com! -nargs=* -complete=custom,CustomComplete DoCmd : + call feedkeys(":DoCmd \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd January February Mars', @:) + delcom DoCmd + delfunc CustomComplete + + " Called in <expr> + cnoremap <expr>a setcmdline('let foo=') + call feedkeys(":a\<CR>", 'tx') + call assert_equal('let foo=0', @:) + cunmap a +endfunc + +func Test_rulerformat_position() + CheckScreendump + + let buf = RunVimInTerminal('', #{rows: 2, cols: 20}) + call term_sendkeys(buf, ":set ruler rulerformat=longish\<CR>") + call term_sendkeys(buf, ":set laststatus=0 winwidth=1\<CR>") + call term_sendkeys(buf, "\<C-W>v\<C-W>|\<C-W>p") + call VerifyScreenDump(buf, 'Test_rulerformat_position', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_getcompletion_usercmd() + command! -nargs=* -complete=command TestCompletion echo <q-args> + + call assert_equal(getcompletion('', 'cmdline'), + \ getcompletion('TestCompletion ', 'cmdline')) + call assert_equal(['<buffer>'], + \ getcompletion('TestCompletion map <bu', 'cmdline')) + + delcom TestCompletion +endfunc + +func Test_custom_completion() + func CustomComplete1(lead, line, pos) + return "a\nb\nc" + endfunc + func CustomComplete2(lead, line, pos) + return ['a', 'b']->filter({ _, val -> val->stridx(a:lead) == 0 }) + endfunc + func Check_custom_completion() + call assert_equal('custom,CustomComplete1', getcmdcompltype()) + return '' + endfunc + func Check_customlist_completion() + call assert_equal('customlist,CustomComplete2', getcmdcompltype()) + return '' + endfunc + + command -nargs=1 -complete=custom,CustomComplete1 Test1 echo + command -nargs=1 -complete=customlist,CustomComplete2 Test2 echo + + call feedkeys(":Test1 \<C-R>=Check_custom_completion()\<CR>\<Esc>", "xt") + call feedkeys(":Test2 \<C-R>=Check_customlist_completion()\<CR>\<Esc>", "xt") + + call assert_fails("call getcompletion('', 'custom')", 'E475:') + call assert_fails("call getcompletion('', 'customlist')", 'E475:') + + call assert_equal(getcompletion('', 'custom,CustomComplete1'), ['a', 'b', 'c']) + call assert_equal(getcompletion('', 'customlist,CustomComplete2'), ['a', 'b']) + call assert_equal(getcompletion('b', 'customlist,CustomComplete2'), ['b']) + + delcom Test1 + delcom Test2 + + delfunc CustomComplete1 + delfunc CustomComplete2 + delfunc Check_custom_completion + delfunc Check_customlist_completion +endfunc + +func Test_custom_completion_with_glob() + func TestGlobComplete(A, L, P) + return split(glob('Xglob*'), "\n") + endfunc + + command -nargs=* -complete=customlist,TestGlobComplete TestGlobComplete : + call writefile([], 'Xglob1', 'D') + call writefile([], 'Xglob2', 'D') + + call feedkeys(":TestGlobComplete \<Tab> \<Tab>\<C-N> \<Tab>\<C-P>;\<C-B>\"\<CR>", 'xt') + call assert_equal('"TestGlobComplete Xglob1 Xglob2 ;', @:) + + delcommand TestGlobComplete + delfunc TestGlobComplete +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_cmdwin.vim b/test/old/testdir/test_cmdwin.vim new file mode 100644 index 0000000000..f07fd99f8a --- /dev/null +++ b/test/old/testdir/test_cmdwin.vim @@ -0,0 +1,96 @@ +" Tests for editing the command line. + +source check.vim +source screendump.vim + + +func Test_cant_open_cmdwin_in_cmdwin() + try + call feedkeys("q:q::q\<CR>", "x!") + catch + let caught = v:exception + endtry + call assert_match('E1292:', caught) +endfunc + +func Test_cmdwin_virtual_edit() + enew! + set ve=all cpo+=$ + silent normal q/s + + set ve= cpo-=$ +endfunc + +" Check that a :normal command can be used to stop Visual mode without side +" effects. +func Test_normal_escape() + call feedkeys("q:i\" foo\<Esc>:normal! \<C-V>\<Esc>\<CR>:\" bar\<CR>", 'ntx') + call assert_equal('" bar', @:) +endfunc + +" This was using a pointer to a freed buffer +func Test_cmdwin_freed_buffer_ptr() + " this does not work on MS-Windows because renaming an open file fails + CheckNotMSWindows + + au BufEnter * next 0| file + edit 0 + silent! norm q/ + + au! BufEnter + bwipe! +endfunc + +" This was resulting in a window with negative width. +" The test doesn't reproduce the illegal memory access though... +func Test_cmdwin_split_often() + let lines = &lines + let columns = &columns + set t_WS= + + try + " set encoding=iso8859 + set ruler + winsize 0 0 + noremap 0 H + sil norm 0000000q: + catch /E36:/ + endtry + + bwipe! + set encoding=utf8 + let &lines = lines + let &columns = columns +endfunc + +func Test_cmdwin_restore_heights() + set showtabline=0 cmdheight=2 laststatus=0 + call feedkeys("q::set cmdheight=1\<CR>:q\<CR>", 'ntx') + call assert_equal(&lines - 1, winheight(0)) + + set showtabline=2 cmdheight=3 + call feedkeys("q::set showtabline=0\<CR>:q\<CR>", 'ntx') + call assert_equal(&lines - 3, winheight(0)) + + set cmdheight=1 laststatus=2 + call feedkeys("q::set laststatus=0\<CR>:q\<CR>", 'ntx') + call assert_equal(&lines - 1, winheight(0)) + + set laststatus=2 + call feedkeys("q::set laststatus=1\<CR>:q\<CR>", 'ntx') + call assert_equal(&lines - 1, winheight(0)) + + set laststatus=2 + belowright vsplit + wincmd _ + let restcmds = winrestcmd() + call feedkeys("q::set laststatus=1\<CR>:q\<CR>", 'ntx') + " As we have 2 windows, &ls = 1 should still have a statusline on the last + " window. As such, the number of available rows hasn't changed and the window + " sizes should be restored. + call assert_equal(restcmds, winrestcmd()) + + set cmdheight& showtabline& laststatus& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_codestyle.vim b/test/old/testdir/test_codestyle.vim new file mode 100644 index 0000000000..01dd03f693 --- /dev/null +++ b/test/old/testdir/test_codestyle.vim @@ -0,0 +1,63 @@ +" Test for checking the source code style. + +func s:ReportError(fname, lnum, msg) + if a:lnum > 0 + call assert_report(a:fname .. ' line ' .. a:lnum .. ': ' .. a:msg) + endif +endfunc + +func Test_help_files() + set nowrapscan + + for fpath in glob('../../../runtime/doc/*.txt', 0, 1) + let g:ignoreSwapExists = 'e' + exe 'edit ' .. fpath + + let fname = fnamemodify(fpath, ":t") + + " todo.txt is for developers, it's not need a strictly check + " version*.txt is a history and large size, so it's not checked + if fname == 'todo.txt' || fname =~ 'version.*\.txt' + continue + endif + + " Check for mixed tabs and spaces + call cursor(1, 1) + while 1 + let lnum = search('[^/] \t') + if fname == 'visual.txt' && getline(lnum) =~ "STRING \tjkl" + \ || fname == 'usr_27.txt' && getline(lnum) =~ "\[^\? \t\]" + continue + endif + call s:ReportError(fpath, lnum, 'space before tab') + if lnum == 0 + break + endif + endwhile + + " Check for unnecessary whitespace at the end of a line + call cursor(1, 1) + while 1 + let lnum = search('[^/~\\]\s$') + " skip line that are known to have trailing white space + if fname == 'map.txt' && getline(lnum) =~ "unmap @@ $" + \ || fname == 'usr_12.txt' && getline(lnum) =~ "^\t/ \t$" + \ || fname == 'usr_41.txt' && getline(lnum) =~ "map <F4> o#include $" + \ || fname == 'change.txt' && getline(lnum) =~ "foobar bla $" + continue + endif + call s:ReportError('testdir' .. fpath, lnum, 'trailing white space') + if lnum == 0 + break + endif + endwhile + + + endfor + + set wrapscan&vim + bwipe! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_command_count.vim b/test/old/testdir/test_command_count.vim new file mode 100644 index 0000000000..55b230373f --- /dev/null +++ b/test/old/testdir/test_command_count.vim @@ -0,0 +1,196 @@ +" 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 diff --git a/test/old/testdir/test_comments.vim b/test/old/testdir/test_comments.vim new file mode 100644 index 0000000000..c34b85c42d --- /dev/null +++ b/test/old/testdir/test_comments.vim @@ -0,0 +1,277 @@ +" 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 + { + X + Xa + XaY + XY + XYZ + X Y + X YZ + XX + XXa + XXY + } + END + call setline(1, t) + call cursor(2, 1) + + set tw=2 fo=cqm comments=n:X + exe "normal gqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgq" + let t =<< trim END + X + Xa + XaY + XY + XYZ + X Y + X YZ + XX + XXa + XXY + END + exe "normal o\n" . join(t, "\n") + + let expected =<< trim END + { + X + Xa + Xa + XY + XY + XY + XZ + X Y + X Y + X Z + XX + XXa + XXY + + X + Xa + Xa + XY + XY + XY + XZ + X Y + X Y + X Z + XX + XXa + XXY + } + 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 diff --git a/test/old/testdir/test_comparators.vim b/test/old/testdir/test_comparators.vim new file mode 100644 index 0000000000..87be006cf2 --- /dev/null +++ b/test/old/testdir/test_comparators.vim @@ -0,0 +1,9 @@ +function Test_Comparators() + try + let oldisident=&isident + set isident+=# + call assert_equal(1, 1 is#1) + finally + let &isident=oldisident + endtry +endfunction diff --git a/test/old/testdir/test_compiler.vim b/test/old/testdir/test_compiler.vim new file mode 100644 index 0000000000..0b22bafabb --- /dev/null +++ b/test/old/testdir/test_compiler.vim @@ -0,0 +1,77 @@ +" Test the :compiler command + +source check.vim +source shared.vim + +func Test_compiler() + CheckExecutable perl + CheckFeature quickfix + + let save_LC_ALL = $LC_ALL + let $LC_ALL= "C" + + " %: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! + let $LC_ALL = save_LC_ALL +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 diff --git a/test/old/testdir/test_conceal.vim b/test/old/testdir/test_conceal.vim new file mode 100644 index 0000000000..a679061544 --- /dev/null +++ b/test/old/testdir/test_conceal.vim @@ -0,0 +1,412 @@ +" Tests for 'conceal'. + +source check.vim +CheckFeature conceal + +source screendump.vim +source view_util.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', 'D') + " 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) +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', 'D') + 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) +endfunc + +func Test_conceal_with_cursorcolumn() + CheckScreendump + + " Check that cursorcolumn and colorcolumn don't get broken in presence of + " wrapped lines containing concealed text + let code =<< trim [CODE] + let lines = ["one one one |hidden| one one one one one one one one", + \ "two two two two |hidden| here two two", + \ "three |hidden| three three three three three three three three"] + call setline(1, lines) + set wrap linebreak + set showbreak=\ >>>\ + syntax match test /|hidden|/ conceal + set conceallevel=2 + set concealcursor= + exe "normal /here\r" + set cursorcolumn + set colorcolumn=50 + [CODE] + + call writefile(code, 'XTest_conceal_cuc', 'D') + let buf = RunVimInTerminal('-S XTest_conceal_cuc', {'rows': 10, 'cols': 40}) + call VerifyScreenDump(buf, 'Test_conceal_cuc_01', {}) + + " move cursor to the end of line (the cursor jumps to the next screen line) + call term_sendkeys(buf, "$") + call VerifyScreenDump(buf, 'Test_conceal_cuc_02', {}) + + " clean up + call StopVimInTerminal(buf) +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', 'D') + 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 VerifyScreenDump(buf, 'Test_conceal_resize_02', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_conceal_linebreak() + CheckScreendump + + let code =<< trim [CODE] + vim9script + &wrap = true + &conceallevel = 2 + &concealcursor = 'nc' + &linebreak = true + &showbreak = '+ ' + var line: string = 'a`a`a`a`' + .. 'a'->repeat(&columns - 15) + .. ' b`b`' + .. 'b'->repeat(&columns - 10) + .. ' cccccc' + ['x'->repeat(&columns), '', line]->setline(1) + syntax region CodeSpan matchgroup=Delimiter start=/\z(`\+\)/ end=/\z1/ concealends + [CODE] + call writefile(code, 'XTest_conceal_linebreak', 'D') + let buf = RunVimInTerminal('-S XTest_conceal_linebreak', {'rows': 8}) + call VerifyScreenDump(buf, 'Test_conceal_linebreak_1', {}) + + " clean up + call StopVimInTerminal(buf) +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', 'D') + + 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') +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 + +func Test_conceal_mouse_click() + enew! + set mouse=a + setlocal conceallevel=2 concealcursor=nc + syn match Concealed "this" conceal + hi link Concealed Search + call setline(1, 'conceal this click here') + redraw + call assert_equal(['conceal click here '], ScreenLines(1, 20)) + + " click on the space between "this" and "click" puts cursor there + call Ntest_setmouse(1, 9) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 13, 0, 13], getcurpos()) + " click on 'h' of "here" puts cursor there + call Ntest_setmouse(1, 16) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 20, 0, 20], getcurpos()) + " click on 'e' of "here" puts cursor there + call Ntest_setmouse(1, 19) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 23, 0, 23], getcurpos()) + " click after end of line puts cursor on 'e' without 'virtualedit' + call Ntest_setmouse(1, 20) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 23, 0, 24], getcurpos()) + call Ntest_setmouse(1, 21) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 23, 0, 25], getcurpos()) + call Ntest_setmouse(1, 22) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 23, 0, 26], getcurpos()) + call Ntest_setmouse(1, 31) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 23, 0, 35], getcurpos()) + call Ntest_setmouse(1, 32) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 23, 0, 36], getcurpos()) + + set virtualedit=all + redraw + " click on the space between "this" and "click" puts cursor there + call Ntest_setmouse(1, 9) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 13, 0, 13], getcurpos()) + " click on 'h' of "here" puts cursor there + call Ntest_setmouse(1, 16) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 20, 0, 20], getcurpos()) + " click on 'e' of "here" puts cursor there + call Ntest_setmouse(1, 19) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 23, 0, 23], getcurpos()) + " click after end of line puts cursor there without 'virtualedit' + call Ntest_setmouse(1, 20) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 24, 0, 24], getcurpos()) + call Ntest_setmouse(1, 21) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 24, 1, 25], getcurpos()) + call Ntest_setmouse(1, 22) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 24, 2, 26], getcurpos()) + call Ntest_setmouse(1, 31) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 24, 11, 35], getcurpos()) + call Ntest_setmouse(1, 32) + call feedkeys("\<LeftMouse>", "tx") + call assert_equal([0, 1, 24, 12, 36], getcurpos()) + + bwipe! + set mouse& virtualedit& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_const.vim b/test/old/testdir/test_const.vim new file mode 100644 index 0000000000..4a6c8779dd --- /dev/null +++ b/test/old/testdir/test_const.vim @@ -0,0 +1,294 @@ + +" 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 diff --git a/test/old/testdir/test_cpoptions.vim b/test/old/testdir/test_cpoptions.vim new file mode 100644 index 0000000000..915f418712 --- /dev/null +++ b/test/old/testdir/test_cpoptions.vim @@ -0,0 +1,934 @@ +" 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 XcpoAfile1 + write XcpoAfile2 + call assert_equal('', @#) + %bw + call delete('XcpoAfile2') + new XcpoAfile1 + set cpo+=A + write XcpoAfile2 + call assert_equal('XcpoAfile2', @#) + close! + call delete('XcpoAfile2') + 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 diff --git a/test/old/testdir/test_crash.vim b/test/old/testdir/test_crash.vim new file mode 100644 index 0000000000..b093b053c5 --- /dev/null +++ b/test/old/testdir/test_crash.vim @@ -0,0 +1,155 @@ +" Some tests, that used to crash Vim +source check.vim +source screendump.vim + +CheckScreendump + +func Test_crash1() + CheckNotBSD + CheckExecutable dash + " Test 7 fails on Mac ... + CheckNotMac + + " The following used to crash Vim + let opts = #{cmd: 'sh'} + let vim = GetVimProg() + + let buf = RunVimInTerminal('sh', opts) + + let file = 'crash/poc_huaf1' + let cmn_args = "%s -u NONE -i NONE -n -e -s -S %s -c ':qa!'" + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' && echo "crash 1: [OK]" > X_crash1_result.txt' .. "\<cr>") + call TermWait(buf, 50) + + let file = 'crash/poc_huaf2' + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' && echo "crash 2: [OK]" >> X_crash1_result.txt' .. "\<cr>") + call TermWait(buf, 50) + + let file = 'crash/poc_huaf3' + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' && echo "crash 3: [OK]" >> X_crash1_result.txt' .. "\<cr>") + call TermWait(buf, 100) + + let file = 'crash/bt_quickfix_poc' + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' && echo "crash 4: [OK]" >> X_crash1_result.txt' .. "\<cr>") + " clean up + call delete('Xerr') + " This test takes a bit longer + call TermWait(buf, 1000) + + let file = 'crash/poc_tagfunc.vim' + let args = printf(cmn_args, vim, file) + " using || because this poc causes vim to exit with exitstatus != 0 + call term_sendkeys(buf, args .. + \ ' || echo "crash 5: [OK]" >> X_crash1_result.txt' .. "\<cr>") + + call TermWait(buf, 100) + + let file = 'crash/bt_quickfix1_poc' + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' && echo "crash 6: [OK]" >> X_crash1_result.txt' .. "\<cr>") + " clean up + call delete('X') + call TermWait(buf, 3000) + + let file = 'crash/vim_regsub_both_poc' + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' && echo "crash 7: [OK]" >> X_crash1_result.txt' .. "\<cr>") + call TermWait(buf, 3000) + + let file = 'crash/vim_msg_trunc_poc' + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' || echo "crash 8: [OK]" >> X_crash1_result.txt' .. "\<cr>") + call TermWait(buf, 3000) + + let file = 'crash/crash_scrollbar' + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' && echo "crash 9: [OK]" >> X_crash1_result.txt' .. "\<cr>") + call TermWait(buf, 1000) + + let file = 'crash/editing_arg_idx_POC_1' + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' || echo "crash 10: [OK]" >> X_crash1_result.txt' .. "\<cr>") + call TermWait(buf, 1000) + call delete('Xerr') + call delete('@') + + " clean up + exe buf .. "bw!" + + sp X_crash1_result.txt + + let expected = [ + \ 'crash 1: [OK]', + \ 'crash 2: [OK]', + \ 'crash 3: [OK]', + \ 'crash 4: [OK]', + \ 'crash 5: [OK]', + \ 'crash 6: [OK]', + \ 'crash 7: [OK]', + \ 'crash 8: [OK]', + \ 'crash 9: [OK]', + \ 'crash 10: [OK]', + \ ] + + call assert_equal(expected, getline(1, '$')) + bw! + + call delete('X_crash1_result.txt') +endfunc + +func Test_crash1_2() + CheckNotBSD + CheckExecutable dash + + " The following used to crash Vim + let opts = #{cmd: 'sh'} + let vim = GetVimProg() + let result = 'X_crash1_1_result.txt' + + let buf = RunVimInTerminal('sh', opts) + + let file = 'crash/poc1' + let cmn_args = "%s -u NONE -i NONE -n -e -s -S %s -c ':qa!'" + let args = printf(cmn_args, vim, file) + call term_sendkeys(buf, args .. + \ ' && echo "crash 1: [OK]" > '.. result .. "\<cr>") + call TermWait(buf, 150) + + " clean up + exe buf .. "bw!" + + exe "sp " .. result + + let expected = [ + \ 'crash 1: [OK]', + \ ] + + call assert_equal(expected, getline(1, '$')) + bw! + + call delete(result) +endfunc + +func Test_crash2() + " The following used to crash Vim + let opts = #{wait_for_ruler: 0, rows: 20} + let args = ' -u NONE -i NONE -n -e -s -S ' + let buf = RunVimInTerminal(args .. ' crash/vim_regsub_both', opts) + call VerifyScreenDump(buf, 'Test_crash_01', {}) + exe buf .. "bw!" +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_cursor_func.vim b/test/old/testdir/test_cursor_func.vim new file mode 100644 index 0000000000..cf131e8dad --- /dev/null +++ b/test/old/testdir/test_cursor_func.vim @@ -0,0 +1,606 @@ +" 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 + +func Test_curswant_maxcol() + new + call setline(1, 'foo') + + " Test that after "$" command curswant is set to the same value as v:maxcol. + normal! 1G$ + call assert_equal(v:maxcol, getcurpos()[4]) + call assert_equal(v:maxcol, winsaveview().curswant) + + 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)) + + 1split + + " w_leftcol should be subtracted + setlocal nowrap + normal G050zl$ + redraw + call assert_equal({'row': winrow + 0, + \ 'col': wincol + 10 - 1, + \ 'curscol': wincol + 10 - 1, + \ 'endcol': wincol + 10 - 1}, + \ screenpos(win_getid(), line('.'), col('.'))) + + " w_skipcol should be taken into account + setlocal wrap + normal $ + redraw + call assert_equal({'row': winrow + 0, + \ 'col': wincol + 20 - 1, + \ 'curscol': wincol + 20 - 1, + \ 'endcol': wincol + 20 - 1}, + \ screenpos(win_getid(), line('.'), col('.'))) + call assert_equal({'row': 0, 'col': 0, 'curscol': 0, 'endcol': 0}, + \ screenpos(win_getid(), line('.'), col('.') - 20)) + setlocal number + redraw + call assert_equal({'row': winrow + 0, + \ 'col': wincol + 16 - 1, + \ 'curscol': wincol + 16 - 1, + \ 'endcol': wincol + 16 - 1}, + \ screenpos(win_getid(), line('.'), col('.'))) + call assert_equal({'row': 0, 'col': 0, 'curscol': 0, 'endcol': 0}, + \ screenpos(win_getid(), line('.'), col('.') - 16)) + set cpoptions+=n + redraw + call assert_equal({'row': winrow + 0, + \ 'col': wincol + 4 - 1, + \ 'curscol': wincol + 4 - 1, + \ 'endcol': wincol + 4 - 1}, + \ screenpos(win_getid(), line('.'), col('.'))) + call assert_equal({'row': 0, 'col': 0, 'curscol': 0, 'endcol': 0}, + \ screenpos(win_getid(), line('.'), col('.') - 4)) + + wincmd + + call setline(line('$') + 1, 'last line') + setlocal smoothscroll + normal G$ + redraw + call assert_equal({'row': winrow + 1, + \ 'col': wincol + 4 + 9 - 1, + \ 'curscol': wincol + 4 + 9 - 1, + \ 'endcol': wincol + 4 + 9 - 1}, + \ screenpos(win_getid(), line('.'), col('.'))) + set cpoptions-=n + redraw + call assert_equal({'row': winrow + 1, + \ 'col': wincol + 4 + 9 - 1, + \ 'curscol': wincol + 4 + 9 - 1, + \ 'endcol': wincol + 4 + 9 - 1}, + \ screenpos(win_getid(), line('.'), col('.'))) + setlocal nonumber + redraw + call assert_equal({'row': winrow + 1, + \ 'col': wincol + 9 - 1, + \ 'curscol': wincol + 9 - 1, + \ 'endcol': wincol + 9 - 1}, + \ screenpos(win_getid(), line('.'), col('.'))) + + 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)) + call assert_equal(#{col: 3, row: 8, endcol: 3, curscol: 3}, screenpos(0, 5, 1)) + exe "normal! 3\<C-E>" + call assert_equal(#{col: 3, row: 4, endcol: 3, curscol: 3}, screenpos(0, 4, 1)) + call assert_equal(#{col: 3, row: 5, endcol: 3, curscol: 3}, screenpos(0, 5, 1)) + exe "normal! \<C-E>" + call assert_equal(#{col: 3, row: 3, endcol: 3, curscol: 3}, screenpos(0, 4, 1)) + call assert_equal(#{col: 3, row: 4, endcol: 3, curscol: 3}, screenpos(0, 5, 1)) + exe "normal! \<C-E>" + call assert_equal(#{col: 3, row: 2, endcol: 3, curscol: 3}, screenpos(0, 4, 1)) + call assert_equal(#{col: 3, row: 3, endcol: 3, curscol: 3}, screenpos(0, 5, 1)) + exe "normal! \<C-E>" + call assert_equal(#{col: 3, row: 1, endcol: 3, curscol: 3}, screenpos(0, 4, 1)) + call assert_equal(#{col: 3, row: 2, endcol: 3, curscol: 3}, screenpos(0, 5, 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)) + + " Multibyte character + call setline(1, ['a✅✅✅']) + call assert_equal(1, virtcol2col(0, 1, 1)) + call assert_equal(2, virtcol2col(0, 1, 3)) + call assert_equal(5, virtcol2col(0, 1, 5)) + call assert_equal(8, virtcol2col(0, 1, 7)) + call assert_equal(8, virtcol2col(0, 1, 8)) + + " These used to cause invalid memory access + call setline(1, '') + call assert_equal(0, virtcol2col(0, 1, 1)) + call assert_equal(0, virtcol2col(0, 1, 2)) + + let w = winwidth(0) + call setline(2, repeat('a', w + 2)) + let win_nosbr = win_getid() + split + setlocal showbreak=!! + let win_sbr = win_getid() + call assert_equal(w, virtcol2col(win_nosbr, 2, w)) + call assert_equal(w + 1, virtcol2col(win_nosbr, 2, w + 1)) + call assert_equal(w + 2, virtcol2col(win_nosbr, 2, w + 2)) + call assert_equal(w + 2, virtcol2col(win_nosbr, 2, w + 3)) + call assert_equal(w, virtcol2col(win_sbr, 2, w)) + call assert_equal(w + 1, virtcol2col(win_sbr, 2, w + 1)) + call assert_equal(w + 1, virtcol2col(win_sbr, 2, w + 2)) + call assert_equal(w + 1, virtcol2col(win_sbr, 2, w + 3)) + call assert_equal(w + 2, virtcol2col(win_sbr, 2, w + 4)) + call assert_equal(w + 2, virtcol2col(win_sbr, 2, w + 5)) + close + + call assert_fails('echo virtcol2col("0", 1, 20)', 'E1210:') + call assert_fails('echo virtcol2col(0, "1", 20)', 'E1210:') + call assert_fails('echo virtcol2col(0, 1, "1")', 'E1210:') + + bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_cursorline.vim b/test/old/testdir/test_cursorline.vim new file mode 100644 index 0000000000..99a812b1de --- /dev/null +++ b/test/old/testdir/test_cursorline.vim @@ -0,0 +1,333 @@ +" 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 VerifyScreenDump(buf, 'Test_'. filename. '_1', {}) + call term_sendkeys(buf, "fagj") + call VerifyScreenDump(buf, 'Test_'. filename. '_2', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_3', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_4', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_5', {}) + call term_sendkeys(buf, "gj") + 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 VerifyScreenDump(buf, 'Test_'. filename. '_8', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_9', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_10', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_11', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_12', {}) + if exists("+foldcolumn") && exists("+signcolumn") && exists("+breakindent") + " test with set foldcolumn signcolumn 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 VerifyScreenDump(buf, 'Test_'. filename. '_14', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_15', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_16', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_17', {}) + call term_sendkeys(buf, "gj") + 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 VerifyScreenDump(buf, 'Test_'. filename. '_20', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_21', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_22', {}) + call term_sendkeys(buf, "gj") + call VerifyScreenDump(buf, 'Test_'. filename. '_23', {}) + call term_sendkeys(buf, "gj") + 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 diff --git a/test/old/testdir/test_curswant.vim b/test/old/testdir/test_curswant.vim new file mode 100644 index 0000000000..e54cd4b280 --- /dev/null +++ b/test/old/testdir/test_curswant.vim @@ -0,0 +1,23 @@ +" 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 diff --git a/test/old/testdir/test_debugger.vim b/test/old/testdir/test_debugger.vim new file mode 100644 index 0000000000..ad03443cb4 --- /dev/null +++ b/test/old/testdir/test_debugger.vim @@ -0,0 +1,1496 @@ +" Tests for the Vim script debug commands + +source shared.vim +source screendump.vim +source check.vim + +func CheckCWD() + " Check that the longer lines don't wrap due to the length of the script name + " in cwd + let script_len = len( getcwd() .. '/Xtest1.vim' ) + let longest_line = len( 'Breakpoint in "" line 1' ) + if script_len > ( 75 - longest_line ) + throw 'Skipped: Your CWD has too many characters' + endif +endfunc +command! -nargs=0 -bar CheckCWD call CheckCWD() + +" "options" argument can contain: +" 'msec' - time to wait for a match +" 'match' - "pattern" to use "lines" as pattern instead of text +func CheckDbgOutput(buf, lines, options = {}) + " Verify the expected output + let lnum = 20 - len(a:lines) + let msec = get(a:options, 'msec', 1000) + for l in a:lines + if get(a:options, 'match', 'equal') ==# 'pattern' + call WaitForAssert({-> assert_match(l, term_getline(a:buf, lnum))}, msec) + else + call WaitForAssert({-> assert_equal(l, term_getline(a:buf, lnum))}, msec) + endif + let lnum += 1 + endfor +endfunc + +" Run a Vim debugger command +" If the expected output argument is supplied, then check for it. +func RunDbgCmd(buf, cmd, ...) + call term_sendkeys(a:buf, a:cmd . "\r") + call TermWait(a:buf) + + if a:0 != 0 + let options = #{match: 'equal'} + if a:0 > 1 + call extend(options, a:2) + endif + call CheckDbgOutput(a:buf, a:1, options) + endif +endfunc + +" Debugger tests +func Test_Debugger() + CheckRunVimInTerminal + + " Create a Vim script with some functions + let lines =<< trim END + func Foo() + let var1 = 1 + let var2 = Bar(var1) + 9 + return var2 + endfunc + func Bar(var) + let var1 = 2 + a:var + let var2 = Bazz(var1) + 4 + return var2 + endfunc + func Bazz(var) + try + let var1 = 3 + a:var + let var3 = "another var" + let var3 = "value2" + catch + let var4 = "exception" + endtry + return var1 + endfunc + def Vim9Func() + for cmd in ['confirm', 'xxxxxxx'] + for _ in [1, 2] + echo cmd + endfor + endfor + enddef + END + call writefile(lines, 'XtestDebug.vim', 'D') + + " Start Vim in a terminal + let buf = RunVimInTerminal('-S XtestDebug.vim', {}) + + " Start the Vim debugger + call RunDbgCmd(buf, ':debug echo Foo()', ['cmd: echo Foo()']) + + " Create a few stack frames by stepping through functions + call RunDbgCmd(buf, 'step', ['line 1: let var1 = 1']) + call RunDbgCmd(buf, 'step', ['line 2: let var2 = Bar(var1) + 9']) + call RunDbgCmd(buf, 'step', ['line 1: let var1 = 2 + a:var']) + call RunDbgCmd(buf, 'step', ['line 2: let var2 = Bazz(var1) + 4']) + call RunDbgCmd(buf, 'step', ['line 1: try']) + call RunDbgCmd(buf, 'step', ['line 2: let var1 = 3 + a:var']) + call RunDbgCmd(buf, 'step', ['line 3: let var3 = "another var"']) + + " check backtrace + call RunDbgCmd(buf, 'backtrace', [ + \ ' 2 function Foo[2]', + \ ' 1 Bar[2]', + \ '->0 Bazz', + \ 'line 3: let var3 = "another var"']) + + " Check variables in different stack frames + call RunDbgCmd(buf, 'echo var1', ['6']) + + call RunDbgCmd(buf, 'up') + call RunDbgCmd(buf, 'back', [ + \ ' 2 function Foo[2]', + \ '->1 Bar[2]', + \ ' 0 Bazz', + \ 'line 3: let var3 = "another var"']) + call RunDbgCmd(buf, 'echo var1', ['3']) + + call RunDbgCmd(buf, 'u') + call RunDbgCmd(buf, 'bt', [ + \ '->2 function Foo[2]', + \ ' 1 Bar[2]', + \ ' 0 Bazz', + \ 'line 3: let var3 = "another var"']) + call RunDbgCmd(buf, 'echo var1', ['1']) + + " Undefined variables + call RunDbgCmd(buf, 'step') + call RunDbgCmd(buf, 'frame 2') + call RunDbgCmd(buf, 'echo var3', [ + \ 'Error detected while processing function Foo[2]..Bar[2]..Bazz:', + \ 'line 4:', + \ 'E121: Undefined variable: var3']) + + " var3 is defined in this level with some other value + call RunDbgCmd(buf, 'fr 0') + call RunDbgCmd(buf, 'echo var3', ['another var']) + + call RunDbgCmd(buf, 'step') + call RunDbgCmd(buf, '') + call RunDbgCmd(buf, '') + call RunDbgCmd(buf, '') + call RunDbgCmd(buf, '') + call RunDbgCmd(buf, 'step', [ + \ 'function Foo[2]..Bar', + \ 'line 3: End of function']) + call RunDbgCmd(buf, 'up') + + " Undefined var2 + call RunDbgCmd(buf, 'echo var2', [ + \ 'Error detected while processing function Foo[2]..Bar:', + \ 'line 3:', + \ 'E121: Undefined variable: var2']) + + " Var2 is defined with 10 + call RunDbgCmd(buf, 'down') + call RunDbgCmd(buf, 'echo var2', ['10']) + + " Backtrace movements + call RunDbgCmd(buf, 'b', [ + \ ' 1 function Foo[2]', + \ '->0 Bar', + \ 'line 3: End of function']) + + " next command cannot go down, we are on bottom + call RunDbgCmd(buf, 'down', ['frame is zero']) + call RunDbgCmd(buf, 'up') + + " next command cannot go up, we are on top + call RunDbgCmd(buf, 'up', ['frame at highest level: 1']) + call RunDbgCmd(buf, 'where', [ + \ '->1 function Foo[2]', + \ ' 0 Bar', + \ 'line 3: End of function']) + + " fil is not frame or finish, it is file + call RunDbgCmd(buf, 'fil', ['"[No Name]" --No lines in buffer--']) + + " relative backtrace movement + call RunDbgCmd(buf, 'fr -1') + call RunDbgCmd(buf, 'frame', [ + \ ' 1 function Foo[2]', + \ '->0 Bar', + \ 'line 3: End of function']) + + call RunDbgCmd(buf, 'fr +1') + call RunDbgCmd(buf, 'fram', [ + \ '->1 function Foo[2]', + \ ' 0 Bar', + \ 'line 3: End of function']) + + " go beyond limits does not crash + call RunDbgCmd(buf, 'fr 100', ['frame at highest level: 1']) + call RunDbgCmd(buf, 'fra', [ + \ '->1 function Foo[2]', + \ ' 0 Bar', + \ 'line 3: End of function']) + + call RunDbgCmd(buf, 'frame -40', ['frame is zero']) + call RunDbgCmd(buf, 'fram', [ + \ ' 1 function Foo[2]', + \ '->0 Bar', + \ 'line 3: End of function']) + + " final result 19 + call RunDbgCmd(buf, 'cont', ['19']) + + " breakpoints tests + + " Start a debug session, so that reading the last line from the terminal + " works properly. + call RunDbgCmd(buf, ':debug echo Foo()', ['cmd: echo Foo()']) + + " No breakpoints + call RunDbgCmd(buf, 'breakl', ['No breakpoints defined']) + + " Place some breakpoints + call RunDbgCmd(buf, 'breaka func Bar') + call RunDbgCmd(buf, 'breaklis', [' 1 func Bar line 1']) + call RunDbgCmd(buf, 'breakadd func 3 Bazz') + call RunDbgCmd(buf, 'breaklist', [' 1 func Bar line 1', + \ ' 2 func Bazz line 3']) + + " Check whether the breakpoints are hit + call RunDbgCmd(buf, 'cont', [ + \ 'Breakpoint in "Bar" line 1', + \ 'function Foo[2]..Bar', + \ 'line 1: let var1 = 2 + a:var']) + call RunDbgCmd(buf, 'cont', [ + \ 'Breakpoint in "Bazz" line 3', + \ 'function Foo[2]..Bar[2]..Bazz', + \ 'line 3: let var3 = "another var"']) + + " Delete the breakpoints + call RunDbgCmd(buf, 'breakd 1') + call RunDbgCmd(buf, 'breakli', [' 2 func Bazz line 3']) + call RunDbgCmd(buf, 'breakdel func 3 Bazz') + call RunDbgCmd(buf, 'breakl', ['No breakpoints defined']) + + call RunDbgCmd(buf, 'cont') + + " Make sure the breakpoints are removed + call RunDbgCmd(buf, ':echo Foo()', ['19']) + + " Delete a non-existing breakpoint + call RunDbgCmd(buf, ':breakdel 2', ['E161: Breakpoint not found: 2']) + + " Expression breakpoint + call RunDbgCmd(buf, ':breakadd func 2 Bazz') + call RunDbgCmd(buf, ':echo Bazz(1)', [ + \ 'Entering Debug mode. Type "cont" to continue.', + \ 'function Bazz', + \ 'line 2: let var1 = 3 + a:var']) + call RunDbgCmd(buf, 'step') + call RunDbgCmd(buf, 'step') + call RunDbgCmd(buf, 'breaka expr var3') + call RunDbgCmd(buf, 'breakl', [' 3 func Bazz line 2', + \ ' 4 expr var3']) + call RunDbgCmd(buf, 'cont', ['Breakpoint in "Bazz" line 5', + \ 'Oldval = "''another var''"', + \ 'Newval = "''value2''"', + \ 'function Bazz', + \ 'line 5: catch']) + + call RunDbgCmd(buf, 'breakdel *') + call RunDbgCmd(buf, 'breakl', ['No breakpoints defined']) + + " Check for error cases + call RunDbgCmd(buf, 'breakadd abcd', [ + \ 'Error detected while processing function Bazz:', + \ 'line 5:', + \ 'E475: Invalid argument: abcd']) + call RunDbgCmd(buf, 'breakadd func', ['E475: Invalid argument: func']) + call RunDbgCmd(buf, 'breakadd func 2', ['E475: Invalid argument: func 2']) + call RunDbgCmd(buf, 'breaka func a()', ['E475: Invalid argument: func a()']) + call RunDbgCmd(buf, 'breakd abcd', ['E475: Invalid argument: abcd']) + call RunDbgCmd(buf, 'breakd func', ['E475: Invalid argument: func']) + call RunDbgCmd(buf, 'breakd func a()', ['E475: Invalid argument: func a()']) + call RunDbgCmd(buf, 'breakd func a', ['E161: Breakpoint not found: func a']) + call RunDbgCmd(buf, 'breakd expr', ['E475: Invalid argument: expr']) + call RunDbgCmd(buf, 'breakd expr x', ['E161: Breakpoint not found: expr x']) + + " finish the current function + call RunDbgCmd(buf, 'finish', [ + \ 'function Bazz', + \ 'line 8: End of function']) + call RunDbgCmd(buf, 'cont') + + " Test for :next + call RunDbgCmd(buf, ':debug echo Bar(1)') + call RunDbgCmd(buf, 'step') + call RunDbgCmd(buf, 'next') + call RunDbgCmd(buf, '', [ + \ 'function Bar', + \ 'line 3: return var2']) + call RunDbgCmd(buf, 'c') + + " Test for :interrupt + call RunDbgCmd(buf, ':debug echo Bazz(1)') + call RunDbgCmd(buf, 'step') + call RunDbgCmd(buf, 'step') + call RunDbgCmd(buf, 'interrupt', [ + \ 'Exception thrown: Vim:Interrupt', + \ 'function Bazz', + \ 'line 5: catch']) + call RunDbgCmd(buf, 'c') + + " Test showing local variable in :def function + call RunDbgCmd(buf, ':breakadd func 2 Vim9Func') + call RunDbgCmd(buf, ':call Vim9Func()', ['line 2: for _ in [1, 2]']) + call RunDbgCmd(buf, 'next', ['line 2: for _ in [1, 2]']) + call RunDbgCmd(buf, 'echo cmd', ['confirm']) + call RunDbgCmd(buf, 'breakdel *') + call RunDbgCmd(buf, 'cont') + + " Test for :quit + call RunDbgCmd(buf, ':debug echo Foo()') + call RunDbgCmd(buf, 'breakdel *') + call RunDbgCmd(buf, 'breakadd func 3 Foo') + call RunDbgCmd(buf, 'breakadd func 3 Bazz') + call RunDbgCmd(buf, 'cont', [ + \ 'Breakpoint in "Bazz" line 3', + \ 'function Foo[2]..Bar[2]..Bazz', + \ 'line 3: let var3 = "another var"']) + call RunDbgCmd(buf, 'quit', [ + \ 'Breakpoint in "Foo" line 3', + \ 'function Foo', + \ 'line 3: return var2']) + call RunDbgCmd(buf, 'breakdel *') + call RunDbgCmd(buf, 'quit') + call RunDbgCmd(buf, 'enew! | only!') + + call StopVimInTerminal(buf) +endfunc + +func Test_Debugger_breakadd() + " Tests for :breakadd file and :breakadd here + " Breakpoints should be set before sourcing the file + CheckRunVimInTerminal + + let lines =<< trim END + let var1 = 10 + let var2 = 20 + let var3 = 30 + let var4 = 40 + END + call writefile(lines, 'XdebugBreakadd.vim', 'D') + + " Start Vim in a terminal + let buf = RunVimInTerminal('XdebugBreakadd.vim', {}) + call RunDbgCmd(buf, ':breakadd file 2 XdebugBreakadd.vim') + call RunDbgCmd(buf, ':4 | breakadd here') + call RunDbgCmd(buf, ':source XdebugBreakadd.vim', ['line 2: let var2 = 20']) + call RunDbgCmd(buf, 'cont', ['line 4: let var4 = 40']) + call RunDbgCmd(buf, 'cont') + + call StopVimInTerminal(buf) + + %bw! + + call assert_fails('breakadd here', 'E32:') + call assert_fails('breakadd file Xtest.vim /\)/', 'E55:') +endfunc + +" Test for expression breakpoint set using ":breakadd expr <expr>" +func Test_Debugger_breakadd_expr() + CheckRunVimInTerminal + CheckCWD + + let lines =<< trim END + let g:Xtest_var += 1 + END + call writefile(lines, 'XdebugBreakExpr.vim', 'D') + + " Start Vim in a terminal + let buf = RunVimInTerminal('XdebugBreakExpr.vim', {}) + call RunDbgCmd(buf, ':let g:Xtest_var = 10') + call RunDbgCmd(buf, ':breakadd expr g:Xtest_var') + call RunDbgCmd(buf, ':source %') + let expected =<< trim eval END + Oldval = "10" + Newval = "11" + {fnamemodify('XdebugBreakExpr.vim', ':p')} + line 1: let g:Xtest_var += 1 + END + call RunDbgCmd(buf, ':source %', expected) + call RunDbgCmd(buf, 'cont') + let expected =<< trim eval END + Oldval = "11" + Newval = "12" + {fnamemodify('XdebugBreakExpr.vim', ':p')} + line 1: let g:Xtest_var += 1 + END + call RunDbgCmd(buf, ':source %', expected) + + call StopVimInTerminal(buf) +endfunc + +func Test_Backtrace_Through_Source() + CheckRunVimInTerminal + CheckCWD + let file1 =<< trim END + func SourceAnotherFile() + source Xtest2.vim + endfunc + + func CallAFunction() + call SourceAnotherFile() + call File2Function() + endfunc + + func GlobalFunction() + call CallAFunction() + endfunc + END + call writefile(file1, 'Xtest1.vim', 'D') + + let file2 =<< trim END + func DoAThing() + echo "DoAThing" + endfunc + + func File2Function() + call DoAThing() + endfunc + + call File2Function() + END + call writefile(file2, 'Xtest2.vim', 'D') + + let buf = RunVimInTerminal('-S Xtest1.vim', {}) + + call RunDbgCmd(buf, + \ ':debug call GlobalFunction()', + \ ['cmd: call GlobalFunction()']) + call RunDbgCmd(buf, 'step', ['line 1: call CallAFunction()']) + + call RunDbgCmd(buf, 'backtrace', ['>backtrace', + \ '->0 function GlobalFunction', + \ 'line 1: call CallAFunction()']) + + call RunDbgCmd(buf, 'step', ['line 1: call SourceAnotherFile()']) + call RunDbgCmd(buf, 'step', ['line 1: source Xtest2.vim']) + + call RunDbgCmd(buf, 'backtrace', ['>backtrace', + \ ' 2 function GlobalFunction[1]', + \ ' 1 CallAFunction[1]', + \ '->0 SourceAnotherFile', + \ 'line 1: source Xtest2.vim']) + + " Step into the 'source' command. Note that we print the full trace all the + " way though the source command. + call RunDbgCmd(buf, 'step', ['line 1: func DoAThing()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ '->0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()']) + + call RunDbgCmd( buf, 'up' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ '->1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'up' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 function GlobalFunction[1]', + \ '->2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'up' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ '->3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'up', [ 'frame at highest level: 3' ] ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ '->3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'down' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 function GlobalFunction[1]', + \ '->2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'down' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ '->1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'down' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ '->0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'down', [ 'frame is zero' ] ) + + " step until we have another meaninfgul trace + call RunDbgCmd(buf, 'step', ['line 5: func File2Function()']) + call RunDbgCmd(buf, 'step', ['line 9: call File2Function()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ '->0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 9: call File2Function()']) + + call RunDbgCmd(buf, 'step', ['line 1: call DoAThing()']) + call RunDbgCmd(buf, 'step', ['line 1: echo "DoAThing"']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 5 function GlobalFunction[1]', + \ ' 4 CallAFunction[1]', + \ ' 3 SourceAnotherFile[1]', + \ ' 2 script ' .. getcwd() .. '/Xtest2.vim[9]', + \ ' 1 function File2Function[1]', + \ '->0 DoAThing', + \ 'line 1: echo "DoAThing"']) + + " Now, step (back to Xfile1.vim), and call the function _in_ Xfile2.vim + call RunDbgCmd(buf, 'step', ['line 1: End of function']) + call RunDbgCmd(buf, 'step', ['line 1: End of function']) + call RunDbgCmd(buf, 'step', ['line 10: End of sourced file']) + call RunDbgCmd(buf, 'step', ['line 1: End of function']) + call RunDbgCmd(buf, 'step', ['line 2: call File2Function()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 1 function GlobalFunction[1]', + \ '->0 CallAFunction', + \ 'line 2: call File2Function()']) + + call RunDbgCmd(buf, 'step', ['line 1: call DoAThing()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 2 function GlobalFunction[1]', + \ ' 1 CallAFunction[2]', + \ '->0 File2Function', + \ 'line 1: call DoAThing()']) + + call StopVimInTerminal(buf) +endfunc + +func Test_Backtrace_Autocmd() + CheckRunVimInTerminal + CheckCWD + let file1 =<< trim END + func SourceAnotherFile() + source Xtest2.vim + endfunc + + func CallAFunction() + call SourceAnotherFile() + call File2Function() + endfunc + + func GlobalFunction() + call CallAFunction() + endfunc + + au User TestGlobalFunction :call GlobalFunction() | echo "Done" + END + call writefile(file1, 'Xtest1.vim', 'D') + + let file2 =<< trim END + func DoAThing() + echo "DoAThing" + endfunc + + func File2Function() + call DoAThing() + endfunc + + call File2Function() + END + call writefile(file2, 'Xtest2.vim', 'D') + + let buf = RunVimInTerminal('-S Xtest1.vim', {}) + + call RunDbgCmd(buf, + \ ':debug doautocmd User TestGlobalFunction', + \ ['cmd: doautocmd User TestGlobalFunction']) + call RunDbgCmd(buf, 'step', ['cmd: call GlobalFunction() | echo "Done"']) + + " At this point the ontly thing in the stack is the autocommand + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ '->0 User Autocommands for "TestGlobalFunction"', + \ 'cmd: call GlobalFunction() | echo "Done"']) + + " And now we're back into the call stack + call RunDbgCmd(buf, 'step', ['line 1: call CallAFunction()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 1 User Autocommands for "TestGlobalFunction"', + \ '->0 function GlobalFunction', + \ 'line 1: call CallAFunction()']) + + call RunDbgCmd(buf, 'step', ['line 1: call SourceAnotherFile()']) + call RunDbgCmd(buf, 'step', ['line 1: source Xtest2.vim']) + + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 User Autocommands for "TestGlobalFunction"', + \ ' 2 function GlobalFunction[1]', + \ ' 1 CallAFunction[1]', + \ '->0 SourceAnotherFile', + \ 'line 1: source Xtest2.vim']) + + " Step into the 'source' command. Note that we print the full trace all the + " way though the source command. + call RunDbgCmd(buf, 'step', ['line 1: func DoAThing()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 4 User Autocommands for "TestGlobalFunction"', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ '->0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()']) + + call RunDbgCmd( buf, 'up' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 4 User Autocommands for "TestGlobalFunction"', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ '->1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'up' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 4 User Autocommands for "TestGlobalFunction"', + \ ' 3 function GlobalFunction[1]', + \ '->2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'up' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 4 User Autocommands for "TestGlobalFunction"', + \ '->3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'up' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ '->4 User Autocommands for "TestGlobalFunction"', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'up', [ 'frame at highest level: 4' ] ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ '->4 User Autocommands for "TestGlobalFunction"', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'down' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 4 User Autocommands for "TestGlobalFunction"', + \ '->3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + + call RunDbgCmd( buf, 'down' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 4 User Autocommands for "TestGlobalFunction"', + \ ' 3 function GlobalFunction[1]', + \ '->2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'down' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 4 User Autocommands for "TestGlobalFunction"', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ '->1 SourceAnotherFile[1]', + \ ' 0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'down' ) + call RunDbgCmd( buf, 'backtrace', [ + \ '>backtrace', + \ ' 4 User Autocommands for "TestGlobalFunction"', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ '->0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 1: func DoAThing()' ] ) + + call RunDbgCmd( buf, 'down', [ 'frame is zero' ] ) + + " step until we have another meaninfgul trace + call RunDbgCmd(buf, 'step', ['line 5: func File2Function()']) + call RunDbgCmd(buf, 'step', ['line 9: call File2Function()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 4 User Autocommands for "TestGlobalFunction"', + \ ' 3 function GlobalFunction[1]', + \ ' 2 CallAFunction[1]', + \ ' 1 SourceAnotherFile[1]', + \ '->0 script ' .. getcwd() .. '/Xtest2.vim', + \ 'line 9: call File2Function()']) + + call RunDbgCmd(buf, 'step', ['line 1: call DoAThing()']) + call RunDbgCmd(buf, 'step', ['line 1: echo "DoAThing"']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 6 User Autocommands for "TestGlobalFunction"', + \ ' 5 function GlobalFunction[1]', + \ ' 4 CallAFunction[1]', + \ ' 3 SourceAnotherFile[1]', + \ ' 2 script ' .. getcwd() .. '/Xtest2.vim[9]', + \ ' 1 function File2Function[1]', + \ '->0 DoAThing', + \ 'line 1: echo "DoAThing"']) + + " Now, step (back to Xfile1.vim), and call the function _in_ Xfile2.vim + call RunDbgCmd(buf, 'step', ['line 1: End of function']) + call RunDbgCmd(buf, 'step', ['line 1: End of function']) + call RunDbgCmd(buf, 'step', ['line 10: End of sourced file']) + call RunDbgCmd(buf, 'step', ['line 1: End of function']) + call RunDbgCmd(buf, 'step', ['line 2: call File2Function()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 2 User Autocommands for "TestGlobalFunction"', + \ ' 1 function GlobalFunction[1]', + \ '->0 CallAFunction', + \ 'line 2: call File2Function()']) + + call RunDbgCmd(buf, 'step', ['line 1: call DoAThing()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 User Autocommands for "TestGlobalFunction"', + \ ' 2 function GlobalFunction[1]', + \ ' 1 CallAFunction[2]', + \ '->0 File2Function', + \ 'line 1: call DoAThing()']) + + + " Now unwind so that we get back to the original autocommand (and the second + " cmd echo "Done") + call RunDbgCmd(buf, 'finish', ['line 1: End of function']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 3 User Autocommands for "TestGlobalFunction"', + \ ' 2 function GlobalFunction[1]', + \ ' 1 CallAFunction[2]', + \ '->0 File2Function', + \ 'line 1: End of function']) + + call RunDbgCmd(buf, 'finish', ['line 2: End of function']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 2 User Autocommands for "TestGlobalFunction"', + \ ' 1 function GlobalFunction[1]', + \ '->0 CallAFunction', + \ 'line 2: End of function']) + + call RunDbgCmd(buf, 'finish', ['line 1: End of function']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 1 User Autocommands for "TestGlobalFunction"', + \ '->0 function GlobalFunction', + \ 'line 1: End of function']) + + call RunDbgCmd(buf, 'step', ['cmd: echo "Done"']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ '->0 User Autocommands for "TestGlobalFunction"', + \ 'cmd: echo "Done"']) + + call StopVimInTerminal(buf) +endfunc + +func Test_Backtrace_CmdLine() + CheckRunVimInTerminal + CheckCWD + let file1 =<< trim END + func SourceAnotherFile() + source Xtest2.vim + endfunc + + func CallAFunction() + call SourceAnotherFile() + call File2Function() + endfunc + + func GlobalFunction() + call CallAFunction() + endfunc + + au User TestGlobalFunction :call GlobalFunction() | echo "Done" + END + call writefile(file1, 'Xtest1.vim', 'D') + + let file2 =<< trim END + func DoAThing() + echo "DoAThing" + endfunc + + func File2Function() + call DoAThing() + endfunc + + call File2Function() + END + call writefile(file2, 'Xtest2.vim', 'D') + + let buf = RunVimInTerminal( + \ '-S Xtest1.vim -c "debug call GlobalFunction()"', + \ {'wait_for_ruler': 0}) + + " Need to wait for the vim-in-terminal to be ready. + " With valgrind this can take quite long. + call CheckDbgOutput(buf, ['command line', + \ 'cmd: call GlobalFunction()'], #{msec: 5000}) + + " At this point the ontly thing in the stack is the cmdline + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ '->0 command line', + \ 'cmd: call GlobalFunction()']) + + " And now we're back into the call stack + call RunDbgCmd(buf, 'step', ['line 1: call CallAFunction()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '>backtrace', + \ ' 1 command line', + \ '->0 function GlobalFunction', + \ 'line 1: call CallAFunction()']) + + call StopVimInTerminal(buf) +endfunc + +func Test_Backtrace_DefFunction() + CheckRunVimInTerminal + CheckCWD + let file1 =<< trim END + vim9script + import './Xtest2.vim' as imp + + def SourceAnotherFile() + source Xtest2.vim + enddef + + def CallAFunction() + SourceAnotherFile() + imp.File2Function() + enddef + + def g:GlobalFunction() + var some = "some var" + CallAFunction() + enddef + + defcompile + END + call writefile(file1, 'Xtest1.vim', 'D') + + let file2 =<< trim END + vim9script + + def DoAThing(): number + var a = 100 * 2 + a += 3 + return a + enddef + + export def File2Function() + DoAThing() + enddef + + defcompile + File2Function() + END + call writefile(file2, 'Xtest2.vim', 'D') + + let buf = RunVimInTerminal('-S Xtest1.vim', {}) + + call RunDbgCmd(buf, + \ ':debug call GlobalFunction()', + \ ['cmd: call GlobalFunction()']) + + call RunDbgCmd(buf, 'step', ['line 1: var some = "some var"']) + call RunDbgCmd(buf, 'step', ['line 2: CallAFunction()']) + call RunDbgCmd(buf, 'echo some', ['some var']) + + call RunDbgCmd(buf, 'backtrace', [ + \ '\V>backtrace', + \ '\V->0 function GlobalFunction', + \ '\Vline 2: CallAFunction()', + \ ], + \ #{match: 'pattern'}) + + call RunDbgCmd(buf, 'step', ['line 1: SourceAnotherFile()']) + call RunDbgCmd(buf, 'step', ['line 1: source Xtest2.vim']) + " Repeated line, because we fist are in the compiled function before the + " EXEC and then in do_cmdline() before the :source command. + call RunDbgCmd(buf, 'step', ['line 1: source Xtest2.vim']) + call RunDbgCmd(buf, 'step', ['line 1: vim9script']) + call RunDbgCmd(buf, 'step', ['line 3: def DoAThing(): number']) + call RunDbgCmd(buf, 'step', ['line 9: export def File2Function()']) + call RunDbgCmd(buf, 'step', ['line 9: def File2Function()']) + call RunDbgCmd(buf, 'step', ['line 13: defcompile']) + call RunDbgCmd(buf, 'step', ['line 14: File2Function()']) + call RunDbgCmd(buf, 'backtrace', [ + \ '\V>backtrace', + \ '\V 3 function GlobalFunction[2]', + \ '\V 2 <SNR>\.\*_CallAFunction[1]', + \ '\V 1 <SNR>\.\*_SourceAnotherFile[1]', + \ '\V->0 script ' .. getcwd() .. '/Xtest2.vim', + \ '\Vline 14: File2Function()'], + \ #{match: 'pattern'}) + + " Don't step into compiled functions... + call RunDbgCmd(buf, 'next', ['line 15: End of sourced file']) + call RunDbgCmd(buf, 'backtrace', [ + \ '\V>backtrace', + \ '\V 3 function GlobalFunction[2]', + \ '\V 2 <SNR>\.\*_CallAFunction[1]', + \ '\V 1 <SNR>\.\*_SourceAnotherFile[1]', + \ '\V->0 script ' .. getcwd() .. '/Xtest2.vim', + \ '\Vline 15: End of sourced file'], + \ #{match: 'pattern'}) + + call StopVimInTerminal(buf) +endfunc + +func Test_DefFunction_expr() + CheckRunVimInTerminal + CheckCWD + let file3 =<< trim END + vim9script + g:someVar = "foo" + def g:ChangeVar() + g:someVar = "bar" + echo "changed" + enddef + defcompile + END + call writefile(file3, 'Xtest3.vim', 'D') + let buf = RunVimInTerminal('-S Xtest3.vim', {}) + + call RunDbgCmd(buf, ':breakadd expr g:someVar') + call RunDbgCmd(buf, ':call g:ChangeVar()', ['Oldval = "''foo''"', 'Newval = "''bar''"', 'function ChangeVar', 'line 2: echo "changed"']) + + call StopVimInTerminal(buf) +endfunc + +func Test_debug_def_and_legacy_function() + CheckRunVimInTerminal + CheckCWD + let file =<< trim END + vim9script + def g:SomeFunc() + echo "here" + echo "and" + echo "there" + breakadd func 2 LocalFunc + LocalFunc() + enddef + + def LocalFunc() + echo "first" + echo "second" + breakadd func LegacyFunc + LegacyFunc() + enddef + + func LegacyFunc() + echo "legone" + echo "legtwo" + endfunc + + breakadd func 2 g:SomeFunc + END + call writefile(file, 'XtestDebug.vim', 'D') + + let buf = RunVimInTerminal('-S XtestDebug.vim', {}) + + call RunDbgCmd(buf,':call SomeFunc()', ['line 2: echo "and"']) + call RunDbgCmd(buf,'next', ['line 3: echo "there"']) + call RunDbgCmd(buf,'next', ['line 4: breakadd func 2 LocalFunc']) + + " continue, next breakpoint is in LocalFunc() + call RunDbgCmd(buf,'cont', ['line 2: echo "second"']) + + " continue, next breakpoint is in LegacyFunc() + call RunDbgCmd(buf,'cont', ['line 1: echo "legone"']) + + call RunDbgCmd(buf, 'cont') + + call StopVimInTerminal(buf) +endfunc + +func Test_debug_def_function() + CheckRunVimInTerminal + CheckCWD + let file =<< trim END + vim9script + def g:Func() + var n: number + def Closure(): number + return n + 3 + enddef + n += Closure() + echo 'result: ' .. n + enddef + + def g:FuncWithArgs(text: string, nr: number, ...items: list<number>) + echo text .. nr + for it in items + echo it + endfor + echo "done" + enddef + + def g:FuncWithDict() + var d = { + a: 1, + b: 2, + } + # comment + def Inner() + eval 1 + 2 + enddef + enddef + + def g:FuncComment() + # comment + echo "first" + .. "one" + # comment + echo "second" + enddef + + def g:FuncForLoop() + eval 1 + 2 + for i in [11, 22, 33] + eval i + 2 + endfor + echo "done" + enddef + + def g:FuncWithSplitLine() + eval 1 + 2 + | eval 2 + 3 + enddef + END + call writefile(file, 'Xtest.vim', 'D') + + let buf = RunVimInTerminal('-S Xtest.vim', {}) + + call RunDbgCmd(buf, + \ ':debug call Func()', + \ ['cmd: call Func()']) + call RunDbgCmd(buf, 'next', ['result: 3']) + call term_sendkeys(buf, "\r") + call RunDbgCmd(buf, 'cont') + + call RunDbgCmd(buf, + \ ':debug call FuncWithArgs("asdf", 42, 1, 2, 3)', + \ ['cmd: call FuncWithArgs("asdf", 42, 1, 2, 3)']) + call RunDbgCmd(buf, 'step', ['line 1: echo text .. nr']) + call RunDbgCmd(buf, 'echo text', ['asdf']) + call RunDbgCmd(buf, 'echo nr', ['42']) + call RunDbgCmd(buf, 'echo items', ['[1, 2, 3]']) + call RunDbgCmd(buf, 'step', ['asdf42', 'function FuncWithArgs', 'line 2: for it in items']) + call RunDbgCmd(buf, 'step', ['function FuncWithArgs', 'line 2: for it in items']) + call RunDbgCmd(buf, 'echo it', ['0']) + call RunDbgCmd(buf, 'step', ['line 3: echo it']) + call RunDbgCmd(buf, 'echo it', ['1']) + call RunDbgCmd(buf, 'step', ['1', 'function FuncWithArgs', 'line 4: endfor']) + call RunDbgCmd(buf, 'step', ['line 2: for it in items']) + call RunDbgCmd(buf, 'echo it', ['1']) + call RunDbgCmd(buf, 'step', ['line 3: echo it']) + call RunDbgCmd(buf, 'step', ['2', 'function FuncWithArgs', 'line 4: endfor']) + call RunDbgCmd(buf, 'step', ['line 2: for it in items']) + call RunDbgCmd(buf, 'echo it', ['2']) + call RunDbgCmd(buf, 'step', ['line 3: echo it']) + call RunDbgCmd(buf, 'step', ['3', 'function FuncWithArgs', 'line 4: endfor']) + call RunDbgCmd(buf, 'step', ['line 2: for it in items']) + call RunDbgCmd(buf, 'step', ['line 5: echo "done"']) + call RunDbgCmd(buf, 'cont') + + call RunDbgCmd(buf, + \ ':debug call FuncWithDict()', + \ ['cmd: call FuncWithDict()']) + call RunDbgCmd(buf, 'step', ['line 1: var d = { a: 1, b: 2, }']) + call RunDbgCmd(buf, 'step', ['line 6: def Inner()']) + call RunDbgCmd(buf, 'cont') + + call RunDbgCmd(buf, ':breakadd func 1 FuncComment') + call RunDbgCmd(buf, ':call FuncComment()', ['function FuncComment', 'line 2: echo "first" .. "one"']) + call RunDbgCmd(buf, ':breakadd func 3 FuncComment') + call RunDbgCmd(buf, 'cont', ['function FuncComment', 'line 5: echo "second"']) + call RunDbgCmd(buf, 'cont') + + call RunDbgCmd(buf, ':breakadd func 2 FuncForLoop') + call RunDbgCmd(buf, ':call FuncForLoop()', ['function FuncForLoop', 'line 2: for i in [11, 22, 33]']) + call RunDbgCmd(buf, 'step', ['line 2: for i in [11, 22, 33]']) + call RunDbgCmd(buf, 'next', ['function FuncForLoop', 'line 3: eval i + 2']) + call RunDbgCmd(buf, 'echo i', ['11']) + call RunDbgCmd(buf, 'next', ['function FuncForLoop', 'line 4: endfor']) + call RunDbgCmd(buf, 'next', ['function FuncForLoop', 'line 2: for i in [11, 22, 33]']) + call RunDbgCmd(buf, 'next', ['line 3: eval i + 2']) + call RunDbgCmd(buf, 'echo i', ['22']) + + call RunDbgCmd(buf, 'breakdel *') + call RunDbgCmd(buf, 'cont') + + call RunDbgCmd(buf, ':breakadd func FuncWithSplitLine') + call RunDbgCmd(buf, ':call FuncWithSplitLine()', ['function FuncWithSplitLine', 'line 1: eval 1 + 2 | eval 2 + 3']) + + call RunDbgCmd(buf, 'cont') + call StopVimInTerminal(buf) +endfunc + +func Test_debug_def_function_with_lambda() + CheckRunVimInTerminal + CheckCWD + let lines =<< trim END + vim9script + def g:Func() + var s = 'a' + ['b']->map((_, v) => s) + echo "done" + enddef + breakadd func 2 g:Func + END + call writefile(lines, 'XtestLambda.vim', 'D') + + let buf = RunVimInTerminal('-S XtestLambda.vim', {}) + + call RunDbgCmd(buf, + \ ':call g:Func()', + \ ['function Func', 'line 2: [''b'']->map((_, v) => s)']) + call RunDbgCmd(buf, + \ 'next', + \ ['function Func', 'line 3: echo "done"']) + + call RunDbgCmd(buf, 'cont') + call StopVimInTerminal(buf) +endfunc + +func Test_debug_backtrace_level() + CheckRunVimInTerminal + CheckCWD + let lines =<< trim END + let s:file1_var = 'file1' + let g:global_var = 'global' + + func s:File1Func( arg ) + let s:file1_var .= a:arg + let local_var = s:file1_var .. ' test1' + let g:global_var .= local_var + source Xtest2.vim + endfunc + + call s:File1Func( 'arg1' ) + END + call writefile(lines, 'Xtest1.vim', 'D') + + let lines =<< trim END + let s:file2_var = 'file2' + + func s:File2Func( arg ) + let s:file2_var .= a:arg + let local_var = s:file2_var .. ' test2' + let g:global_var .= local_var + endfunc + + call s:File2Func( 'arg2' ) + END + call writefile(lines, 'Xtest2.vim', 'D') + + let file1 = getcwd() .. '/Xtest1.vim' + let file2 = getcwd() .. '/Xtest2.vim' + + " set a breakpoint and source file1.vim + let buf = RunVimInTerminal( + \ '-c "breakadd file 1 Xtest1.vim" -S Xtest1.vim', + \ #{wait_for_ruler: 0}) + + call CheckDbgOutput(buf, [ + \ 'Breakpoint in "' .. file1 .. '" line 1', + \ 'Entering Debug mode. Type "cont" to continue.', + \ 'command line..script ' .. file1, + \ 'line 1: let s:file1_var = ''file1''' + \ ], #{msec: 5000}) + + " step through the initial declarations + call RunDbgCmd(buf, 'step', [ 'line 2: let g:global_var = ''global''' ] ) + call RunDbgCmd(buf, 'step', [ 'line 4: func s:File1Func( arg )' ] ) + call RunDbgCmd(buf, 'echo s:file1_var', [ 'file1' ] ) + call RunDbgCmd(buf, 'echo g:global_var', [ 'global' ] ) + call RunDbgCmd(buf, 'echo global_var', [ 'global' ] ) + + " step in to the first function + call RunDbgCmd(buf, 'step', [ 'line 11: call s:File1Func( ''arg1'' )' ] ) + call RunDbgCmd(buf, 'step', [ 'line 1: let s:file1_var .= a:arg' ] ) + call RunDbgCmd(buf, 'echo a:arg', [ 'arg1' ] ) + call RunDbgCmd(buf, 'echo s:file1_var', [ 'file1' ] ) + call RunDbgCmd(buf, 'echo g:global_var', [ 'global' ] ) + call RunDbgCmd(buf, + \'echo global_var', + \[ 'E121: Undefined variable: global_var' ] ) + call RunDbgCmd(buf, + \'echo local_var', + \[ 'E121: Undefined variable: local_var' ] ) + call RunDbgCmd(buf, + \'echo l:local_var', + \[ 'E121: Undefined variable: l:local_var' ] ) + + " backtrace up + call RunDbgCmd(buf, 'backtrace', [ + \ '\V>backtrace', + \ '\V 2 command line', + \ '\V 1 script ' .. file1 .. '[11]', + \ '\V->0 function <SNR>\.\*_File1Func', + \ '\Vline 1: let s:file1_var .= a:arg', + \ ], + \ #{ match: 'pattern' } ) + call RunDbgCmd(buf, 'up', [ '>up' ] ) + + call RunDbgCmd(buf, 'backtrace', [ + \ '\V>backtrace', + \ '\V 2 command line', + \ '\V->1 script ' .. file1 .. '[11]', + \ '\V 0 function <SNR>\.\*_File1Func', + \ '\Vline 1: let s:file1_var .= a:arg', + \ ], + \ #{ match: 'pattern' } ) + + " Expression evaluation in the script frame (not the function frame) + " FIXME: Unexpected in this scope (a: should not be visibnle) + call RunDbgCmd(buf, 'echo a:arg', [ 'arg1' ] ) + call RunDbgCmd(buf, 'echo s:file1_var', [ 'file1' ] ) + call RunDbgCmd(buf, 'echo g:global_var', [ 'global' ] ) + " FIXME: Unexpected in this scope (global should be found) + call RunDbgCmd(buf, + \'echo global_var', + \[ 'E121: Undefined variable: global_var' ] ) + call RunDbgCmd(buf, + \'echo local_var', + \[ 'E121: Undefined variable: local_var' ] ) + call RunDbgCmd(buf, + \'echo l:local_var', + \[ 'E121: Undefined variable: l:local_var' ] ) + + + " step while backtraced jumps to the latest frame + call RunDbgCmd(buf, 'step', [ + \ 'line 2: let local_var = s:file1_var .. '' test1''' ] ) + call RunDbgCmd(buf, 'backtrace', [ + \ '\V>backtrace', + \ '\V 2 command line', + \ '\V 1 script ' .. file1 .. '[11]', + \ '\V->0 function <SNR>\.\*_File1Func', + \ '\Vline 2: let local_var = s:file1_var .. '' test1''', + \ ], + \ #{ match: 'pattern' } ) + + call RunDbgCmd(buf, 'step', [ 'line 3: let g:global_var .= local_var' ] ) + call RunDbgCmd(buf, 'echo local_var', [ 'file1arg1 test1' ] ) + call RunDbgCmd(buf, 'echo l:local_var', [ 'file1arg1 test1' ] ) + + call RunDbgCmd(buf, 'step', [ 'line 4: source Xtest2.vim' ] ) + call RunDbgCmd(buf, 'step', [ 'line 1: let s:file2_var = ''file2''' ] ) + call RunDbgCmd(buf, 'backtrace', [ + \ '\V>backtrace', + \ '\V 3 command line', + \ '\V 2 script ' .. file1 .. '[11]', + \ '\V 1 function <SNR>\.\*_File1Func[4]', + \ '\V->0 script ' .. file2, + \ '\Vline 1: let s:file2_var = ''file2''', + \ ], + \ #{ match: 'pattern' } ) + + " Expression evaluation in the script frame file2 (not the function frame) + call RunDbgCmd(buf, 'echo a:arg', [ 'E121: Undefined variable: a:arg' ] ) + call RunDbgCmd(buf, + \ 'echo s:file1_var', + \ [ 'E121: Undefined variable: s:file1_var' ] ) + call RunDbgCmd(buf, 'echo g:global_var', [ 'globalfile1arg1 test1' ] ) + call RunDbgCmd(buf, 'echo global_var', [ 'globalfile1arg1 test1' ] ) + call RunDbgCmd(buf, + \'echo local_var', + \[ 'E121: Undefined variable: local_var' ] ) + call RunDbgCmd(buf, + \'echo l:local_var', + \[ 'E121: Undefined variable: l:local_var' ] ) + call RunDbgCmd(buf, + \ 'echo s:file2_var', + \ [ 'E121: Undefined variable: s:file2_var' ] ) + + call RunDbgCmd(buf, 'step', [ 'line 3: func s:File2Func( arg )' ] ) + call RunDbgCmd(buf, 'echo s:file2_var', [ 'file2' ] ) + + " Up the stack to the other script context + call RunDbgCmd(buf, 'up') + call RunDbgCmd(buf, 'backtrace', [ + \ '\V>backtrace', + \ '\V 3 command line', + \ '\V 2 script ' .. file1 .. '[11]', + \ '\V->1 function <SNR>\.\*_File1Func[4]', + \ '\V 0 script ' .. file2, + \ '\Vline 3: func s:File2Func( arg )', + \ ], + \ #{ match: 'pattern' } ) + " FIXME: Unexpected. Should see the a: and l: dicts from File1Func + call RunDbgCmd(buf, 'echo a:arg', [ 'E121: Undefined variable: a:arg' ] ) + call RunDbgCmd(buf, + \ 'echo l:local_var', + \ [ 'E121: Undefined variable: l:local_var' ] ) + + call RunDbgCmd(buf, 'up') + call RunDbgCmd(buf, 'backtrace', [ + \ '\V>backtrace', + \ '\V 3 command line', + \ '\V->2 script ' .. file1 .. '[11]', + \ '\V 1 function <SNR>\.\*_File1Func[4]', + \ '\V 0 script ' .. file2, + \ '\Vline 3: func s:File2Func( arg )', + \ ], + \ #{ match: 'pattern' } ) + + " FIXME: Unexpected (wrong script vars are used) + call RunDbgCmd(buf, + \ 'echo s:file1_var', + \ [ 'E121: Undefined variable: s:file1_var' ] ) + call RunDbgCmd(buf, 'echo s:file2_var', [ 'file2' ] ) + + call RunDbgCmd(buf, 'cont') + call StopVimInTerminal(buf) +endfunc + +" Test for setting a breakpoint on a :endif where the :if condition is false +" and then quit the script. This should generate an interrupt. +func Test_breakpt_endif_intr() + func F() + let g:Xpath ..= 'a' + if v:false + let g:Xpath ..= 'b' + endif + invalid_command + endfunc + + let g:Xpath = '' + breakadd func 4 F + try + let caught_intr = 0 + debuggreedy + call feedkeys(":call F()\<CR>quit\<CR>", "xt") + catch /^Vim:Interrupt$/ + call assert_match('\.F, line 4', v:throwpoint) + let caught_intr = 1 + endtry + 0debuggreedy + call assert_equal(1, caught_intr) + call assert_equal('a', g:Xpath) + breakdel * + delfunc F +endfunc + +" Test for setting a breakpoint on a :else where the :if condition is false +" and then quit the script. This should generate an interrupt. +func Test_breakpt_else_intr() + func F() + let g:Xpath ..= 'a' + if v:false + let g:Xpath ..= 'b' + else + invalid_command + endif + invalid_command + endfunc + + let g:Xpath = '' + breakadd func 4 F + try + let caught_intr = 0 + debuggreedy + call feedkeys(":call F()\<CR>quit\<CR>", "xt") + catch /^Vim:Interrupt$/ + call assert_match('\.F, line 4', v:throwpoint) + let caught_intr = 1 + endtry + 0debuggreedy + call assert_equal(1, caught_intr) + call assert_equal('a', g:Xpath) + breakdel * + delfunc F +endfunc + +" Test for setting a breakpoint on a :endwhile where the :while condition is +" false and then quit the script. This should generate an interrupt. +func Test_breakpt_endwhile_intr() + func F() + let g:Xpath ..= 'a' + while v:false + let g:Xpath ..= 'b' + endwhile + invalid_command + endfunc + + let g:Xpath = '' + breakadd func 4 F + try + let caught_intr = 0 + debuggreedy + call feedkeys(":call F()\<CR>quit\<CR>", "xt") + catch /^Vim:Interrupt$/ + call assert_match('\.F, line 4', v:throwpoint) + let caught_intr = 1 + endtry + 0debuggreedy + call assert_equal(1, caught_intr) + call assert_equal('a', g:Xpath) + breakdel * + delfunc F +endfunc + +" Test for setting a breakpoint on a script local function +func Test_breakpt_scriptlocal_func() + let g:Xpath = '' + func s:G() + let g:Xpath ..= 'a' + endfunc + + let funcname = expand("<SID>") .. "G" + exe "breakadd func 1 " .. funcname + debuggreedy + redir => output + call feedkeys(":call " .. funcname .. "()\<CR>c\<CR>", "xt") + redir END + 0debuggreedy + call assert_match('Breakpoint in "' .. funcname .. '" line 1', output) + call assert_equal('a', g:Xpath) + breakdel * + exe "delfunc " .. funcname +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_delete.vim b/test/old/testdir/test_delete.vim new file mode 100644 index 0000000000..c00b8ca47d --- /dev/null +++ b/test/old/testdir/test_delete.vim @@ -0,0 +1,133 @@ +" Test for delete(). + +source check.vim +source term_util.vim +source screendump.vim + +func Test_file_delete() + split Xfdelfile + call setline(1, ['a', 'b']) + wq + call assert_equal(['a', 'b'], readfile('Xfdelfile')) + call assert_equal(0, delete('Xfdelfile')) + call assert_fails('call readfile("Xfdelfile")', 'E484:') + call assert_equal(-1, delete('Xfdelfile')) + bwipe Xfdelfile +endfunc + +func Test_dir_delete() + call mkdir('Xdirdel') + call assert_true(isdirectory('Xdirdel')) + call assert_equal(0, delete('Xdirdel', 'd')) + call assert_false(isdirectory('Xdirdel')) + call assert_equal(-1, delete('Xdirdel', 'd')) +endfunc + +func Test_recursive_delete() + call mkdir('Xrecdel') + call mkdir('Xrecdel/subdir') + call mkdir('Xrecdel/empty') + split Xrecdel/Xfile + call setline(1, ['a', 'b']) + w + w Xrecdel/subdir/Xfile + close + call assert_true(isdirectory('Xrecdel')) + call assert_equal(['a', 'b'], readfile('Xrecdel/Xfile')) + call assert_true(isdirectory('Xrecdel/subdir')) + call assert_equal(['a', 'b'], readfile('Xrecdel/subdir/Xfile')) + call assert_true('Xrecdel/empty'->isdirectory()) + call assert_equal(0, delete('Xrecdel', 'rf')) + call assert_false(isdirectory('Xrecdel')) + call assert_equal(-1, delete('Xrecdel', 'd')) + bwipe Xrecdel/Xfile + bwipe Xrecdel/subdir/Xfile +endfunc + +func Test_symlink_delete() + CheckUnix + split Xslfile + call setline(1, ['a', 'b']) + wq + silent !ln -s Xslfile Xdellink + " Delete the link, not the file + call assert_equal(0, delete('Xdellink')) + call assert_equal(-1, delete('Xdellink')) + call assert_equal(0, delete('Xslfile')) + bwipe Xslfile +endfunc + +func Test_symlink_dir_delete() + CheckUnix + call mkdir('Xsymdir') + silent !ln -s Xsymdir Xdirlink + call assert_true(isdirectory('Xsymdir')) + call assert_true(isdirectory('Xdirlink')) + " Delete the link, not the directory + call assert_equal(0, delete('Xdirlink')) + call assert_equal(-1, delete('Xdirlink')) + call assert_equal(0, delete('Xsymdir', 'd')) +endfunc + +func Test_symlink_recursive_delete() + CheckUnix + call mkdir('Xrecdir3') + call mkdir('Xrecdir3/subdir') + call mkdir('Xrecdir4') + split Xrecdir3/Xfile + call setline(1, ['a', 'b']) + w + w Xrecdir3/subdir/Xfile + w Xrecdir4/Xfile + close + silent !ln -s ../Xrecdir4 Xrecdir3/Xreclink + + call assert_true(isdirectory('Xrecdir3')) + call assert_equal(['a', 'b'], readfile('Xrecdir3/Xfile')) + call assert_true(isdirectory('Xrecdir3/subdir')) + call assert_equal(['a', 'b'], readfile('Xrecdir3/subdir/Xfile')) + call assert_true(isdirectory('Xrecdir4')) + call assert_true(isdirectory('Xrecdir3/Xreclink')) + call assert_equal(['a', 'b'], readfile('Xrecdir4/Xfile')) + + call assert_equal(0, delete('Xrecdir3', 'rf')) + call assert_false(isdirectory('Xrecdir3')) + call assert_equal(-1, delete('Xrecdir3', 'd')) + " symlink is deleted, not the directory it points to + call assert_true(isdirectory('Xrecdir4')) + call assert_equal(['a', 'b'], readfile('Xrecdir4/Xfile')) + call assert_equal(0, delete('Xrecdir4/Xfile')) + call assert_equal(0, delete('Xrecdir4', 'd')) + + bwipe Xrecdir3/Xfile + bwipe Xrecdir3/subdir/Xfile + bwipe Xrecdir4/Xfile +endfunc + +func Test_delete_errors() + call assert_fails('call delete('''')', 'E474:') + call assert_fails('call delete(''foo'', 0)', 'E15:') +endfunc + +" This should no longer trigger ml_get errors +func Test_delete_ml_get_errors() + CheckRunVimInTerminal + let lines =<< trim END + set noshowcmd noruler scrolloff=0 + source samples/matchparen.vim + END + call writefile(lines, 'XDelete_ml_get_error', 'D') + let buf = RunVimInTerminal('-S XDelete_ml_get_error samples/box.txt', #{rows: 10, wait_for_ruler: 0}) + call TermWait(buf) + call term_sendkeys(buf, "249GV\<C-End>d") + call TermWait(buf) + " The following used to trigger ml_get errors + call term_sendkeys(buf, "\<PageUp>") + call TermWait(buf) + call term_sendkeys(buf, ":mess\<cr>") + call VerifyScreenDump(buf, 'Test_delete_ml_get_errors_1', {}) + call term_sendkeys(buf, ":q!\<cr>") + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_diffmode.vim b/test/old/testdir/test_diffmode.vim new file mode 100644 index 0000000000..fd94f4a7b2 --- /dev/null +++ b/test/old/testdir/test_diffmode.vim @@ -0,0 +1,1685 @@ +" Tests for diff mode + +source shared.vim +source screendump.vim +source check.vim + +func Test_diff_fold_sync() + enew! + let g:update_count = 0 + au DiffUpdated * let g:update_count += 1 + + let l = range(50) + call setline(1, l) + diffthis + let winone = win_getid() + new + let l[25] = 'diff' + call setline(1, l) + diffthis + let wintwo = win_getid() + " line 15 is inside the closed fold + call assert_equal(19, foldclosedend(10)) + call win_gotoid(winone) + call assert_equal(19, foldclosedend(10)) + " open the fold + normal zv + call assert_equal(-1, foldclosedend(10)) + " fold in other window must have opened too + call win_gotoid(wintwo) + call assert_equal(-1, foldclosedend(10)) + + " cursor position is in sync + normal 23G + call win_gotoid(winone) + call assert_equal(23, getcurpos()[1]) + + " depending on how redraw is done DiffUpdated may be triggered once or twice + call assert_inrange(1, 2, g:update_count) + au! DiffUpdated + + windo diffoff + close! + set nomodified +endfunc + +func Test_vert_split() + set diffopt=filler + call Common_vert_split() + set diffopt& +endfunc + +func Test_vert_split_internal() + set diffopt=internal,filler + call Common_vert_split() + set diffopt& +endfunc + +func Common_vert_split() + " Disable the title to avoid xterm keeping the wrong one. + set notitle noicon + new + let l = ['1 aa', '2 bb', '3 cc', '4 dd', '5 ee'] + call setline(1, l) + w! Xtest + normal dd + $ + put + normal kkrXoxxx + w! Xtest2 + file Nop + normal ggoyyyjjjozzzz + set foldmethod=marker foldcolumn=4 + call assert_equal(0, &diff) + call assert_equal('marker', &foldmethod) + call assert_equal('4', &foldcolumn) + call assert_equal(0, &scrollbind) + call assert_equal(0, &cursorbind) + call assert_equal(1, &wrap) + + vert diffsplit Xtest + vert diffsplit Xtest2 + call assert_equal(1, &diff) + call assert_equal('diff', &foldmethod) + call assert_equal('2', &foldcolumn) + call assert_equal(1, &scrollbind) + call assert_equal(1, &cursorbind) + call assert_equal(0, &wrap) + + let diff_fdm = &fdm + let diff_fdc = &fdc + " repeat entering diff mode here to see if this saves the wrong settings + diffthis + " jump to second window for a moment to have filler line appear at start of + " first window + wincmd w + normal gg + wincmd p + normal gg + call assert_equal(2, winline()) + normal j + call assert_equal(4, winline()) + normal j + call assert_equal(5, winline()) + normal j + call assert_equal(6, winline()) + normal j + call assert_equal(8, winline()) + normal j + call assert_equal(9, winline()) + + wincmd w + normal gg + call assert_equal(1, winline()) + normal j + call assert_equal(2, winline()) + normal j + call assert_equal(4, winline()) + normal j + call assert_equal(5, winline()) + normal j + call assert_equal(8, winline()) + + wincmd w + normal gg + call assert_equal(2, winline()) + normal j + call assert_equal(3, winline()) + normal j + call assert_equal(4, winline()) + normal j + call assert_equal(5, winline()) + normal j + call assert_equal(6, winline()) + normal j + call assert_equal(7, winline()) + normal j + call assert_equal(8, winline()) + + " Test diffoff + diffoff! + 1wincmd w + let &diff = 1 + let &fdm = diff_fdm + let &fdc = diff_fdc + 4wincmd w + diffoff! + 1wincmd w + call assert_equal(0, &diff) + call assert_equal('marker', &foldmethod) + call assert_equal('4', &foldcolumn) + call assert_equal(0, &scrollbind) + call assert_equal(0, &cursorbind) + call assert_equal(1, &wrap) + + wincmd w + call assert_equal(0, &diff) + call assert_equal('marker', &foldmethod) + call assert_equal('4', &foldcolumn) + call assert_equal(0, &scrollbind) + call assert_equal(0, &cursorbind) + call assert_equal(1, &wrap) + + wincmd w + call assert_equal(0, &diff) + call assert_equal('marker', &foldmethod) + call assert_equal('4', &foldcolumn) + call assert_equal(0, &scrollbind) + call assert_equal(0, &cursorbind) + call assert_equal(1, &wrap) + + call delete('Xtest') + call delete('Xtest2') + windo bw! +endfunc + +func Test_filler_lines() + " Test that diffing shows correct filler lines + enew! + put =range(4,10) + 1d _ + vnew + put =range(1,10) + 1d _ + windo diffthis + wincmd h + call assert_equal(1, line('w0')) + unlet! diff_fdm diff_fdc + windo diffoff + bwipe! + enew! +endfunc + +func Test_diffget_diffput() + enew! + let l = range(50) + call setline(1, l) + call assert_fails('diffget', 'E99:') + diffthis + call assert_fails('diffget', 'E100:') + new + let l[10] = 'one' + let l[20] = 'two' + let l[30] = 'three' + let l[40] = 'four' + call setline(1, l) + diffthis + call assert_equal('one', getline(11)) + 11diffget + call assert_equal('10', getline(11)) + 21diffput + wincmd w + call assert_equal('two', getline(21)) + normal 31Gdo + call assert_equal('three', getline(31)) + call assert_equal('40', getline(41)) + normal 41Gdp + wincmd w + call assert_equal('40', getline(41)) + new + diffthis + call assert_fails('diffget', 'E101:') + + windo diffoff + %bwipe! +endfunc + +" Test putting two changes from one buffer to another +func Test_diffput_two() + new a + let win_a = win_getid() + call setline(1, range(1, 10)) + diffthis + new b + let win_b = win_getid() + call setline(1, range(1, 10)) + 8del + 5del + diffthis + call win_gotoid(win_a) + %diffput + call win_gotoid(win_b) + call assert_equal(map(range(1, 10), 'string(v:val)'), getline(1, '$')) + bwipe! a + bwipe! b +endfunc + +" Test for :diffget/:diffput with a range that is inside a diff chunk +func Test_diffget_diffput_range() + call setline(1, range(1, 10)) + new + call setline(1, range(11, 20)) + windo diffthis + 3,5diffget + call assert_equal(['13', '14', '15'], getline(3, 5)) + call setline(1, range(1, 10)) + 4,8diffput + wincmd p + call assert_equal(['13', '4', '5', '6', '7', '8', '19'], getline(3, 9)) + %bw! +endfunc + +" Test for :diffget/:diffput with an empty buffer and a non-empty buffer +func Test_diffget_diffput_empty_buffer() + %d _ + new + call setline(1, 'one') + windo diffthis + diffget + call assert_equal(['one'], getline(1, '$')) + %d _ + diffput + wincmd p + call assert_equal([''], getline(1, '$')) + %bw! +endfunc + +" :diffput and :diffget completes names of buffers which +" are in diff mode and which are different then current buffer. +" No completion when the current window is not in diff mode. +func Test_diffget_diffput_completion() + e Xdiff1 | diffthis + botright new Xdiff2 + botright new Xdiff3 | split | diffthis + botright new Xdiff4 | diffthis + + wincmd t + call assert_equal('Xdiff1', bufname('%')) + call feedkeys(":diffput \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffput Xdiff3 Xdiff4', @:) + call feedkeys(":diffget \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffget Xdiff3 Xdiff4', @:) + call assert_equal(['Xdiff3', 'Xdiff4'], getcompletion('', 'diff_buffer')) + + " Xdiff2 is not in diff mode, so no completion for :diffput, :diffget + wincmd j + call assert_equal('Xdiff2', bufname('%')) + call feedkeys(":diffput \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffput ', @:) + call feedkeys(":diffget \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffget ', @:) + call assert_equal([], getcompletion('', 'diff_buffer')) + + " Xdiff3 is split in 2 windows, only the top one is in diff mode. + " So completion of :diffput :diffget only happens in the top window. + wincmd j + call assert_equal('Xdiff3', bufname('%')) + call assert_equal(1, &diff) + call feedkeys(":diffput \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffput Xdiff1 Xdiff4', @:) + call feedkeys(":diffget \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffget Xdiff1 Xdiff4', @:) + call assert_equal(['Xdiff1', 'Xdiff4'], getcompletion('', 'diff_buffer')) + + wincmd j + call assert_equal('Xdiff3', bufname('%')) + call assert_equal(0, &diff) + call feedkeys(":diffput \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffput ', @:) + call feedkeys(":diffget \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffget ', @:) + call assert_equal([], getcompletion('', 'diff_buffer')) + + wincmd j + call assert_equal('Xdiff4', bufname('%')) + call feedkeys(":diffput \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffput Xdiff1 Xdiff3', @:) + call feedkeys(":diffget \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"diffget Xdiff1 Xdiff3', @:) + call assert_equal(['Xdiff1', 'Xdiff3'], getcompletion('', 'diff_buffer')) + + %bwipe +endfunc + +func Test_dp_do_buffer() + e! one + let bn1=bufnr('%') + let l = range(60) + call setline(1, l) + diffthis + + new two + let l[10] = 'one' + let l[20] = 'two' + let l[30] = 'three' + let l[40] = 'four' + let l[50] = 'five' + call setline(1, l) + diffthis + + " dp and do with invalid buffer number. + 11 + call assert_fails('norm 99999dp', 'E102:') + call assert_fails('norm 99999do', 'E102:') + call assert_fails('diffput non_existing_buffer', 'E94:') + call assert_fails('diffget non_existing_buffer', 'E94:') + + " dp and do with valid buffer number. + call assert_equal('one', getline('.')) + exe 'norm ' . bn1 . 'do' + call assert_equal('10', getline('.')) + 21 + call assert_equal('two', getline('.')) + diffget one + call assert_equal('20', getline('.')) + + 31 + exe 'norm ' . bn1 . 'dp' + 41 + diffput one + wincmd w + 31 + call assert_equal('three', getline('.')) + 41 + call assert_equal('four', getline('.')) + + " dp and do with buffer number which is not in diff mode. + new not_in_diff_mode + let bn3=bufnr('%') + wincmd w + 51 + call assert_fails('exe "norm" . bn3 . "dp"', 'E103:') + call assert_fails('exe "norm" . bn3 . "do"', 'E103:') + call assert_fails('diffput not_in_diff_mode', 'E94:') + call assert_fails('diffget not_in_diff_mode', 'E94:') + + windo diffoff + %bwipe! +endfunc + +func Test_do_lastline() + e! one + call setline(1, ['1','2','3','4','5','6']) + diffthis + + new two + call setline(1, ['2','4','5']) + diffthis + + 1 + norm dp]c + norm dp]c + wincmd w + call assert_equal(4, line('$')) + norm G + norm do + call assert_equal(3, line('$')) + + windo diffoff + %bwipe! +endfunc + +func Test_diffoff() + enew! + call setline(1, ['Two', 'Three']) + redraw + let normattr = screenattr(1, 1) + diffthis + botright vert new + call setline(1, ['One', '', 'Two', 'Three']) + diffthis + redraw + call assert_notequal(normattr, 1->screenattr(1)) + diffoff! + redraw + call assert_equal(normattr, screenattr(1, 1)) + bwipe! + bwipe! +endfunc + +func Common_icase_test() + edit one + call setline(1, ['One', 'Two', 'Three', 'Four', 'Fi#ve']) + redraw + let normattr = screenattr(1, 1) + diffthis + + botright vert new two + call setline(1, ['one', 'TWO', 'Three ', 'Four', 'fI=VE']) + diffthis + + redraw + call assert_equal(normattr, screenattr(1, 1)) + call assert_equal(normattr, screenattr(2, 1)) + call assert_notequal(normattr, screenattr(3, 1)) + call assert_equal(normattr, screenattr(4, 1)) + + let dtextattr = screenattr(5, 3) + call assert_notequal(dtextattr, screenattr(5, 1)) + call assert_notequal(dtextattr, screenattr(5, 5)) + + diffoff! + %bwipe! +endfunc + +func Test_diffopt_icase() + set diffopt=icase,foldcolumn:0 + call Common_icase_test() + set diffopt& +endfunc + +func Test_diffopt_icase_internal() + set diffopt=icase,foldcolumn:0,internal + call Common_icase_test() + set diffopt& +endfunc + +func Common_iwhite_test() + edit one + " Difference in trailing spaces and amount of spaces should be ignored, + " but not other space differences. + call setline(1, ["One \t", 'Two', 'Three', 'one two', 'one two', 'Four']) + redraw + let normattr = screenattr(1, 1) + diffthis + + botright vert new two + call setline(1, ["One\t ", "Two\t ", 'Three', 'one two', 'onetwo', ' Four']) + diffthis + + redraw + call assert_equal(normattr, screenattr(1, 1)) + call assert_equal(normattr, screenattr(2, 1)) + call assert_equal(normattr, screenattr(3, 1)) + call assert_equal(normattr, screenattr(4, 1)) + call assert_notequal(normattr, screenattr(5, 1)) + call assert_notequal(normattr, screenattr(6, 1)) + + diffoff! + %bwipe! +endfunc + +func Test_diffopt_iwhite() + set diffopt=iwhite,foldcolumn:0 + call Common_iwhite_test() + set diffopt& +endfunc + +func Test_diffopt_iwhite_internal() + set diffopt=internal,iwhite,foldcolumn:0 + call Common_iwhite_test() + set diffopt& +endfunc + +func Test_diffopt_context() + enew! + call setline(1, ['1', '2', '3', '4', '5', '6', '7']) + diffthis + new + call setline(1, ['1', '2', '3', '4', '5x', '6', '7']) + diffthis + + set diffopt=context:2 + call assert_equal('+-- 2 lines: 1', foldtextresult(1)) + set diffopt=internal,context:2 + call assert_equal('+-- 2 lines: 1', foldtextresult(1)) + + set diffopt=context:1 + call assert_equal('+-- 3 lines: 1', foldtextresult(1)) + set diffopt=internal,context:1 + call assert_equal('+-- 3 lines: 1', foldtextresult(1)) + + diffoff! + %bwipe! + set diffopt& +endfunc + +func Test_diffopt_horizontal() + set diffopt=internal,horizontal + diffsplit + + call assert_equal(&columns, winwidth(1)) + call assert_equal(&columns, winwidth(2)) + call assert_equal(&lines, winheight(1) + winheight(2) + 3) + call assert_inrange(0, 1, winheight(1) - winheight(2)) + + set diffopt& + diffoff! + %bwipe +endfunc + +func Test_diffopt_vertical() + set diffopt=internal,vertical + diffsplit + + call assert_equal(&lines - 2, winheight(1)) + call assert_equal(&lines - 2, winheight(2)) + call assert_equal(&columns, winwidth(1) + winwidth(2) + 1) + call assert_inrange(0, 1, winwidth(1) - winwidth(2)) + + set diffopt& + diffoff! + %bwipe +endfunc + +func Test_diffopt_hiddenoff() + set diffopt=internal,filler,foldcolumn:0,hiddenoff + e! one + call setline(1, ['Two', 'Three']) + redraw + let normattr = screenattr(1, 1) + diffthis + botright vert new two + call setline(1, ['One', 'Four']) + diffthis + redraw + call assert_notequal(normattr, screenattr(1, 1)) + set hidden + close + redraw + " should not diffing with hidden buffer two while 'hiddenoff' is enabled + call assert_equal(normattr, screenattr(1, 1)) + + bwipe! + bwipe! + set hidden& diffopt& +endfunc + +func Test_diffoff_hidden() + set diffopt=internal,filler,foldcolumn:0 + e! one + call setline(1, ['Two', 'Three']) + redraw + let normattr = screenattr(1, 1) + diffthis + botright vert new two + call setline(1, ['One', 'Four']) + diffthis + redraw + call assert_notequal(normattr, screenattr(1, 1)) + set hidden + close + redraw + " diffing with hidden buffer two + call assert_notequal(normattr, screenattr(1, 1)) + diffoff + redraw + call assert_equal(normattr, screenattr(1, 1)) + diffthis + redraw + " still diffing with hidden buffer two + call assert_notequal(normattr, screenattr(1, 1)) + diffoff! + redraw + call assert_equal(normattr, screenattr(1, 1)) + diffthis + redraw + " no longer diffing with hidden buffer two + call assert_equal(normattr, screenattr(1, 1)) + + bwipe! + bwipe! + set hidden& diffopt& +endfunc + +func Test_setting_cursor() + new Xtest1 + put =range(1,90) + wq + new Xtest2 + put =range(1,100) + wq + + tabe Xtest2 + $ + diffsp Xtest1 + tabclose + + call delete('Xtest1') + call delete('Xtest2') +endfunc + +func Test_diff_move_to() + new + call setline(1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + diffthis + vnew + call setline(1, [1, '2x', 3, 4, 4, 5, '6x', 7, '8x', 9, '10x']) + diffthis + norm ]c + call assert_equal(2, line('.')) + norm 3]c + call assert_equal(9, line('.')) + norm 10]c + call assert_equal(11, line('.')) + norm [c + call assert_equal(9, line('.')) + norm 2[c + call assert_equal(5, line('.')) + norm 10[c + call assert_equal(2, line('.')) + %bwipe! +endfunc + +func Test_diffexpr() + CheckExecutable diff + + func DiffExpr() + " Prepend some text to check diff type detection + call writefile(['warning', ' message'], v:fname_out) + silent exe '!diff ' . v:fname_in . ' ' . v:fname_new . '>>' . v:fname_out + endfunc + set diffexpr=DiffExpr() + set diffopt=foldcolumn:0 + + enew! + call setline(1, ['one', 'two', 'three']) + redraw + let normattr = screenattr(1, 1) + diffthis + + botright vert new + call setline(1, ['one', 'two', 'three.']) + diffthis + + redraw + call assert_equal(normattr, screenattr(1, 1)) + call assert_equal(normattr, screenattr(2, 1)) + call assert_notequal(normattr, screenattr(3, 1)) + diffoff! + + " Try using an non-existing function for 'diffexpr'. + set diffexpr=NewDiffFunc() + call assert_fails('windo diffthis', ['E117:', 'E97:']) + diffoff! + + " Using a script-local function + func s:NewDiffExpr() + endfunc + set diffexpr=s:NewDiffExpr() + call assert_equal(expand('<SID>') .. 'NewDiffExpr()', &diffexpr) + set diffexpr=<SID>NewDiffExpr() + call assert_equal(expand('<SID>') .. 'NewDiffExpr()', &diffexpr) + + %bwipe! + set diffexpr& diffopt& + delfunc DiffExpr + delfunc s:NewDiffExpr +endfunc + +func Test_diffpatch() + " The patch program on MS-Windows may fail or hang. + CheckExecutable patch + CheckUnix + new + insert +*************** +*** 1,3 **** + 1 +! 2 + 3 +--- 1,4 ---- + 1 +! 2x + 3 ++ 4 +. + saveas! Xpatch + bwipe! + new + call assert_fails('diffpatch Xpatch', 'E816:') + + for name in ['Xpatch', 'Xpatch$HOME', 'Xpa''tch'] + call setline(1, ['1', '2', '3']) + if name != 'Xpatch' + call rename('Xpatch', name) + endif + exe 'diffpatch ' . escape(name, '$') + call assert_equal(['1', '2x', '3', '4'], getline(1, '$')) + if name != 'Xpatch' + call rename(name, 'Xpatch') + endif + bwipe! + endfor + + call delete('Xpatch') + bwipe! +endfunc + +func Test_diff_too_many_buffers() + for i in range(1, 8) + exe "new Xtest" . i + diffthis + endfor + new Xtest9 + call assert_fails('diffthis', 'E96:') + %bwipe! +endfunc + +func Test_diff_nomodifiable() + new + call setline(1, [1, 2, 3, 4]) + setl nomodifiable + diffthis + vnew + call setline(1, ['1x', 2, 3, 3, 4]) + diffthis + call assert_fails('norm dp', 'E793:') + setl nomodifiable + call assert_fails('norm do', 'E21:') + %bwipe! +endfunc + +func Test_diff_filler() + new + call setline(1, [1, 2, 3, 'x', 4]) + diffthis + vnew + call setline(1, [1, 2, 'y', 'y', 3, 4]) + diffthis + redraw + + call assert_equal([0, 0, 0, 0, 0, 0, 0, 1, 0], map(range(-1, 7), 'v:val->diff_filler()')) + wincmd w + call assert_equal([0, 0, 0, 0, 2, 0, 0, 0], map(range(-1, 6), 'diff_filler(v:val)')) + + %bwipe! +endfunc + +func Test_diff_hlID() + new + call setline(1, [1, 2, 3]) + diffthis + vnew + call setline(1, ['1x', 2, 'x', 3]) + diffthis + redraw + + call diff_hlID(-1, 1)->synIDattr("name")->assert_equal("") + + call diff_hlID(1, 1)->synIDattr("name")->assert_equal("DiffChange") + call diff_hlID(1, 2)->synIDattr("name")->assert_equal("DiffText") + call diff_hlID(2, 1)->synIDattr("name")->assert_equal("") + call diff_hlID(3, 1)->synIDattr("name")->assert_equal("DiffAdd") + eval 4->diff_hlID(1)->synIDattr("name")->assert_equal("") + + wincmd w + call assert_equal(synIDattr(diff_hlID(1, 1), "name"), "DiffChange") + call assert_equal(synIDattr(diff_hlID(2, 1), "name"), "") + call assert_equal(synIDattr(diff_hlID(3, 1), "name"), "") + + %bwipe! +endfunc + +func Test_diff_lastline() + enew! + only! + call setline(1, ['This is a ', 'line with five ', 'rows']) + diffthis + botright vert new + call setline(1, ['This is', 'a line with ', 'four rows']) + diffthis + 1 + call feedkeys("Je a\<CR>", 'tx') + call feedkeys("Je a\<CR>", 'tx') + let w1lines = winline() + wincmd w + $ + let w2lines = winline() + call assert_equal(w2lines, w1lines) + bwipe! + bwipe! +endfunc + +func WriteDiffFiles(buf, list1, list2) + call writefile(a:list1, 'Xdifile1') + call writefile(a:list2, 'Xdifile2') + if a:buf + call term_sendkeys(a:buf, ":checktime\<CR>") + endif +endfunc + +" Verify a screendump with both the internal and external diff. +func VerifyBoth(buf, dumpfile, extra) + " trailing : for leaving the cursor on the command line + for cmd in [":set diffopt=filler" . a:extra . "\<CR>:", ":set diffopt+=internal\<CR>:"] + call term_sendkeys(a:buf, cmd) + if VerifyScreenDump(a:buf, a:dumpfile, {}, cmd =~ 'internal' ? 'internal' : 'external') + break " don't let the next iteration overwrite the "failed" file. + " don't let the next iteration overwrite the "failed" file. + return + endif + endfor + + " also test unified diff + call term_sendkeys(a:buf, ":call SetupUnified()\<CR>:") + call term_sendkeys(a:buf, ":redraw!\<CR>:") + call VerifyScreenDump(a:buf, a:dumpfile, {}, 'unified') + call term_sendkeys(a:buf, ":call StopUnified()\<CR>:") +endfunc + +" Verify a screendump with the internal diff only. +func VerifyInternal(buf, dumpfile, extra) + call term_sendkeys(a:buf, ":diffupdate!\<CR>") + " trailing : for leaving the cursor on the command line + call term_sendkeys(a:buf, ":set diffopt=internal,filler" . a:extra . "\<CR>:") + call VerifyScreenDump(a:buf, a:dumpfile, {}) +endfunc + +func Test_diff_screen() + let g:test_is_flaky = 1 + CheckScreendump + CheckFeature menu + + let lines =<< trim END + func UnifiedDiffExpr() + " Prepend some text to check diff type detection + call writefile(['warning', ' message'], v:fname_out) + silent exe '!diff -U0 ' .. v:fname_in .. ' ' .. v:fname_new .. '>>' .. v:fname_out + endfunc + func SetupUnified() + set diffexpr=UnifiedDiffExpr() + diffupdate + endfunc + func StopUnified() + set diffexpr= + endfunc + END + call writefile(lines, 'XdiffSetup', 'D') + + " clean up already existing swap files, just in case + call delete('.Xdifile1.swp') + call delete('.Xdifile2.swp') + + " Test 1: Add a line in beginning of file 2 + call WriteDiffFiles(0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + let buf = RunVimInTerminal('-d -S XdiffSetup Xdifile1 Xdifile2', {}) + " Set autoread mode, so that Vim won't complain once we re-write the test + " files + call term_sendkeys(buf, ":set autoread\<CR>\<c-w>w:set autoread\<CR>\<c-w>w") + + call VerifyBoth(buf, 'Test_diff_01', '') + + " Test 2: Add a line in beginning of file 1 + call WriteDiffFiles(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + call VerifyBoth(buf, 'Test_diff_02', '') + + " Test 3: Add a line at the end of file 2 + call WriteDiffFiles(buf, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) + call VerifyBoth(buf, 'Test_diff_03', '') + + " Test 4: Add a line at the end of file 1 + call WriteDiffFiles(buf, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + call VerifyBoth(buf, 'Test_diff_04', '') + + " Test 5: Add a line in the middle of file 2, remove on at the end of file 1 + call WriteDiffFiles(buf, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10]) + call VerifyBoth(buf, 'Test_diff_05', '') + + " Test 6: Add a line in the middle of file 1, remove on at the end of file 2 + call WriteDiffFiles(buf, [1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) + call VerifyBoth(buf, 'Test_diff_06', '') + + " Variants on test 6 with different context settings + call term_sendkeys(buf, ":set diffopt+=context:2\<cr>") + call VerifyScreenDump(buf, 'Test_diff_06.2', {}) + call term_sendkeys(buf, ":set diffopt-=context:2\<cr>") + call term_sendkeys(buf, ":set diffopt+=context:1\<cr>") + call VerifyScreenDump(buf, 'Test_diff_06.1', {}) + call term_sendkeys(buf, ":set diffopt-=context:1\<cr>") + call term_sendkeys(buf, ":set diffopt+=context:0\<cr>") + call VerifyScreenDump(buf, 'Test_diff_06.0', {}) + call term_sendkeys(buf, ":set diffopt-=context:0\<cr>") + + " Test 7 - 9: Test normal/patience/histogram diff algorithm + call WriteDiffFiles(buf, ['#include <stdio.h>', '', '// Frobs foo heartily', 'int frobnitz(int foo)', '{', + \ ' int i;', ' for(i = 0; i < 10; i++)', ' {', ' printf("Your answer is: ");', + \ ' printf("%d\n", foo);', ' }', '}', '', 'int fact(int n)', '{', ' if(n > 1)', ' {', + \ ' return fact(n-1) * n;', ' }', ' return 1;', '}', '', 'int main(int argc, char **argv)', + \ '{', ' frobnitz(fact(10));', '}'], + \ ['#include <stdio.h>', '', 'int fib(int n)', '{', ' if(n > 2)', ' {', + \ ' return fib(n-1) + fib(n-2);', ' }', ' return 1;', '}', '', '// Frobs foo heartily', + \ 'int frobnitz(int foo)', '{', ' int i;', ' for(i = 0; i < 10; i++)', ' {', + \ ' printf("%d\n", foo);', ' }', '}', '', + \ 'int main(int argc, char **argv)', '{', ' frobnitz(fib(10));', '}']) + call term_sendkeys(buf, ":diffupdate!\<cr>") + call term_sendkeys(buf, ":set diffopt+=internal\<cr>") + call VerifyScreenDump(buf, 'Test_diff_07', {}) + + call term_sendkeys(buf, ":set diffopt+=algorithm:patience\<cr>") + call VerifyScreenDump(buf, 'Test_diff_08', {}) + + call term_sendkeys(buf, ":set diffopt+=algorithm:histogram\<cr>") + call VerifyScreenDump(buf, 'Test_diff_09', {}) + + " Test 10-11: normal/indent-heuristic + call term_sendkeys(buf, ":set diffopt&vim\<cr>") + call WriteDiffFiles(buf, ['', ' def finalize(values)', '', ' values.each do |v|', ' v.finalize', ' end'], + \ ['', ' def finalize(values)', '', ' values.each do |v|', ' v.prepare', ' end', '', + \ ' values.each do |v|', ' v.finalize', ' end']) + call term_sendkeys(buf, ":diffupdate!\<cr>") + call term_sendkeys(buf, ":set diffopt+=internal\<cr>") + call VerifyScreenDump(buf, 'Test_diff_10', {}) + + " Leave trailing : at commandline! + call term_sendkeys(buf, ":set diffopt+=indent-heuristic\<cr>:\<cr>") + call VerifyScreenDump(buf, 'Test_diff_11', {}, 'one') + " shouldn't matter, if indent-algorithm comes before or after the algorithm + call term_sendkeys(buf, ":set diffopt&\<cr>") + call term_sendkeys(buf, ":set diffopt+=indent-heuristic,algorithm:patience\<cr>:\<cr>") + call VerifyScreenDump(buf, 'Test_diff_11', {}, 'two') + call term_sendkeys(buf, ":set diffopt&\<cr>") + call term_sendkeys(buf, ":set diffopt+=algorithm:patience,indent-heuristic\<cr>:\<cr>") + call VerifyScreenDump(buf, 'Test_diff_11', {}, 'three') + + " Test 12: diff the same file + call WriteDiffFiles(buf, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + call VerifyBoth(buf, 'Test_diff_12', '') + + " Test 13: diff an empty file + call WriteDiffFiles(buf, [], []) + call VerifyBoth(buf, 'Test_diff_13', '') + + " Test 14: test diffopt+=icase + call WriteDiffFiles(buf, ['a', 'b', 'cd'], ['A', 'b', 'cDe']) + call VerifyBoth(buf, 'Test_diff_14', " diffopt+=filler diffopt+=icase") + + " Test 15-16: test diffopt+=iwhite + call WriteDiffFiles(buf, ['int main()', '{', ' printf("Hello, World!");', ' return 0;', '}'], + \ ['int main()', '{', ' if (0)', ' {', ' printf("Hello, World!");', ' return 0;', ' }', '}']) + call term_sendkeys(buf, ":diffupdate!\<cr>") + call term_sendkeys(buf, ":set diffopt&vim diffopt+=filler diffopt+=iwhite\<cr>") + call VerifyScreenDump(buf, 'Test_diff_15', {}) + call term_sendkeys(buf, ":set diffopt+=internal\<cr>") + call VerifyScreenDump(buf, 'Test_diff_16', {}) + + " Test 17: test diffopt+=iblank + call WriteDiffFiles(buf, ['a', ' ', 'cd', 'ef', 'xxx'], ['a', 'cd', '', 'ef', 'yyy']) + call VerifyInternal(buf, 'Test_diff_17', " diffopt+=iblank") + + " Test 18: test diffopt+=iblank,iwhite / iwhiteall / iwhiteeol + call VerifyInternal(buf, 'Test_diff_18', " diffopt+=iblank,iwhite") + call VerifyInternal(buf, 'Test_diff_18', " diffopt+=iblank,iwhiteall") + call VerifyInternal(buf, 'Test_diff_18', " diffopt+=iblank,iwhiteeol") + + " Test 19: test diffopt+=iwhiteeol + call WriteDiffFiles(buf, ['a ', 'x', 'cd', 'ef', 'xx xx', 'foo', 'bar'], ['a', 'x', 'c d', ' ef', 'xx xx', 'foo', '', 'bar']) + call VerifyInternal(buf, 'Test_diff_19', " diffopt+=iwhiteeol") + + " Test 19: test diffopt+=iwhiteall + call VerifyInternal(buf, 'Test_diff_20', " diffopt+=iwhiteall") + + " clean up + call StopVimInTerminal(buf) + call delete('Xdifile1') + call delete('Xdifile2') +endfunc + +func Test_diff_with_scroll_and_change() + CheckScreendump + + let lines =<< trim END + call setline(1, range(1, 15)) + vnew + call setline(1, range(9, 15)) + windo diffthis + wincmd h + exe "normal Gl5\<C-E>" + END + call writefile(lines, 'Xtest_scroll_change', 'D') + let buf = RunVimInTerminal('-S Xtest_scroll_change', {}) + + call VerifyScreenDump(buf, 'Test_diff_scroll_change_01', {}) + + call term_sendkeys(buf, "ax\<Esc>") + call VerifyScreenDump(buf, 'Test_diff_scroll_change_02', {}) + + call term_sendkeys(buf, "\<C-W>lay\<Esc>") + call VerifyScreenDump(buf, 'Test_diff_scroll_change_03', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_diff_with_cursorline() + CheckScreendump + + call writefile([ + \ 'hi CursorLine ctermbg=red ctermfg=white', + \ 'set cursorline', + \ 'call setline(1, ["foo","foo","foo","bar"])', + \ 'vnew', + \ 'call setline(1, ["bee","foo","foo","baz"])', + \ 'windo diffthis', + \ '2wincmd w', + \ ], 'Xtest_diff_cursorline', 'D') + let buf = RunVimInTerminal('-S Xtest_diff_cursorline', {}) + + call VerifyScreenDump(buf, 'Test_diff_with_cursorline_01', {}) + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_diff_with_cursorline_02', {}) + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_diff_with_cursorline_03', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_diff_with_cursorline_number() + CheckScreendump + + let lines =<< trim END + hi CursorLine ctermbg=red ctermfg=white + hi CursorLineNr ctermbg=white ctermfg=black cterm=underline + set cursorline number + call setline(1, ["baz", "foo", "foo", "bar"]) + 2 + vnew + call setline(1, ["foo", "foo", "bar"]) + windo diffthis + 1wincmd w + END + call writefile(lines, 'Xtest_diff_cursorline_number', 'D') + let buf = RunVimInTerminal('-S Xtest_diff_cursorline_number', {}) + + call VerifyScreenDump(buf, 'Test_diff_with_cursorline_number_01', {}) + call term_sendkeys(buf, ":set cursorlineopt=number\r") + call VerifyScreenDump(buf, 'Test_diff_with_cursorline_number_02', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_diff_with_cursorline_breakindent() + CheckScreendump + + call writefile([ + \ 'hi CursorLine ctermbg=red ctermfg=white', + \ 'set noequalalways wrap diffopt=followwrap cursorline breakindent', + \ '50vnew', + \ 'call setline(1, [" "," "," "," "])', + \ 'exe "norm 20Afoo\<Esc>j20Afoo\<Esc>j20Afoo\<Esc>j20Abar\<Esc>"', + \ 'vnew', + \ 'call setline(1, [" "," "," "," "])', + \ 'exe "norm 20Abee\<Esc>j20Afoo\<Esc>j20Afoo\<Esc>j20Abaz\<Esc>"', + \ 'windo diffthis', + \ '2wincmd w', + \ ], 'Xtest_diff_cursorline_breakindent', 'D') + let buf = RunVimInTerminal('-S Xtest_diff_cursorline_breakindent', {}) + + call term_sendkeys(buf, "gg0") + call VerifyScreenDump(buf, 'Test_diff_with_cul_bri_01', {}) + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_diff_with_cul_bri_02', {}) + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_diff_with_cul_bri_03', {}) + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_diff_with_cul_bri_04', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_diff_with_syntax() + CheckScreendump + + let lines =<< trim END + void doNothing() { + int x = 0; + char *s = "hello"; + return 5; + } + END + call writefile(lines, 'Xprogram1.c', 'D') + let lines =<< trim END + void doSomething() { + int x = 0; + char *s = "there"; + return 5; + } + END + call writefile(lines, 'Xprogram2.c', 'D') + + let lines =<< trim END + edit Xprogram1.c + diffsplit Xprogram2.c + END + call writefile(lines, 'Xtest_diff_syntax', 'D') + let buf = RunVimInTerminal('-S Xtest_diff_syntax', {}) + + call VerifyScreenDump(buf, 'Test_diff_syntax_1', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_diff_of_diff() + CheckScreendump + CheckFeature rightleft + + call writefile([ + \ 'call setline(1, ["aa","bb","cc","@@ -3,2 +5,7 @@","dd","ee","ff"])', + \ 'vnew', + \ 'call setline(1, ["aa","bb","cc"])', + \ 'windo diffthis', + \ '1wincmd w', + \ 'setlocal number', + \ ], 'Xtest_diff_diff', 'D') + let buf = RunVimInTerminal('-S Xtest_diff_diff', {}) + + call VerifyScreenDump(buf, 'Test_diff_of_diff_01', {}) + + call term_sendkeys(buf, ":set rightleft\<cr>") + call VerifyScreenDump(buf, 'Test_diff_of_diff_02', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func CloseoffSetup() + enew + call setline(1, ['one', 'two', 'three']) + diffthis + new + call setline(1, ['one', 'tow', 'three']) + diffthis + call assert_equal(1, &diff) + only! +endfunc + +func Test_diff_closeoff() + " "closeoff" included by default: last diff win gets 'diff' reset' + call CloseoffSetup() + call assert_equal(0, &diff) + enew! + + " "closeoff" excluded: last diff win keeps 'diff' set' + set diffopt-=closeoff + call CloseoffSetup() + call assert_equal(1, &diff) + diffoff! + enew! +endfunc + +func Test_diff_followwrap() + new + set diffopt+=followwrap + set wrap + diffthis + call assert_equal(1, &wrap) + diffoff + set nowrap + diffthis + call assert_equal(0, &wrap) + diffoff + set diffopt& + bwipe! +endfunc + +func Test_diff_maintains_change_mark() + func DiffMaintainsChangeMark() + enew! + call setline(1, ['a', 'b', 'c', 'd']) + diffthis + new + call setline(1, ['a', 'b', 'c', 'e']) + " Set '[ and '] marks + 2,3yank + call assert_equal([2, 3], [line("'["), line("']")]) + " Verify they aren't affected by the implicit diff + diffthis + call assert_equal([2, 3], [line("'["), line("']")]) + " Verify they aren't affected by an explicit diff + diffupdate + call assert_equal([2, 3], [line("'["), line("']")]) + bwipe! + bwipe! + endfunc + + set diffopt-=internal + call DiffMaintainsChangeMark() + set diffopt+=internal + call DiffMaintainsChangeMark() + + set diffopt& + delfunc DiffMaintainsChangeMark +endfunc + +" Test for 'patchexpr' +func Test_patchexpr() + let g:patch_args = [] + func TPatch() + call add(g:patch_args, readfile(v:fname_in)) + call add(g:patch_args, readfile(v:fname_diff)) + call writefile(['output file'], v:fname_out) + endfunc + set patchexpr=TPatch() + + call writefile(['input file'], 'Xinput', 'D') + call writefile(['diff file'], 'Xdiff', 'D') + %bwipe! + edit Xinput + diffpatch Xdiff + call assert_equal('output file', getline(1)) + call assert_equal('Xinput.new', bufname()) + call assert_equal(2, winnr('$')) + call assert_true(&diff) + + " Using a script-local function + func s:NewPatchExpr() + endfunc + set patchexpr=s:NewPatchExpr() + call assert_equal(expand('<SID>') .. 'NewPatchExpr()', &patchexpr) + set patchexpr=<SID>NewPatchExpr() + call assert_equal(expand('<SID>') .. 'NewPatchExpr()', &patchexpr) + + set patchexpr& + delfunc TPatch + delfunc s:NewPatchExpr + %bwipe! +endfunc + +func Test_diff_rnu() + CheckScreendump + + let content =<< trim END + call setline(1, ['a', 'a', 'a', 'y', 'b', 'b', 'b', 'b', 'b']) + vnew + call setline(1, ['a', 'a', 'a', 'x', 'x', 'x', 'b', 'b', 'b', 'b', 'b']) + call setline(1, ['a', 'a', 'a', 'y', 'b', 'b', 'b', 'b', 'b']) + vnew + call setline(1, ['a', 'a', 'a', 'x', 'x', 'x', 'b', 'b', 'b', 'b', 'b']) + windo diffthis + setlocal number rnu foldcolumn=0 + END + call writefile(content, 'Xtest_diff_rnu', 'D') + let buf = RunVimInTerminal('-S Xtest_diff_rnu', {}) + + call VerifyScreenDump(buf, 'Test_diff_rnu_01', {}) + + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_diff_rnu_02', {}) + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_diff_rnu_03', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_diff_multilineconceal() + new + diffthis + + new + call matchadd('Conceal', 'a\nb', 9, -1, {'conceal': 'Y'}) + set cole=2 cocu=n + call setline(1, ["a", "b"]) + diffthis + redraw +endfunc + +func Test_diff_and_scroll() + " this was causing an ml_get error + set ls=2 + for i in range(winheight(0) * 2) + call setline(i, i < winheight(0) - 10 ? i : i + 10) + endfor + vnew + for i in range(winheight(0)*2 + 10) + call setline(i, i < winheight(0) - 10 ? 0 : i) + endfor + diffthis + wincmd p + diffthis + execute 'normal ' . winheight(0) . "\<C-d>" + + bwipe! + bwipe! + set ls& +endfunc + +func Test_diff_filler_cursorcolumn() + CheckScreendump + + let content =<< trim END + call setline(1, ['aa', 'bb', 'cc']) + vnew + call setline(1, ['aa', 'cc']) + windo diffthis + wincmd p + setlocal cursorcolumn foldcolumn=0 + norm! gg0 + redraw! + END + call writefile(content, 'Xtest_diff_cuc', 'D') + let buf = RunVimInTerminal('-S Xtest_diff_cuc', {}) + + call VerifyScreenDump(buf, 'Test_diff_cuc_01', {}) + + call term_sendkeys(buf, "l") + call term_sendkeys(buf, "\<C-l>") + call VerifyScreenDump(buf, 'Test_diff_cuc_02', {}) + call term_sendkeys(buf, "0j") + call term_sendkeys(buf, "\<C-l>") + call VerifyScreenDump(buf, 'Test_diff_cuc_03', {}) + call term_sendkeys(buf, "l") + call term_sendkeys(buf, "\<C-l>") + call VerifyScreenDump(buf, 'Test_diff_cuc_04', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +" Test for adding/removing lines inside diff chunks, between diff chunks +" and before diff chunks +func Test_diff_modify_chunks() + enew! + let w2_id = win_getid() + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + new + let w1_id = win_getid() + call setline(1, ['a', '2', '3', 'd', 'e', 'f', '7', '8', 'i']) + windo diffthis + + " remove a line between two diff chunks and create a new diff chunk + call win_gotoid(w2_id) + 5d + call win_gotoid(w1_id) + call diff_hlID(5, 1)->synIDattr('name')->assert_equal('DiffAdd') + + " add a line between two diff chunks + call win_gotoid(w2_id) + normal! 4Goe + call win_gotoid(w1_id) + call diff_hlID(4, 1)->synIDattr('name')->assert_equal('') + call diff_hlID(5, 1)->synIDattr('name')->assert_equal('') + + " remove all the lines in a diff chunk. + call win_gotoid(w2_id) + 7,8d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', '', '', '', 'DiffAdd', + \ 'DiffAdd', ''], hl) + + " remove lines from one diff chunk to just before the next diff chunk + call win_gotoid(w2_id) + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + 2,6d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', 'DiffAdd', 'DiffAdd', + \ 'DiffAdd', 'DiffAdd', 'DiffAdd', ''], hl) + + " remove lines just before the top of a diff chunk + call win_gotoid(w2_id) + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + 5,6d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', '', 'DiffText', 'DiffText', + \ 'DiffAdd', 'DiffAdd', ''], hl) + + " remove line after the end of a diff chunk + call win_gotoid(w2_id) + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + 4d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', 'DiffAdd', '', '', 'DiffText', + \ 'DiffText', ''], hl) + + " remove lines starting from the end of one diff chunk and ending inside + " another diff chunk + call win_gotoid(w2_id) + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']) + 4,7d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', 'DiffText', 'DiffText', 'DiffText', 'DiffAdd', + \ 'DiffAdd', 'DiffAdd', 'DiffAdd', ''], hl) + + " removing the only remaining diff chunk should make the files equal + call win_gotoid(w2_id) + call setline(1, ['a', '2', '3', 'x', 'd', 'e', 'f', 'x', '7', '8', 'i']) + 8d + let hl = range(1, 10)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', '', '', 'DiffAdd', '', '', '', '', '', ''], hl) + call win_gotoid(w2_id) + 4d + call win_gotoid(w1_id) + let hl = range(1, 9)->map({_, lnum -> diff_hlID(lnum, 1)->synIDattr('name')}) + call assert_equal(['', '', '', '', '', '', '', '', ''], hl) + + %bw! +endfunc + +func Test_diff_binary() + CheckScreendump + + let content =<< trim END + call setline(1, ['a', 'b', "c\n", 'd', 'e', 'f', 'g']) + vnew + call setline(1, ['A', 'b', 'c', 'd', 'E', 'f', 'g']) + windo diffthis + wincmd p + norm! gg0 + redraw! + END + call writefile(content, 'Xtest_diff_bin', 'D') + let buf = RunVimInTerminal('-S Xtest_diff_bin', {}) + + " Test using internal diff + call VerifyScreenDump(buf, 'Test_diff_bin_01', {}) + + " Test using internal diff and case folding + call term_sendkeys(buf, ":set diffopt+=icase\<cr>") + call term_sendkeys(buf, "\<C-l>") + call VerifyScreenDump(buf, 'Test_diff_bin_02', {}) + " Test using external diff + call term_sendkeys(buf, ":set diffopt=filler\<cr>") + call term_sendkeys(buf, "\<C-l>") + call VerifyScreenDump(buf, 'Test_diff_bin_03', {}) + " Test using external diff and case folding + call term_sendkeys(buf, ":set diffopt=filler,icase\<cr>") + call term_sendkeys(buf, "\<C-l>") + call VerifyScreenDump(buf, 'Test_diff_bin_04', {}) + + " clean up + call StopVimInTerminal(buf) + set diffopt&vim +endfunc + +" Test for using the 'zi' command to invert 'foldenable' in diff windows (test +" for the issue fixed by patch 6.2.317) +func Test_diff_foldinvert() + %bw! + edit Xdoffile1 + new Xdoffile2 + new Xdoffile3 + windo diffthis + " open a non-diff window + botright new + 1wincmd w + call assert_true(getwinvar(1, '&foldenable')) + call assert_true(getwinvar(2, '&foldenable')) + call assert_true(getwinvar(3, '&foldenable')) + normal zi + call assert_false(getwinvar(1, '&foldenable')) + call assert_false(getwinvar(2, '&foldenable')) + call assert_false(getwinvar(3, '&foldenable')) + normal zi + call assert_true(getwinvar(1, '&foldenable')) + call assert_true(getwinvar(2, '&foldenable')) + call assert_true(getwinvar(3, '&foldenable')) + + " If the current window has 'noscrollbind', then 'zi' should not change + " 'foldenable' in other windows. + 1wincmd w + set noscrollbind + normal zi + call assert_false(getwinvar(1, '&foldenable')) + call assert_true(getwinvar(2, '&foldenable')) + call assert_true(getwinvar(3, '&foldenable')) + + " 'zi' should not change the 'foldenable' for windows with 'noscrollbind' + 1wincmd w + set scrollbind + normal zi + call setwinvar(2, '&scrollbind', v:false) + normal zi + call assert_false(getwinvar(1, '&foldenable')) + call assert_true(getwinvar(2, '&foldenable')) + call assert_false(getwinvar(3, '&foldenable')) + + %bw! + set scrollbind& +endfunc + +" This was scrolling for 'cursorbind' but 'scrollbind' is more important +func Test_diff_scroll() + CheckScreendump + + let left =<< trim END + line 1 + line 2 + line 3 + line 4 + + // Common block + // one + // containing + // four lines + + // Common block + // two + // containing + // four lines + END + call writefile(left, 'Xleft', 'D') + let right =<< trim END + line 1 + line 2 + line 3 + line 4 + + Lorem + ipsum + dolor + sit + amet, + consectetur + adipiscing + elit. + Etiam + luctus + lectus + sodales, + dictum + + // Common block + // one + // containing + // four lines + + Vestibulum + tincidunt + aliquet + nulla. + + // Common block + // two + // containing + // four lines + END + call writefile(right, 'Xright', 'D') + let buf = RunVimInTerminal('-d Xleft Xright', {'rows': 12}) + call term_sendkeys(buf, "\<C-W>\<C-W>jjjj") + call VerifyScreenDump(buf, 'Test_diff_scroll_1', {}) + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_diff_scroll_2', {}) + + call StopVimInTerminal(buf) +endfunc + +" This was scrolling too many lines. +func Test_diff_scroll_wrap_on() + 20new + 40vsplit + call setline(1, map(range(1, 9), 'repeat(v:val, 200)')) + setlocal number diff so=0 + redraw + normal! jj + call assert_equal(1, winsaveview().topline) + normal! j + call assert_equal(2, winsaveview().topline) + + bwipe! + bwipe! +endfunc + +func Test_diff_scroll_many_filler() + 20new + vnew + call setline(1, ['^^^', '^^^', '$$$', '$$$']) + diffthis + setlocal scrolloff=0 + wincmd p + call setline(1, ['^^^', '^^^'] + repeat(['###'], 41) + ['$$$', '$$$']) + diffthis + setlocal scrolloff=0 + wincmd p + redraw + + " Note: need a redraw after each scroll, otherwise the test always passes. + normal! G + redraw + call assert_equal(3, winsaveview().topline) + call assert_equal(18, winsaveview().topfill) + exe "normal! \<C-B>" + redraw + call assert_equal(3, winsaveview().topline) + call assert_equal(19, winsaveview().topfill) + exe "normal! \<C-B>" + redraw + call assert_equal(2, winsaveview().topline) + call assert_equal(0, winsaveview().topfill) + exe "normal! \<C-B>" + redraw + call assert_equal(1, winsaveview().topline) + call assert_equal(0, winsaveview().topfill) + + bwipe! + bwipe! +endfunc + +" This was trying to update diffs for a buffer being closed +func Test_diff_only() + silent! lfile + set diff + lopen + norm o + silent! norm o + + set nodiff + %bwipe! +endfunc + +" This was causing invalid diff block values +" FIXME: somehow this causes a valgrind error when run directly but not when +" run as a test. +func Test_diff_manipulations() + set diff + split 0 + sil! norm R
doobdeuR
doobdeuR
doobdeu + + set nodiff + %bwipe! +endfunc + +" This was causing the line number in the diff block to go below one. +" FIXME: somehow this causes a valgrind error when run directly but not when +" run as a test. +func Test_diff_put_and_undo() + set diff + next 0 + split 00 + sil! norm o0gguudpo0ggJuudp + + bwipe! + bwipe! + set nodiff +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_digraph.vim b/test/old/testdir/test_digraph.vim new file mode 100644 index 0000000000..8229248f7f --- /dev/null +++ b/test/old/testdir/test_digraph.vim @@ -0,0 +1,602 @@ +" 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('.'))) + " Quadruple prime + call Put_Dig("'4") + call assert_equal("⁗", getline('.')) + " 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('.'))) + " Circumflex + 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() + CheckFeature keymap + 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() + CheckFeature keymap + call assert_fails('loadkeymap', 'E105:') + call writefile(['loadkeymap', 'a'], 'Xkeymap', 'D') + call assert_fails('source Xkeymap', 'E791:') +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 diff --git a/test/old/testdir/test_display.vim b/test/old/testdir/test_display.vim new file mode 100644 index 0000000000..bd90287400 --- /dev/null +++ b/test/old/testdir/test_display.vim @@ -0,0 +1,492 @@ +" 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', 'D') + 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) +endfunc + +func Test_display_listchars_precedes() + 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, 'D') + let buf = RunVimInTerminal('-S '.filename, #{rows: 5, cols: 50}) + call term_sendkeys(buf, "k") + call VerifyScreenDump(buf, 'Test_winline_rnu', {}) + + " clean up + call StopVimInTerminal(buf) +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, 'D') + let buf = RunVimInTerminal('-N -u NONE ' .. longName, #{rows: 8}) + + call VerifyScreenDump(buf, 'Test_long_file_name_1', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_unprintable_fileformats() + CheckScreendump + + call writefile(["unix\r", "two"], 'Xunix.txt', 'D') + call writefile(["mac\r", "two"], 'Xmac.txt', 'D') + let lines =<< trim END + edit Xunix.txt + split Xmac.txt + edit ++ff=mac + END + let filename = 'Xunprintable' + call writefile(lines, filename, 'D') + 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) +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', 'D') + + 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) +endfunc + +" Test for 'eob' (EndOfBuffer) item in 'fillchars' +func Test_eob_fillchars() + " default value + " 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', 'D') + 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) +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) + setl breakindent breakindentopt=shift:2 + 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 + +func Test_display_long_lastline() + CheckScreendump + + let lines =<< trim END + set display=lastline smoothscroll scrolloff=0 + call setline(1, [ + \'aaaaa'->repeat(150), + \'bbbbb '->repeat(7) .. 'ccccc '->repeat(7) .. 'ddddd '->repeat(7) + \]) + END + + call writefile(lines, 'XdispLongline', 'D') + let buf = RunVimInTerminal('-S XdispLongline', #{rows: 14, cols: 35}) + + call term_sendkeys(buf, "736|") + call VerifyScreenDump(buf, 'Test_display_long_line_1', {}) + + " The correct part of the last line is moved into view. + call term_sendkeys(buf, "D") + call VerifyScreenDump(buf, 'Test_display_long_line_2', {}) + + " "w_skipcol" does not change because the topline is still long enough + " to maintain the current skipcol. + call term_sendkeys(buf, "g04l11gkD") + call VerifyScreenDump(buf, 'Test_display_long_line_3', {}) + + " "w_skipcol" is reset to bring the entire topline into view because + " the line length is now smaller than the current skipcol + marker. + call term_sendkeys(buf, "x") + call VerifyScreenDump(buf, 'Test_display_long_line_4', {}) + + call StopVimInTerminal(buf) +endfunc + +" Moving the cursor to a line that doesn't fit in the window should show +" correctly. +func Test_display_cursor_long_line() + CheckScreendump + + let lines =<< trim END + call setline(1, ['a', 'b ' .. 'bbbbb'->repeat(150), 'c']) + norm $j + END + + call writefile(lines, 'XdispCursorLongline', 'D') + let buf = RunVimInTerminal('-S XdispCursorLongline', #{rows: 8}) + + call VerifyScreenDump(buf, 'Test_display_cursor_long_line_1', {}) + + " FIXME: moving the cursor above the topline does not set w_skipcol + " correctly with cpo+=n and zero scrolloff (curs_columns() extra == 1). + call term_sendkeys(buf, ":set number cpo+=n scrolloff=0\<CR>") + call term_sendkeys(buf, '$0') + call VerifyScreenDump(buf, 'Test_display_cursor_long_line_2', {}) + + " Going to the start of the line with "b" did not set w_skipcol correctly + " with 'smoothscroll'. + call term_sendkeys(buf, ":set smoothscroll\<CR>") + call term_sendkeys(buf, '$b') + call VerifyScreenDump(buf, 'Test_display_cursor_long_line_3', {}) + " Same for "ge". + call term_sendkeys(buf, '$ge') + call VerifyScreenDump(buf, 'Test_display_cursor_long_line_4', {}) + + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_edit.vim b/test/old/testdir/test_edit.vim new file mode 100644 index 0000000000..3fe65832c9 --- /dev/null +++ b/test/old/testdir/test_edit.vim @@ -0,0 +1,2122 @@ +" Test for edit functions + +if exists("+t_kD") + let &t_kD="[3;*~" +endif + +source check.vim +source screendump.vim + +" Needed for testing basic rightleft: Test_edit_rightleft +source view_util.vim + +" Needs to come first until the bug in getchar() is +" fixed: https://groups.google.com/d/msg/vim_dev/fXL9yme4H4c/bOR-U6_bAQAJ +func Test_edit_00b() + new + call setline(1, ['abc ']) + inoreabbr <buffer> h here some more + call cursor(1, 4) + " <esc> expands the abbreviation and ends insert mode + " call feedkeys(":set im\<cr> h\<c-l>:set noim\<cr>", 'tix') + call feedkeys("i h\<esc>", 'tix') + call assert_equal(['abc here some more '], getline(1,'$')) + iunabbr <buffer> h + bw! +endfunc + +func Test_edit_01() + " set for Travis CI? + " set nocp noesckeys + new + " 1) empty buffer + call assert_equal([''], getline(1,'$')) + " 2) delete in an empty line + call feedkeys("i\<del>\<esc>", 'tnix') + call assert_equal([''], getline(1,'$')) + %d + " 3) delete one character + call setline(1, 'a') + call feedkeys("i\<del>\<esc>", 'tnix') + call assert_equal([''], getline(1,'$')) + %d + " 4) delete a multibyte character + call setline(1, "\u0401") + call feedkeys("i\<del>\<esc>", 'tnix') + call assert_equal([''], getline(1,'$')) + %d + " 5.1) delete linebreak with 'bs' option containing eol + let _bs=&bs + set bs=eol + call setline(1, ["abc def", "ghi jkl"]) + call cursor(1, 1) + call feedkeys("A\<del>\<esc>", 'tnix') + call assert_equal(['abc defghi jkl'], getline(1, 2)) + %d + " 5.2) delete linebreak with backspace option w/out eol + set bs= + call setline(1, ["abc def", "ghi jkl"]) + call cursor(1, 1) + call feedkeys("A\<del>\<esc>", 'tnix') + call assert_equal(["abc def", "ghi jkl"], getline(1, 2)) + let &bs=_bs + bw! +endfunc + +func Test_edit_02() + " Change cursor position in InsertCharPre command + new + call setline(1, 'abc') + call cursor(1, 1) + fu! DoIt(...) + call cursor(1, 4) + if len(a:000) + let v:char=a:1 + endif + endfu + au InsertCharPre <buffer> :call DoIt('y') + call feedkeys("ix\<esc>", 'tnix') + call assert_equal(['abcy'], getline(1, '$')) + " Setting <Enter> in InsertCharPre + au! InsertCharPre <buffer> :call DoIt("\n") + call setline(1, 'abc') + call cursor(1, 1) + call feedkeys("ix\<esc>", 'tnix') + call assert_equal(['abc', ''], getline(1, '$')) + %d + au! InsertCharPre + " Change cursor position in InsertEnter command + " 1) when setting v:char, keeps changed cursor position + au! InsertEnter <buffer> :call DoIt('y') + call setline(1, 'abc') + call cursor(1, 1) + call feedkeys("ix\<esc>", 'tnix') + call assert_equal(['abxc'], getline(1, '$')) + " 2) when not setting v:char, restores changed cursor position + au! InsertEnter <buffer> :call DoIt() + call setline(1, 'abc') + call cursor(1, 1) + call feedkeys("ix\<esc>", 'tnix') + call assert_equal(['xabc'], getline(1, '$')) + au! InsertEnter + delfu DoIt + bw! +endfunc + +func Test_edit_03() + " Change cursor after <c-o> command to end of line + new + call setline(1, 'abc') + call cursor(1, 1) + call feedkeys("i\<c-o>$y\<esc>", 'tnix') + call assert_equal(['abcy'], getline(1, '$')) + %d + call setline(1, 'abc') + call cursor(1, 1) + call feedkeys("i\<c-o>80|y\<esc>", 'tnix') + call assert_equal(['abcy'], getline(1, '$')) + %d + call setline(1, 'abc') + call feedkeys("Ad\<c-o>:s/$/efg/\<cr>hij", 'tnix') + call assert_equal(['hijabcdefg'], getline(1, '$')) + bw! +endfunc + +func Test_edit_04() + " test for :stopinsert + new + call setline(1, 'abc') + call cursor(1, 1) + call feedkeys("i\<c-o>:stopinsert\<cr>$", 'tnix') + call feedkeys("aX\<esc>", 'tnix') + call assert_equal(['abcX'], getline(1, '$')) + %d + bw! +endfunc + +func Test_edit_05() + " test for folds being opened + new + call setline(1, ['abcX', 'abcX', 'zzzZ']) + call cursor(1, 1) + set foldmethod=manual foldopen+=insert + " create fold for those two lines + norm! Vjzf + call feedkeys("$ay\<esc>", 'tnix') + call assert_equal(['abcXy', 'abcX', 'zzzZ'], getline(1, '$')) + %d + call setline(1, ['abcX', 'abcX', 'zzzZ']) + call cursor(1, 1) + set foldmethod=manual foldopen-=insert + " create fold for those two lines + norm! Vjzf + call feedkeys("$ay\<esc>", 'tnix') + call assert_equal(['abcXy', 'abcX', 'zzzZ'], getline(1, '$')) + %d + bw! +endfunc + +func Test_edit_06() + " Test in diff mode + if !has("diff") || !executable("diff") + return + endif + new + call setline(1, ['abc', 'xxx', 'yyy']) + vnew + call setline(1, ['abc', 'zzz', 'xxx', 'yyy']) + wincmd p + diffthis + wincmd p + diffthis + wincmd p + call cursor(2, 1) + norm! zt + call feedkeys("Ozzz\<esc>", 'tnix') + call assert_equal(['abc', 'zzz', 'xxx', 'yyy'], getline(1,'$')) + bw! + bw! +endfunc + +func Test_edit_07() + " 1) Test with completion <c-l> when popupmenu is visible + new + call setline(1, 'J') + + func! ListMonths() + call complete(col('.')-1, ['January', 'February', 'March', + \ 'April', 'May', 'June', 'July', 'August', 'September', + \ 'October', 'November', 'December']) + return '' + endfunc + inoremap <buffer> <F5> <C-R>=ListMonths()<CR> + + call feedkeys("A\<f5>\<c-p>". repeat("\<down>", 6)."\<c-l>\<down>\<c-l>\<cr>", 'tx') + call assert_equal(['July'], getline(1,'$')) + " 1) Test completion when InsertCharPre kicks in + %d + call setline(1, 'J') + fu! DoIt() + if v:char=='u' + let v:char='an' + endif + endfu + au InsertCharPre <buffer> :call DoIt() + call feedkeys("A\<f5>\<c-p>u\<cr>\<c-l>\<cr>", 'tx') + call assert_equal(["Jan\<c-l>",''], 1->getline('$')) + %d + call setline(1, 'J') + call feedkeys("A\<f5>\<c-p>u\<down>\<c-l>\<cr>", 'tx') + call assert_equal(["January"], 1->getline('$')) + + delfu ListMonths + delfu DoIt + iunmap <buffer> <f5> + bw! +endfunc + +func Test_edit_08() + throw 'skipped: moved to test/functional/legacy/edit_spec.lua' + " reset insertmode from i_ctrl-r_= + let g:bufnr = bufnr('%') + new + call setline(1, ['abc']) + call cursor(1, 4) + call feedkeys(":set im\<cr>ZZZ\<c-r>=setbufvar(g:bufnr,'&im', 0)\<cr>",'tnix') + call assert_equal(['abZZZc'], getline(1,'$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + call assert_false(0, '&im') + bw! + unlet g:bufnr +endfunc + +func Test_edit_09() + " test i_CTRL-\ combinations + new + call setline(1, ['abc', 'def', 'ghi']) + call cursor(1, 1) + " 1) CTRL-\ CTLR-N + " call feedkeys(":set im\<cr>\<c-\>\<c-n>ccABC\<c-l>", 'txin') + call feedkeys("i\<c-\>\<c-n>ccABC\<esc>", 'txin') + call assert_equal(['ABC', 'def', 'ghi'], getline(1,'$')) + call setline(1, ['ABC', 'def', 'ghi']) + " 2) CTRL-\ CTLR-G + " CTRL-\ CTRL-G goes to Insert mode when 'insertmode' is set, but + " 'insertmode' is now removed so skip this test + " call feedkeys("j0\<c-\>\<c-g>ZZZ\<cr>\<esc>", 'txin') + " call assert_equal(['ABC', 'ZZZ', 'def', 'ghi'], getline(1,'$')) + " call feedkeys("I\<c-\>\<c-g>YYY\<c-l>", 'txin') + " call assert_equal(['ABC', 'ZZZ', 'YYYdef', 'ghi'], getline(1,'$')) + " set noinsertmode + " 3) CTRL-\ CTRL-O + call setline(1, ['ABC', 'ZZZ', 'def', 'ghi']) + call cursor(1, 1) + call feedkeys("A\<c-o>ix", 'txin') + call assert_equal(['ABxC', 'ZZZ', 'def', 'ghi'], getline(1,'$')) + call feedkeys("A\<c-\>\<c-o>ix", 'txin') + call assert_equal(['ABxCx', 'ZZZ', 'def', 'ghi'], getline(1,'$')) + " 4) CTRL-\ a (should be inserted literally, not special after <c-\> + call setline(1, ['ABC', 'ZZZ', 'def', 'ghi']) + call cursor(1, 1) + call feedkeys("A\<c-\>a", 'txin') + call assert_equal(["ABC\<c-\>a", 'ZZZ', 'def', 'ghi'], getline(1, '$')) + bw! +endfunc + +func Test_edit_11() + " Test that indenting kicks in + new + set cindent + call setline(1, ['{', '', '']) + call cursor(2, 1) + call feedkeys("i\<c-f>int c;\<esc>", 'tnix') + call cursor(3, 1) + call feedkeys("\<Insert>/* comment */", 'tnix') + call assert_equal(['{', "\<tab>int c;", "/* comment */"], getline(1, '$')) + " added changed cindentkeys slightly + set cindent cinkeys+=*/ + call setline(1, ['{', '', '']) + call cursor(2, 1) + call feedkeys("i\<c-f>int c;\<esc>", 'tnix') + call cursor(3, 1) + call feedkeys("i/* comment */", 'tnix') + call assert_equal(['{', "\<tab>int c;", "\<tab>/* comment */"], getline(1, '$')) + set cindent cinkeys+==end + call feedkeys("oend\<cr>\<esc>", 'tnix') + call assert_equal(['{', "\<tab>int c;", "\<tab>/* comment */", "\tend", ''], getline(1, '$')) + set cinkeys-==end + %d + " Use indentexpr instead of cindenting + func! Do_Indent() + if v:lnum == 3 + return 3*shiftwidth() + else + return 2*shiftwidth() + endif + endfunc + setl indentexpr=Do_Indent() indentkeys+=*/ + call setline(1, ['{', '', '']) + call cursor(2, 1) + call feedkeys("i\<c-f>int c;\<esc>", 'tnix') + call cursor(3, 1) + call feedkeys("i/* comment */", 'tnix') + call assert_equal(['{', "\<tab>\<tab>int c;", "\<tab>\<tab>\<tab>/* comment */"], getline(1, '$')) + set cinkeys&vim indentkeys&vim + set nocindent indentexpr= + delfu Do_Indent + bw! +endfunc + +func Test_edit_11_indentexpr() + " Test that indenting kicks in + new + " Use indentexpr instead of cindenting + func! Do_Indent() + let pline=prevnonblank(v:lnum) + if empty(getline(v:lnum)) + if getline(pline) =~ 'if\|then' + return shiftwidth() + else + return 0 + endif + else + return 0 + endif + endfunc + setl indentexpr=Do_Indent() indentkeys+=0=then,0=fi + call setline(1, ['if [ $this ]']) + call cursor(1, 1) + call feedkeys("othen\<cr>that\<cr>fi", 'tnix') + call assert_equal(['if [ $this ]', "then", "\<tab>that", "fi"], getline(1, '$')) + set cinkeys&vim indentkeys&vim + set nocindent indentexpr= + delfu Do_Indent + + " Using a script-local function + func s:NewIndentExpr() + endfunc + set indentexpr=s:NewIndentExpr() + call assert_equal(expand('<SID>') .. 'NewIndentExpr()', &indentexpr) + call assert_equal(expand('<SID>') .. 'NewIndentExpr()', &g:indentexpr) + set indentexpr=<SID>NewIndentExpr() + call assert_equal(expand('<SID>') .. 'NewIndentExpr()', &indentexpr) + call assert_equal(expand('<SID>') .. 'NewIndentExpr()', &g:indentexpr) + setlocal indentexpr= + setglobal indentexpr=s:NewIndentExpr() + call assert_equal(expand('<SID>') .. 'NewIndentExpr()', &g:indentexpr) + call assert_equal('', &indentexpr) + new + call assert_equal(expand('<SID>') .. 'NewIndentExpr()', &indentexpr) + bw! + setglobal indentexpr=<SID>NewIndentExpr() + call assert_equal(expand('<SID>') .. 'NewIndentExpr()', &g:indentexpr) + call assert_equal('', &indentexpr) + new + call assert_equal(expand('<SID>') .. 'NewIndentExpr()', &indentexpr) + bw! + set indentexpr& + + bw! +endfunc + +" Test changing indent in replace mode +func Test_edit_12() + new + call setline(1, ["\tabc", "\tdef"]) + call cursor(2, 4) + call feedkeys("R^\<c-d>", 'tnix') + call assert_equal(["\tabc", "def"], getline(1, '$')) + call assert_equal([0, 2, 2, 0], '.'->getpos()) + %d + call setline(1, ["\tabc", "\t\tdef"]) + call cursor(2, 2) + call feedkeys("R^\<c-d>", 'tnix') + call assert_equal(["\tabc", "def"], getline(1, '$')) + call assert_equal([0, 2, 1, 0], getpos('.')) + %d + call setline(1, ["\tabc", "\t\tdef"]) + call cursor(2, 2) + call feedkeys("R\<c-t>", 'tnix') + call assert_equal(["\tabc", "\t\t\tdef"], getline(1, '$')) + call assert_equal([0, 2, 2, 0], getpos('.')) + bw! + 10vnew + call setline(1, ["\tabc", "\t\tdef"]) + call cursor(2, 2) + call feedkeys("R\<c-t>", 'tnix') + call assert_equal(["\tabc", "\t\t\tdef"], getline(1, '$')) + call assert_equal([0, 2, 2, 0], getpos('.')) + %d + set sw=4 + call setline(1, ["\tabc", "\t\tdef"]) + call cursor(2, 2) + call feedkeys("R\<c-t>\<c-t>", 'tnix') + call assert_equal(["\tabc", "\t\t\tdef"], getline(1, '$')) + call assert_equal([0, 2, 2, 0], getpos('.')) + %d + call setline(1, ["\tabc", "\t\tdef"]) + call cursor(2, 2) + call feedkeys("R\<c-t>\<c-t>", 'tnix') + call assert_equal(["\tabc", "\t\t\tdef"], getline(1, '$')) + call assert_equal([0, 2, 2, 0], getpos('.')) + set sw& + + " In replace mode, after hitting enter in a line with tab characters, + " pressing backspace should restore the tab characters. + %d + setlocal autoindent backspace=2 + call setline(1, "\tone\t\ttwo") + exe "normal ggRred\<CR>six" .. repeat("\<BS>", 8) + call assert_equal(["\tone\t\ttwo"], getline(1, '$')) + bw! +endfunc + +func Test_edit_13() + " Test smartindenting + new + set smartindent autoindent + call setline(1, ["\tabc"]) + call feedkeys("A {\<cr>more\<cr>}\<esc>", 'tnix') + call assert_equal(["\tabc {", "\t\tmore", "\t}"], getline(1, '$')) + set smartindent& autoindent& + bwipe! + + " Test autoindent removing indent of blank line. + new + call setline(1, ' foo bar baz') + set autoindent + exe "normal 0eea\<CR>\<CR>\<Esc>" + call assert_equal(" foo bar", getline(1)) + call assert_equal("", getline(2)) + call assert_equal(" baz", getline(3)) + set autoindent& + + " pressing <C-U> to erase line should keep the indent with 'autoindent' + set backspace=2 autoindent + %d + exe "normal i\tone\<CR>three\<C-U>two" + call assert_equal(["\tone", "\ttwo"], getline(1, '$')) + set backspace& autoindent& + + bwipe! +endfunc + +" Test for autoindent removing indent when insert mode is stopped. Some parts +" of the code is exercised only when interactive mode is used. So use Vim in a +" terminal. +func Test_autoindent_remove_indent() + CheckRunVimInTerminal + let buf = RunVimInTerminal('-N Xarifile', {'rows': 6, 'cols' : 20}) + call TermWait(buf) + call term_sendkeys(buf, ":set autoindent\n") + " leaving insert mode in a new line with indent added by autoindent, should + " remove the indent. + call term_sendkeys(buf, "i\<Tab>foo\<CR>\<Esc>") + " Need to delay for some time, otherwise the code in getchar.c will not be + " exercised. + call TermWait(buf, 50) + " when a line is wrapped and the cursor is at the start of the second line, + " leaving insert mode, should move the cursor back to the first line. + call term_sendkeys(buf, "o" .. repeat('x', 20) .. "\<Esc>") + " Need to delay for some time, otherwise the code in getchar.c will not be + " exercised. + call TermWait(buf, 50) + call term_sendkeys(buf, ":w\n") + call TermWait(buf) + call StopVimInTerminal(buf) + call assert_equal(["\tfoo", '', repeat('x', 20)], readfile('Xarifile')) + call delete('Xarifile') +endfunc + +func Test_edit_CR() + " Test for <CR> in insert mode + " basically only in quickfix mode it's tested, the rest + " has been taken care of by other tests + CheckFeature quickfix + botright new + call writefile(range(1, 10), 'Xqflist.txt') + call setqflist([{'filename': 'Xqflist.txt', 'lnum': 2}]) + copen + set modifiable + call feedkeys("A\<cr>", 'tnix') + call assert_equal('Xqflist.txt', bufname('')) + call assert_equal(2, line('.')) + cclose + botright new + call setloclist(0, [{'filename': 'Xqflist.txt', 'lnum': 10}]) + lopen + set modifiable + call feedkeys("A\<cr>", 'tnix') + call assert_equal('Xqflist.txt', bufname('')) + call assert_equal(10, line('.')) + call feedkeys("A\<Enter>", 'tnix') + call feedkeys("A\<kEnter>", 'tnix') + call feedkeys("A\n", 'tnix') + call feedkeys("A\r", 'tnix') + call assert_equal(map(range(1, 10), 'string(v:val)') + ['', '', '', ''], getline(1, '$')) + bw! + lclose + call delete('Xqflist.txt') +endfunc + +func Test_edit_CTRL_() + " disabled for Windows builds, why? + if !has("rightleft") || has("win32") + return + endif + let _encoding=&encoding + set encoding=utf-8 + " Test for CTRL-_ + new + call setline(1, ['abc']) + call cursor(1, 1) + call feedkeys("i\<c-_>xyz\<esc>", 'tnix') + call assert_equal(["\<C-_>xyzabc"], getline(1, '$')) + call assert_false(&revins) + set ari + call setline(1, ['abc']) + call cursor(1, 1) + call feedkeys("i\<c-_>xyz\<esc>", 'tnix') + " call assert_equal(["æèñabc"], getline(1, '$')) + call assert_equal(["zyxabc"], getline(1, '$')) + call assert_true(&revins) + call setline(1, ['abc']) + call cursor(1, 1) + call feedkeys("i\<c-_>xyz\<esc>", 'tnix') + call assert_equal(["xyzabc"], getline(1, '$')) + call assert_false(&revins) + set noari + let &encoding=_encoding + bw! +endfunc + +" needs to come first, to have the @. register empty +func Test_edit_00a_CTRL_A() + " Test pressing CTRL-A + new + call setline(1, repeat([''], 5)) + call cursor(1, 1) + try + call feedkeys("A\<NUL>", 'tnix') + catch /^Vim\%((\a\+)\)\=:E29/ + call assert_true(1, 'E29 error caught') + endtry + call cursor(1, 1) + call feedkeys("Afoobar \<esc>", 'tnix') + call cursor(2, 1) + call feedkeys("A\<c-a>more\<esc>", 'tnix') + call cursor(3, 1) + call feedkeys("A\<NUL>and more\<esc>", 'tnix') + call assert_equal(['foobar ', 'foobar more', 'foobar morend more', '', ''], getline(1, '$')) + bw! +endfunc + +func Test_edit_CTRL_EY() + " Ctrl-E/ Ctrl-Y in insert mode completion to scroll + 10new + call setline(1, range(1, 100)) + call cursor(30, 1) + norm! z. + call feedkeys("A\<c-x>\<c-e>\<c-e>\<c-e>\<c-e>\<c-e>", 'tnix') + call assert_equal(30, winsaveview()['topline']) + call assert_equal([0, 30, 2, 0], getpos('.')) + call feedkeys("A\<c-x>\<c-e>\<c-e>\<c-e>\<c-e>\<c-e>", 'tnix') + call feedkeys("A\<c-x>".repeat("\<c-y>", 10), 'tnix') + call assert_equal(21, winsaveview()['topline']) + call assert_equal([0, 30, 2, 0], getpos('.')) + bw! +endfunc + +func Test_edit_CTRL_G() + new + call setline(1, ['foobar', 'foobar', 'foobar']) + call cursor(2, 4) + call feedkeys("ioooooooo\<c-g>k\<c-r>.\<esc>", 'tnix') + call assert_equal(['foooooooooobar', 'foooooooooobar', 'foobar'], getline(1, '$')) + call assert_equal([0, 1, 11, 0], getpos('.')) + call feedkeys("i\<c-g>k\<esc>", 'tnix') + call assert_equal([0, 1, 10, 0], getpos('.')) + call cursor(2, 4) + call feedkeys("i\<c-g>jzzzz\<esc>", 'tnix') + call assert_equal(['foooooooooobar', 'foooooooooobar', 'foozzzzbar'], getline(1, '$')) + call assert_equal([0, 3, 7, 0], getpos('.')) + call feedkeys("i\<c-g>j\<esc>", 'tnix') + call assert_equal([0, 3, 6, 0], getpos('.')) + call assert_nobeep("normal! i\<c-g>\<esc>") + bw! +endfunc + +func Test_edit_CTRL_I() + " Tab in completion mode + let path=expand("%:p:h") + new + call setline(1, [path. "/", '']) + call feedkeys("Arunt\<c-x>\<c-f>\<tab>\<cr>\<esc>", 'tnix') + call assert_match('runtest\.vim', getline(1)) + %d + call writefile(['one', 'two', 'three'], 'Xinclude.txt') + let include='#include Xinclude.txt' + call setline(1, [include, '']) + call cursor(2, 1) + call feedkeys("A\<c-x>\<tab>\<cr>\<esc>", 'tnix') + call assert_equal([include, 'one', ''], getline(1, '$')) + call feedkeys("2ggC\<c-x>\<tab>\<down>\<cr>\<esc>", 'tnix') + call assert_equal([include, 'two', ''], getline(1, '$')) + call feedkeys("2ggC\<c-x>\<tab>\<down>\<down>\<cr>\<esc>", 'tnix') + call assert_equal([include, 'three', ''], getline(1, '$')) + call feedkeys("2ggC\<c-x>\<tab>\<down>\<down>\<down>\<cr>\<esc>", 'tnix') + call assert_equal([include, '', ''], getline(1, '$')) + call delete("Xinclude.txt") + bw! +endfunc + +func Test_edit_CTRL_K() + " Test pressing CTRL-K (basically only dictionary completion and digraphs + " the rest is already covered + call writefile(['A', 'AA', 'AAA', 'AAAA'], 'Xdictionary.txt') + set dictionary=Xdictionary.txt + new + call setline(1, 'A') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-k>\<cr>\<esc>", 'tnix') + call assert_equal(['AA', ''], getline(1, '$')) + %d + call setline(1, 'A') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-k>\<down>\<cr>\<esc>", 'tnix') + call assert_equal(['AAA'], getline(1, '$')) + %d + call setline(1, 'A') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-k>\<down>\<down>\<cr>\<esc>", 'tnix') + call assert_equal(['AAAA'], getline(1, '$')) + %d + call setline(1, 'A') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-k>\<down>\<down>\<down>\<cr>\<esc>", 'tnix') + call assert_equal(['A'], getline(1, '$')) + %d + call setline(1, 'A') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-k>\<down>\<down>\<down>\<down>\<cr>\<esc>", 'tnix') + call assert_equal(['AA'], getline(1, '$')) + + " press an unexpected key after dictionary completion + %d + call setline(1, 'A') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-k>\<c-]>\<cr>\<esc>", 'tnix') + call assert_equal(['AA', ''], getline(1, '$')) + %d + call setline(1, 'A') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-k>\<c-s>\<cr>\<esc>", 'tnix') + call assert_equal(["AA\<c-s>", ''], getline(1, '$')) + %d + call setline(1, 'A') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-k>\<c-f>\<cr>\<esc>", 'tnix') + call assert_equal(["AA\<c-f>", ''], getline(1, '$')) + + set dictionary= + %d + call setline(1, 'A') + call cursor(1, 1) + let v:testing = 1 + try + call feedkeys("A\<c-x>\<c-k>\<esc>", 'tnix') + catch + " error sleeps 2 seconds, when v:testing is not set + let v:testing = 0 + endtry + call delete('Xdictionary.txt') + + if exists('*test_override') + call test_override("char_avail", 1) + set showcmd + %d + call feedkeys("A\<c-k>a:\<esc>", 'tnix') + call assert_equal(['ä'], getline(1, '$')) + call test_override("char_avail", 0) + set noshowcmd + endif + bw! +endfunc + +func Test_edit_CTRL_L() + " Test Ctrl-X Ctrl-L (line completion) + new + set complete=. + call setline(1, ['one', 'two', 'three', '', '', '', '']) + call cursor(4, 1) + call feedkeys("A\<c-x>\<c-l>\<esc>", 'tnix') + call assert_equal(['one', 'two', 'three', 'three', '', '', ''], getline(1, '$')) + call feedkeys("cct\<c-x>\<c-l>\<c-n>\<esc>", 'tnix') + call assert_equal(['one', 'two', 'three', 't', '', '', ''], getline(1, '$')) + call feedkeys("cct\<c-x>\<c-l>\<c-n>\<c-n>\<esc>", 'tnix') + call assert_equal(['one', 'two', 'three', 'two', '', '', ''], getline(1, '$')) + call feedkeys("cct\<c-x>\<c-l>\<c-n>\<c-n>\<c-n>\<esc>", 'tnix') + call assert_equal(['one', 'two', 'three', 'three', '', '', ''], getline(1, '$')) + call feedkeys("cct\<c-x>\<c-l>\<c-n>\<c-n>\<c-n>\<c-n>\<esc>", 'tnix') + call assert_equal(['one', 'two', 'three', 't', '', '', ''], getline(1, '$')) + call feedkeys("cct\<c-x>\<c-l>\<c-p>\<esc>", 'tnix') + call assert_equal(['one', 'two', 'three', 'two', '', '', ''], getline(1, '$')) + call feedkeys("cct\<c-x>\<c-l>\<c-p>\<c-p>\<esc>", 'tnix') + call assert_equal(['one', 'two', 'three', 't', '', '', ''], getline(1, '$')) + call feedkeys("cct\<c-x>\<c-l>\<c-p>\<c-p>\<c-p>\<esc>", 'tnix') + call assert_equal(['one', 'two', 'three', 'three', '', '', ''], getline(1, '$')) + set complete= + call cursor(5, 1) + call feedkeys("A\<c-x>\<c-l>\<c-p>\<c-n>\<esc>", 'tnix') + call assert_equal(['one', 'two', 'three', 'three', "\<c-l>\<c-p>\<c-n>", '', ''], getline(1, '$')) + set complete& + %d + if has("conceal") && has("syntax") && !has("nvim") + call setline(1, ['foo', 'bar', 'foobar']) + call test_override("char_avail", 1) + set conceallevel=2 concealcursor=n + syn on + syn match ErrorMsg "^bar" + call matchadd("Conceal", 'oo', 10, -1, {'conceal': 'X'}) + func! DoIt() + let g:change=1 + endfunc + au! TextChangedI <buffer> :call DoIt() + + call cursor(2, 1) + call assert_false(exists("g:change")) + call feedkeys("A \<esc>", 'tnix') + call assert_equal(['foo', 'bar ', 'foobar'], getline(1, '$')) + call assert_equal(1, g:change) + + call test_override("char_avail", 0) + call clearmatches() + syn off + au! TextChangedI + delfu DoIt + unlet! g:change + endif + bw! +endfunc + +func Test_edit_CTRL_N() + " Check keyword completion + " for e in ['latin1', 'utf-8'] + for e in ['utf-8'] + exe 'set encoding=' .. e + new + set complete=. + call setline(1, ['INFER', 'loWER', '', '', ]) + call cursor(3, 1) + call feedkeys("Ai\<c-n>\<cr>\<esc>", "tnix") + call feedkeys("ILO\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['INFER', 'loWER', 'i', 'LO', '', ''], getline(1, '$'), e) + %d + call setline(1, ['INFER', 'loWER', '', '', ]) + call cursor(3, 1) + set ignorecase infercase + call feedkeys("Ii\<c-n>\<cr>\<esc>", "tnix") + call feedkeys("ILO\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['INFER', 'loWER', 'infer', 'LOWER', '', ''], getline(1, '$'), e) + set noignorecase noinfercase + %d + call setline(1, ['one word', 'two word']) + exe "normal! Goo\<C-P>\<C-X>\<C-P>" + call assert_equal('one word', getline(3)) + %d + set complete& + bw! + endfor +endfunc + +func Test_edit_CTRL_O() + " Check for CTRL-O in insert mode + new + inoreabbr <buffer> h here some more + call setline(1, ['abc', 'def']) + call cursor(1, 1) + " Ctrl-O after an abbreviation + exe "norm A h\<c-o>:set nu\<cr> text" + call assert_equal(['abc here some more text', 'def'], getline(1, '$')) + call assert_true(&nu) + set nonu + iunabbr <buffer> h + " Ctrl-O at end of line with 've'=onemore + call cursor(1, 1) + call feedkeys("A\<c-o>:let g:a=getpos('.')\<cr>\<esc>", 'tnix') + call assert_equal([0, 1, 23, 0], g:a) + call cursor(1, 1) + set ve=onemore + call feedkeys("A\<c-o>:let g:a=getpos('.')\<cr>\<esc>", 'tnix') + call assert_equal([0, 1, 24, 0], g:a) + set ve= + unlet! g:a + bw! +endfunc + +func Test_edit_CTRL_R() + " Insert Register + new + " call test_override("ALL", 1) + set showcmd + call feedkeys("AFOOBAR eins zwei\<esc>", 'tnix') + call feedkeys("O\<c-r>.", 'tnix') + call feedkeys("O\<c-r>=10*500\<cr>\<esc>", 'tnix') + call feedkeys("O\<c-r>=getreg('=', 1)\<cr>\<esc>", 'tnix') + call assert_equal(["getreg('=', 1)", '5000', "FOOBAR eins zwei", "FOOBAR eins zwei"], getline(1, '$')) + " call test_override("ALL", 0) + set noshowcmd + bw! +endfunc + +func Test_edit_CTRL_S() + " Test pressing CTRL-S (basically only spellfile completion) + " the rest is already covered + new + if !has("spell") + call setline(1, 'vim') + call feedkeys("A\<c-x>ss\<cr>\<esc>", 'tnix') + call assert_equal(['vims', ''], getline(1, '$')) + bw! + return + endif + call setline(1, 'vim') + " spell option not yet set + try + call feedkeys("A\<c-x>\<c-s>\<cr>\<esc>", 'tnix') + catch /^Vim\%((\a\+)\)\=:E756/ + call assert_true(1, 'error caught') + endtry + call assert_equal(['vim', ''], getline(1, '$')) + %d + setl spell spelllang=en + call setline(1, 'vim') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-s>\<cr>\<esc>", 'tnix') + call assert_equal(['Vim', ''], getline(1, '$')) + %d + call setline(1, 'vim') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-s>\<down>\<cr>\<esc>", 'tnix') + call assert_equal(['Aim'], getline(1, '$')) + %d + call setline(1, 'vim') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-s>\<c-p>\<cr>\<esc>", 'tnix') + call assert_equal(['vim', ''], getline(1, '$')) + %d + " empty buffer + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-s>\<c-p>\<cr>\<esc>", 'tnix') + call assert_equal(['', ''], getline(1, '$')) + setl nospell + bw! +endfunc + +func Test_edit_CTRL_T() + " Check for CTRL-T and CTRL-X CTRL-T in insert mode + " 1) increase indent + new + call setline(1, "abc") + call cursor(1, 1) + call feedkeys("A\<c-t>xyz", 'tnix') + call assert_equal(["\<tab>abcxyz"], getline(1, '$')) + " 2) also when paste option is set + set paste + call setline(1, "abc") + call cursor(1, 1) + call feedkeys("A\<c-t>xyz", 'tnix') + call assert_equal(["\<tab>abcxyz"], getline(1, '$')) + set nopaste + " CTRL-X CTRL-T (thesaurus complete) + call writefile(['angry furious mad enraged'], 'Xthesaurus') + set thesaurus=Xthesaurus + call setline(1, 'mad') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<cr>\<esc>", 'tnix') + call assert_equal(['mad', ''], getline(1, '$')) + %d + call setline(1, 'mad') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['angry', ''], getline(1, '$')) + %d + call setline(1, 'mad') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<c-n>\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['furious', ''], getline(1, '$')) + %d + call setline(1, 'mad') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<c-n>\<c-n>\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['enraged', ''], getline(1, '$')) + %d + call setline(1, 'mad') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<c-n>\<c-n>\<c-n>\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['mad', ''], getline(1, '$')) + %d + call setline(1, 'mad') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<c-n>\<c-n>\<c-n>\<c-n>\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['mad', ''], getline(1, '$')) + " Using <c-p> <c-n> when 'complete' is empty + set complete= + %d + call setline(1, 'mad') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['angry', ''], getline(1, '$')) + %d + call setline(1, 'mad') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<c-p>\<cr>\<esc>", 'tnix') + call assert_equal(['mad', ''], getline(1, '$')) + set complete& + + set thesaurus= + %d + call setline(1, 'mad') + call cursor(1, 1) + let v:testing = 1 + try + call feedkeys("A\<c-x>\<c-t>\<esc>", 'tnix') + catch + " error sleeps 2 seconds, when v:testing is not set + let v:testing = 0 + endtry + call assert_equal(['mad'], getline(1, '$')) + call delete('Xthesaurus') + bw! +endfunc + +" Test thesaurus completion with different encodings +func Test_thesaurus_complete_with_encoding() + call writefile(['angry furious mad enraged'], 'Xthesaurus') + set thesaurus=Xthesaurus + " for e in ['latin1', 'utf-8'] + for e in ['utf-8'] + exe 'set encoding=' .. e + new + call setline(1, 'mad') + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<cr>\<esc>", 'tnix') + call assert_equal(['mad', ''], getline(1, '$')) + bw! + endfor + set thesaurus= + call delete('Xthesaurus') +endfunc + +" Test 'thesaurusfunc' +func MyThesaurus(findstart, base) + let mythesaurus = [ + \ #{word: "happy", + \ synonyms: "cheerful,blissful,flying high,looking good,peppy"}, + \ #{word: "kind", + \ synonyms: "amiable,bleeding-heart,heart in right place"}] + if a:findstart + " locate the start of the word + let line = getline('.') + let start = col('.') - 1 + while start > 0 && line[start - 1] =~ '\a' + let start -= 1 + endwhile + return start + else + " find strings matching with "a:base" + let res = [] + for w in mythesaurus + if w.word =~ '^' . a:base + call add(res, w.word) + call extend(res, split(w.synonyms, ",")) + endif + endfor + return res + endif +endfunc + +func Test_thesaurus_func() + new + set thesaurus=notused + set thesaurusfunc=NotUsed + setlocal thesaurusfunc=MyThesaurus + call setline(1, "an ki") + call cursor(1, 1) + call feedkeys("A\<c-x>\<c-t>\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['an amiable', ''], getline(1, '$')) + + setlocal thesaurusfunc=NonExistingFunc + call assert_fails("normal $a\<C-X>\<C-T>", 'E117:') + + setlocal thesaurusfunc= + set thesaurusfunc=NonExistingFunc + call assert_fails("normal $a\<C-X>\<C-T>", 'E117:') + %bw! + + set thesaurusfunc= + set thesaurus= +endfunc + +func Test_edit_CTRL_U() + " Test 'completefunc' + new + " -1, -2 and -3 are special return values + let g:special=0 + fun! CompleteMonths(findstart, base) + if a:findstart + " locate the start of the word + return g:special + else + " find months matching with "a:base" + let res = [] + for m in split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec") + if m =~ '^\c'.a:base + call add(res, {'word': m, 'abbr': m.' Month', 'icase': 0}) + endif + endfor + return {'words': res, 'refresh': 'always'} + endif + endfun + set completefunc=CompleteMonths + call setline(1, ['', '']) + call cursor(1, 1) + call feedkeys("AX\<c-x>\<c-u>\<cr>\<esc>", 'tnix') + call assert_equal(['X', '', ''], getline(1, '$')) + %d + let g:special=-1 + call feedkeys("AX\<c-x>\<c-u>\<cr>\<esc>", 'tnix') + call assert_equal(['XJan', ''], getline(1, '$')) + %d + let g:special=-2 + call feedkeys("AX\<c-x>\<c-u>\<cr>\<esc>", 'tnix') + call assert_equal(['X', ''], getline(1, '$')) + %d + let g:special=-3 + call feedkeys("AX\<c-x>\<c-u>\<cr>\<esc>", 'tnix') + call assert_equal(['X', ''], getline(1, '$')) + %d + let g:special=0 + call feedkeys("AM\<c-x>\<c-u>\<cr>\<esc>", 'tnix') + call assert_equal(['Mar', ''], getline(1, '$')) + %d + call feedkeys("AM\<c-x>\<c-u>\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['May', ''], getline(1, '$')) + %d + call feedkeys("AM\<c-x>\<c-u>\<c-n>\<c-n>\<cr>\<esc>", 'tnix') + call assert_equal(['M', ''], getline(1, '$')) + delfu CompleteMonths + %d + try + call feedkeys("A\<c-x>\<c-u>", 'tnix') + call assert_fails(1, 'unknown completion function') + catch /^Vim\%((\a\+)\)\=:E117/ + call assert_true(1, 'E117 error caught') + endtry + set completefunc= + bw! +endfunc + +func Test_edit_completefunc_delete() + func CompleteFunc(findstart, base) + if a:findstart == 1 + return col('.') - 1 + endif + normal dd + return ['a', 'b'] + endfunc + new + set completefunc=CompleteFunc + call setline(1, ['', 'abcd', '']) + 2d + call assert_fails("normal 2G$a\<C-X>\<C-U>", 'E565:') + bwipe! +endfunc + +func Test_edit_CTRL_Z() + " Ctrl-Z when insertmode is not set inserts it literally + new + call setline(1, 'abc') + call feedkeys("A\<c-z>\<esc>", 'tnix') + call assert_equal(["abc\<c-z>"], getline(1,'$')) + bw! + " TODO: How to Test Ctrl-Z in insert mode, e.g. suspend? +endfunc + +func Test_edit_DROP() + if !has("dnd") + return + endif + new + call setline(1, ['abc def ghi']) + call cursor(1, 1) + try + call feedkeys("i\<Drop>\<Esc>", 'tnix') + call assert_fails(1, 'Invalid register name') + catch /^Vim\%((\a\+)\)\=:E353/ + call assert_true(1, 'error caught') + endtry + bw! +endfunc + +func Test_edit_CTRL_V() + new + call setline(1, ['abc']) + call cursor(2, 1) + + " force some redraws + set showmode showcmd + " call test_override('char_avail', 1) + + call feedkeys("A\<c-v>\<c-n>\<c-v>\<c-l>\<c-v>\<c-b>\<esc>", 'tnix') + call assert_equal(["abc\x0e\x0c\x02"], getline(1, '$')) + + if has("rightleft") && exists("+rl") + set rl + call setline(1, ['abc']) + call cursor(2, 1) + call feedkeys("A\<c-v>\<c-n>\<c-v>\<c-l>\<c-v>\<c-b>\<esc>", 'tnix') + call assert_equal(["abc\x0e\x0c\x02"], getline(1, '$')) + set norl + endif + + set noshowmode showcmd + " call test_override('char_avail', 0) + + " No modifiers should be applied to the char typed using i_CTRL-V_digit. + call feedkeys(":append\<CR>\<C-V>76c\<C-V>76\<C-F2>\<C-V>u3c0j\<C-V>u3c0\<M-F3>\<CR>.\<CR>", 'tnix') + call assert_equal('LcL<C-F2>πjπ<M-F3>', getline(2)) + + if has('osx') + " A char with a modifier should not be a valid char for i_CTRL-V_digit. + call feedkeys("o\<C-V>\<D-j>\<C-V>\<D-1>\<C-V>\<D-o>\<C-V>\<D-x>\<C-V>\<D-u>", 'tnix') + call assert_equal('<D-j><D-1><D-o><D-x><D-u>', getline(3)) + endif + + bw! +endfunc + +func Test_edit_F1() + CheckFeature quickfix + + " Pressing <f1> + new + " call feedkeys(":set im\<cr>\<f1>\<c-l>", 'tnix') + call feedkeys("i\<f1>\<esc>", 'tnix') + set noinsertmode + call assert_equal('help', &buftype) + bw + bw +endfunc + +func Test_edit_F21() + " Pressing <f21> + " sends a netbeans command + if has("netbeans_intg") + new + " I have no idea what this is supposed to do :) + call feedkeys("A\<F21>\<F1>\<esc>", 'tnix') + bw + endif +endfunc + +func Test_edit_HOME_END() + " Test Home/End Keys + new + set foldopen+=hor + call setline(1, ['abc', 'def']) + call cursor(1, 1) + call feedkeys("AX\<Home>Y\<esc>", 'tnix') + call cursor(2, 1) + call feedkeys("iZ\<End>Y\<esc>", 'tnix') + call assert_equal(['YabcX', 'ZdefY'], getline(1, '$')) + + set foldopen-=hor + bw! +endfunc + +func Test_edit_INS() + " Test for Pressing <Insert> + new + call setline(1, ['abc', 'def']) + call cursor(1, 1) + call feedkeys("i\<Insert>ZYX>", 'tnix') + call assert_equal(['ZYX>', 'def'], getline(1, '$')) + call setline(1, ['abc', 'def']) + call cursor(1, 1) + call feedkeys("i\<Insert>Z\<Insert>YX>", 'tnix') + call assert_equal(['ZYX>bc', 'def'], getline(1, '$')) + bw! +endfunc + +func Test_edit_LEFT_RIGHT() + " Left, Shift-Left, Right, Shift-Right + new + call setline(1, ['abc def ghi', 'ABC DEF GHI', 'ZZZ YYY XXX']) + let _ww=&ww + set ww= + call cursor(2, 1) + call feedkeys("i\<left>\<esc>", 'tnix') + call assert_equal([0, 2, 1, 0], getpos('.')) + " Is this a bug, <s-left> does not respect whichwrap option + call feedkeys("i\<s-left>\<esc>", 'tnix') + call assert_equal([0, 1, 8, 0], getpos('.')) + call feedkeys("i". repeat("\<s-left>", 3). "\<esc>", 'tnix') + call assert_equal([0, 1, 1, 0], getpos('.')) + call feedkeys("i\<right>\<esc>", 'tnix') + call assert_equal([0, 1, 1, 0], getpos('.')) + call feedkeys("i\<right>\<right>\<esc>", 'tnix') + call assert_equal([0, 1, 2, 0], getpos('.')) + call feedkeys("A\<right>\<esc>", 'tnix') + call assert_equal([0, 1, 11, 0], getpos('.')) + call feedkeys("A\<s-right>\<esc>", 'tnix') + call assert_equal([0, 2, 1, 0], getpos('.')) + call feedkeys("i\<s-right>\<esc>", 'tnix') + call assert_equal([0, 2, 4, 0], getpos('.')) + call cursor(3, 11) + call feedkeys("A\<right>\<esc>", 'tnix') + call feedkeys("A\<s-right>\<esc>", 'tnix') + call assert_equal([0, 3, 11, 0], getpos('.')) + call cursor(2, 11) + " <S-Right> does not respect 'whichwrap' option + call feedkeys("A\<s-right>\<esc>", 'tnix') + call assert_equal([0, 3, 1, 0], getpos('.')) + " Check motion when 'whichwrap' contains cursor keys for insert mode + set ww+=[,] + call cursor(2, 1) + call feedkeys("i\<left>\<esc>", 'tnix') + call assert_equal([0, 1, 11, 0], getpos('.')) + call cursor(2, 11) + call feedkeys("A\<right>\<esc>", 'tnix') + call assert_equal([0, 3, 1, 0], getpos('.')) + call cursor(2, 11) + call feedkeys("A\<s-right>\<esc>", 'tnix') + call assert_equal([0, 3, 1, 0], getpos('.')) + let &ww = _ww + bw! +endfunc + +func Test_edit_MOUSE() + " This is a simple test, since we're not really using the mouse here + CheckFeature mouse + 10new + call setline(1, range(1, 100)) + call cursor(1, 1) + call assert_equal(1, line('w0')) + call assert_equal(10, line('w$')) + set mouse=a + " One scroll event moves three lines. + call feedkeys("A\<ScrollWheelDown>\<esc>", 'tnix') + call assert_equal(4, line('w0')) + call assert_equal(13, line('w$')) + " This should move by one page down. + call feedkeys("A\<S-ScrollWheelDown>\<esc>", 'tnix') + call assert_equal(14, line('w0')) + set nostartofline + " Another page down. + call feedkeys("A\<C-ScrollWheelDown>\<esc>", 'tnix') + call assert_equal(24, line('w0')) + + call assert_equal([0, 24, 2, 0], getpos('.')) + call Ntest_setmouse(4, 3) + call feedkeys("A\<LeftMouse>\<esc>", 'tnix') + call assert_equal([0, 27, 2, 0], getpos('.')) + set mousemodel=extend + call Ntest_setmouse(5, 3) + call feedkeys("A\<RightMouse>\<esc>\<esc>", 'tnix') + call assert_equal([0, 28, 2, 0], getpos('.')) + set mousemodel& + call cursor(1, 100) + norm! zt + " this should move by a screen up, but when the test + " is run, it moves up to the top of the buffer... + call feedkeys("A\<ScrollWheelUp>\<esc>", 'tnix') + call assert_equal([0, 1, 1, 0], getpos('.')) + call cursor(1, 30) + norm! zt + call feedkeys("A\<S-ScrollWheelUp>\<esc>", 'tnix') + call assert_equal([0, 1, 1, 0], getpos('.')) + call cursor(1, 30) + norm! zt + call feedkeys("A\<C-ScrollWheelUp>\<esc>", 'tnix') + call assert_equal([0, 1, 1, 0], getpos('.')) + %d + call setline(1, repeat(["12345678901234567890"], 100)) + call cursor(2, 1) + call feedkeys("A\<ScrollWheelRight>\<esc>", 'tnix') + call assert_equal([0, 2, 20, 0], getpos('.')) + call feedkeys("A\<ScrollWheelLeft>\<esc>", 'tnix') + call assert_equal([0, 2, 20, 0], getpos('.')) + call feedkeys("A\<S-ScrollWheelRight>\<esc>", 'tnix') + call assert_equal([0, 2, 20, 0], getpos('.')) + call feedkeys("A\<S-ScrollWheelLeft>\<esc>", 'tnix') + call assert_equal([0, 2, 20, 0], getpos('.')) + call feedkeys("A\<C-ScrollWheelRight>\<esc>", 'tnix') + call assert_equal([0, 2, 20, 0], getpos('.')) + call feedkeys("A\<C-ScrollWheelLeft>\<esc>", 'tnix') + call assert_equal([0, 2, 20, 0], getpos('.')) + set mouse& startofline + bw! +endfunc + +func Test_edit_PAGEUP_PAGEDOWN() + 10new + call setline(1, repeat(['abc def ghi'], 30)) + call cursor(1, 1) + call feedkeys("i\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 9, 1, 0], getpos('.')) + call feedkeys("i\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 17, 1, 0], getpos('.')) + call feedkeys("i\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 25, 1, 0], getpos('.')) + call feedkeys("i\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 30, 1, 0], getpos('.')) + call feedkeys("i\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 30, 1, 0], getpos('.')) + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 29, 1, 0], getpos('.')) + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 21, 1, 0], getpos('.')) + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 13, 1, 0], getpos('.')) + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 5, 1, 0], getpos('.')) + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 5, 11, 0], getpos('.')) + " <S-Up> is the same as <PageUp> + " <S-Down> is the same as <PageDown> + call cursor(1, 1) + call feedkeys("i\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 9, 1, 0], getpos('.')) + call feedkeys("i\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 17, 1, 0], getpos('.')) + call feedkeys("i\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 25, 1, 0], getpos('.')) + call feedkeys("i\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 30, 1, 0], getpos('.')) + call feedkeys("i\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 30, 1, 0], getpos('.')) + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 29, 1, 0], getpos('.')) + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 21, 1, 0], getpos('.')) + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 13, 1, 0], getpos('.')) + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 5, 1, 0], getpos('.')) + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 5, 11, 0], getpos('.')) + set nostartofline + call cursor(30, 11) + norm! zt + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 29, 11, 0], getpos('.')) + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 21, 11, 0], getpos('.')) + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 13, 11, 0], getpos('.')) + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 5, 11, 0], getpos('.')) + call feedkeys("A\<PageUp>\<esc>", 'tnix') + call assert_equal([0, 5, 11, 0], getpos('.')) + call cursor(1, 1) + call feedkeys("A\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 9, 11, 0], getpos('.')) + call feedkeys("A\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 17, 11, 0], getpos('.')) + call feedkeys("A\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 25, 11, 0], getpos('.')) + call feedkeys("A\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 30, 11, 0], getpos('.')) + call feedkeys("A\<PageDown>\<esc>", 'tnix') + call assert_equal([0, 30, 11, 0], getpos('.')) + " <S-Up> is the same as <PageUp> + " <S-Down> is the same as <PageDown> + call cursor(30, 11) + norm! zt + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 29, 11, 0], getpos('.')) + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 21, 11, 0], getpos('.')) + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 13, 11, 0], getpos('.')) + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 5, 11, 0], getpos('.')) + call feedkeys("A\<S-Up>\<esc>", 'tnix') + call assert_equal([0, 5, 11, 0], getpos('.')) + call cursor(1, 1) + call feedkeys("A\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 9, 11, 0], getpos('.')) + call feedkeys("A\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 17, 11, 0], getpos('.')) + call feedkeys("A\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 25, 11, 0], getpos('.')) + call feedkeys("A\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 30, 11, 0], getpos('.')) + call feedkeys("A\<S-Down>\<esc>", 'tnix') + call assert_equal([0, 30, 11, 0], getpos('.')) + bw! +endfunc + +func Test_edit_forbidden() + new + " 1) edit in the sandbox is not allowed + call setline(1, 'a') + com! Sandbox :sandbox call feedkeys("i\<del>\<esc>", 'tnix') + call assert_fails(':Sandbox', 'E48:') + com! Sandbox :sandbox exe "norm! i\<del>" + call assert_fails(':Sandbox', 'E48:') + delcom Sandbox + call assert_equal(['a'], getline(1,'$')) + + " 2) edit with textlock set + fu! DoIt() + call feedkeys("i\<del>\<esc>", 'tnix') + endfu + au InsertCharPre <buffer> :call DoIt() + try + call feedkeys("ix\<esc>", 'tnix') + call assert_fails(1, 'textlock') + catch /^Vim\%((\a\+)\)\=:E565/ " catch E565: not allowed here + endtry + " TODO: Might be a bug: should x really be inserted here + call assert_equal(['xa'], getline(1, '$')) + delfu DoIt + try + call feedkeys("ix\<esc>", 'tnix') + call assert_fails(1, 'unknown function') + catch /^Vim\%((\a\+)\)\=:E117/ " catch E117: unknown function + endtry + au! InsertCharPre + + " 3) edit when completion is shown + fun! Complete(findstart, base) + if a:findstart + return col('.') + else + call feedkeys("i\<del>\<esc>", 'tnix') + return [] + endif + endfun + set completefunc=Complete + try + call feedkeys("i\<c-x>\<c-u>\<esc>", 'tnix') + call assert_fails(1, 'change in complete function') + catch /^Vim\%((\a\+)\)\=:E565/ " catch E565 + endtry + delfu Complete + set completefunc= + + if has("rightleft") && exists("+fkmap") + " 4) 'R' when 'fkmap' and 'revins' is set. + set revins fkmap + try + normal Ri + call assert_fails(1, "R with 'fkmap' and 'ri' set") + catch + finally + set norevins nofkmap + endtry + endif + bw! +endfunc + +func Test_edit_rightleft() + " Cursor in rightleft mode moves differently + CheckFeature rightleft + call NewWindow(10, 20) + call setline(1, ['abc', 'def', 'ghi']) + call cursor(1, 2) + set rightleft + " Screen looks as expected + let lines = ScreenLines([1, 4], winwidth(0)) + let expect = [ + \" cba", + \" fed", + \" ihg", + \" ~"] + call assert_equal(join(expect, "\n"), join(lines, "\n")) + " 2) right moves to the left + call feedkeys("i\<right>\<esc>x", 'txin') + call assert_equal(['bc', 'def', 'ghi'], getline(1,'$')) + call cursor(1, 2) + call feedkeys("i\<s-right>\<esc>", 'txin') + call cursor(1, 2) + call feedkeys("i\<c-right>\<esc>", 'txin') + " Screen looks as expected + let lines = ScreenLines([1, 4], winwidth(0)) + let expect = [ + \" cb", + \" fed", + \" ihg", + \" ~"] + call assert_equal(join(expect, "\n"), join(lines, "\n")) + " 2) left moves to the right + call setline(1, ['abc', 'def', 'ghi']) + call cursor(1, 2) + call feedkeys("i\<left>\<esc>x", 'txin') + call assert_equal(['ac', 'def', 'ghi'], getline(1,'$')) + call cursor(1, 2) + call feedkeys("i\<s-left>\<esc>", 'txin') + call cursor(1, 2) + call feedkeys("i\<c-left>\<esc>", 'txin') + " Screen looks as expected + let lines = ScreenLines([1, 4], winwidth(0)) + let expect = [ + \" ca", + \" fed", + \" ihg", + \" ~"] + call assert_equal(join(expect, "\n"), join(lines, "\n")) + %d _ + " call test_override('redraw_flag', 1) + " call test_override('char_avail', 1) + call feedkeys("a\<C-V>x41", "xt") + redraw! + call assert_equal(repeat(' ', 19) .. 'A', Screenline(1)) + " call test_override('ALL', 0) + set norightleft + bw! +endfunc + +func Test_edit_complete_very_long_name() + " Long directory names only work on Unix. + CheckUnix + + let dirname = getcwd() . "/Xlongdir" + let longdirname = dirname . repeat('/' . repeat('d', 255), 4) + try + call mkdir(longdirname, 'p') + catch /E739:/ + " Long directory name probably not supported. + call delete(dirname, 'rf') + return + endtry + + " Try to get the Vim window position before setting 'columns', so that we can + " move the window back to where it was. + let winposx = getwinposx() + let winposy = getwinposy() + + if winposx >= 0 && winposy >= 0 && !has('gui_running') + " We did get the window position, but xterm may report the wrong numbers. + " Move the window to the reported position and compute any offset. + exe 'winpos ' . winposx . ' ' . winposy + sleep 100m + let x = getwinposx() + if x >= 0 + let winposx += winposx - x + endif + let y = getwinposy() + if y >= 0 + let winposy += winposy - y + endif + endif + + let save_columns = &columns + " Need at least about 1100 columns to reproduce the problem. + set columns=2000 + set noswapfile + + let longfilename = longdirname . '/' . repeat('a', 255) + call writefile(['Totum', 'Table'], longfilename) + new + exe "next Xnofile " . longfilename + exe "normal iT\<C-N>" + + bwipe! + exe 'bwipe! ' . longfilename + call delete(dirname, 'rf') + let &columns = save_columns + if winposx >= 0 && winposy >= 0 + exe 'winpos ' . winposx . ' ' . winposy + endif + set swapfile& +endfunc + +func Test_edit_backtick() + next a\`b c + call assert_equal('a`b', expand('%')) + next + call assert_equal('c', expand('%')) + call assert_equal('a\`b c', expand('##')) +endfunc + +func Test_edit_quit() + edit foo.txt + split + new + call setline(1, 'hello') + 3wincmd w + redraw! + call assert_fails('1q', 'E37:') + bwipe! foo.txt + only +endfunc + +func Test_edit_alt() + " Keeping the cursor line didn't happen when the first line has indent. + new + call setline(1, [' one', 'two', 'three']) + w XAltFile + $ + call assert_equal(3, line('.')) + e Xother + e # + call assert_equal(3, line('.')) + + bwipe XAltFile + call delete('XAltFile') +endfunc + +func Test_edit_InsertLeave() + new + au InsertLeavePre * let g:did_au_pre = 1 + au InsertLeave * let g:did_au = 1 + let g:did_au_pre = 0 + let g:did_au = 0 + call feedkeys("afoo\<Esc>", 'tx') + call assert_equal(1, g:did_au_pre) + call assert_equal(1, g:did_au) + call assert_equal('foo', getline(1)) + + let g:did_au_pre = 0 + let g:did_au = 0 + call feedkeys("Sbar\<C-C>", 'tx') + call assert_equal(1, g:did_au_pre) + call assert_equal(0, g:did_au) + call assert_equal('bar', getline(1)) + + inoremap x xx<Esc> + let g:did_au_pre = 0 + let g:did_au = 0 + call feedkeys("Saax", 'tx') + call assert_equal(1, g:did_au_pre) + call assert_equal(1, g:did_au) + call assert_equal('aaxx', getline(1)) + + inoremap x xx<C-C> + let g:did_au_pre = 0 + let g:did_au = 0 + call feedkeys("Sbbx", 'tx') + call assert_equal(1, g:did_au_pre) + call assert_equal(0, g:did_au) + call assert_equal('bbxx', getline(1)) + + bwipe! + au! InsertLeave InsertLeavePre + iunmap x +endfunc + +func Test_edit_InsertLeave_undo() + new XtestUndo + set undofile + au InsertLeave * wall + exe "normal ofoo\<Esc>" + call assert_equal(2, line('$')) + normal u + call assert_equal(1, line('$')) + + bwipe! + au! InsertLeave + call delete('XtestUndo') + call delete(undofile('XtestUndo')) + set undofile& +endfunc + +" Test for inserting characters using CTRL-V followed by a number. +func Test_edit_special_chars() + new + + let t = "o\<C-V>65\<C-V>x42\<C-V>o103 \<C-V>33a\<C-V>xfg\<C-V>o78\<Esc>" + + exe "normal " . t + call assert_equal("ABC !a\<C-O>g\<C-G>8", getline(2)) + + close! +endfunc + +func Test_edit_startinsert() + new + set backspace+=start + call setline(1, 'foobar') + call feedkeys("A\<C-U>\<Esc>", 'xt') + call assert_equal('', getline(1)) + + call setline(1, 'foobar') + call feedkeys(":startinsert!\<CR>\<C-U>\<Esc>", 'xt') + call assert_equal('', getline(1)) + + set backspace& + bwipe! +endfunc + +" Test for :startreplace and :startgreplace +func Test_edit_startreplace() + new + call setline(1, 'abc') + call feedkeys("l:startreplace\<CR>xyz\e", 'xt') + call assert_equal('axyz', getline(1)) + call feedkeys("0:startreplace!\<CR>abc\e", 'xt') + call assert_equal('axyzabc', getline(1)) + call setline(1, "a\tb") + call feedkeys("0l:startgreplace\<CR>xyz\e", 'xt') + call assert_equal("axyz\tb", getline(1)) + call feedkeys("0i\<C-R>=execute('startreplace')\<CR>12\e", 'xt') + call assert_equal("12axyz\tb", getline(1)) + close! +endfunc + +func Test_edit_noesckeys() + CheckNotGui + new + + " <Left> moves cursor when 'esckeys' is set + exe "set t_kl=\<Esc>OD" + " set esckeys + call feedkeys("axyz\<Esc>ODX", "xt") + " call assert_equal("xyXz", getline(1)) + + " <Left> exits Insert mode when 'esckeys' is off + " set noesckeys + call setline(1, '') + call feedkeys("axyz\<Esc>ODX", "xt") + call assert_equal(["DX", "xyz"], getline(1, 2)) + + bwipe! + " set esckeys +endfunc + +" Test for running an invalid ex command in insert mode using CTRL-O +func Test_edit_ctrl_o_invalid_cmd() + new + set showmode showcmd + " Avoid a sleep of 3 seconds. Zero might have side effects. + " call test_override('ui_delay', 50) + let caught_e492 = 0 + try + call feedkeys("i\<C-O>:invalid\<CR>abc\<Esc>", "xt") + catch /E492:/ + let caught_e492 = 1 + endtry + call assert_equal(1, caught_e492) + call assert_equal('abc', getline(1)) + set showmode& showcmd& + " call test_override('ui_delay', 0) + close! +endfunc + +" Test for editing a file with a very long name +func Test_edit_illegal_filename() + CheckEnglish + new + redir => msg + exe 'edit ' . repeat('f', 5000) + redir END + call assert_match("Illegal file name$", split(msg, "\n")[0]) + close! +endfunc + +" Test for editing a directory +func Test_edit_is_a_directory() + CheckEnglish + let dirname = getcwd() . "/Xeditdir" + call mkdir(dirname, 'p') + + new + redir => msg + exe 'edit' dirname + redir END + call assert_match("is a directory$", split(msg, "\n")[0]) + bwipe! + + let dirname .= '/' + + new + redir => msg + exe 'edit' dirname + redir END + call assert_match("is a directory$", split(msg, "\n")[0]) + bwipe! + + call delete(dirname, 'rf') +endfunc + +" Test for editing a file using invalid file encoding +func Test_edit_invalid_encoding() + CheckEnglish + call writefile([], 'Xinvfile') + redir => msg + new ++enc=axbyc Xinvfile + redir END + call assert_match('\[NOT converted\]', msg) + call delete('Xinvfile') + close! +endfunc + +" Test for the "charconvert" option +func Test_edit_charconvert() + CheckEnglish + call writefile(['one', 'two'], 'Xccfile') + + " set 'charconvert' to a non-existing function + set charconvert=NonExitingFunc() + new + let caught_e117 = v:false + try + redir => msg + edit ++enc=axbyc Xccfile + catch /E117:/ + let caught_e117 = v:true + finally + redir END + endtry + call assert_true(caught_e117) + call assert_equal(['one', 'two'], getline(1, '$')) + call assert_match("Conversion with 'charconvert' failed", msg) + close! + set charconvert& + + " 'charconvert' function doesn't create an output file + func Cconv1() + endfunc + set charconvert=Cconv1() + new + redir => msg + edit ++enc=axbyc Xccfile + redir END + call assert_equal(['one', 'two'], getline(1, '$')) + call assert_match("can't read output of 'charconvert'", msg) + close! + delfunc Cconv1 + set charconvert& + + " 'charconvert' function to convert to upper case + func Cconv2() + let data = readfile(v:fname_in) + call map(data, 'toupper(v:val)') + call writefile(data, v:fname_out) + endfunc + set charconvert=Cconv2() + new Xccfile + write ++enc=ucase Xccfile1 + call assert_equal(['ONE', 'TWO'], readfile('Xccfile1')) + call delete('Xccfile1') + close! + delfunc Cconv2 + set charconvert& + + " 'charconvert' function removes the input file + func Cconv3() + call delete(v:fname_in) + endfunc + set charconvert=Cconv3() + new + call assert_fails('edit ++enc=lcase Xccfile', 'E202:') + call assert_equal([''], getline(1, '$')) + close! + delfunc Cconv3 + set charconvert& + + call delete('Xccfile') +endfunc + +" Test for editing a file without read permission +func Test_edit_file_no_read_perm() + CheckUnix + CheckNotRoot + + call writefile(['one', 'two'], 'Xnrpfile') + call setfperm('Xnrpfile', '-w-------') + new + redir => msg + edit Xnrpfile + redir END + call assert_equal(1, &readonly) + call assert_equal([''], getline(1, '$')) + call assert_match('\[Permission Denied\]', msg) + close! + call delete('Xnrpfile') +endfunc + +" Using :edit without leaving 'insertmode' should not cause Insert mode to be +" re-entered immediately after <C-L> +func Test_edit_insertmode_ex_edit() + CheckRunVimInTerminal + + let lines =<< trim END + set insertmode noruler + inoremap <C-B> <Cmd>edit Xfoo<CR> + END + call writefile(lines, 'Xtest_edit_insertmode_ex_edit') + + let buf = RunVimInTerminal('-S Xtest_edit_insertmode_ex_edit', #{rows: 6}) + " Somehow this can be very slow with valgrind. A separate TermWait() works + " better than a longer time with WaitForAssert() (why?) + call TermWait(buf, 1000) + call WaitForAssert({-> assert_match('^-- INSERT --\s*$', term_getline(buf, 6))}) + call term_sendkeys(buf, "\<C-B>\<C-L>") + call WaitForAssert({-> assert_notmatch('^-- INSERT --\s*$', term_getline(buf, 6))}) + + " clean up + call StopVimInTerminal(buf) + call delete('Xtest_edit_insertmode_ex_edit') +endfunc + +" Pressing escape in 'insertmode' should beep +" FIXME: Execute this later, when using valgrind it makes the next test +" Test_edit_insertmode_ex_edit() fail. +func Test_z_edit_insertmode_esc_beeps() + new + " set insertmode + " call assert_beeps("call feedkeys(\"one\<Esc>\", 'xt')") + set insertmode& + " unsupported "CTRL-G l" command should beep in insert mode. + call assert_beeps("normal i\<C-G>l") + bwipe! +endfunc + +" Test for 'hkmap' and 'hkmapp' +func Test_edit_hkmap() + throw "Skipped: Nvim does not support 'hkmap'" + CheckFeature rightleft + if has('win32') && !has('gui') + " Test fails on the MS-Windows terminal version + return + endif + new + + set revins hkmap + let str = 'abcdefghijklmnopqrstuvwxyz' + let str ..= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + let str ..= '`/'',.;' + call feedkeys('i' .. str, 'xt') + let expected = "óõú,.;" + let expected ..= "ZYXWVUTSRQPONMLKJIHGFEDCBA" + let expected ..= "æèñ'äåàãø/ôíîöêìçïéòë÷âáðù" + call assert_equal(expected, getline(1)) + + %d + set revins hkmap hkmapp + let str = 'abcdefghijklmnopqrstuvwxyz' + let str ..= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + call feedkeys('i' .. str, 'xt') + let expected = "õYXWVUTSRQóOïíLKJIHGFEDêBA" + let expected ..= "öòXùåèúæø'ôñðîì÷çéäâóǟãëáà" + call assert_equal(expected, getline(1)) + + set revins& hkmap& hkmapp& + close! +endfunc + +" Test for 'allowrevins' and using CTRL-_ in insert mode +func Test_edit_allowrevins() + CheckFeature rightleft + new + set allowrevins + call feedkeys("iABC\<C-_>DEF\<C-_>GHI", 'xt') + call assert_equal('ABCFEDGHI', getline(1)) + set allowrevins& + close! +endfunc + +" Test for inserting a register in insert mode using CTRL-R +func Test_edit_insert_reg() + throw 'Skipped: use test/functional/legacy/edit_spec.lua' + new + let g:Line = '' + func SaveFirstLine() + let g:Line = Screenline(1) + return 'r' + endfunc + inoremap <expr> <buffer> <F2> SaveFirstLine() + call test_override('redraw_flag', 1) + call test_override('char_avail', 1) + let @r = 'sample' + call feedkeys("a\<C-R>=SaveFirstLine()\<CR>", "xt") + call assert_equal('"', g:Line) + call test_override('ALL', 0) + close! +endfunc + +" Test for positioning cursor after CTRL-R expression failed +func Test_edit_ctrl_r_failed() + CheckRunVimInTerminal + + let buf = RunVimInTerminal('', #{rows: 6, cols: 60}) + + " trying to insert a dictionary produces an error + call term_sendkeys(buf, "i\<C-R>={}\<CR>") + + " ending Insert mode should put the cursor back on the ':' + call term_sendkeys(buf, ":\<Esc>") + call VerifyScreenDump(buf, 'Test_edit_ctlr_r_failed_1', {}) + + call StopVimInTerminal(buf) +endfunc + +" When a character is inserted at the last position of the last line in a +" window, the window contents should be scrolled one line up. If the top line +" is part of a fold, then the entire fold should be scrolled up. +func Test_edit_lastline_scroll() + new + let h = winheight(0) + let lines = ['one', 'two', 'three'] + let lines += repeat(['vim'], h - 4) + call setline(1, lines) + call setline(h, repeat('x', winwidth(0) - 1)) + call feedkeys("GAx", 'xt') + redraw! + call assert_equal(h - 1, winline()) + call assert_equal(2, line('w0')) + + " scroll with a fold + 1,2fold + normal gg + call setline(h + 1, repeat('x', winwidth(0) - 1)) + call feedkeys("GAx", 'xt') + redraw! + call assert_equal(h - 1, winline()) + call assert_equal(3, line('w0')) + + close! +endfunc + +func Test_edit_browse() + " in the GUI this opens a file picker, we only test the terminal behavior + CheckNotGui + + " ":browse xxx" checks for the FileExplorer augroup and assumes editing "." + " works then. + augroup FileExplorer + au! + augroup END + + " When the USE_FNAME_CASE is defined this used to cause a crash. + browse enew + bwipe! + + browse split + bwipe! +endfunc + +func Test_read_invalid() + " set encoding=latin1 + " This was not properly checking for going past the end. + call assert_fails('r`=', 'E484') + set encoding=utf-8 +endfunc + +" Test for the 'revins' option +func Test_edit_revins() + CheckFeature rightleft + new + set revins + exe "normal! ione\ttwo three" + call assert_equal("eerht owt\teno", getline(1)) + call setline(1, "one\ttwo three") + normal! gg$bi a + call assert_equal("one\ttwo a three", getline(1)) + exe "normal! $bi\<BS>\<BS>" + call assert_equal("one\ttwo a ree", getline(1)) + exe "normal! 0wi\<C-W>" + call assert_equal("one\t a ree", getline(1)) + exe "normal! 0wi\<C-U>" + call assert_equal("one\t ", getline(1)) + " newline in insert mode starts at the end of the line + call setline(1, 'one two three') + exe "normal! wi\nfour" + call assert_equal(['one two three', 'ruof'], getline(1, '$')) + set revins& + bw! +endfunc + +" Test for getting the character of the line below after "p" +func Test_edit_put_CTRL_E() + " set encoding=latin1 + new + let @" = '' + sil! norm orggRx + sil! norm pr + call assert_equal(['r', 'r'], getline(1, 2)) + bwipe! + set encoding=utf-8 +endfunc + +" Test toggling of input method. See :help i_CTRL-^ +func Test_edit_CTRL_hat() + CheckFeature xim + + " FIXME: test fails with Motif GUI. + " test also fails when running in the GUI. + CheckFeature gui_gtk + CheckNotGui + + new + + call assert_equal(0, &iminsert) + call feedkeys("i\<C-^>", 'xt') + call assert_equal(2, &iminsert) + call feedkeys("i\<C-^>", 'xt') + call assert_equal(0, &iminsert) + + bwipe! +endfunc + +" Weird long file name was going over the end of NameBuff +func Test_edit_overlong_file_name() + CheckUnix + + file 0000000000000000000000000000 + file %%%%%%%%%%%%%%%%%%%%%%%%%% + file %%%%%% + set readonly + set ls=2 + + redraw! + set noreadonly ls& + bwipe! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_environ.vim b/test/old/testdir/test_environ.vim new file mode 100644 index 0000000000..b5dbdce104 --- /dev/null +++ b/test/old/testdir/test_environ.vim @@ -0,0 +1,89 @@ +" 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 diff --git a/test/old/testdir/test_erasebackword.vim b/test/old/testdir/test_erasebackword.vim new file mode 100644 index 0000000000..9522ec2cd6 --- /dev/null +++ b/test/old/testdir/test_erasebackword.vim @@ -0,0 +1,19 @@ + +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 diff --git a/test/old/testdir/test_escaped_glob.vim b/test/old/testdir/test_escaped_glob.vim new file mode 100644 index 0000000000..9f53c76a2c --- /dev/null +++ b/test/old/testdir/test_escaped_glob.vim @@ -0,0 +1,34 @@ +" 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 diff --git a/test/old/testdir/test_eval_stuff.vim b/test/old/testdir/test_eval_stuff.vim new file mode 100644 index 0000000000..b1c1136809 --- /dev/null +++ b/test/old/testdir/test_eval_stuff.vim @@ -0,0 +1,488 @@ +" 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') + call assert_equal(0, mkdir(v:_null_string)) + call assert_fails('call mkdir([])', 'E730:') + call assert_fails('call mkdir("abc", [], [])', 'E745:') +endfunc + +func DoMkdirDel(name) + call mkdir(a:name, 'pD') + call assert_true(isdirectory(a:name)) +endfunc + +func DoMkdirDelAddFile(name) + call mkdir(a:name, 'pD') + call assert_true(isdirectory(a:name)) + call writefile(['text'], a:name .. '/file') +endfunc + +func DoMkdirDelRec(name) + call mkdir(a:name, 'pR') + call assert_true(isdirectory(a:name)) +endfunc + +func DoMkdirDelRecAddFile(name) + call mkdir(a:name, 'pR') + call assert_true(isdirectory(a:name)) + call writefile(['text'], a:name .. '/file') +endfunc + +func Test_mkdir_defer_del() + " Xtopdir/tmp is created thus deleted, not Xtopdir itself + call mkdir('Xtopdir', 'R') + call DoMkdirDel('Xtopdir/tmp') + call assert_true(isdirectory('Xtopdir')) + call assert_false(isdirectory('Xtopdir/tmp')) + + " Deletion fails because "tmp" contains "sub" + call DoMkdirDel('Xtopdir/tmp/sub') + call assert_true(isdirectory('Xtopdir')) + call assert_true(isdirectory('Xtopdir/tmp')) + call delete('Xtopdir/tmp', 'rf') + + " Deletion fails because "tmp" contains "file" + call DoMkdirDelAddFile('Xtopdir/tmp') + call assert_true(isdirectory('Xtopdir')) + call assert_true(isdirectory('Xtopdir/tmp')) + call assert_true(filereadable('Xtopdir/tmp/file')) + call delete('Xtopdir/tmp', 'rf') + + " Xtopdir/tmp is created thus deleted, not Xtopdir itself + call DoMkdirDelRec('Xtopdir/tmp') + call assert_true(isdirectory('Xtopdir')) + call assert_false(isdirectory('Xtopdir/tmp')) + + " Deletion works even though "tmp" contains "sub" + call DoMkdirDelRec('Xtopdir/tmp/sub') + call assert_true(isdirectory('Xtopdir')) + call assert_false(isdirectory('Xtopdir/tmp')) + + " Deletion works even though "tmp" contains "file" + call DoMkdirDelRecAddFile('Xtopdir/tmp') + call assert_true(isdirectory('Xtopdir')) + call assert_false(isdirectory('Xtopdir/tmp')) +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_with_modifier() + " this checks has_loop_cmd() works with a modifier + let result = [] + horizontal for i in range(3) + call extend(result, [i]) + endfor + call assert_equal([0, 1, 2], result) +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) + + if has('float') + let a = 'A' + let b = 1.234 + call assert_equal('A1.234', a .. b) + endif +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_execute_cmd_with_null() + call assert_fails('execute v:_null_list', 'E730:') + call assert_fails('execute v:_null_dict', 'E731:') + call assert_fails('execute v:_null_blob', 'E976:') + execute v:_null_string + " Nvim doesn't have null partials + " call assert_fails('execute test_null_partial()', 'E729:') + " Nvim doesn't have test_unknown() + " call assert_fails('execute test_unknown()', 'E908:') + if has('job') + call assert_fails('execute test_null_job()', 'E908:') + call assert_fails('execute test_null_channel()', 'E908:') + endif +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 + +func Test_eval_string_in_special_key() + " this was using the '{' inside <> as the start of an interpolated string + silent! echo 0{1-$"\<S--{>n|nö% +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_ex_equal.vim b/test/old/testdir/test_ex_equal.vim new file mode 100644 index 0000000000..32e23704eb --- /dev/null +++ b/test/old/testdir/test_ex_equal.vim @@ -0,0 +1,41 @@ +" 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("\n1", a) + + call assert_fails('3=', 'E16:') + bwipe! +endfunc + +func Test_ex_equal_arg() + throw 'skipped: Nvim evaluates lua with := [arg]' + + new + call setline(1, ["foo\tbar", "bar\tfoo"]) + + 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) + + call assert_fails('=x', 'E488:') + + bwipe! +endfunc diff --git a/test/old/testdir/test_ex_mode.vim b/test/old/testdir/test_ex_mode.vim new file mode 100644 index 0000000000..42f08868a0 --- /dev/null +++ b/test/old/testdir/test_ex_mode.vim @@ -0,0 +1,285 @@ +" 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 + +func Test_open_command_flush_line() + throw 'Skipped: Nvim does not have :open' + " this was accessing freed memory: the regexp match uses a pointer to the + " current line which becomes invalid when searching for the ') mark. + new + call setline(1, ['one', 'two. three']) + s/one/ONE + try + open /\%')/ + catch /E479/ + endtry + bwipe! +endfunc + +" FIXME: this doesn't fail without the fix but hangs +func Skip_Test_open_command_state() + " Tricky script that failed because State was not set properly + let lines =<< trim END + !ls + 0scìi + so! Xsourced + set t_û0=0 + v/-/o + END + call writefile(lines, 'XopenScript', '') + + let sourced = ["!f\u0083\x02\<Esc>z=0"] + call writefile(sourced, 'Xsourced', 'b') + + CheckRunVimInTerminal + let buf = RunVimInTerminal('-u NONE -i NONE -n -m -X -Z -e -s -S XopenScript -c qa!', #{rows: 6, wait_for_ruler: 0, no_clean: 1}) + sleep 3 + + call StopVimInTerminal(buf) +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 + + au CmdlineEnter * : + call feedkeys("gQecho 1\r", 'xt') + + au! CmdlineEnter + + 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 diff --git a/test/old/testdir/test_ex_undo.vim b/test/old/testdir/test_ex_undo.vim new file mode 100644 index 0000000000..44feb3680a --- /dev/null +++ b/test/old/testdir/test_ex_undo.vim @@ -0,0 +1,19 @@ +" 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 diff --git a/test/old/testdir/test_ex_z.vim b/test/old/testdir/test_ex_z.vim new file mode 100644 index 0000000000..665bcc1d76 --- /dev/null +++ b/test/old/testdir/test_ex_z.vim @@ -0,0 +1,115 @@ +" 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_overflow() + " This used to access invalid memory as a result of an integer overflow + " and freeze vim. + normal ox + normal Heat + z777777776666666 + ') +endfunc + +func Test_z_negative_lnum() + new + z^ + call assert_equal(1, line('.')) + bwipe! +endfunc diff --git a/test/old/testdir/test_excmd.vim b/test/old/testdir/test_excmd.vim new file mode 100644 index 0000000000..c729ff4929 --- /dev/null +++ b/test/old/testdir/test_excmd.vim @@ -0,0 +1,753 @@ +" 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() + 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 + +" catch address lines overflow +func Test_ex_address_range_overflow() + call assert_fails(':--+foobar', 'E492:') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_exec_while_if.vim b/test/old/testdir/test_exec_while_if.vim new file mode 100644 index 0000000000..3f13b09945 --- /dev/null +++ b/test/old/testdir/test_exec_while_if.vim @@ -0,0 +1,43 @@ +" 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 diff --git a/test/old/testdir/test_execute_func.vim b/test/old/testdir/test_execute_func.vim new file mode 100644 index 0000000000..2edae39b8f --- /dev/null +++ b/test/old/testdir/test_execute_func.vim @@ -0,0 +1,193 @@ +" test execute() + +source view_util.vim +source check.vim +source vim9.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:') +" 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!')) + if has('float') + call assert_fails('call execute(3.4)', 'E492:') + call assert_equal("\nx", execute("echo \"x\"", 3.4)) + call CheckDefExecAndScriptFailure(['execute("echo \"x\"", 3.4)'], 'E806:') + endif +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([])) +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() + CheckFeature quickfix + + 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 + +func Test_execute_cmd_with_null() + call assert_equal("", execute(v:_null_string)) + call assert_equal("", execute(v:_null_list)) + call assert_fails('call execute(v:_null_dict)', 'E731:') + call assert_fails('call execute(v:_null_blob)', 'E976:') + " Nvim doesn't have null partials + " call assert_fails('call execute(test_null_partial())','E729:') + if has('job') + call assert_fails('call execute(test_null_job())', 'E908:') + call assert_fails('call execute(test_null_channel())', 'E908:') + endif +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_exists.vim b/test/old/testdir/test_exists.vim new file mode 100644 index 0000000000..62c66192ef --- /dev/null +++ b/test/old/testdir/test_exists.vim @@ -0,0 +1,331 @@ +" 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 diff --git a/test/old/testdir/test_exists_autocmd.vim b/test/old/testdir/test_exists_autocmd.vim new file mode 100644 index 0000000000..7e44a72653 --- /dev/null +++ b/test/old/testdir/test_exists_autocmd.vim @@ -0,0 +1,26 @@ +" 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 diff --git a/test/old/testdir/test_exit.vim b/test/old/testdir/test_exit.vim new file mode 100644 index 0000000000..93e55ce575 --- /dev/null +++ b/test/old/testdir/test_exit.vim @@ -0,0 +1,147 @@ +" 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') + + " ExitPre autocommand also executed on :wqall + let after =<< trim [CODE] + au QuitPre * call writefile(["QuitPre"], "Xtestout", "a") + au ExitPre * call writefile(["ExitPre"], "Xtestout", "a") + wqall + [CODE] + + if RunVim([], after, '') + call assert_equal(['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 diff --git a/test/old/testdir/test_expand.vim b/test/old/testdir/test_expand.vim new file mode 100644 index 0000000000..cd537f4ea1 --- /dev/null +++ b/test/old/testdir/test_expand.vim @@ -0,0 +1,229 @@ +" 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 diff --git a/test/old/testdir/test_expand_func.vim b/test/old/testdir/test_expand_func.vim new file mode 100644 index 0000000000..454d76f0aa --- /dev/null +++ b/test/old/testdir/test_expand_func.vim @@ -0,0 +1,146 @@ +" 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 diff --git a/test/old/testdir/test_expr.vim b/test/old/testdir/test_expr.vim new file mode 100644 index 0000000000..d316e63818 --- /dev/null +++ b/test/old/testdir/test_expr.vim @@ -0,0 +1,929 @@ +" Tests for expressions. + +source check.vim +source vim9.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') + " Nvim doesn't have null functions + " call assert_equal(0, test_null_function() == function('min')) + " call assert_equal(1, test_null_function() == test_null_function()) + " Nvim doesn't have test_unknown() + " call assert_fails('eval 10 == test_unknown()', 'E685:') +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_op_ternary() + let lines =<< trim END + call assert_equal('yes', 1 ? 'yes' : 'no') + call assert_equal('no', 0 ? 'yes' : 'no') + + call assert_fails('echo [1] ? "yes" : "no"', 'E745:') + call assert_fails('echo {} ? "yes" : "no"', 'E728:') + END + call CheckLegacyAndVim9Success(lines) + + call assert_equal('no', 'x' ? 'yes' : 'no') + call CheckDefAndScriptFailure(["'x' ? 'yes' : 'no'"], 'E1135:') + call assert_equal('yes', '1x' ? 'yes' : 'no') + call CheckDefAndScriptFailure(["'1x' ? 'yes' : 'no'"], 'E1135:') +endfunc + +func Test_op_falsy() + let lines =<< trim END + call assert_equal(v:true, v:true ?? 456) + call assert_equal(123, 123 ?? 456) + call assert_equal('yes', 'yes' ?? 456) + call assert_equal(0z00, 0z00 ?? 456) + call assert_equal([1], [1] ?? 456) + call assert_equal({'one': 1}, {'one': 1} ?? 456) + call assert_equal(0.1, 0.1 ?? 456) + + call assert_equal(456, v:false ?? 456) + call assert_equal(456, 0 ?? 456) + call assert_equal(456, '' ?? 456) + call assert_equal(456, 0z ?? 456) + call assert_equal(456, [] ?? 456) + call assert_equal(456, {} ?? 456) + call assert_equal(456, 0.0 ?? 456) + + call assert_equal(456, v:null ?? 456) + #" call assert_equal(456, v:none ?? 456) + call assert_equal(456, v:_null_string ?? 456) + call assert_equal(456, v:_null_blob ?? 456) + call assert_equal(456, v:_null_list ?? 456) + call assert_equal(456, v:_null_dict ?? 456) + #" Nvim doesn't have null functions + #" call assert_equal(456, test_null_function() ?? 456) + #" Nvim doesn't have null partials + #" call assert_equal(456, test_null_partial() ?? 456) + if has('job') + call assert_equal(456, test_null_job() ?? 456) + endif + if has('channel') + call assert_equal(456, test_null_channel() ?? 456) + endif + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_dict() + let lines =<< trim END + VAR 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')) + + 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' ]) + END + call CheckLegacyAndVim9Success(lines) + + call CheckLegacyAndVim9Failure(["VAR i = has_key([], 'a')"], ['E1206:', 'E1013:', 'E1206:']) +endfunc + +func Test_strgetchar() + let lines =<< trim END + 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)) + END + call CheckLegacyAndVim9Success(lines) + + call CheckLegacyAndVim9Failure(["VAR c = strgetchar([], 1)"], ['E730:', 'E1013:', 'E1174:']) + call CheckLegacyAndVim9Failure(["VAR c = strgetchar('axb', [])"], ['E745:', 'E1013:', 'E1210:']) +endfunc + +func Test_strcharpart() + let lines =<< trim END + 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]) + END + call CheckLegacyAndVim9Success(lines) + + call assert_fails('call strcharpart("", 0, 0, {})', ['E728:', 'E728:']) + call assert_fails('call strcharpart("", 0, 0, -1)', ['E1023:', 'E1023:']) +endfunc + +func Test_getreg_empty_list() + let lines =<< trim END + call assert_equal('', getreg('x')) + call assert_equal([], getreg('x', 1, 1)) + VAR x = getreg('x', 1, 1) + VAR y = x + call add(x, 'foo') + call assert_equal(['foo'], y) + END + call CheckLegacyAndVim9Success(lines) + + call CheckLegacyAndVim9Failure(['call getreg([])'], ['E730:', 'E1013:', 'E1174:']) +endfunc + +func Test_loop_over_null_list() + let lines =<< trim END + VAR null_list = v:_null_list + for i in null_list + call assert_report('should not get here') + endfor + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_setreg_null_list() + let lines =<< trim END + call setreg('x', v:_null_list) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_special_char() + " The failure is only visible using valgrind. + call CheckLegacyAndVim9Failure(['echo "\<C-">'], ['E15:', 'E1004:', 'E1004:']) +endfunc + +func Test_method_with_prefix() + let lines =<< trim END + call assert_equal(TRUE, !range(5)->empty()) + call assert_equal(FALSE, !-3) + END + call CheckLegacyAndVim9Success(lines) + + call assert_equal([0, 1, 2], --3->range()) + call CheckDefAndScriptFailure(['eval --3->range()'], 'E15') + + call assert_equal(1, !+-+0) + call CheckDefAndScriptFailure(['eval !+-+0'], 'E15') +endfunc + +func Test_option_value() + let lines =<< trim END + #" boolean + set bri + call assert_equal(TRUE, &bri) + set nobri + call assert_equal(FALSE, &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 + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_printf_misc() + let lines =<< trim END + call assert_equal('123', printf('123')) + + call assert_equal('', printf('%')) + call assert_equal('', printf('%.0d', 0)) + 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)) + call assert_notequal('', printf('%p', "abc")) + END + call CheckLegacyAndVim9Success(lines) + + call CheckLegacyAndVim9Failure(["call printf('123', 3)"], "E767:") + + " this was using uninitialized memory + call CheckLegacyAndVim9Failure(["eval ''->printf()"], "E119:") +endfunc + +func Test_printf_float() + if has('float') + let lines =<< trim END + 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)) + END + call CheckLegacyAndVim9Success(lines) + + call CheckLegacyAndVim9Failure(['echo printf("%f", "a")'], 'E807:') + endif +endfunc + +func Test_printf_errors() + call CheckLegacyAndVim9Failure(['echo printf("%d", {})'], 'E728:') + call CheckLegacyAndVim9Failure(['echo printf("%d", [])'], 'E745:') + call CheckLegacyAndVim9Failure(['echo printf("%d", 1, 2)'], 'E767:') + call CheckLegacyAndVim9Failure(['echo printf("%*d", 1)'], 'E766:') + call CheckLegacyAndVim9Failure(['echo printf("%s")'], 'E766:') + if has('float') + call CheckLegacyAndVim9Failure(['echo printf("%d", 1.2)'], 'E805:') + call CheckLegacyAndVim9Failure(['echo printf("%f")'], 'E766:') + endif +endfunc + +func Test_printf_64bit() + let lines =<< trim END + call assert_equal("123456789012345", printf('%d', 123456789012345)) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_printf_spec_s() + let lines =<< trim END + #" number + call assert_equal("1234567890", printf('%s', 1234567890)) + + #" string + call assert_equal("abcdefgi", printf('%s', "abcdefgi")) + + #" float + if has('float') + call assert_equal("1.23", printf('%s', 1.23)) + endif + + #" list + VAR lvalue = [1, 'two', ['three', 4]] + call assert_equal(string(lvalue), printf('%s', lvalue)) + + #" dict + VAR dvalue = {'key1': 'value1', 'key2': ['list', 'lvalue'], 'key3': {'dict': 'lvalue'}} + call assert_equal(string(dvalue), printf('%s', dvalue)) + + #" funcref + call assert_equal('printf', printf('%s', 'printf'->function())) + + #" partial + call assert_equal(string(function('printf', ['%s'])), printf('%s', function('printf', ['%s']))) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_printf_spec_b() + let lines =<< trim END + 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)) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_max_min_errors() + call CheckLegacyAndVim9Failure(['call max(v:true)'], ['E712:', 'E1013:', 'E1227:']) + call CheckLegacyAndVim9Failure(['call max(v:true)'], ['max()', 'E1013:', 'E1227:']) + call CheckLegacyAndVim9Failure(['call min(v:true)'], ['E712:', 'E1013:', 'E1227:']) + call CheckLegacyAndVim9Failure(['call min(v:true)'], ['min()', 'E1013:', 'E1227:']) +endfunc + +func Test_function_with_funcref() + let lines =<< trim END + 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 s:Len = {s -> strlen(s)} + call assert_equal(6, s:Len('foobar')) + let name = string(s:Len) + " can evaluate "function('<lambda>99')" + call execute('let Ref = ' .. name) + call assert_equal(4, Ref('text')) + END + call CheckScriptSuccess(lines) + + let lines =<< trim END + vim9script + var F = function('type') + var Fref = function(F) + call assert_equal(v:t_string, Fref('x')) + call assert_fails("call function('F')", 'E700:') + + call assert_fails("call function('foo()')", 'E475:') + call assert_fails("call function('foo()')", 'foo()') + call assert_fails("function('')", 'E129:') + + var Len = (s) => strlen(s) + call assert_equal(6, Len('foobar')) + var name = string(Len) + # can evaluate "function('<lambda>99')" + call execute('var Ref = ' .. name) + call assert_equal(4, Ref('text')) + END + call CheckScriptSuccess(lines) +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() + let lines =<< trim END + hi def link 1 Comment + hi def link 2 PreProc + VAR set = [{"group": 1, "pattern": 2, "id": 3, "priority": 4}] + VAR 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()) + END + call CheckLegacyAndVim9Success(lines) + + call CheckLegacyAndVim9Failure(['VAR m = setmatches([], [])'], ['E745:', 'E1013:', 'E1210:']) +endfunc + +func Test_empty_concatenate() + let lines =<< trim END + call assert_equal('b', 'a'[4 : 0] .. 'b') + call assert_equal('b', 'b' .. 'a'[4 : 0]) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_broken_number() + call CheckLegacyAndVim9Failure(['VAR X = "bad"', 'echo 1X'], 'E15:') + call CheckLegacyAndVim9Failure(['VAR X = "bad"', 'echo 0b1X'], 'E15:') + call CheckLegacyAndVim9Failure(['echo 0b12'], 'E15:') + call CheckLegacyAndVim9Failure(['VAR X = "bad"', 'echo 0x1X'], 'E15:') + call CheckLegacyAndVim9Failure(['VAR X = "bad"', 'echo 011X'], 'E15:') + + call CheckLegacyAndVim9Success(['call assert_equal(2, str2nr("2a"))']) + + call CheckLegacyAndVim9Failure(['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 CheckLegacyAndVim9Failure(["VAR i = 'abc' .. []"], ['E730:', 'E1105:', 'E730:']) + call CheckLegacyAndVim9Failure(["VAR l = [] + 10"], ['E745:', 'E1051:', 'E745']) + call CheckLegacyAndVim9Failure(["VAR v = 10 + []"], ['E745:', 'E1051:', 'E745:']) + call CheckLegacyAndVim9Failure(["VAR v = 10 / []"], ['E745:', 'E1036:', 'E745:']) + call CheckLegacyAndVim9Failure(["VAR v = -{}"], ['E728:', 'E1012:', 'E728:']) +endfunc + +func Test_white_in_function_call() + let lines =<< trim END + VAR text = substitute ( 'some text' , 't' , 'T' , 'g' ) + call assert_equal('some TexT', text) + END + call CheckTransLegacySuccess(lines) + + let lines =<< trim END + var text = substitute ( 'some text' , 't' , 'T' , 'g' ) + call assert_equal('some TexT', text) + END + call CheckDefAndScriptFailure(lines, ['E1001:', 'E121:']) +endfunc + +" Test for float value comparison +func Test_float_compare() + CheckFeature float + + let lines =<< trim END + call assert_true(1.2 == 1.2) + call assert_true(1.0 != 1.2) + call assert_true(1.2 > 1.0) + call assert_true(1.2 >= 1.2) + call assert_true(1.0 < 1.2) + call assert_true(1.2 <= 1.2) + call assert_true(+0.0 == -0.0) + #" two NaNs (not a number) are not equal + call assert_true(sqrt(-4.01) != (0.0 / 0.0)) + #" two inf (infinity) are equal + call assert_true((1.0 / 0) == (2.0 / 0)) + #" two -inf (infinity) are equal + call assert_true(-(1.0 / 0) == -(2.0 / 0)) + #" +infinity != -infinity + call assert_true((1.0 / 0) != -(2.0 / 0)) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_string_interp() + let lines =<< trim END + call assert_equal('', $"") + call assert_equal('foobar', $"foobar") + #" Escaping rules. + call assert_equal('"foo"{bar}', $"\"foo\"{{bar}}") + call assert_equal('"foo"{bar}', $'"foo"{{bar}}') + call assert_equal('foobar', $"{"foo"}" .. $'{'bar'}') + #" Whitespace before/after the expression. + call assert_equal('3', $"{ 1 + 2 }") + #" String conversion. + call assert_equal('hello from ' .. v:version, $"hello from {v:version}") + call assert_equal('hello from ' .. v:version, $'hello from {v:version}') + #" Paper over a small difference between VimScript behaviour. + call assert_equal(string(v:true), $"{v:true}") + call assert_equal('(1+1=2)', $"(1+1={1 + 1})") + #" Hex-escaped opening brace: char2nr('{') == 0x7b + call assert_equal('esc123ape', $"esc{123}ape") + call assert_equal('me{}me', $"me{"\x7b"}\x7dme") + VAR var1 = "sun" + VAR var2 = "shine" + call assert_equal('sunshine', $"{var1}{var2}") + call assert_equal('sunsunsun', $"{var1->repeat(3)}") + #" Multibyte strings. + call assert_equal('say ハロー・ワールド', $"say {'ハロー・ワールド'}") + #" Nested. + call assert_equal('foobarbaz', $"foo{$"{'bar'}"}baz") + #" Do not evaluate blocks when the expr is skipped. + VAR tmp = 0 + if v:false + echo "${ LET tmp += 1 }" + endif + call assert_equal(0, tmp) + + #" Stray closing brace. + call assert_fails('echo $"moo}"', 'E1278:') + #" Undefined variable in expansion. + call assert_fails('echo $"{moo}"', 'E121:') + #" Empty blocks are rejected. + call assert_fails('echo $"{}"', 'E15:') + call assert_fails('echo $"{ }"', 'E15:') + END + call CheckLegacyAndVim9Success(lines) + + let lines =<< trim END + call assert_equal('5', $"{({x -> x + 1})(4)}") + END + call CheckLegacySuccess(lines) + + let lines =<< trim END + call assert_equal('5', $"{((x) => x + 1)(4)}") + call assert_fails('echo $"{ # foo }"', 'E1279:') + END + call CheckDefAndScriptSuccess(lines) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_expr_utf8.vim b/test/old/testdir/test_expr_utf8.vim new file mode 100644 index 0000000000..c6d2e4ed7e --- /dev/null +++ b/test/old/testdir/test_expr_utf8.vim @@ -0,0 +1,44 @@ +" 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)) + + + call assert_equal('a', strcharpart('àxb', 0, 1, 0)) + call assert_equal('à', strcharpart('àxb', 0, 1, 1)) + call assert_equal('x', strcharpart('àxb', 1, 1, 1)) + + call assert_fails("let v = strcharpart('abc', 0, 0, [])", 'E745:') + call assert_fails("let v = strcharpart('abc', 0, 0, 2)", 'E1023:') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_file_perm.vim b/test/old/testdir/test_file_perm.vim new file mode 100644 index 0000000000..1cb09e8647 --- /dev/null +++ b/test/old/testdir/test_file_perm.vim @@ -0,0 +1,30 @@ +" 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 diff --git a/test/old/testdir/test_file_size.vim b/test/old/testdir/test_file_size.vim new file mode 100644 index 0000000000..3e78a7b23c --- /dev/null +++ b/test/old/testdir/test_file_size.vim @@ -0,0 +1,58 @@ +" 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 diff --git a/test/old/testdir/test_filechanged.vim b/test/old/testdir/test_filechanged.vim new file mode 100644 index 0000000000..fef0eb732f --- /dev/null +++ b/test/old/testdir/test_filechanged.vim @@ -0,0 +1,274 @@ +" 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 diff --git a/test/old/testdir/test_fileformat.vim b/test/old/testdir/test_fileformat.vim new file mode 100644 index 0000000000..e12b1d1a9a --- /dev/null +++ b/test/old/testdir/test_fileformat.vim @@ -0,0 +1,314 @@ +" 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') + + " The :bwipe commands below cause us to get back to the current buffer. + " Avoid stray errors for various 'fileformat' values which may cause a + " modeline to be misinterpreted by wiping the buffer and editing a new one. + only! + bwipe! + enew + + " 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 diff --git a/test/old/testdir/test_filetype.vim b/test/old/testdir/test_filetype.vim new file mode 100644 index 0000000000..87044a06b5 --- /dev/null +++ b/test/old/testdir/test_filetype.vim @@ -0,0 +1,2282 @@ +" Test :setfiletype + +func Test_detection() + filetype on + augroup filetypedetect + au BufNewFile,BufRead * call assert_equal(1, did_filetype()) + augroup END + new something.vim + call assert_equal('vim', &filetype) + + bwipe! + filetype off +endfunc + +func Test_conf_type() + filetype on + call writefile(['# some comment', 'must be conf'], 'Xconffile', 'D') + augroup filetypedetect + au BufNewFile,BufRead * call assert_equal(0, did_filetype()) + augroup END + split Xconffile + call assert_equal('conf', &filetype) + + bwipe! + filetype off +endfunc + +func Test_other_type() + filetype on + augroup filetypedetect + au BufNewFile,BufRead * call assert_equal(0, did_filetype()) + au BufNewFile,BufRead Xotherfile setf testfile + au BufNewFile,BufRead * call assert_equal(1, did_filetype()) + augroup END + call writefile(['# some comment', 'must be conf'], 'Xotherfile', 'D') + split Xotherfile + call assert_equal('testfile', &filetype) + + bwipe! + filetype off +endfunc + +" If $XDG_CONFIG_HOME is set return "fname" expanded in a list. +" Otherwise return an empty list. +func s:WhenConfigHome(fname) + if exists('$XDG_CONFIG_HOME') + return [expand(a:fname)] + endif + return [] +endfunc + +" Return the name used for the $XDG_CONFIG_HOME directory. +func s:GetConfigHome() + return getcwd() .. '/Xdg_config_home' +endfunc + +" saved value of $XDG_CONFIG_HOME +let s:saveConfigHome = '' + +func s:SetupConfigHome() + " Nvim on Windows may use $XDG_CONFIG_HOME, and runnvim.sh sets it. + " if empty(windowsversion()) + let s:saveConfigHome = $XDG_CONFIG_HOME + call setenv("XDG_CONFIG_HOME", s:GetConfigHome()) + " endif +endfunc + +" Filetypes detected just from matching the file name. +" First one is checking that these files have no filetype. +func s:GetFilenameChecks() abort + return { + \ 'none': ['bsd', 'some-bsd'], + \ '8th': ['file.8th'], + \ 'a2ps': ['/etc/a2ps.cfg', '/etc/a2ps/file.cfg', 'a2psrc', '.a2psrc', 'any/etc/a2ps.cfg', 'any/etc/a2ps/file.cfg'], + \ 'a65': ['file.a65'], + \ 'aap': ['file.aap'], + \ 'abap': ['file.abap'], + \ 'abc': ['file.abc'], + \ 'abel': ['file.abl'], + \ 'acedb': ['file.wrm'], + \ 'ada': ['file.adb', 'file.ads', 'file.ada', 'file.gpr'], + \ 'ahdl': ['file.tdf'], + \ 'aidl': ['file.aidl'], + \ 'alsaconf': ['.asoundrc', '/usr/share/alsa/alsa.conf', '/etc/asound.conf', 'any/etc/asound.conf', 'any/usr/share/alsa/alsa.conf'], + \ 'aml': ['file.aml'], + \ 'ampl': ['file.run'], + \ 'ant': ['build.xml'], + \ 'apache': ['.htaccess', '/etc/httpd/file.conf', '/etc/apache2/sites-2/file.com', '/etc/apache2/some.config', '/etc/apache2/conf.file/conf', '/etc/apache2/mods-some/file', '/etc/apache2/sites-some/file', '/etc/httpd/conf.d/file.config', '/etc/apache2/conf.file/file', '/etc/apache2/file.conf', '/etc/apache2/file.conf-file', '/etc/apache2/mods-file/file', '/etc/apache2/sites-file/file', '/etc/apache2/sites-file/file.com', '/etc/httpd/conf.d/file.conf', '/etc/httpd/conf.d/file.conf-file', 'access.conf', 'access.conf-file', 'any/etc/apache2/conf.file/file', 'any/etc/apache2/file.conf', 'any/etc/apache2/file.conf-file', 'any/etc/apache2/mods-file/file', 'any/etc/apache2/sites-file/file', 'any/etc/apache2/sites-file/file.com', 'any/etc/httpd/conf.d/file.conf', 'any/etc/httpd/conf.d/file.conf-file', 'any/etc/httpd/file.conf', 'apache.conf', 'apache.conf-file', 'apache2.conf', 'apache2.conf-file', 'httpd.conf', 'httpd.conf-file', 'srm.conf', 'srm.conf-file', '/etc/httpd/mods-some/file', '/etc/httpd/sites-some/file', '/etc/httpd/conf.file/conf'], + \ 'apachestyle': ['/etc/proftpd/file.config,/etc/proftpd/conf.file/file', '/etc/proftpd/conf.file/file', '/etc/proftpd/file.conf', '/etc/proftpd/file.conf-file', 'any/etc/proftpd/conf.file/file', 'any/etc/proftpd/file.conf', 'any/etc/proftpd/file.conf-file', 'proftpd.conf', 'proftpd.conf-file'], + \ 'applescript': ['file.scpt'], + \ 'aptconf': ['apt.conf', '/.aptitude/config', 'any/.aptitude/config'], + \ 'arch': ['.arch-inventory', '=tagging-method'], + \ 'arduino': ['file.ino', 'file.pde'], + \ 'art': ['file.art'], + \ 'asciidoc': ['file.asciidoc', 'file.adoc'], + \ 'asn': ['file.asn', 'file.asn1'], + \ 'asterisk': ['asterisk/file.conf', 'asterisk/file.conf-file', 'some-asterisk/file.conf', 'some-asterisk/file.conf-file'], + \ 'astro': ['file.astro'], + \ 'atlas': ['file.atl', 'file.as'], + \ 'authzed': ['file.zed'], + \ 'autohotkey': ['file.ahk'], + \ 'autoit': ['file.au3'], + \ 'automake': ['GNUmakefile.am', 'makefile.am', 'Makefile.am'], + \ 'ave': ['file.ave'], + \ 'awk': ['file.awk', 'file.gawk'], + \ 'b': ['file.mch', 'file.ref', 'file.imp'], + \ 'basic': ['file.bas', 'file.bi', 'file.bm'], + \ 'bass': ['file.bass'], + \ 'bc': ['file.bc'], + \ 'bdf': ['file.bdf'], + \ 'beancount': ['file.beancount'], + \ 'bib': ['file.bib'], + \ 'bicep': ['file.bicep', 'file.bicepparam'], + \ 'bindzone': ['named.root', '/bind/db.file', '/named/db.file', 'any/bind/db.file', 'any/named/db.file'], + \ 'bitbake': ['file.bb', 'file.bbappend', 'file.bbclass', 'build/conf/local.conf', 'meta/conf/layer.conf', 'build/conf/bbappend.conf', 'meta-layer/conf/distro/foo.conf'], + \ 'blade': ['file.blade.php'], + \ 'blank': ['file.bl'], + \ 'blueprint': ['file.blp'], + \ 'bsdl': ['file.bsd', 'file.bsdl'], + \ 'bst': ['file.bst'], + \ 'bzl': ['file.bazel', 'file.bzl', 'WORKSPACE', 'WORKSPACE.bzlmod'], + \ 'bzr': ['bzr_log.any', 'bzr_log.file'], + \ 'c': ['enlightenment/file.cfg', 'file.qc', 'file.c', 'some-enlightenment/file.cfg'], + \ 'cabal': ['file.cabal'], + \ 'cabalconfig': ['cabal.config', expand("$HOME/.config/cabal/config")] + s:WhenConfigHome('$XDG_CONFIG_HOME/cabal/config'), + \ 'cabalproject': ['cabal.project', 'cabal.project.local'], + \ 'cairo': ['file.cairo'], + \ 'calendar': ['calendar', '/.calendar/file', '/share/calendar/any/calendar.file', '/share/calendar/calendar.file', 'any/share/calendar/any/calendar.file', 'any/share/calendar/calendar.file'], + \ 'capnp': ['file.capnp'], + \ 'catalog': ['catalog', 'sgml.catalogfile', 'sgml.catalog', 'sgml.catalog-file'], + \ 'cdl': ['file.cdl'], + \ 'cdrdaoconf': ['/etc/cdrdao.conf', '/etc/defaults/cdrdao', '/etc/default/cdrdao', '.cdrdao', 'any/etc/cdrdao.conf', 'any/etc/default/cdrdao', 'any/etc/defaults/cdrdao'], + \ 'cdrtoc': ['file.toc'], + \ 'cf': ['file.cfm', 'file.cfi', 'file.cfc'], + \ 'cfengine': ['cfengine.conf'], + \ 'cfg': ['file.hgrc', 'filehgrc', 'hgrc', 'some-hgrc'], + \ 'ch': ['file.chf'], + \ 'chaiscript': ['file.chai'], + \ 'chaskell': ['file.chs'], + \ 'chatito': ['file.chatito'], + \ 'chill': ['file..ch'], + \ 'chordpro': ['file.chopro', 'file.crd', 'file.cho', 'file.crdpro', 'file.chordpro'], + \ 'cl': ['file.eni'], + \ 'clean': ['file.dcl', 'file.icl'], + \ 'clojure': ['file.clj', 'file.cljs', 'file.cljx', 'file.cljc'], + \ 'cmake': ['CMakeLists.txt', 'file.cmake', 'file.cmake.in'], + \ 'cmod': ['file.cmod'], + \ 'cmusrc': ['any/.cmus/autosave', 'any/.cmus/rc', 'any/.cmus/command-history', 'any/.cmus/file.theme', 'any/cmus/rc', 'any/cmus/file.theme', '/.cmus/autosave', '/.cmus/command-history', '/.cmus/file.theme', '/.cmus/rc', '/cmus/file.theme', '/cmus/rc'], + \ 'cobol': ['file.cbl', 'file.cob', 'file.lib'], + \ 'coco': ['file.atg'], + \ 'conaryrecipe': ['file.recipe'], + \ 'conf': ['auto.master', 'file.conf'], + \ 'config': ['configure.in', 'configure.ac', '/etc/hostname.file', 'any/etc/hostname.file'], + \ 'confini': ['/etc/pacman.conf', 'any/etc/pacman.conf', 'mpv.conf', 'any/.aws/config', 'any/.aws/credentials', 'file.nmconnection'], + \ 'context': ['tex/context/any/file.tex', 'file.mkii', 'file.mkiv', 'file.mkvi', 'file.mkxl', 'file.mklx'], + \ 'cook': ['file.cook'], + \ 'corn': ['file.corn'], + \ 'cpon': ['file.cpon'], + \ 'cpp': ['file.cxx', 'file.c++', 'file.hh', 'file.hxx', 'file.hpp', 'file.ipp', 'file.moc', 'file.tcc', 'file.inl', 'file.tlh', 'file.cppm', 'file.ccm', 'file.cxxm', 'file.c++m'], + \ 'cqlang': ['file.cql'], + \ 'crm': ['file.crm'], + \ 'crontab': ['crontab', 'crontab.file', '/etc/cron.d/file', 'any/etc/cron.d/file'], + \ 'crystal': ['file.cr'], + \ 'cs': ['file.cs', 'file.csx'], + \ 'csc': ['file.csc'], + \ 'csdl': ['file.csdl'], + \ 'csp': ['file.csp', 'file.fdr'], + \ 'css': ['file.css'], + \ 'cterm': ['file.con'], + \ 'csv': ['file.csv'], + \ 'cucumber': ['file.feature'], + \ 'cuda': ['file.cu', 'file.cuh'], + \ 'cue': ['file.cue'], + \ 'cupl': ['file.pld'], + \ 'cuplsim': ['file.si'], + \ 'cvs': ['cvs123'], + \ 'cvsrc': ['.cvsrc'], + \ 'cynpp': ['file.cyn'], + \ 'cypher': ['file.cypher'], + \ 'd': ['file.d'], + \ 'dart': ['file.dart', 'file.drt'], + \ 'datascript': ['file.ds'], + \ 'dcd': ['file.dcd'], + \ 'debchangelog': ['changelog.Debian', 'changelog.dch', 'NEWS.Debian', 'NEWS.dch', '/debian/changelog'], + \ 'debcontrol': ['/debian/control', 'any/debian/control'], + \ 'debcopyright': ['/debian/copyright', 'any/debian/copyright'], + \ 'debsources': ['/etc/apt/sources.list', '/etc/apt/sources.list.d/file.list', 'any/etc/apt/sources.list', 'any/etc/apt/sources.list.d/file.list'], + \ 'deb822sources': ['/etc/apt/sources.list.d/file.sources', 'any/etc/apt/sources.list.d/file.sources'], + \ 'def': ['file.def'], + \ 'denyhosts': ['denyhosts.conf'], + \ 'desc': ['file.desc'], + \ 'desktop': ['file.desktop', '.directory', 'file.directory'], + \ 'dhall': ['file.dhall'], + \ 'dictconf': ['dict.conf', '.dictrc'], + \ 'dictdconf': ['dictd.conf', 'dictdfile.conf', 'dictd-file.conf'], + \ 'diff': ['file.diff', 'file.rej'], + \ 'dircolors': ['.dir_colors', '.dircolors', '/etc/DIR_COLORS', 'any/etc/DIR_COLORS'], + \ 'dnsmasq': ['/etc/dnsmasq.conf', '/etc/dnsmasq.d/file', 'any/etc/dnsmasq.conf', 'any/etc/dnsmasq.d/file'], + \ 'dockerfile': ['Containerfile', 'Dockerfile', 'dockerfile', 'file.Dockerfile', 'file.dockerfile', 'Dockerfile.debian', 'Containerfile.something'], + \ 'dosbatch': ['file.bat'], + \ 'dosini': ['/etc/yum.conf', 'file.ini', 'npmrc', '.npmrc', 'php.ini', 'php.ini-5', 'php.ini-file', '/etc/yum.repos.d/file', 'any/etc/yum.conf', 'any/etc/yum.repos.d/file', 'file.wrap', 'file.vbp', 'ja2.ini', 'JA2.INI'], + \ 'dot': ['file.dot', 'file.gv'], + \ 'dracula': ['file.drac', 'file.drc', 'filelvs', 'filelpe', 'drac.file', 'lpe', 'lvs', 'some-lpe', 'some-lvs'], + \ 'dtd': ['file.dtd'], + \ 'dtrace': ['/usr/lib/dtrace/io.d'], + \ 'dts': ['file.dts', 'file.dtsi'], + \ 'dune': ['jbuild', 'dune', 'dune-project', 'dune-workspace'], + \ 'dylan': ['file.dylan'], + \ 'dylanintr': ['file.intr'], + \ 'dylanlid': ['file.lid'], + \ 'ecd': ['file.ecd'], + \ 'edif': ['file.edf', 'file.edif', 'file.edo'], + \ 'editorconfig': ['.editorconfig'], + \ 'eelixir': ['file.eex', 'file.leex'], + \ 'elinks': ['elinks.conf'], + \ 'elixir': ['file.ex', 'file.exs', 'mix.lock'], + \ 'elm': ['file.elm'], + \ 'elmfilt': ['filter-rules'], + \ 'elsa': ['file.lc'], + \ 'elvish': ['file.elv'], + \ 'epuppet': ['file.epp'], + \ 'erlang': ['file.erl', 'file.hrl', 'file.yaws'], + \ 'eruby': ['file.erb', 'file.rhtml'], + \ 'esdl': ['file.esdl'], + \ 'esmtprc': ['anyesmtprc', 'esmtprc', 'some-esmtprc'], + \ 'esqlc': ['file.ec', 'file.EC'], + \ 'esterel': ['file.strl'], + \ 'eterm': ['anyEterm/file.cfg', 'Eterm/file.cfg', 'some-Eterm/file.cfg'], + \ 'exim': ['exim.conf'], + \ 'expect': ['file.exp'], + \ 'exports': ['exports'], + \ 'factor': ['file.factor'], + \ 'falcon': ['file.fal'], + \ 'fan': ['file.fan', 'file.fwt'], + \ 'fennel': ['file.fnl'], + \ 'fetchmail': ['.fetchmailrc'], + \ 'fgl': ['file.4gl', 'file.4gh', 'file.m4gl'], + \ 'firrtl': ['file.fir'], + \ 'fish': ['file.fish'], + \ 'focexec': ['file.fex', 'file.focexec'], + \ 'form': ['file.frm'], + \ 'forth': ['file.ft', 'file.fth', 'file.4th'], + \ 'fortran': ['file.f', 'file.for', 'file.fortran', 'file.fpp', 'file.ftn', 'file.f77', 'file.f90', 'file.f95', 'file.f03', 'file.f08'], + \ 'fpcmake': ['file.fpc'], + \ 'framescript': ['file.fsl'], + \ 'freebasic': ['file.fb'], + \ 'fsh': ['file.fsh'], + \ 'fsharp': ['file.fs', 'file.fsi', 'file.fsx'], + \ 'fstab': ['fstab', 'mtab'], + \ 'func': ['file.fc'], + \ 'fusion': ['file.fusion'], + \ 'fvwm': ['/.fvwm/file', 'any/.fvwm/file'], + \ 'gdb': ['.gdbinit', 'gdbinit', 'file.gdb', '.config/gdbearlyinit', '.gdbearlyinit'], + \ 'gdmo': ['file.mo', 'file.gdmo'], + \ 'gdresource': ['file.tscn', 'file.tres'], + \ 'gdscript': ['file.gd'], + \ 'gdshader': ['file.gdshader', 'file.shader'], + \ 'gedcom': ['file.ged', 'lltxxxxx.txt', '/tmp/lltmp', '/tmp/lltmp-file', 'any/tmp/lltmp', 'any/tmp/lltmp-file'], + \ 'gemtext': ['file.gmi', 'file.gemini'], + \ 'gift': ['file.gift'], + \ 'gitattributes': ['file.git/info/attributes', '.gitattributes', '/.config/git/attributes', '/etc/gitattributes', '/usr/local/etc/gitattributes', 'some.git/info/attributes'] + s:WhenConfigHome('$XDG_CONFIG_HOME/git/attributes'), + \ 'gitcommit': ['COMMIT_EDITMSG', 'MERGE_MSG', 'TAG_EDITMSG', 'NOTES_EDITMSG', 'EDIT_DESCRIPTION'], + \ 'gitconfig': ['file.git/config', 'file.git/config.worktree', 'file.git/worktrees/x/config.worktree', '.gitconfig', '.gitmodules', 'file.git/modules//config', '/.config/git/config', '/etc/gitconfig', '/usr/local/etc/gitconfig', '/etc/gitconfig.d/file', 'any/etc/gitconfig.d/file', '/.gitconfig.d/file', 'any/.config/git/config', 'any/.gitconfig.d/file', 'some.git/config', 'some.git/modules/any/config'] + s:WhenConfigHome('$XDG_CONFIG_HOME/git/config'), + \ 'gitignore': ['file.git/info/exclude', '.gitignore', '/.config/git/ignore', 'some.git/info/exclude'] + s:WhenConfigHome('$XDG_CONFIG_HOME/git/ignore'), + \ 'gitolite': ['gitolite.conf', '/gitolite-admin/conf/file', 'any/gitolite-admin/conf/file'], + \ 'gitrebase': ['git-rebase-todo'], + \ 'gitsendemail': ['.gitsendemail.msg.xxxxxx'], + \ 'gkrellmrc': ['gkrellmrc', 'gkrellmrc_x'], + \ 'gleam': ['file.gleam'], + \ 'glsl': ['file.glsl'], + \ 'gn': ['file.gn', 'file.gni'], + \ 'gnash': ['gnashrc', '.gnashrc', 'gnashpluginrc', '.gnashpluginrc'], + \ 'gnuplot': ['file.gpi', '.gnuplot'], + \ 'go': ['file.go'], + \ 'gomod': ['go.mod'], + \ 'gosum': ['go.sum', 'go.work.sum'], + \ 'gowork': ['go.work'], + \ 'gp': ['file.gp', '.gprc'], + \ 'gpg': ['/.gnupg/options', '/.gnupg/gpg.conf', '/usr/any/gnupg/options.skel', 'any/.gnupg/gpg.conf', 'any/.gnupg/options', 'any/usr/any/gnupg/options.skel'], + \ 'grads': ['file.gs'], + \ 'graphql': ['file.graphql', 'file.graphqls', 'file.gql'], + \ 'gretl': ['file.gretl'], + \ 'groovy': ['file.gradle', 'file.groovy', 'Jenkinsfile'], + \ 'group': ['any/etc/group', 'any/etc/group-', 'any/etc/group.edit', 'any/etc/gshadow', 'any/etc/gshadow-', 'any/etc/gshadow.edit', 'any/var/backups/group.bak', 'any/var/backups/gshadow.bak', '/etc/group', '/etc/group-', '/etc/group.edit', '/etc/gshadow', '/etc/gshadow-', '/etc/gshadow.edit', '/var/backups/group.bak', '/var/backups/gshadow.bak'], + \ 'grub': ['/boot/grub/menu.lst', '/boot/grub/grub.conf', '/etc/grub.conf', 'any/boot/grub/grub.conf', 'any/boot/grub/menu.lst', 'any/etc/grub.conf'], + \ 'gsp': ['file.gsp'], + \ 'gtkrc': ['.gtkrc', 'gtkrc', '.gtkrc-file', 'gtkrc-file'], + \ 'gyp': ['file.gyp', 'file.gypi'], + \ 'hack': ['file.hack', 'file.hackpartial'], + \ 'haml': ['file.haml'], + \ 'hamster': ['file.hsm'], + \ 'handlebars': ['file.hbs'], + \ 'hare': ['file.ha'], + \ 'haskell': ['file.hs', 'file.hsc', 'file.hs-boot', 'file.hsig'], + \ 'haskellpersistent': ['file.persistentmodels'], + \ 'haste': ['file.ht'], + \ 'hastepreproc': ['file.htpp'], + \ 'hb': ['file.hb'], + \ 'hcl': ['file.hcl'], + \ 'heex': ['file.heex'], + \ 'hercules': ['file.vc', 'file.ev', 'file.sum', 'file.errsum'], + \ 'hex': ['file.hex', 'file.h32'], + \ 'hgcommit': ['hg-editor-file.txt'], + \ 'hjson': ['file.hjson'], + \ 'hlsplaylist': ['file.m3u', 'file.m3u8'], + \ 'hog': ['file.hog', 'snort.conf', 'vision.conf'], + \ 'hollywood': ['file.hws'], + \ 'hoon': ['file.hoon'], + \ 'hostconf': ['/etc/host.conf', 'any/etc/host.conf'], + \ 'hostsaccess': ['/etc/hosts.allow', '/etc/hosts.deny', 'any/etc/hosts.allow', 'any/etc/hosts.deny'], + \ 'html': ['file.html', 'file.htm', 'file.cshtml'], + \ 'htmlm4': ['file.html.m4'], + \ 'httest': ['file.htt', 'file.htb'], + \ 'hurl': ['file.hurl'], + \ 'i3config': ['/home/user/.i3/config', '/home/user/.config/i3/config', '/etc/i3/config', '/etc/xdg/i3/config'], + \ 'ibasic': ['file.iba', 'file.ibi'], + \ 'icemenu': ['/.icewm/menu', 'any/.icewm/menu'], + \ 'icon': ['file.icn'], + \ 'indent': ['.indent.pro', 'indentrc'], + \ 'inform': ['file.inf', 'file.INF'], + \ 'initng': ['/etc/initng/any/file.i', 'file.ii', 'any/etc/initng/any/file.i'], + \ 'inittab': ['inittab'], + \ 'ipfilter': ['ipf.conf', 'ipf6.conf', 'ipf.rules'], + \ 'iss': ['file.iss'], + \ 'ist': ['file.ist', 'file.mst'], + \ 'j': ['file.ijs'], + \ 'jal': ['file.jal', 'file.JAL'], + \ 'jam': ['file.jpl', 'file.jpr', 'JAM-file.file', 'JAM.file', 'Prl-file.file', 'Prl.file'], + \ 'janet': ['file.janet'], + \ 'java': ['file.java', 'file.jav'], + \ 'javacc': ['file.jj', 'file.jjt'], + \ 'javascript': ['file.js', 'file.jsm', 'file.javascript', 'file.es', 'file.mjs', 'file.cjs'], + \ 'javascript.glimmer': ['file.gjs'], + \ 'javascriptreact': ['file.jsx'], + \ 'jess': ['file.clp'], + \ 'jgraph': ['file.jgr'], + \ 'jq': ['file.jq'], + \ 'jovial': ['file.jov', 'file.j73', 'file.jovial'], + \ 'jproperties': ['file.properties', 'file.properties_xx', 'file.properties_xx_xx', 'some.properties_xx_xx_file', 'org.eclipse.xyz.prefs'], + \ 'json': ['file.json', 'file.jsonp', 'file.json-patch', 'file.geojson', 'file.webmanifest', 'Pipfile.lock', 'file.ipynb', '.prettierrc', '.firebaserc', '.stylelintrc', 'file.slnf'], + \ 'json5': ['file.json5'], + \ 'jsonc': ['file.jsonc', '.babelrc', '.eslintrc', '.jsfmtrc', '.jshintrc', '.hintrc', '.swrc', 'jsconfig.json', 'tsconfig.json', 'tsconfig.test.json', 'tsconfig-test.json'], + \ 'jsonl': ['file.jsonl'], + \ 'jsonnet': ['file.jsonnet', 'file.libsonnet'], + \ 'jsp': ['file.jsp'], + \ 'julia': ['file.jl'], + \ 'just': ['justfile', 'Justfile', '.justfile', 'config.just'], + \ 'kconfig': ['Kconfig', 'Kconfig.debug', 'Kconfig.file'], + \ 'kdl': ['file.kdl'], + \ 'kivy': ['file.kv'], + \ 'kix': ['file.kix'], + \ 'kotlin': ['file.kt', 'file.ktm', 'file.kts'], + \ 'krl': ['file.sub', 'file.Sub', 'file.SUB'], + \ 'kscript': ['file.ks'], + \ 'kwt': ['file.k'], + \ 'lace': ['file.ace', 'file.ACE'], + \ 'latte': ['file.latte', 'file.lte'], + \ 'ld': ['file.ld'], + \ 'ldif': ['file.ldif'], + \ 'lean': ['file.lean'], + \ 'ledger': ['file.ldg', 'file.ledger', 'file.journal'], + \ 'less': ['file.less'], + \ 'lex': ['file.lex', 'file.l', 'file.lxx', 'file.l++'], + \ 'lftp': ['lftp.conf', '.lftprc', 'anylftp/rc', 'lftp/rc', 'some-lftp/rc'], + \ 'lhaskell': ['file.lhs'], + \ 'libao': ['/etc/libao.conf', '/.libao', 'any/.libao', 'any/etc/libao.conf'], + \ 'lifelines': ['file.ll'], + \ 'lilo': ['lilo.conf', 'lilo.conf-file'], + \ 'lilypond': ['file.ly', 'file.ily'], + \ 'limits': ['/etc/limits', '/etc/anylimits.conf', '/etc/anylimits.d/file.conf', '/etc/limits.conf', '/etc/limits.d/file.conf', '/etc/some-limits.conf', '/etc/some-limits.d/file.conf', 'any/etc/limits', 'any/etc/limits.conf', 'any/etc/limits.d/file.conf', 'any/etc/some-limits.conf', 'any/etc/some-limits.d/file.conf'], + \ 'liquidsoap': ['file.liq'], + \ 'liquid': ['file.liquid'], + \ 'lisp': ['file.lsp', 'file.lisp', 'file.asd', 'file.el', 'file.cl', '.emacs', '.sawfishrc', 'sbclrc', '.sbclrc'], + \ 'lite': ['file.lite', 'file.lt'], + \ 'litestep': ['/LiteStep/any/file.rc', 'any/LiteStep/any/file.rc'], + \ 'logcheck': ['/etc/logcheck/file.d-some/file', '/etc/logcheck/file.d/file', 'any/etc/logcheck/file.d-some/file', 'any/etc/logcheck/file.d/file'], + \ 'livebook': ['file.livemd'], + \ 'loginaccess': ['/etc/login.access', 'any/etc/login.access'], + \ 'logindefs': ['/etc/login.defs', 'any/etc/login.defs'], + \ 'logtalk': ['file.lgt'], + \ 'lotos': ['file.lot', 'file.lotos'], + \ 'lout': ['file.lou', 'file.lout'], + \ 'lpc': ['file.lpc', 'file.ulpc'], + \ 'lsl': ['file.lsl'], + \ 'lss': ['file.lss'], + \ 'lua': ['file.lua', 'file.rockspec', 'file.nse', '.luacheckrc', '.busted'], + \ 'luau': ['file.luau'], + \ 'lynx': ['lynx.cfg'], + \ 'lyrics': ['file.lrc'], + \ 'm3build': ['m3makefile', 'm3overrides'], + \ 'm3quake': ['file.quake', 'cm3.cfg'], + \ 'm4': ['file.at'], + \ 'mail': ['snd.123', '.letter', '.letter.123', '.followup', '.article', '.article.123', 'pico.123', 'mutt-xx-xxx', 'muttng-xx-xxx', 'ae123.txt', 'file.eml', 'reportbug-file'], + \ 'mailaliases': ['/etc/mail/aliases', '/etc/aliases', 'any/etc/aliases', 'any/etc/mail/aliases'], + \ 'mailcap': ['.mailcap', 'mailcap'], + \ 'make': ['file.mk', 'file.mak', 'file.dsp', 'makefile', 'Makefile', 'makefile-file', 'Makefile-file', 'some-makefile', 'some-Makefile'], + \ 'mallard': ['file.page'], + "\ 'man': ['file.man'], + \ 'manconf': ['/etc/man.conf', 'man.config', 'any/etc/man.conf'], + \ 'map': ['file.map'], + \ 'maple': ['file.mv', 'file.mpl', 'file.mws'], + \ 'markdown': ['file.markdown', 'file.mdown', 'file.mkd', 'file.mkdn', 'file.mdwn', 'file.md'], + \ 'mason': ['file.mason', 'file.mhtml', 'file.comp'], + \ 'master': ['file.mas', 'file.master'], + \ 'matlab': ['file.m'], + \ 'maxima': ['file.demo', 'file.dmt', 'file.dm1', 'file.dm2', 'file.dm3', + \ 'file.wxm', 'maxima-init.mac'], + \ 'mel': ['file.mel'], + \ 'mermaid': ['file.mmd', 'file.mmdc', 'file.mermaid'], + \ 'meson': ['meson.build', 'meson.options', 'meson_options.txt'], + \ 'messages': ['/log/auth', '/log/cron', '/log/daemon', '/log/debug', '/log/kern', '/log/lpr', '/log/mail', '/log/messages', '/log/news/news', '/log/syslog', '/log/user', + \ '/log/auth.log', '/log/cron.log', '/log/daemon.log', '/log/debug.log', '/log/kern.log', '/log/lpr.log', '/log/mail.log', '/log/messages.log', '/log/news/news.log', '/log/syslog.log', '/log/user.log', + \ '/log/auth.err', '/log/cron.err', '/log/daemon.err', '/log/debug.err', '/log/kern.err', '/log/lpr.err', '/log/mail.err', '/log/messages.err', '/log/news/news.err', '/log/syslog.err', '/log/user.err', + \ '/log/auth.info', '/log/cron.info', '/log/daemon.info', '/log/debug.info', '/log/kern.info', '/log/lpr.info', '/log/mail.info', '/log/messages.info', '/log/news/news.info', '/log/syslog.info', '/log/user.info', + \ '/log/auth.warn', '/log/cron.warn', '/log/daemon.warn', '/log/debug.warn', '/log/kern.warn', '/log/lpr.warn', '/log/mail.warn', '/log/messages.warn', '/log/news/news.warn', '/log/syslog.warn', '/log/user.warn', + \ '/log/auth.crit', '/log/cron.crit', '/log/daemon.crit', '/log/debug.crit', '/log/kern.crit', '/log/lpr.crit', '/log/mail.crit', '/log/messages.crit', '/log/news/news.crit', '/log/syslog.crit', '/log/user.crit', + \ '/log/auth.notice', '/log/cron.notice', '/log/daemon.notice', '/log/debug.notice', '/log/kern.notice', '/log/lpr.notice', '/log/mail.notice', '/log/messages.notice', '/log/news/news.notice', '/log/syslog.notice', '/log/user.notice'], + \ 'mf': ['file.mf'], + \ 'mgl': ['file.mgl'], + \ 'mgp': ['file.mgp'], + \ 'mib': ['file.mib', 'file.my'], + \ 'mix': ['file.mix', 'file.mixal'], + \ 'mma': ['file.nb'], + \ 'mmp': ['file.mmp'], + \ 'modconf': ['/etc/modules.conf', '/etc/modules', '/etc/conf.modules', '/etc/modprobe.file', 'any/etc/conf.modules', 'any/etc/modprobe.file', 'any/etc/modules', 'any/etc/modules.conf'], + \ 'modula2': ['file.m2', 'file.mi'], + \ 'modula3': ['file.m3', 'file.mg', 'file.i3', 'file.ig', 'file.lm3'], + \ 'monk': ['file.isc', 'file.monk', 'file.ssc', 'file.tsc'], + \ 'moo': ['file.moo'], + \ 'moonscript': ['file.moon'], + \ 'move': ['file.move'], + \ 'mp': ['file.mp', 'file.mpxl', 'file.mpiv', 'file.mpvi'], + \ 'mplayerconf': ['mplayer.conf', '/.mplayer/config', 'any/.mplayer/config'], + \ 'mrxvtrc': ['mrxvtrc', '.mrxvtrc'], + \ 'msidl': ['file.odl', 'file.mof'], + \ 'msql': ['file.msql'], + \ 'mojo': ['file.mojo', 'file.🔥'], + \ 'mupad': ['file.mu'], + \ 'mush': ['file.mush'], + \ 'muttrc': ['Muttngrc', 'Muttrc', '.muttngrc', '.muttngrc-file', '.muttrc', '.muttrc-file', '/.mutt/muttngrc', '/.mutt/muttngrc-file', '/.mutt/muttrc', '/.mutt/muttrc-file', '/.muttng/muttngrc', '/.muttng/muttngrc-file', '/.muttng/muttrc', '/.muttng/muttrc-file', '/etc/Muttrc.d/file', '/etc/Muttrc.d/file.rc', 'Muttngrc-file', 'Muttrc-file', 'any/.mutt/muttngrc', 'any/.mutt/muttngrc-file', 'any/.mutt/muttrc', 'any/.mutt/muttrc-file', 'any/.muttng/muttngrc', 'any/.muttng/muttngrc-file', 'any/.muttng/muttrc', 'any/.muttng/muttrc-file', 'any/etc/Muttrc.d/file', 'muttngrc', 'muttngrc-file', 'muttrc', 'muttrc-file'], + \ 'mysql': ['file.mysql'], + \ 'n1ql': ['file.n1ql', 'file.nql'], + \ 'named': ['namedfile.conf', 'rndcfile.conf', 'named-file.conf', 'named.conf', 'rndc-file.conf', 'rndc-file.key', 'rndc.conf', 'rndc.key'], + \ 'nanorc': ['/etc/nanorc', 'file.nanorc', 'any/etc/nanorc'], + \ 'natural': ['file.NSA', 'file.NSC', 'file.NSG', 'file.NSL', 'file.NSM', 'file.NSN', 'file.NSP', 'file.NSS'], + \ 'ncf': ['file.ncf'], + \ 'neomuttrc': ['Neomuttrc', '.neomuttrc', '.neomuttrc-file', '/.neomutt/neomuttrc', '/.neomutt/neomuttrc-file', 'Neomuttrc', 'Neomuttrc-file', 'any/.neomutt/neomuttrc', 'any/.neomutt/neomuttrc-file', 'neomuttrc', 'neomuttrc-file'], + \ 'netrc': ['.netrc'], + \ 'nginx': ['file.nginx', 'nginxfile.conf', 'filenginx.conf', 'any/etc/nginx/file', 'any/usr/local/nginx/conf/file', 'any/nginx/file.conf'], + \ 'nim': ['file.nim', 'file.nims', 'file.nimble'], + \ 'ninja': ['file.ninja'], + \ 'nix': ['file.nix'], + \ 'norg': ['file.norg'], + \ 'nqc': ['file.nqc'], + \ 'nroff': ['file.tr', 'file.nr', 'file.roff', 'file.tmac', 'file.mom', 'tmac.file'], + \ 'nsis': ['file.nsi', 'file.nsh'], + \ 'nu': ['file.nu'], + \ 'obj': ['file.obj'], + \ 'objdump': ['file.objdump', 'file.cppobjdump'], + \ 'obse': ['file.obl', 'file.obse', 'file.oblivion', 'file.obscript'], + \ 'ocaml': ['file.ml', 'file.mli', 'file.mll', 'file.mly', '.ocamlinit', 'file.mlt', 'file.mlp', 'file.mlip', 'file.mli.cppo', 'file.ml.cppo'], + \ 'occam': ['file.occ'], + \ 'octave': ['octaverc', '.octaverc', 'octave.conf'], + \ 'odin': ['file.odin'], + \ 'omnimark': ['file.xom', 'file.xin'], + \ 'opam': ['opam', 'file.opam', 'file.opam.template'], + \ 'openroad': ['file.or'], + \ 'openscad': ['file.scad'], + \ 'openvpn': ['file.ovpn', '/etc/openvpn/client/client.conf', '/usr/share/openvpn/examples/server.conf'], + \ 'opl': ['file.OPL', 'file.OPl', 'file.OpL', 'file.Opl', 'file.oPL', 'file.oPl', 'file.opL', 'file.opl'], + \ 'ora': ['file.ora'], + \ 'org': ['file.org', 'file.org_archive'], + \ 'pamconf': ['/etc/pam.conf', '/etc/pam.d/file', 'any/etc/pam.conf', 'any/etc/pam.d/file'], + \ 'pamenv': ['/etc/security/pam_env.conf', '/home/user/.pam_environment', '.pam_environment', 'pam_env.conf'], + \ 'papp': ['file.papp', 'file.pxml', 'file.pxsl'], + \ 'pascal': ['file.pas', 'file.dpr', 'file.lpr'], + \ 'passwd': ['any/etc/passwd', 'any/etc/passwd-', 'any/etc/passwd.edit', 'any/etc/shadow', 'any/etc/shadow-', 'any/etc/shadow.edit', 'any/var/backups/passwd.bak', 'any/var/backups/shadow.bak', '/etc/passwd', '/etc/passwd-', '/etc/passwd.edit', '/etc/shadow', '/etc/shadow-', '/etc/shadow.edit', '/var/backups/passwd.bak', '/var/backups/shadow.bak'], + \ 'pbtxt': ['file.pbtxt'], + \ 'pccts': ['file.g'], + \ 'pcmk': ['file.pcmk'], + \ 'pdf': ['file.pdf'], + \ 'pem': ['file.pem', 'file.cer', 'file.crt', 'file.csr'], + \ 'perl': ['file.plx', 'file.al', 'file.psgi', 'gitolite.rc', '.gitolite.rc', 'example.gitolite.rc', '.latexmkrc', 'latexmkrc'], + \ 'pf': ['pf.conf'], + \ 'pfmain': ['main.cf', 'main.cf.proto'], + \ 'php': ['file.php', 'file.php9', 'file.phtml', 'file.ctp', 'file.phpt', 'file.theme'], + \ 'pike': ['file.pike', 'file.pmod'], + \ 'pilrc': ['file.rcp'], + \ 'pine': ['.pinerc', 'pinerc', '.pinercex', 'pinercex'], + \ 'pinfo': ['/etc/pinforc', '/.pinforc', 'any/.pinforc', 'any/etc/pinforc'], + \ 'pli': ['file.pli', 'file.pl1'], + \ 'plm': ['file.plm', 'file.p36', 'file.pac'], + \ 'plp': ['file.plp'], + \ 'plsql': ['file.pls', 'file.plsql'], + \ 'po': ['file.po', 'file.pot'], + \ 'pod': ['file.pod'], + \ 'poefilter': ['file.filter'], + \ 'poke': ['file.pk'], + \ 'pony': ['file.pony'], + \ 'postscr': ['file.ps', 'file.pfa', 'file.afm', 'file.eps', 'file.epsf', 'file.epsi', 'file.ai'], + \ 'pov': ['file.pov'], + \ 'povini': ['.povrayrc'], + \ 'ppd': ['file.ppd'], + \ 'ppwiz': ['file.it', 'file.ih'], + \ 'prisma': ['file.prisma'], + \ 'privoxy': ['file.action'], + \ 'proc': ['file.pc'], + \ 'procmail': ['.procmail', '.procmailrc'], + \ 'prolog': ['file.pdb'], + \ 'promela': ['file.pml'], + \ 'proto': ['file.proto'], + \ 'protocols': ['/etc/protocols', 'any/etc/protocols'], + \ 'ps1': ['file.ps1', 'file.psd1', 'file.psm1', 'file.pssc'], + \ 'ps1xml': ['file.ps1xml'], + \ 'psf': ['file.psf'], + \ 'psl': ['file.psl'], + \ 'pug': ['file.pug'], + \ 'puppet': ['file.pp'], + \ 'pymanifest': ['MANIFEST.in'], + \ 'pyret': ['file.arr'], + \ 'pyrex': ['file.pyx', 'file.pxd'], + \ 'python': ['file.py', 'file.pyw', '.pythonstartup', '.pythonrc', 'file.ptl', 'file.pyi', 'SConstruct'], + \ 'ql': ['file.ql', 'file.qll'], + \ 'qml': ['file.qml', 'file.qbs'], + \ 'qmldir': ['qmldir'], + \ 'quake': ['anybaseq2/file.cfg', 'anyid1/file.cfg', 'quake3/file.cfg', 'baseq2/file.cfg', 'id1/file.cfg', 'quake1/file.cfg', 'some-baseq2/file.cfg', 'some-id1/file.cfg', 'some-quake1/file.cfg'], + \ 'quarto': ['file.qmd'], + \ 'r': ['file.r', '.Rprofile', 'Rprofile', 'Rprofile.site'], + \ 'racket': ['file.rkt', 'file.rktd', 'file.rktl'], + \ 'radiance': ['file.rad', 'file.mat'], + \ 'raku': ['file.pm6', 'file.p6', 'file.t6', 'file.pod6', 'file.raku', 'file.rakumod', 'file.rakudoc', 'file.rakutest'], + \ 'raml': ['file.raml'], + \ 'ratpoison': ['.ratpoisonrc', 'ratpoisonrc'], + \ 'rbs': ['file.rbs'], + \ 'rc': ['file.rc', 'file.rch'], + \ 'rcs': ['file,v'], + \ 'readline': ['.inputrc', 'inputrc'], + \ 'rego': ['file.rego'], + \ 'remind': ['.reminders', 'file.remind', 'file.rem', '.reminders-file'], + \ 'requirements': ['file.pip', 'requirements.txt'], + \ 'rescript': ['file.res', 'file.resi'], + \ 'resolv': ['resolv.conf'], + \ 'reva': ['file.frt'], + \ 'rexx': ['file.rex', 'file.orx', 'file.rxo', 'file.rxj', 'file.jrexx', 'file.rexxj', 'file.rexx', 'file.testGroup', 'file.testUnit'], + \ 'rhelp': ['file.rd'], + \ 'rib': ['file.rib'], + \ 'rmd': ['file.rmd', 'file.smd'], + \ 'rnc': ['file.rnc'], + \ 'rng': ['file.rng'], + \ 'rnoweb': ['file.rnw', 'file.snw'], + \ 'rpgle': ['file.rpgle', 'file.rpgleinc'], + \ 'robot': ['file.robot', 'file.resource'], + \ 'robots': ['robots.txt'], + \ 'ron': ['file.ron'], + \ 'routeros': ['file.rsc'], + \ 'rpcgen': ['file.x'], + \ 'rpl': ['file.rpl'], + \ 'rrst': ['file.rrst', 'file.srst'], + \ 'rst': ['file.rst'], + \ 'rtf': ['file.rtf'], + \ 'ruby': ['.irbrc', 'irbrc', 'file.rb', 'file.rbw', 'file.gemspec', 'file.ru', 'Gemfile', 'file.builder', 'file.rxml', 'file.rjs', 'file.rant', 'file.rake', 'rakefile', 'Rakefile', 'rantfile', 'Rantfile', 'rakefile-file', 'Rakefile-file', 'Puppetfile', 'Vagrantfile'], + \ 'rust': ['file.rs'], + \ 'samba': ['smb.conf'], + \ 'sas': ['file.sas'], + \ 'sass': ['file.sass'], + \ 'sather': ['file.sa'], + \ 'sbt': ['file.sbt'], + \ 'scala': ['file.scala'], + \ 'scheme': ['file.scm', 'file.ss', 'file.sld'], + \ 'scilab': ['file.sci', 'file.sce'], + \ 'screen': ['.screenrc', 'screenrc'], + \ 'scss': ['file.scss'], + \ 'sd': ['file.sd'], + \ 'sdc': ['file.sdc'], + \ 'sdl': ['file.sdl', 'file.pr'], + \ 'sed': ['file.sed'], + \ 'sensors': ['/etc/sensors.conf', '/etc/sensors3.conf', '/etc/sensors.d/file', 'any/etc/sensors.conf', 'any/etc/sensors3.conf', 'any/etc/sensors.d/file'], + \ 'services': ['/etc/services', 'any/etc/services'], + \ 'setserial': ['/etc/serial.conf', 'any/etc/serial.conf'], + \ 'sexplib': ['file.sexp'], + \ 'sh': ['.bashrc', '.bash_profile', '.bash-profile', '.bash_logout', '.bash-logout', '.bash_aliases', '.bash-aliases', '/tmp/bash-fc-3Ozjlw', '/tmp/bash-fc.3Ozjlw', 'PKGBUILD', 'APKBUILD', 'file.bash', '/usr/share/doc/bash-completion/filter.sh', '/etc/udev/cdsymlinks.conf', 'any/etc/udev/cdsymlinks.conf'], + \ 'sieve': ['file.siv', 'file.sieve'], + \ 'sil': ['file.sil'], + \ 'simula': ['file.sim'], + \ 'sinda': ['file.sin', 'file.s85'], + \ 'sisu': ['file.sst', 'file.ssm', 'file.ssi', 'file.-sst', 'file._sst', 'file.sst.meta', 'file.-sst.meta', 'file._sst.meta'], + \ 'skill': ['file.il', 'file.ils', 'file.cdf'], + \ 'cdc': ['file.cdc'], + \ 'slang': ['file.sl'], + \ 'sage': ['file.sage'], + \ 'slice': ['file.ice'], + \ 'slpconf': ['/etc/slp.conf', 'any/etc/slp.conf'], + \ 'slpreg': ['/etc/slp.reg', 'any/etc/slp.reg'], + \ 'slpspi': ['/etc/slp.spi', 'any/etc/slp.spi'], + \ 'slrnrc': ['.slrnrc'], + \ 'slrnsc': ['file.score'], + \ 'sm': ['sendmail.cf'], + \ 'smali': ['file.smali'], + \ 'smarty': ['file.tpl'], + \ 'smcl': ['file.hlp', 'file.ihlp', 'file.smcl'], + \ 'smith': ['file.smt', 'file.smith'], + \ 'smithy': ['file.smithy'], + \ 'sml': ['file.sml'], + \ 'snobol4': ['file.sno', 'file.spt'], + \ 'solidity': ['file.sol'], + \ 'solution': ['file.sln'], + \ 'sparql': ['file.rq', 'file.sparql'], + \ 'spec': ['file.spec'], + \ 'spice': ['file.sp', 'file.spice'], + \ 'spup': ['file.speedup', 'file.spdata', 'file.spd'], + \ 'spyce': ['file.spy', 'file.spi'], + \ 'sql': ['file.tyb', 'file.tyc', 'file.pkb', 'file.pks'], + \ 'sqlj': ['file.sqlj'], + \ 'prql': ['file.prql'], + \ 'sqr': ['file.sqr', 'file.sqi'], + \ 'squid': ['squid.conf'], + \ 'squirrel': ['file.nut'], + \ 'srec': ['file.s19', 'file.s28', 'file.s37', 'file.mot', 'file.srec'], + \ 'srt': ['file.srt'], + \ 'ssa': ['file.ass', 'file.ssa'], + \ 'sshconfig': ['ssh_config', '/.ssh/config', '/etc/ssh/ssh_config.d/file.conf', 'any/etc/ssh/ssh_config.d/file.conf', 'any/.ssh/config', 'any/.ssh/file.conf'], + \ 'sshdconfig': ['sshd_config', '/etc/ssh/sshd_config.d/file.conf', 'any/etc/ssh/sshd_config.d/file.conf'], + \ 'st': ['file.st'], + \ 'starlark': ['file.ipd', 'file.star', 'file.starlark'], + \ 'stata': ['file.ado', 'file.do', 'file.imata', 'file.mata'], + \ 'stp': ['file.stp'], + \ 'sudoers': ['any/etc/sudoers', 'sudoers.tmp', '/etc/sudoers', 'any/etc/sudoers.d/file'], + \ 'supercollider': ['file.quark'], + \ 'surface': ['file.sface'], + \ 'svelte': ['file.svelte'], + \ 'svg': ['file.svg'], + \ 'svn': ['svn-commitfile.tmp', 'svn-commit-file.tmp', 'svn-commit.tmp'], + \ 'swayconfig': ['/home/user/.sway/config', '/home/user/.config/sway/config', '/etc/sway/config', '/etc/xdg/sway/config'], + \ 'swift': ['file.swift'], + \ 'swiftgyb': ['file.swift.gyb'], + \ 'swig': ['file.swg', 'file.swig'], + \ 'sysctl': ['/etc/sysctl.conf', '/etc/sysctl.d/file.conf', 'any/etc/sysctl.conf', 'any/etc/sysctl.d/file.conf'], + \ 'systemd': ['any/systemd/file.automount', 'any/systemd/file.dnssd', 'any/systemd/file.link', 'any/systemd/file.mount', 'any/systemd/file.netdev', 'any/systemd/file.network', 'any/systemd/file.nspawn', 'any/systemd/file.path', 'any/systemd/file.service', 'any/systemd/file.slice', 'any/systemd/file.socket', 'any/systemd/file.swap', 'any/systemd/file.target', 'any/systemd/file.timer', '/etc/systemd/some.conf.d/file.conf', '/etc/systemd/system/some.d/file.conf', '/etc/systemd/system/some.d/.#file', '/etc/systemd/system/.#otherfile', '/home/user/.config/systemd/user/some.d/mine.conf', '/home/user/.config/systemd/user/some.d/.#file', '/home/user/.config/systemd/user/.#otherfile', '/.config/systemd/user/.#', '/.config/systemd/user/.#-file', '/.config/systemd/user/file.d/.#', '/.config/systemd/user/file.d/.#-file', '/.config/systemd/user/file.d/file.conf', '/etc/systemd/file.conf.d/file.conf', '/etc/systemd/system/.#', '/etc/systemd/system/.#-file', '/etc/systemd/system/file.d/.#', '/etc/systemd/system/file.d/.#-file', '/etc/systemd/system/file.d/file.conf', '/systemd/file.automount', '/systemd/file.dnssd', '/systemd/file.link', '/systemd/file.mount', '/systemd/file.netdev', '/systemd/file.network', '/systemd/file.nspawn', '/systemd/file.path', '/systemd/file.service', '/systemd/file.slice', '/systemd/file.socket', '/systemd/file.swap', '/systemd/file.target', '/systemd/file.timer', 'any/.config/systemd/user/.#', 'any/.config/systemd/user/.#-file', 'any/.config/systemd/user/file.d/.#', 'any/.config/systemd/user/file.d/.#-file', 'any/.config/systemd/user/file.d/file.conf', 'any/etc/systemd/file.conf.d/file.conf', 'any/etc/systemd/system/.#', 'any/etc/systemd/system/.#-file', 'any/etc/systemd/system/file.d/.#', 'any/etc/systemd/system/file.d/.#-file', 'any/etc/systemd/system/file.d/file.conf'], + \ 'systemverilog': ['file.sv', 'file.svh'], + \ 'trace32': ['file.cmm', 'file.t32'], + \ 'tags': ['tags'], + \ 'tak': ['file.tak'], + \ 'tal': ['file.tal'], + \ 'taskdata': ['pending.data', 'completed.data', 'undo.data'], + \ 'taskedit': ['file.task'], + \ 'tcl': ['file.tcl', 'file.tm', 'file.tk', 'file.itcl', 'file.itk', 'file.jacl', '.tclshrc', 'tclsh.rc', '.wishrc'], + \ 'tablegen': ['file.td'], + \ 'teal': ['file.tl'], + \ 'template': ['file.tmpl'], + \ 'teraterm': ['file.ttl'], + \ 'terminfo': ['file.ti'], + \ 'terraform-vars': ['file.tfvars'], + \ 'tex': ['file.latex', 'file.sty', 'file.dtx', 'file.ltx', 'file.bbl'], + \ 'texinfo': ['file.texinfo', 'file.texi', 'file.txi'], + \ 'texmf': ['texmf.cnf'], + \ 'text': ['file.text', 'file.txt', 'README', 'LICENSE', 'COPYING', 'AUTHORS', '/usr/share/doc/bash-completion/AUTHORS', '/etc/apt/apt.conf.d/README', '/etc/Muttrc.d/README'], + \ 'tf': ['file.tf', '.tfrc', 'tfrc'], + \ 'thrift': ['file.thrift'], + \ 'tidy': ['.tidyrc', 'tidyrc', 'tidy.conf'], + \ 'tilde': ['file.t.html'], + \ 'tla': ['file.tla'], + \ 'tli': ['file.tli'], + \ 'tmux': ['tmuxfile.conf', '.tmuxfile.conf', '.tmux-file.conf', '.tmux.conf', 'tmux-file.conf', 'tmux.conf', 'tmux.conf.local'], + \ 'toml': ['file.toml', 'Gopkg.lock', 'Pipfile', '/home/user/.cargo/config'], + \ 'tpp': ['file.tpp'], + \ 'treetop': ['file.treetop'], + \ 'trustees': ['trustees.conf'], + \ 'tsalt': ['file.slt'], + \ 'tsscl': ['file.tsscl'], + \ 'tssgm': ['file.tssgm'], + \ 'tssop': ['file.tssop'], + \ 'tsv': ['file.tsv'], + \ 'twig': ['file.twig'], + \ 'typescript': ['file.mts', 'file.cts'], + \ 'typescript.glimmer': ['file.gts'], + \ 'typescriptreact': ['file.tsx'], + \ 'ungrammar': ['file.ungram'], + \ 'uc': ['file.uc'], + \ 'udevconf': ['/etc/udev/udev.conf', 'any/etc/udev/udev.conf'], + \ 'udevperm': ['/etc/udev/permissions.d/file.permissions', 'any/etc/udev/permissions.d/file.permissions'], + \ 'udevrules': ['/etc/udev/rules.d/file.rules', '/usr/lib/udev/rules.d/file.rules', '/lib/udev/rules.d/file.rules'], + \ 'uil': ['file.uit', 'file.uil'], + \ 'unison': ['file.u', 'file.uu'], + \ 'updatedb': ['/etc/updatedb.conf', 'any/etc/updatedb.conf'], + \ 'upstart': ['/usr/share/upstart/file.conf', '/usr/share/upstart/file.override', '/etc/init/file.conf', '/etc/init/file.override', '/.init/file.conf', '/.init/file.override', '/.config/upstart/file.conf', '/.config/upstart/file.override', 'any/.config/upstart/file.conf', 'any/.config/upstart/file.override', 'any/.init/file.conf', 'any/.init/file.override', 'any/etc/init/file.conf', 'any/etc/init/file.override', 'any/usr/share/upstart/file.conf', 'any/usr/share/upstart/file.override'], + \ 'upstreamdat': ['upstream.dat', 'UPSTREAM.DAT', 'upstream.file.dat', 'UPSTREAM.FILE.DAT', 'file.upstream.dat', 'FILE.UPSTREAM.DAT'], + \ 'upstreaminstalllog': ['upstreaminstall.log', 'UPSTREAMINSTALL.LOG', 'upstreaminstall.file.log', 'UPSTREAMINSTALL.FILE.LOG', 'file.upstreaminstall.log', 'FILE.UPSTREAMINSTALL.LOG'], + \ 'upstreamlog': ['fdrupstream.log', 'upstream.log', 'UPSTREAM.LOG', 'upstream.file.log', 'UPSTREAM.FILE.LOG', 'file.upstream.log', 'FILE.UPSTREAM.LOG', 'UPSTREAM-file.log', 'UPSTREAM-FILE.LOG'], + \ 'urlshortcut': ['file.url'], + \ 'usd': ['file.usda', 'file.usd'], + \ 'usserverlog': ['usserver.log', 'USSERVER.LOG', 'usserver.file.log', 'USSERVER.FILE.LOG', 'file.usserver.log', 'FILE.USSERVER.LOG'], + \ 'usw2kagtlog': ['usw2kagt.log', 'USW2KAGT.LOG', 'usw2kagt.file.log', 'USW2KAGT.FILE.LOG', 'file.usw2kagt.log', 'FILE.USW2KAGT.LOG'], + \ 'v': ['file.vsh', 'file.vv'], + \ 'vala': ['file.vala'], + \ 'vb': ['file.sba', 'file.vb', 'file.vbs', 'file.dsm', 'file.ctl', 'file.dob', 'file.dsr'], + \ 'vdf': ['file.vdf'], + \ 'vdmpp': ['file.vpp', 'file.vdmpp'], + \ 'vdmrt': ['file.vdmrt'], + \ 'vdmsl': ['file.vdm', 'file.vdmsl'], + \ 'vera': ['file.vr', 'file.vri', 'file.vrh'], + \ 'verilogams': ['file.va', 'file.vams'], + \ 'vgrindefs': ['vgrindefs'], + \ 'vhdl': ['file.hdl', 'file.vhd', 'file.vhdl', 'file.vbe', 'file.vst', 'file.vhdl_123', 'file.vho', 'some.vhdl_1', 'some.vhdl_1-file'], + \ 'vhs': ['file.tape'], + \ 'vim': ['file.vim', '.exrc', '_exrc', 'some-vimrc', 'some-vimrc-file', 'vimrc', 'vimrc-file'], + \ 'viminfo': ['.viminfo', '_viminfo'], + \ 'vmasm': ['file.mar'], + \ 'voscm': ['file.cm'], + \ 'vrml': ['file.wrl'], + \ 'vroom': ['file.vroom'], + \ 'vue': ['file.vue'], + \ 'wat': ['file.wat', 'file.wast'], + \ 'wdl': ['file.wdl'], + \ 'webmacro': ['file.wm'], + \ 'wget': ['.wgetrc', 'wgetrc'], + \ 'wget2': ['.wget2rc', 'wget2rc'], + \ 'wgsl': ['file.wgsl'], + \ 'winbatch': ['file.wbt'], + \ 'wit': ['file.wit'], + \ 'wml': ['file.wml'], + \ 'wsh': ['file.wsf', 'file.wsc'], + \ 'wsml': ['file.wsml'], + \ 'wvdial': ['wvdial.conf', '.wvdialrc'], + \ 'xcompose': ['.XCompose', 'Compose'], + \ 'xdefaults': ['.Xdefaults', '.Xpdefaults', '.Xresources', 'xdm-config', 'file.ad', '/Xresources/file', '/app-defaults/file', 'Xresources', 'Xresources-file', 'any/Xresources/file', 'any/app-defaults/file'], + \ 'xf86conf': ['xorg.conf', 'xorg.conf-4'], + \ 'xhtml': ['file.xhtml', 'file.xht'], + \ 'xinetd': ['/etc/xinetd.conf', '/etc/xinetd.d/file', 'any/etc/xinetd.conf', 'any/etc/xinetd.d/file'], + \ 'xkb': ['/usr/share/X11/xkb/compat/pc', '/usr/share/X11/xkb/geometry/pc', '/usr/share/X11/xkb/keycodes/evdev', '/usr/share/X11/xkb/symbols/pc', '/usr/share/X11/xkb/types/pc'], + \ 'xmath': ['file.msc', 'file.msf'], + \ 'xml': ['/etc/blkid.tab', '/etc/blkid.tab.old', 'file.xmi', 'file.csproj', 'file.csproj.user', 'file.fsproj', 'file.fsproj.user', 'file.vbproj', 'file.vbproj.user', 'file.ui', 'file.tpm', '/etc/xdg/menus/file.menu', 'fglrxrc', 'file.xlf', 'file.xliff', 'file.xul', 'file.wsdl', 'file.wpl', 'any/etc/blkid.tab', 'any/etc/blkid.tab.old', 'any/etc/xdg/menus/file.menu', 'file.atom', 'file.rss', 'file.cdxml', 'file.psc1', 'file.mpd'], + \ 'xmodmap': ['anyXmodmap', 'Xmodmap', 'some-Xmodmap', 'some-xmodmap', 'some-xmodmap-file', 'xmodmap', 'xmodmap-file'], + \ 'xpm': ['file.xpm'], + \ 'xpm2': ['file.xpm2'], + \ 'xquery': ['file.xq', 'file.xql', 'file.xqm', 'file.xquery', 'file.xqy'], + \ 'xs': ['file.xs'], + \ 'xsd': ['file.xsd'], + \ 'xslt': ['file.xsl', 'file.xslt'], + \ 'yacc': ['file.yy', 'file.yxx', 'file.y++'], + \ 'yaml': ['file.yaml', 'file.yml', 'file.eyaml', '.clangd', '.clang-format', '.clang-tidy'], + \ 'yang': ['file.yang'], + \ 'yuck': ['file.yuck'], + \ 'z8a': ['file.z8a'], + \ 'zig': ['file.zig', 'build.zig.zon'], + \ 'zimbu': ['file.zu'], + \ 'zimbutempl': ['file.zut'], + \ 'zserio': ['file.zs'], + \ 'zsh': ['.zprofile', '/etc/zprofile', '.zfbfmarks', 'file.zsh', '.zcompdump', '.zlogin', '.zlogout', '.zshenv', '.zshrc', '.zcompdump-file', '.zlog', '.zlog-file', '.zsh', '.zsh-file', 'any/etc/zprofile', 'zlog', 'zlog-file', 'zsh', 'zsh-file'], + \ + \ 'help': [$VIMRUNTIME . '/doc/help.txt'], + \ } +endfunc + +let s:filename_case_checks = { + \ 'modula2': ['file.DEF'], + \ 'bzl': ['file.BUILD', 'BUILD', 'BUCK'], + \ } + +func CheckItems(checks) + set noswapfile + for [ft, names] in items(a:checks) + for i in range(0, len(names) - 1) + new + try + exe 'edit ' .. fnameescape(names[i]) + catch + call assert_report('cannot edit "' .. names[i] .. '": ' .. v:exception) + endtry + if &filetype == '' && &readonly + " File exists but not able to edit it (permission denied) + else + let expected = ft == 'none' ? '' : ft + call assert_equal(expected, &filetype, 'with file name: ' .. names[i]) + endif + bwipe! + endfor + endfor + + set swapfile& +endfunc + +func Test_filetype_detection() + call s:SetupConfigHome() + if !empty(s:saveConfigHome) + defer setenv("XDG_CONFIG_HOME", s:saveConfigHome) + endif + call mkdir(s:GetConfigHome(), 'R') + + filetype on + call CheckItems(s:GetFilenameChecks()) + if has('fname_case') + call CheckItems(s:filename_case_checks) + endif + filetype off +endfunc + +" Content lines that should not result in filetype detection +let s:false_positive_checks = { + \ '': [['test execve("/usr/bin/pstree", ["pstree"], 0x7ff0 /* 63 vars */) = 0']], + \ } + +" Filetypes detected from the file contents by scripts.vim +let s:script_checks = { + \ 'virata': [['% Virata'], + \ ['', '% Virata'], + \ ['', '', '% Virata'], + \ ['', '', '', '% Virata'], + \ ['', '', '', '', '% Virata']], + \ 'strace': [['execve("/usr/bin/pstree", ["pstree"], 0x7ff0 /* 63 vars */) = 0'], + \ ['15:17:47 execve("/usr/bin/pstree", ["pstree"], ... "_=/usr/bin/strace"]) = 0'], + \ ['__libc_start_main and something']], + \ 'clojure': [['#!/path/clojure']], + \ 'scala': [['#!/path/scala']], + \ 'sh': [['#!/path/sh'], + \ ['#!/path/bash'], + \ ['#!/path/bash2'], + \ ['#!/path/dash'], + \ ['#!/path/ksh'], + \ ['#!/path/ksh93']], + \ 'csh': [['#!/path/csh']], + \ 'tcsh': [['#!/path/tcsh']], + \ 'zsh': [['#!/path/zsh']], + \ 'tcl': [['#!/path/tclsh'], + \ ['#!/path/wish'], + \ ['#!/path/expectk'], + \ ['#!/path/itclsh'], + \ ['#!/path/itkwish']], + \ 'expect': [['#!/path/expect']], + \ 'gnuplot': [['#!/path/gnuplot']], + \ 'make': [['#!/path/make']], + \ 'nix': [['#!/path/nix-shell']], + \ 'pike': [['#!/path/pike'], + \ ['#!/path/pike0'], + \ ['#!/path/pike9']], + \ 'lua': [['#!/path/lua']], + \ 'raku': [['#!/path/raku']], + \ 'perl': [['#!/path/perl']], + \ 'php': [['#!/path/php']], + \ 'python': [['#!/path/python'], + \ ['#!/path/python2'], + \ ['#!/path/python3']], + \ 'groovy': [['#!/path/groovy']], + \ 'ruby': [['#!/path/ruby']], + \ 'javascript': [['#!/path/node'], + \ ['#!/path/js'], + \ ['#!/path/nodejs'], + \ ['#!/path/rhino']], + \ 'bc': [['#!/path/bc']], + \ 'sed': [['#!/path/sed'], ['#n'], ['#n comment']], + \ 'ocaml': [['#!/path/ocaml']], + \ 'awk': [['#!/path/awk'], + \ ['#!/path/gawk']], + \ 'wml': [['#!/path/wml']], + \ 'scheme': [['#!/path/scheme'], + \ ['#!/path/guile']], + \ 'cfengine': [['#!/path/cfengine']], + \ 'erlang': [['#!/path/escript']], + \ 'haskell': [['#!/path/haskell']], + \ 'cpp': [['// Standard iostream objects -*- C++ -*-'], + \ ['// -*- C++ -*-']], + \ 'yaml': [['%YAML 1.2']], + \ 'pascal': [['#!/path/instantfpc']], + \ 'fennel': [['#!/path/fennel']], + \ 'routeros': [['#!/path/rsc']], + \ 'fish': [['#!/path/fish']], + \ 'forth': [['#!/path/gforth']], + \ 'icon': [['#!/path/icon']], + \ 'crystal': [['#!/path/crystal']], + \ 'rexx': [['#!/path/rexx'], + \ ['#!/path/regina']], + \ 'janet': [['#!/path/janet']], + \ 'dart': [['#!/path/dart']], + \ } + +" Various forms of "env" optional arguments. +let s:script_env_checks = { + \ 'perl': [['#!/usr/bin/env VAR=val perl']], + \ 'scala': [['#!/usr/bin/env VAR=val VVAR=vval scala']], + \ 'awk': [['#!/usr/bin/env VAR=val -i awk']], + \ 'scheme': [['#!/usr/bin/env VAR=val --ignore-environment scheme']], + \ 'python': [['#!/usr/bin/env VAR=val -S python -w -T']], + \ 'wml': [['#!/usr/bin/env VAR=val --split-string wml']], + \ 'nix': [['#!/usr/bin/env nix-shell']], + \ } + +func Run_script_detection(test_dict) + filetype on + for [ft, files] in items(a:test_dict) + for file in files + call writefile(file, 'Xtest', 'D') + split Xtest + call assert_equal(ft, &filetype, 'for text: ' . string(file)) + bwipe! + endfor + endfor + filetype off +endfunc + +func Test_script_detection() + call Run_script_detection(s:false_positive_checks) + call Run_script_detection(s:script_checks) + call Run_script_detection(s:script_env_checks) +endfunc + +func Test_setfiletype_completion() + call feedkeys(":setfiletype java\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"setfiletype java javacc javascript javascriptreact', @:) +endfunc + +" Test for ':filetype detect' command for a buffer without a file +func Test_emptybuf_ftdetect() + new + call setline(1, '#!/bin/sh') + call assert_equal('', &filetype) + filetype detect + call assert_equal('sh', &filetype) + close! +endfunc + +" Test for ':filetype indent on' and ':filetype indent off' commands +func Test_filetype_indent_off() + new Xtest.vim + filetype indent on + call assert_equal(1, g:did_indent_on) + call assert_equal(['filetype detection:ON plugin:OFF indent:ON'], + \ execute('filetype')->split("\n")) + filetype indent off + call assert_equal(0, exists('g:did_indent_on')) + call assert_equal(['filetype detection:ON plugin:OFF indent:OFF'], + \ execute('filetype')->split("\n")) + close +endfunc + +""""""""""""""""""""""""""""""""""""""""""""""""" +" Tests for specific extensions and filetypes. +" Keep sorted. +""""""""""""""""""""""""""""""""""""""""""""""""" + +func Test_bas_file() + filetype on + + call writefile(['looks like BASIC'], 'Xfile.bas', 'D') + split Xfile.bas + call assert_equal('basic', &filetype) + bwipe! + + " Test dist#ft#FTbas() + + let g:filetype_bas = 'freebasic' + split Xfile.bas + call assert_equal('freebasic', &filetype) + bwipe! + unlet g:filetype_bas + + " FreeBASIC + + call writefile(["/' FreeBASIC multiline comment '/"], 'Xfile.bas') + split Xfile.bas + call assert_equal('freebasic', &filetype) + bwipe! + + call writefile(['#define TESTING'], 'Xfile.bas') + split Xfile.bas + call assert_equal('freebasic', &filetype) + bwipe! + + call writefile(['option byval'], 'Xfile.bas') + split Xfile.bas + call assert_equal('freebasic', &filetype) + bwipe! + + call writefile(['extern "C"'], 'Xfile.bas') + split Xfile.bas + call assert_equal('freebasic', &filetype) + bwipe! + + " QB64 + + call writefile(['$LET TESTING = 1'], 'Xfile.bas') + split Xfile.bas + call assert_equal('qb64', &filetype) + bwipe! + + call writefile(['OPTION _EXPLICIT'], 'Xfile.bas') + split Xfile.bas + call assert_equal('qb64', &filetype) + bwipe! + + " Visual Basic + + call writefile(['Attribute VB_NAME = "Testing"', 'Enum Foo', 'End Enum'], 'Xfile.bas') + split Xfile.bas + call assert_equal('vb', &filetype) + bwipe! + + filetype off +endfunc + +" Test dist#ft#FTcfg() +func Test_cfg_file() + filetype on + + " *.cfg defaults to cfg + call writefile(['looks like cfg'], 'cfgfile.cfg', 'D') + split cfgfile.cfg + call assert_equal('cfg', &filetype) + + let g:filetype_cfg = 'other' + edit + call assert_equal('other', &filetype) + bwipe! + unlet g:filetype_cfg + + " RAPID cfg + let ext = 'cfg' + for i in ['EIO', 'MMC', 'MOC', 'PROC', 'SIO', 'SYS'] + call writefile([i .. ':CFG'], 'cfgfile.' .. ext) + execute "split cfgfile." .. ext + call assert_equal('rapid', &filetype) + bwipe! + call delete('cfgfile.' .. ext) + " check different case of file extension + let ext = substitute(ext, '\(\l\)', '\u\1', '') + endfor + + " clean up + filetype off +endfunc + +func Test_d_file() + filetype on + + call writefile(['looks like D'], 'Xfile.d', 'D') + split Xfile.d + call assert_equal('d', &filetype) + bwipe! + + call writefile(['#!/some/bin/dtrace'], 'Xfile.d') + split Xfile.d + call assert_equal('dtrace', &filetype) + bwipe! + + call writefile(['#pragma D option'], 'Xfile.d') + split Xfile.d + call assert_equal('dtrace', &filetype) + bwipe! + + call writefile([':some:thing:'], 'Xfile.d') + split Xfile.d + call assert_equal('dtrace', &filetype) + bwipe! + + call writefile(['module this', '#pragma D option'], 'Xfile.d') + split Xfile.d + call assert_equal('d', &filetype) + bwipe! + + call writefile(['import that', '#pragma D option'], 'Xfile.d') + split Xfile.d + call assert_equal('d', &filetype) + bwipe! + + " clean up + filetype off +endfunc + +func Test_dat_file() + filetype on + + " KRL header start with "&WORD", but is not always present. + call writefile(['&ACCESS'], 'datfile.dat') + split datfile.dat + call assert_equal('krl', &filetype) + bwipe! + call delete('datfile.dat') + + " KRL defdat with leading spaces, for KRL file extension is not case + " sensitive. + call writefile([' DEFDAT datfile'], 'datfile.Dat') + split datfile.Dat + call assert_equal('krl', &filetype) + bwipe! + call delete('datfile.Dat') + + " KRL defdat with embedded spaces, file starts with empty line(s). + call writefile(['', 'defdat datfile public'], 'datfile.DAT') + split datfile.DAT + call assert_equal('krl', &filetype) + bwipe! + + " User may overrule file inspection + let g:filetype_dat = 'dat' + split datfile.DAT + call assert_equal('dat', &filetype) + bwipe! + call delete('datfile.DAT') + unlet g:filetype_dat + + filetype off +endfunc + +func Test_dep3patch_file() + filetype on + + call assert_true(mkdir('debian/patches', 'pR')) + + " series files are not patches + call writefile(['Description: some awesome patch'], 'debian/patches/series') + split debian/patches/series + call assert_notequal('dep3patch', &filetype) + bwipe! + + " diff/patch files without the right headers should still show up as ft=diff + call writefile([], 'debian/patches/foo.diff') + split debian/patches/foo.diff + call assert_equal('diff', &filetype) + bwipe! + + " Files with the right headers are detected as dep3patch, even if they don't + " have a diff/patch extension + call writefile(['Subject: dep3patches'], 'debian/patches/bar') + split debian/patches/bar + call assert_equal('dep3patch', &filetype) + bwipe! + + " Files in sub-directories are detected + call assert_true(mkdir('debian/patches/s390x', 'p')) + call writefile(['Subject: dep3patches'], 'debian/patches/s390x/bar') + split debian/patches/s390x/bar + call assert_equal('dep3patch', &filetype) + bwipe! + + " The detection stops when seeing the "header end" marker + call writefile(['---', 'Origin: the cloud'], 'debian/patches/baz') + split debian/patches/baz + call assert_notequal('dep3patch', &filetype) + bwipe! +endfunc + +func Test_dsl_file() + filetype on + + call writefile([' <!doctype dsssl-spec ['], 'dslfile.dsl', 'D') + split dslfile.dsl + call assert_equal('dsl', &filetype) + bwipe! + + call writefile(['workspace {'], 'dslfile.dsl') + split dslfile.dsl + call assert_equal('structurizr', &filetype) + bwipe! + + filetype off +endfunc + +func Test_ex_file() + filetype on + + call writefile(['arbitrary content'], 'Xfile.ex', 'D') + split Xfile.ex + call assert_equal('elixir', &filetype) + bwipe! + let g:filetype_euphoria = 'euphoria4' + split Xfile.ex + call assert_equal('euphoria4', &filetype) + bwipe! + unlet g:filetype_euphoria + + call writefile(['-- filetype euphoria comment'], 'Xfile.ex') + split Xfile.ex + call assert_equal('euphoria3', &filetype) + bwipe! + + call writefile(['--filetype euphoria comment'], 'Xfile.ex') + split Xfile.ex + call assert_equal('euphoria3', &filetype) + bwipe! + + call writefile(['ifdef '], 'Xfile.ex') + split Xfile.ex + call assert_equal('euphoria3', &filetype) + bwipe! + + call writefile(['include '], 'Xfile.ex') + split Xfile.ex + call assert_equal('euphoria3', &filetype) + bwipe! + + filetype off +endfunc + +func Test_f_file() + filetype on + + call writefile(['looks like Fortran'], 'Xfile.f', 'D') + split Xfile.f + call assert_equal('fortran', &filetype) + bwipe! + + let g:filetype_f = 'forth' + split Xfile.f + call assert_equal('forth', &filetype) + bwipe! + unlet g:filetype_f + + " Test dist#ft#FTf() + + " Forth + + call writefile(['( Forth inline comment )'], 'Xfile.f') + split Xfile.f + call assert_equal('forth', &filetype) + bwipe! + + call writefile(['\ Forth line comment'], 'Xfile.f') + split Xfile.f + call assert_equal('forth', &filetype) + bwipe! + + call writefile([': squared ( n -- n^2 )', 'dup * ;'], 'Xfile.f') + split Xfile.f + call assert_equal('forth', &filetype) + bwipe! + + " SwiftForth + + call writefile(['{ ================', 'Header comment', '================ }'], 'Xfile.f') + split Xfile.f + call assert_equal('forth', &filetype) + bwipe! + + call writefile(['OPTIONAL Maybe Descriptive text'], 'Xfile.f') + split Xfile.f + call assert_equal('forth', &filetype) + bwipe! + + filetype off +endfunc + +func Test_foam_file() + filetype on + call assert_true(mkdir('0', 'pR')) + call assert_true(mkdir('0.orig', 'pR')) + + call writefile(['FoamFile {', ' object something;'], 'Xfile1Dict', 'D') + split Xfile1Dict + call assert_equal('foam', &filetype) + bwipe! + + call writefile(['FoamFile {', ' object something;'], 'Xfile1Dict.something', 'D') + split Xfile1Dict.something + call assert_equal('foam', &filetype) + bwipe! + + call writefile(['FoamFile {', ' object something;'], 'XfileProperties', 'D') + split XfileProperties + call assert_equal('foam', &filetype) + bwipe! + + call writefile(['FoamFile {', ' object something;'], 'XfileProperties.something', 'D') + split XfileProperties.something + call assert_equal('foam', &filetype) + bwipe! + + call writefile(['FoamFile {', ' object something;'], 'XfileProperties') + split XfileProperties + call assert_equal('foam', &filetype) + bwipe! + + call writefile(['FoamFile {', ' object something;'], 'XfileProperties.something') + split XfileProperties.something + call assert_equal('foam', &filetype) + bwipe! + + call writefile(['FoamFile {', ' object something;'], '0/Xfile') + split 0/Xfile + call assert_equal('foam', &filetype) + bwipe! + + call writefile(['FoamFile {', ' object something;'], '0.orig/Xfile') + split 0.orig/Xfile + call assert_equal('foam', &filetype) + bwipe! + + filetype off +endfunc + +func Test_frm_file() + filetype on + + call writefile(['looks like FORM'], 'Xfile.frm', 'D') + split Xfile.frm + call assert_equal('form', &filetype) + bwipe! + + " Test dist#ft#FTfrm() + + let g:filetype_frm = 'form' + split Xfile.frm + call assert_equal('form', &filetype) + bwipe! + unlet g:filetype_frm + + " Visual Basic + + call writefile(['VERSION 5.00', 'Begin VB.Form Form1'], 'Xfile.frm') + split Xfile.frm + call assert_equal('vb', &filetype) + bwipe! + + filetype off +endfunc + +func Test_fs_file() + filetype on + + call writefile(['looks like F#'], 'Xfile.fs', 'D') + split Xfile.fs + call assert_equal('fsharp', &filetype) + bwipe! + + let g:filetype_fs = 'forth' + split Xfile.fs + call assert_equal('forth', &filetype) + bwipe! + unlet g:filetype_fs + + " Test dist#ft#FTfs() + + " Forth + + call writefile(['( Forth inline comment )'], 'Xfile.fs') + split Xfile.fs + call assert_equal('forth', &filetype) + bwipe! + + call writefile(['\ Forth line comment'], 'Xfile.fs') + split Xfile.fs + call assert_equal('forth', &filetype) + bwipe! + + call writefile([': squared ( n -- n^2 )', 'dup * ;'], 'Xfile.fs') + split Xfile.fs + call assert_equal('forth', &filetype) + bwipe! + + " SwiftForth + + call writefile(['{ ================', 'Header comment', '================ }'], 'Xfile.fs') + split Xfile.fs + call assert_equal('forth', &filetype) + bwipe! + + call writefile(['OPTIONAL Maybe Descriptive text'], 'Xfile.fs') + split Xfile.fs + call assert_equal('forth', &filetype) + bwipe! + + filetype off +endfunc + +func Test_git_file() + filetype on + + call assert_true(mkdir('Xrepo.git', 'pR')) + + call writefile([], 'Xrepo.git/HEAD') + split Xrepo.git/HEAD + call assert_equal('', &filetype) + bwipe! + + call writefile(['0000000000000000000000000000000000000000'], 'Xrepo.git/HEAD') + split Xrepo.git/HEAD + call assert_equal('git', &filetype) + bwipe! + + call writefile(['0000000000000000000000000000000000000000000000000000000000000000'], 'Xrepo.git/HEAD') + split Xrepo.git/HEAD + call assert_equal('git', &filetype) + bwipe! + + call writefile(['ref: refs/heads/master'], 'Xrepo.git/HEAD') + split Xrepo.git/HEAD + call assert_equal('git', &filetype) + bwipe! + + filetype off +endfunc + +func Test_hook_file() + filetype on + + call writefile(['[Trigger]', 'this is pacman config'], 'Xfile.hook', 'D') + split Xfile.hook + call assert_equal('confini', &filetype) + bwipe! + + call writefile(['not pacman'], 'Xfile.hook') + split Xfile.hook + call assert_notequal('confini', &filetype) + bwipe! + + filetype off +endfunc + +func Test_m_file() + filetype on + + call writefile(['looks like Matlab'], 'Xfile.m', 'D') + split Xfile.m + call assert_equal('matlab', &filetype) + bwipe! + + let g:filetype_m = 'octave' + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + unlet g:filetype_m + + " Test dist#ft#FTm() + + " Objective-C + + call writefile(['// Objective-C line comment'], 'Xfile.m') + split Xfile.m + call assert_equal('objc', &filetype) + bwipe! + + call writefile(['/* Objective-C block comment */'], 'Xfile.m') + split Xfile.m + call assert_equal('objc', &filetype) + bwipe! + + call writefile(['#import "test.m"'], 'Xfile.m') + split Xfile.m + call assert_equal('objc', &filetype) + bwipe! + + call writefile(['#include <header.h>'], 'Xfile.m') + split Xfile.m + call assert_equal('objc', &filetype) + bwipe! + + call writefile(['#define FORTY_TWO'], 'Xfile.m') + split Xfile.m + call assert_equal('objc', &filetype) + bwipe! + + " Octave + + call writefile(['# Octave line comment'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + call writefile(['%!test "Octave test"'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + call writefile(['unwind_protect'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + call writefile(['try; 42; end_try_catch'], 'Xfile.m') + split Xfile.m + call assert_equal('octave', &filetype) + bwipe! + + " Mathematica + + call writefile(['(* Mathematica comment'], 'Xfile.m') + split Xfile.m + call assert_equal('mma', &filetype) + bwipe! + + " MATLAB + + call writefile(['% MATLAB line comment'], 'Xfile.m') + split Xfile.m + call assert_equal('matlab', &filetype) + bwipe! + + " Murphi + + call writefile(['-- Murphi comment'], 'Xfile.m') + split Xfile.m + call assert_equal('murphi', &filetype) + bwipe! + + call writefile(['/* Murphi block comment */', 'Type'], 'Xfile.m') + split Xfile.m + call assert_equal('murphi', &filetype) + bwipe! + + call writefile(['Type'], 'Xfile.m') + split Xfile.m + call assert_equal('murphi', &filetype) + bwipe! + + filetype off +endfunc + +func Test_mod_file() + filetype on + + " *.mod defaults to Modsim III + call writefile(['locks like Modsim III'], 'modfile.mod') + split modfile.mod + call assert_equal('modsim3', &filetype) + bwipe! + + " Users preference set by g:filetype_mod + let g:filetype_mod = 'lprolog' + split modfile.mod + call assert_equal('lprolog', &filetype) + unlet g:filetype_mod + bwipe! + + " RAPID header start with a line containing only "%%%", + " but is not always present. + call writefile(['%%%'], 'modfile.mod') + split modfile.mod + call assert_equal('rapid', &filetype) + bwipe! + call delete('modfile.mod') + + " RAPID supports umlauts in module names, leading spaces, + " the .mod extension is not case sensitive. + call writefile([' module ÜmlautModule'], 'modfile.Mod') + split modfile.Mod + call assert_equal('rapid', &filetype) + bwipe! + call delete('modfile.Mod') + + " RAPID is not case sensitive, embedded spaces, sysmodule, + " file starts with empty line(s). + call writefile(['', 'MODULE rapidmödüle (SYSMODULE,NOSTEPIN)'], 'modfile.MOD') + split modfile.MOD + call assert_equal('rapid', &filetype) + bwipe! + + " Modula-2 MODULE not start of line + call writefile(['IMPLEMENTATION MODULE Module2Mod;'], 'modfile.MOD') + split modfile.MOD + call assert_equal('modula2', &filetype) + bwipe! + + " Modula-2 with comment and empty lines prior MODULE + call writefile(['', '(* with', ' comment *)', '', 'MODULE Module2Mod;'], 'modfile.MOD') + split modfile.MOD + call assert_equal('modula2', &filetype) + bwipe! + call delete('modfile.MOD') + + " LambdaProlog module + call writefile(['module lpromod.'], 'modfile.mod') + split modfile.mod + call assert_equal('lprolog', &filetype) + bwipe! + + " LambdaProlog with comment and empty lines prior module + call writefile(['', '% with', '% comment', '', 'module lpromod.'], 'modfile.mod') + split modfile.mod + call assert_equal('lprolog', &filetype) + bwipe! + call delete('modfile.mod') + + " go.mod + call writefile(['module example.com/M'], 'go.mod') + split go.mod + call assert_equal('gomod', &filetype) + bwipe! + call delete('go.mod') + + call writefile(['module M'], 'go.mod') + split go.mod + call assert_equal('gomod', &filetype) + bwipe! + call delete('go.mod') + + filetype off +endfunc + +func Test_patch_file() + filetype on + + call writefile([], 'Xfile.patch', 'D') + split Xfile.patch + call assert_equal('diff', &filetype) + bwipe! + + call writefile(['From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001'], 'Xfile.patch') + split Xfile.patch + call assert_equal('gitsendemail', &filetype) + bwipe! + + call writefile(['From 0000000000000000000000000000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001'], 'Xfile.patch') + split Xfile.patch + call assert_equal('gitsendemail', &filetype) + bwipe! + + filetype off +endfunc + +func Test_perl_file() + filetype on + + " only tests one case, should do more + let lines =<< trim END + + use a + END + call writefile(lines, "Xfile.t", 'D') + split Xfile.t + call assert_equal('perl', &filetype) + bwipe + + filetype off +endfunc + +func Test_pp_file() + filetype on + + call writefile(['looks like puppet'], 'Xfile.pp', 'D') + split Xfile.pp + call assert_equal('puppet', &filetype) + bwipe! + + let g:filetype_pp = 'pascal' + split Xfile.pp + call assert_equal('pascal', &filetype) + bwipe! + unlet g:filetype_pp + + " Test dist#ft#FTpp() + call writefile(['{ pascal comment'], 'Xfile.pp') + split Xfile.pp + call assert_equal('pascal', &filetype) + bwipe! + + call writefile(['procedure pascal'], 'Xfile.pp') + split Xfile.pp + call assert_equal('pascal', &filetype) + bwipe! + + filetype off +endfunc + +" Test dist#ft#FTprg() +func Test_prg_file() + filetype on + + " *.prg defaults to clipper + call writefile(['looks like clipper'], 'prgfile.prg') + split prgfile.prg + call assert_equal('clipper', &filetype) + bwipe! + + " Users preference set by g:filetype_prg + let g:filetype_prg = 'eviews' + split prgfile.prg + call assert_equal('eviews', &filetype) + unlet g:filetype_prg + bwipe! + + " RAPID header start with a line containing only "%%%", + " but is not always present. + call writefile(['%%%'], 'prgfile.prg') + split prgfile.prg + call assert_equal('rapid', &filetype) + bwipe! + call delete('prgfile.prg') + + " RAPID supports umlauts in module names, leading spaces, + " the .prg extension is not case sensitive. + call writefile([' module ÜmlautModule'], 'prgfile.Prg') + split prgfile.Prg + call assert_equal('rapid', &filetype) + bwipe! + call delete('prgfile.Prg') + + " RAPID is not case sensitive, embedded spaces, sysmodule, + " file starts with empty line(s). + call writefile(['', 'MODULE rapidmödüle (SYSMODULE,NOSTEPIN)'], 'prgfile.PRG') + split prgfile.PRG + call assert_equal('rapid', &filetype) + bwipe! + call delete('prgfile.PRG') + + filetype off +endfunc + +" Test dist#ft#FTsc() +func Test_sc_file() + filetype on + + " SC classes are defined with '+ Class {}' + call writefile(['+ SCNvim {', '*methodArgs {|method|'], 'srcfile.sc') + split srcfile.sc + call assert_equal('supercollider', &filetype) + bwipe! + call delete('srcfile.sc') + + " Some SC class files start with comment and define methods many lines later + call writefile(['// Query', '//Method','^this {'], 'srcfile.sc') + split srcfile.sc + call assert_equal('supercollider', &filetype) + bwipe! + call delete('srcfile.sc') + + " Some SC class files put comments between method declaration after class + call writefile(['PingPong {', '//comment','*ar { arg'], 'srcfile.sc') + split srcfile.sc + call assert_equal('supercollider', &filetype) + bwipe! + call delete('srcfile.sc') + + filetype off +endfunc + +" Test dist#ft#FTscd() +func Test_scd_file() + filetype on + + call writefile(['ijq(1)'], 'srcfile.scd', 'D') + split srcfile.scd + call assert_equal('scdoc', &filetype) + + bwipe! + filetype off +endfunc + +func Test_src_file() + filetype on + + " KRL header start with "&WORD", but is not always present. + call writefile(['&ACCESS'], 'srcfile.src') + split srcfile.src + call assert_equal('krl', &filetype) + bwipe! + call delete('srcfile.src') + + " KRL def with leading spaces, for KRL file extension is not case sensitive. + call writefile([' DEF srcfile()'], 'srcfile.Src') + split srcfile.Src + call assert_equal('krl', &filetype) + bwipe! + call delete('srcfile.Src') + + " KRL global deffct with embedded spaces, file starts with empty line(s). + for text in ['global def srcfile()', 'global deffct srcfile()'] + call writefile(['', text], 'srcfile.SRC') + split srcfile.SRC + call assert_equal('krl', &filetype, text) + bwipe! + endfor + + " User may overrule file inspection + let g:filetype_src = 'src' + split srcfile.SRC + call assert_equal('src', &filetype) + bwipe! + call delete('srcfile.SRC') + unlet g:filetype_src + + filetype off +endfunc + +func Test_sys_file() + filetype on + + " *.sys defaults to Batch file for MSDOS + call writefile(['looks like dos batch'], 'sysfile.sys') + split sysfile.sys + call assert_equal('bat', &filetype) + bwipe! + + " Users preference set by g:filetype_sys + let g:filetype_sys = 'sys' + split sysfile.sys + call assert_equal('sys', &filetype) + unlet g:filetype_sys + bwipe! + + " RAPID header start with a line containing only "%%%", + " but is not always present. + call writefile(['%%%'], 'sysfile.sys') + split sysfile.sys + call assert_equal('rapid', &filetype) + bwipe! + call delete('sysfile.sys') + + " RAPID supports umlauts in module names, leading spaces, + " the .sys extension is not case sensitive. + call writefile([' module ÜmlautModule'], 'sysfile.Sys') + split sysfile.Sys + call assert_equal('rapid', &filetype) + bwipe! + call delete('sysfile.Sys') + + " RAPID is not case sensitive, embedded spaces, sysmodule, + " file starts with empty line(s). + call writefile(['', 'MODULE rapidmödüle (SYSMODULE,NOSTEPIN)'], 'sysfile.SYS') + split sysfile.SYS + call assert_equal('rapid', &filetype) + bwipe! + call delete('sysfile.SYS') + + filetype off +endfunc + +func Test_tex_file() + filetype on + + call writefile(['%& pdflatex'], 'Xfile.tex') + split Xfile.tex + call assert_equal('tex', &filetype) + bwipe + + call writefile(['\newcommand{\test}{some text}'], 'Xfile.tex') + split Xfile.tex + call assert_equal('tex', &filetype) + bwipe + + " tex_flavor is unset + call writefile(['%& plain'], 'Xfile.tex') + split Xfile.tex + call assert_equal('plaintex', &filetype) + bwipe + + let g:tex_flavor = 'plain' + call writefile(['just some text'], 'Xfile.tex') + split Xfile.tex + call assert_equal('plaintex', &filetype) + bwipe + + let lines =<< trim END + % This is a comment. + + \usemodule[translate] + END + call writefile(lines, 'Xfile.tex') + split Xfile.tex + call assert_equal('context', &filetype) + bwipe + + let g:tex_flavor = 'context' + call writefile(['just some text'], 'Xfile.tex') + split Xfile.tex + call assert_equal('context', &filetype) + bwipe + unlet g:tex_flavor + + call delete('Xfile.tex') + filetype off +endfunc + +func Test_tf_file() + filetype on + + call writefile([';;; TF MUD client is super duper cool'], 'Xfile.tf', 'D') + split Xfile.tf + call assert_equal('tf', &filetype) + bwipe! + + call writefile(['provider "azurerm" {'], 'Xfile.tf') + split Xfile.tf + call assert_equal('terraform', &filetype) + bwipe! + + filetype off +endfunc + +func Test_ts_file() + filetype on + + call writefile(['<?xml version="1.0" encoding="utf-8"?>'], 'Xfile.ts', 'D') + split Xfile.ts + call assert_equal('xml', &filetype) + bwipe! + + call writefile(['// looks like Typescript'], 'Xfile.ts') + split Xfile.ts + call assert_equal('typescript', &filetype) + bwipe! + + filetype off +endfunc + +func Test_ttl_file() + filetype on + + call writefile(['@base <http://example.org/> .'], 'Xfile.ttl', 'D') + split Xfile.ttl + call assert_equal('turtle', &filetype) + bwipe! + + call writefile(['looks like Tera Term Language'], 'Xfile.ttl') + split Xfile.ttl + call assert_equal('teraterm', &filetype) + bwipe! + + filetype off +endfunc + +func Test_v_file() + filetype on + + call writefile(['module tb; // Looks like a Verilog'], 'Xfile.v', 'D') + split Xfile.v + call assert_equal('verilog', &filetype) + bwipe! + + call writefile(['module main'], 'Xfile.v') + split Xfile.v + call assert_equal('v', &filetype) + bwipe! + + call writefile(['Definition x := 10. (*'], 'Xfile.v') + split Xfile.v + call assert_equal('coq', &filetype) + bwipe! + + filetype off +endfunc + +func Test_xpm_file() + filetype on + + call writefile(['this is XPM2'], 'file.xpm', 'D') + split file.xpm + call assert_equal('xpm2', &filetype) + bwipe! + + filetype off +endfunc + +func Test_cls_file() + filetype on + + call writefile(['looks like Smalltalk'], 'Xfile.cls', 'D') + split Xfile.cls + call assert_equal('st', &filetype) + bwipe! + + " Test dist#ft#FTcls() + + let g:filetype_cls = 'vb' + split Xfile.cls + call assert_equal('vb', &filetype) + bwipe! + unlet g:filetype_cls + + " TeX + + call writefile(['%'], 'Xfile.cls') + split Xfile.cls + call assert_equal('tex', &filetype) + bwipe! + + call writefile(['\NeedsTeXFormat{LaTeX2e}'], 'Xfile.cls') + split Xfile.cls + call assert_equal('tex', &filetype) + bwipe! + + " Rexx + + call writefile(['#!/usr/bin/rexx'], 'Xfile.cls') + split Xfile.cls + call assert_equal('rexx', &filetype) + bwipe! + + call writefile(['#!/usr/bin/regina'], 'Xfile.cls') + split Xfile.cls + call assert_equal('rexx', &filetype) + bwipe! + + call writefile(['/* Comment */'], 'Xfile.cls') + split Xfile.cls + call assert_equal('rexx', &filetype) + bwipe! + + call writefile(['::class Foo subclass Bar public'], 'Xfile.cls') + split Xfile.cls + call assert_equal('rexx', &filetype) + bwipe! + + " Visual Basic + + call writefile(['VERSION 1.0 CLASS'], 'Xfile.cls') + split Xfile.cls + call assert_equal('vb', &filetype) + bwipe! + + filetype off +endfunc + +func Test_sig_file() + filetype on + + call writefile(['this is neither Lambda Prolog nor SML'], 'Xfile.sig', 'D') + split Xfile.sig + call assert_equal('', &filetype) + bwipe! + + " Test dist#ft#FTsig() + + let g:filetype_sig = 'sml' + split Xfile.sig + call assert_equal('sml', &filetype) + bwipe! + unlet g:filetype_sig + + " Lambda Prolog + + call writefile(['sig foo.'], 'Xfile.sig') + split Xfile.sig + call assert_equal('lprolog', &filetype) + bwipe! + + call writefile(['/* ... */'], 'Xfile.sig') + split Xfile.sig + call assert_equal('lprolog', &filetype) + bwipe! + + call writefile(['% ...'], 'Xfile.sig') + split Xfile.sig + call assert_equal('lprolog', &filetype) + bwipe! + + " SML signature file + + call writefile(['signature FOO ='], 'Xfile.sig') + split Xfile.sig + call assert_equal('sml', &filetype) + bwipe! + + call writefile(['structure FOO ='], 'Xfile.sig') + split Xfile.sig + call assert_equal('sml', &filetype) + bwipe! + + call writefile(['(* ... *)'], 'Xfile.sig') + split Xfile.sig + call assert_equal('sml', &filetype) + bwipe! + + filetype off +endfunc + +" Test dist#ft#FTsil() +func Test_sil_file() + filetype on + + split Xfile.sil + call assert_equal('sil', &filetype) + bwipe! + + let lines =<< trim END + // valid + let protoErasedPathA = \ABCProtocol.a + + // also valid + let protoErasedPathA = + \ABCProtocol.a + END + call writefile(lines, 'Xfile.sil', 'D') + + split Xfile.sil + call assert_equal('sil', &filetype) + bwipe! + + " SILE + + call writefile(['% some comment'], 'Xfile.sil') + split Xfile.sil + call assert_equal('sile', &filetype) + bwipe! + + call writefile(['\begin[papersize=a6]{document}foo\end{document}'], 'Xfile.sil') + split Xfile.sil + call assert_equal('sile', &filetype) + bwipe! + + filetype off +endfunc + +func Test_inc_file() + filetype on + + call writefile(['this is the fallback'], 'Xfile.inc', 'D') + split Xfile.inc + call assert_equal('pov', &filetype) + bwipe! + + let g:filetype_inc = 'foo' + split Xfile.inc + call assert_equal('foo', &filetype) + bwipe! + unlet g:filetype_inc + + " aspperl + call writefile(['perlscript'], 'Xfile.inc') + split Xfile.inc + call assert_equal('aspperl', &filetype) + bwipe! + + " aspvbs + call writefile(['<% something'], 'Xfile.inc') + split Xfile.inc + call assert_equal('aspvbs', &filetype) + bwipe! + + " php + call writefile(['<?php'], 'Xfile.inc') + split Xfile.inc + call assert_equal('php', &filetype) + bwipe! + + " pascal + call writefile(['program'], 'Xfile.inc') + split Xfile.inc + call assert_equal('pascal', &filetype) + bwipe! + + " bitbake + call writefile(['require foo'], 'Xfile.inc') + split Xfile.inc + call assert_equal('bitbake', &filetype) + bwipe! + + call writefile(['S = "${WORKDIR}"'], 'Xfile.inc') + split Xfile.inc + call assert_equal('bitbake', &filetype) + bwipe! + + call writefile(['DEPENDS:append = " somedep"'], 'Xfile.inc') + split Xfile.inc + call assert_equal('bitbake', &filetype) + bwipe! + + call writefile(['MACHINE ??= "qemu"'], 'Xfile.inc') + split Xfile.inc + call assert_equal('bitbake', &filetype) + bwipe! + + call writefile(['PROVIDES := "test"'], 'Xfile.inc') + split Xfile.inc + call assert_equal('bitbake', &filetype) + bwipe! + + call writefile(['RDEPENDS_${PN} += "bar"'], 'Xfile.inc') + split Xfile.inc + call assert_equal('bitbake', &filetype) + bwipe! + + " asm + call writefile(['asmsyntax=foo'], 'Xfile.inc') + split Xfile.inc + call assert_equal('foo', &filetype) + bwipe! + + filetype off +endfunc + +func Test_lsl_file() + filetype on + + call writefile(['looks like Linden Scripting Language'], 'Xfile.lsl', 'D') + split Xfile.lsl + call assert_equal('lsl', &filetype) + bwipe! + + " Test dist#ft#FTlsl() + + let g:filetype_lsl = 'larch' + split Xfile.lsl + call assert_equal('larch', &filetype) + bwipe! + unlet g:filetype_lsl + + " Larch Shared Language + + call writefile(['% larch comment'], 'Xfile.lsl') + split Xfile.lsl + call assert_equal('larch', &filetype) + bwipe! + + call writefile(['foo: trait'], 'Xfile.lsl') + split Xfile.lsl + call assert_equal('larch', &filetype) + bwipe! + + filetype off +endfunc + +func Test_typ_file() + filetype on + + " SQL type file + + call writefile(['CASE = LOWER'], 'Xfile.typ', 'D') + split Xfile.typ + call assert_equal('sql', &filetype) + bwipe! + + call writefile(['TYPE foo'], 'Xfile.typ') + split Xfile.typ + call assert_equal('sql', &filetype) + bwipe! + + " typst document + + call writefile(['this is a fallback'], 'Xfile.typ') + split Xfile.typ + call assert_equal('typst', &filetype) + bwipe! + + let g:filetype_typ = 'typst' + split test.typ + call assert_equal('typst', &filetype) + bwipe! + unlet g:filetype_typ + + filetype off +endfunc + +func Test_vba_file() + filetype on + + " Test dist#ft#FTvba() + + " Visual Basic + + call writefile(['looks like Visual Basic'], 'Xfile.vba', 'D') + split Xfile.vba + call assert_equal('vb', &filetype) + bwipe! + + " Vimball Archiver (ft=vim) + + call writefile(['" Vimball Archiver by Charles E. Campbell, Ph.D.', 'UseVimball', 'finish'], 'Xfile.vba', 'D') + split Xfile.vba + call assert_equal('vim', &filetype) + bwipe! + + filetype off +endfunc + +func Test_i_file() + filetype on + + " Swig: keyword + call writefile(['%module mymodule', '/* a comment */'], 'Xfile.i', 'D') + split Xfile.i + call assert_equal('swig', &filetype) + bwipe! + + " Swig: verbatim block + call writefile(['%{', '#include <header.hpp>', '%}'], 'Xfile.i', 'D') + split Xfile.i + call assert_equal('swig', &filetype) + bwipe! + + " ASM + call writefile(['; comment', ';'], 'Xfile.i', 'D') + split Xfile.i + call assert_equal('asm', &filetype) + bwipe! + + " *.i defaults to progress + call writefile(['looks like progress'], 'Xfile.i', 'D') + split Xfile.i + call assert_equal('progress', &filetype) + bwipe! + + filetype off +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_filter_cmd.vim b/test/old/testdir/test_filter_cmd.vim new file mode 100644 index 0000000000..b84081e384 --- /dev/null +++ b/test/old/testdir/test_filter_cmd.vim @@ -0,0 +1,194 @@ +" Test the :filter command modifier + +source check.vim + +func Test_filter() + edit Xdoesnotmatch + edit Xwillmatch + call assert_equal('"Xwillmatch"', substitute(execute('filter willma ls'), '[^"]*\(".*"\)[^"]*', '\1', '')) + bwipe Xdoesnotmatch + bwipe Xwillmatch + + new + call setline(1, ['foo1', 'foo2', 'foo3', 'foo4', 'foo5']) + call assert_equal("\nfoo2\nfoo4", execute('filter /foo[24]/ 1,$print')) + call assert_equal("\n 2 foo2\n 4 foo4", execute('filter /foo[24]/ 1,$number')) + call assert_equal("\nfoo2$\nfoo4$", execute('filter /foo[24]/ 1,$list')) + + call assert_equal("\nfoo1$\nfoo3$\nfoo5$", execute('filter! /foo[24]/ 1,$list')) + bwipe! + + command XTryThis echo 'this' + command XTryThat echo 'that' + command XDoThat echo 'that' + let lines = split(execute('filter XTry command'), "\n") + call assert_equal(3, len(lines)) + call assert_match("XTryThat", lines[1]) + call assert_match("XTryThis", lines[2]) + delcommand XTryThis + delcommand XTryThat + delcommand XDoThat + + map f1 the first key + map f2 the second key + map f3 not a key + let lines = split(execute('filter the map f'), "\n") + call assert_equal(2, len(lines)) + call assert_match("f2", lines[0]) + call assert_match("f1", lines[1]) + unmap f1 + unmap f2 + unmap f3 +endfunc + +func Test_filter_fails() + call assert_fails('filter', 'E471:') + call assert_fails('filter pat', 'E476:') + call assert_fails('filter /pat', 'E476:') + call assert_fails('filter /pat/', 'E476:') + call assert_fails('filter /pat/ asdf', 'E492:') + " Using assert_fails() causes E476 instead of E866. So use a try-catch. + let caught_e866 = 0 + try + filter /\@>b/ ls + catch /E866:/ + let caught_e866 = 1 + endtry + call assert_equal(1, caught_e866) + + call assert_fails('filter!', 'E471:') + call assert_fails('filter! pat', 'E476:') + call assert_fails('filter! /pat', 'E476:') + call assert_fails('filter! /pat/', 'E476:') + call assert_fails('filter! /pat/ asdf', 'E492:') +endfunc + +function s:complete_filter_cmd(filtcmd) + let keystroke = "\<TAB>\<C-R>=execute('let cmdline = getcmdline()')\<CR>\<C-C>" + let cmdline = '' + call feedkeys(':' . a:filtcmd . keystroke, 'ntx') + return cmdline +endfunction + +func Test_filter_cmd_completion() + " Do not complete pattern + call assert_equal("filter \t", s:complete_filter_cmd('filter ')) + call assert_equal("filter pat\t", s:complete_filter_cmd('filter pat')) + call assert_equal("filter /pat\t", s:complete_filter_cmd('filter /pat')) + call assert_equal("filter /pat/\t", s:complete_filter_cmd('filter /pat/')) + + " Complete after string pattern + call assert_equal('filter pat print', s:complete_filter_cmd('filter pat pri')) + + " Complete after regexp pattern + call assert_equal('filter /pat/ print', s:complete_filter_cmd('filter /pat/ pri')) + call assert_equal('filter #pat# print', s:complete_filter_cmd('filter #pat# pri')) +endfunc + +func Test_filter_cmd_with_filter() + new + set shelltemp + %!echo "a|b" + let out = getline(1) + bw! + if has('win32') + let out = trim(out, '" ') + endif + call assert_equal('a|b', out) + set shelltemp& +endfunction + +func Test_filter_commands() + CheckFeature quickfix + + let g:test_filter_a = 1 + let b:test_filter_b = 2 + let test_filter_c = 3 + + " Test filtering :let command + let res = split(execute("filter /^test_filter/ let"), "\n") + call assert_equal(["test_filter_a #1"], res) + + let res = split(execute("filter /\\v^(b:)?test_filter/ let"), "\n") + call assert_equal(["test_filter_a #1", "b:test_filter_b #2"], res) + + unlet g:test_filter_a + unlet b:test_filter_b + unlet test_filter_c + + " Test filtering :set command + let helplang=&helplang + set helplang=en + let res = join(split(execute("filter /^help/ set"), "\n")[1:], " ") + call assert_match('^\s*helplang=\w*$', res) + let &helplang=helplang + + " Test filtering :llist command + call setloclist(0, [{"filename": "/path/vim.c"}, {"filename": "/path/vim.h"}, {"module": "Main.Test"}]) + let res = split(execute("filter /\\.c$/ llist"), "\n") + call assert_equal([" 1 /path/vim.c: "], res) + + let res = split(execute("filter /\\.Test$/ llist"), "\n") + call assert_equal([" 3 Main.Test: "], res) + + " Test filtering :jump command + e file.c + e file.h + e file.hs + let res = split(execute("filter /\.c$/ jumps"), "\n")[1:] + call assert_equal([" 2 1 0 file.c", ">"], res) + + " Test filtering :marks command + b file.c + mark A + b file.h + mark B + let res = split(execute("filter /\.c$/ marks"), "\n")[1:] + call assert_equal([" A 1 0 file.c"], res) + + call setline(1, ['one', 'two', 'three']) + 1mark a + 2mark b + 3mark c + let res = split(execute("filter /two/ marks abc"), "\n")[1:] + call assert_equal([" b 2 0 two"], res) + + bwipe! file.c + bwipe! file.h + bwipe! file.hs +endfunc + +func Test_filter_display() + edit Xdoesnotmatch + let @a = '!!willmatch' + let @b = '!!doesnotmatch' + let @c = "oneline\ntwoline\nwillmatch\n" + let @/ = '!!doesnotmatch' + call feedkeys(":echo '!!doesnotmatch:'\<CR>", 'ntx') + let lines = map(split(execute('filter /willmatch/ display'), "\n"), 'v:val[5:6]') + + call assert_true(index(lines, '"a') >= 0) + call assert_false(index(lines, '"b') >= 0) + call assert_true(index(lines, '"c') >= 0) + call assert_false(index(lines, '"/') >= 0) + call assert_false(index(lines, '":') >= 0) + call assert_false(index(lines, '"%') >= 0) + + let lines = map(split(execute('filter /doesnotmatch/ display'), "\n"), 'v:val[5:6]') + call assert_true(index(lines, '"a') < 0) + call assert_false(index(lines, '"b') < 0) + call assert_true(index(lines, '"c') < 0) + call assert_false(index(lines, '"/') < 0) + call assert_false(index(lines, '":') < 0) + call assert_false(index(lines, '"%') < 0) + + bwipe! +endfunc + +func Test_filter_scriptnames() + let lines = split(execute('filter /test_filter_cmd/ scriptnames'), "\n") + call assert_equal(1, len(lines)) + call assert_match('filter_cmd', lines[0]) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_filter_map.vim b/test/old/testdir/test_filter_map.vim new file mode 100644 index 0000000000..7658797759 --- /dev/null +++ b/test/old/testdir/test_filter_map.vim @@ -0,0 +1,242 @@ +" Test filter() and map() + +source vim9.vim + +" list with expression string +func Test_filter_map_list_expr_string() + " filter() + call assert_equal([2, 3, 4], filter([1, 2, 3, 4], 'v:val > 1')) + call assert_equal([3, 4], filter([1, 2, 3, 4], 'v:key > 1')) + call assert_equal([], filter([1, 2, 3, 4], 0)) + + " map() + call assert_equal([2, 4, 6, 8], map([1, 2, 3, 4], 'v:val * 2')) + call assert_equal([0, 2, 4, 6], map([1, 2, 3, 4], 'v:key * 2')) + call assert_equal([9, 9, 9, 9], map([1, 2, 3, 4], 9)) + call assert_equal([7, 7, 7], map([1, 2, 3], ' 7 ')) +endfunc + +" dict with expression string +func Test_filter_map_dict_expr_string() + let dict = {"foo": 1, "bar": 2, "baz": 3} + + " filter() + call assert_equal({"bar": 2, "baz": 3}, filter(copy(dict), 'v:val > 1')) + call assert_equal({"foo": 1, "baz": 3}, filter(copy(dict), 'v:key > "bar"')) + call assert_equal({}, filter(copy(dict), 0)) + + " map() + call assert_equal({"foo": 2, "bar": 4, "baz": 6}, map(copy(dict), 'v:val * 2')) + call assert_equal({"foo": "f", "bar": "b", "baz": "b"}, map(copy(dict), 'v:key[0]')) + call assert_equal({"foo": 9, "bar": 9, "baz": 9}, map(copy(dict), 9)) +endfunc + +" list with funcref +func Test_filter_map_list_expr_funcref() + " filter() + func! s:filter1(index, val) abort + return a:val > 1 + endfunc + call assert_equal([2, 3, 4], filter([1, 2, 3, 4], function('s:filter1'))) + + func! s:filter2(index, val) abort + return a:index > 1 + endfunc + call assert_equal([3, 4], filter([1, 2, 3, 4], function('s:filter2'))) + + " map() + func! s:filter3(index, val) abort + return a:val * 2 + endfunc + call assert_equal([2, 4, 6, 8], map([1, 2, 3, 4], function('s:filter3'))) + + func! s:filter4(index, val) abort + return a:index * 2 + endfunc + call assert_equal([0, 2, 4, 6], map([1, 2, 3, 4], function('s:filter4'))) +endfunc + +" dict with funcref +func Test_filter_map_dict_expr_funcref() + let dict = {"foo": 1, "bar": 2, "baz": 3} + + " filter() + func! s:filter1(key, val) abort + return a:val > 1 + endfunc + call assert_equal({"bar": 2, "baz": 3}, filter(copy(dict), function('s:filter1'))) + + func! s:filter2(key, val) abort + return a:key > "bar" + endfunc + call assert_equal({"foo": 1, "baz": 3}, filter(copy(dict), function('s:filter2'))) + + " map() + func! s:filter3(key, val) abort + return a:val * 2 + endfunc + call assert_equal({"foo": 2, "bar": 4, "baz": 6}, map(copy(dict), function('s:filter3'))) + + func! s:filter4(key, val) abort + return a:key[0] + endfunc + call assert_equal({"foo": "f", "bar": "b", "baz": "b"}, map(copy(dict), function('s:filter4'))) +endfunc + +func Test_map_filter_fails() + call assert_fails('call map([1], "42 +")', 'E15:') + call assert_fails('call filter([1], "42 +")', 'E15:') + call assert_fails("let l = filter([1, 2, 3], '{}')", 'E728:') + call assert_fails("let l = filter({'k' : 10}, '{}')", 'E728:') + call assert_fails("let l = filter([1, 2], {})", 'E731:') + call assert_equal(v:_null_list, filter(v:_null_list, 0)) + call assert_equal(v:_null_dict, filter(v:_null_dict, 0)) + call assert_equal(v:_null_list, map(v:_null_list, '"> " .. v:val')) + call assert_equal(v:_null_dict, map(v:_null_dict, '"> " .. v:val')) + " Nvim doesn't have null functions + " call assert_equal([1, 2, 3], filter([1, 2, 3], test_null_function())) + call assert_fails("let l = filter([1, 2], function('min'))", 'E118:') + " Nvim doesn't have null partials + " call assert_equal([1, 2, 3], filter([1, 2, 3], test_null_partial())) + call assert_fails("let l = filter([1, 2], {a, b, c -> 1})", 'E119:') +endfunc + +func Test_map_and_modify() + let l = ["abc"] + " cannot change the list halfway a map() + call assert_fails('call map(l, "remove(l, 0)[0]")', 'E741:') + + let d = #{a: 1, b: 2, c: 3} + call assert_fails('call map(d, "remove(d, v:key)[0]")', 'E741:') + call assert_fails('echo map(d, {k,v -> remove(d, k)})', 'E741:') + + let b = 0z1234 + call assert_fails('call filter(b, "remove(b, 0)")', 'E741:') +endfunc + +func Test_filter_and_modify() + let l = [0] + " cannot change the list halfway a map() + call assert_fails('call filter(l, "remove(l, 0)")', 'E741:') + + let d = #{a: 0, b: 0, c: 0} + call assert_fails('call filter(d, "remove(d, v:key)")', 'E741:') + + let b = 0z1234 + call assert_fails('call filter(b, "remove(b, 0)")', 'E741:') +endfunc + +func Test_mapnew_dict() + let din = #{one: 1, two: 2} + let dout = mapnew(din, {k, v -> string(v)}) + call assert_equal(#{one: 1, two: 2}, din) + call assert_equal(#{one: '1', two: '2'}, dout) + + const dconst = #{one: 1, two: 2, three: 3} + call assert_equal(#{one: 2, two: 3, three: 4}, mapnew(dconst, {_, v -> v + 1})) +endfunc + +func Test_mapnew_list() + let lin = [1, 2, 3] + let lout = mapnew(lin, {k, v -> string(v)}) + call assert_equal([1, 2, 3], lin) + call assert_equal(['1', '2', '3'], lout) + + const lconst = [1, 2, 3] + call assert_equal([2, 3, 4], mapnew(lconst, {_, v -> v + 1})) +endfunc + +func Test_mapnew_blob() + let bin = 0z123456 + let bout = mapnew(bin, {k, v -> k == 1 ? 0x99 : v}) + call assert_equal(0z123456, bin) + call assert_equal(0z129956, bout) +endfunc + +" Test for using map(), filter() and mapnew() with a string +func Test_filter_map_string() + " filter() + let lines =<< trim END + VAR s = "abc" + call filter(s, '"b" != v:val') + call assert_equal('abc', s) + call assert_equal('ac', filter('abc', '"b" != v:val')) + call assert_equal('あいうえお', filter('あxいxうxえxお', '"x" != v:val')) + call assert_equal('あa😊💕💕b💕', filter('あxax😊x💕💕b💕x', '"x" != v:val')) + call assert_equal('xxxx', filter('あxax😊x💕💕b💕x', '"x" == v:val')) + VAR t = "%),:;>?]}’”†‡…‰,‱‼⁇⁈⁉℃℉,、。〉》」,』】〕〗〙〛,!),.:,;?,]}" + VAR u = "%):;>?]}’”†‡…‰‱‼⁇⁈⁉℃℉、。〉》」』】〕〗〙〛!),.:;?]}" + call assert_equal(u, filter(t, '"," != v:val')) + call assert_equal('', filter('abc', '0')) + call assert_equal('ac', filter('abc', LSTART i, x LMIDDLE "b" != x LEND)) + call assert_equal('あいうえお', filter('あxいxうxえxお', LSTART i, x LMIDDLE "x" != x LEND)) + call assert_equal('', filter('abc', LSTART i, x LMIDDLE v:false LEND)) + call assert_equal('', filter('', "v:val == 'a'")) + call assert_equal('', filter(v:_null_string, "v:val == 'a'")) + END + call CheckLegacyAndVim9Success(lines) + + " map() + let lines =<< trim END + VAR s = "abc" + call map(s, 'nr2char(char2nr(v:val) + 2)') + call assert_equal('abc', s) + call assert_equal('cde', map('abc', 'nr2char(char2nr(v:val) + 2)')) + call assert_equal('[あ][i][う][え][お]', map('あiうえお', '"[" .. v:val .. "]"')) + call assert_equal('[あ][a][😊][,][‱][‼][⁇][⁈][⁉][💕][b][💕][c][💕]', map('あa😊,‱‼⁇⁈⁉💕b💕c💕', '"[" .. v:val .. "]"')) + call assert_equal('', map('abc', '""')) + call assert_equal('cde', map('abc', LSTART i, x LMIDDLE nr2char(char2nr(x) + 2) LEND)) + call assert_equal('[あ][i][う][え][お]', map('あiうえお', LSTART i, x LMIDDLE '[' .. x .. ']' LEND)) + call assert_equal('', map('abc', LSTART i, x LMIDDLE '' LEND)) + call assert_equal('', map('', "v:val == 'a'")) + call assert_equal('', map(v:_null_string, "v:val == 'a'")) + call assert_fails('echo map("abc", "10")', 'E928:') + call assert_fails('echo map("abc", "a10")', 'E121:') + END + call CheckLegacyAndVim9Success(lines) + + " mapnew() + let lines =<< trim END + VAR s = "abc" + call mapnew(s, 'nr2char(char2nr(v:val) + 2)') + call assert_equal('abc', s) + call assert_equal('cde', mapnew('abc', 'nr2char(char2nr(v:val) + 2)')) + call assert_equal('[あ][i][う][え][お]', mapnew('あiうえお', '"[" .. v:val .. "]"')) + call assert_equal('[あ][a][😊][,][‱][‼][⁇][⁈][⁉][💕][b][💕][c][💕]', mapnew('あa😊,‱‼⁇⁈⁉💕b💕c💕', '"[" .. v:val .. "]"')) + call assert_equal('', mapnew('abc', '""')) + call assert_equal('cde', mapnew('abc', LSTART i, x LMIDDLE nr2char(char2nr(x) + 2) LEND)) + call assert_equal('[あ][i][う][え][お]', mapnew('あiうえお', LSTART i, x LMIDDLE '[' .. x .. ']' LEND)) + call assert_equal('', mapnew('abc', LSTART i, x LMIDDLE '' LEND)) + call assert_equal('', mapnew('', "v:val == 'a'")) + call assert_equal('', mapnew(v:_null_string, "v:val == 'a'")) + END + call CheckLegacyAndVim9Success(lines) + + let lines =<< trim END + #" map() and filter() + call assert_equal('[あ][⁈][a][😊][⁉][💕][💕][b][💕]', map(filter('あx⁈ax😊x⁉💕💕b💕x', '"x" != v:val'), '"[" .. v:val .. "]"')) + + #" patterns-composing(\Z) + call assert_equal('ॠॠ', filter('ऊॠॡ,ऊॠॡ', LSTART i, x LMIDDLE x =~ '\Z' .. nr2char(0x0960) LEND)) + call assert_equal('àà', filter('càt,càt', LSTART i, x LMIDDLE x =~ '\Za' LEND)) + call assert_equal('ÅÅ', filter('Åström,Åström', LSTART i, x LMIDDLE x =~ '\Z' .. nr2char(0xc5) LEND)) + call assert_equal('öö', filter('Åström,Åström', LSTART i, x LMIDDLE x =~ '\Z' .. nr2char(0xf6) LEND)) + call assert_equal('ऊ@ॡ', map('ऊॠॡ', LSTART i, x LMIDDLE x =~ '\Z' .. nr2char(0x0960) ? '@' : x LEND)) + call assert_equal('c@t', map('càt', LSTART i, x LMIDDLE x =~ '\Za' ? '@' : x LEND)) + call assert_equal('@ström', map('Åström', LSTART i, x LMIDDLE x =~ '\Z' .. nr2char(0xc5) ? '@' : x LEND)) + call assert_equal('Åstr@m', map('Åström', LSTART i, x LMIDDLE x =~ '\Z' .. nr2char(0xf6) ? '@' : x LEND)) + + #" patterns-composing(\%C) + call assert_equal('ॠॠ', filter('ऊॠॡ,ऊॠॡ', LSTART i, x LMIDDLE x =~ nr2char(0x0960) .. '\%C' LEND)) + call assert_equal('àà', filter('càt,càt', LSTART i, x LMIDDLE x =~ 'a' .. '\%C' LEND)) + call assert_equal('ÅÅ', filter('Åström,Åström', LSTART i, x LMIDDLE x =~ nr2char(0xc5) .. '\%C' LEND)) + call assert_equal('öö', filter('Åström,Åström', LSTART i, x LMIDDLE x =~ nr2char(0xf6) .. '\%C' LEND)) + call assert_equal('ऊ@ॡ', map('ऊॠॡ', LSTART i, x LMIDDLE x =~ nr2char(0x0960) .. '\%C' ? '@' : x LEND)) + call assert_equal('c@t', map('càt', LSTART i, x LMIDDLE x =~ 'a' .. '\%C' ? '@' : x LEND)) + call assert_equal('@ström', map('Åström', LSTART i, x LMIDDLE x =~ nr2char(0xc5) .. '\%C' ? '@' : x LEND)) + call assert_equal('Åstr@m', map('Åström', LSTART i, x LMIDDLE x =~ nr2char(0xf6) .. '\%C' ? '@' : x LEND)) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_find_complete.vim b/test/old/testdir/test_find_complete.vim new file mode 100644 index 0000000000..32ca9672ef --- /dev/null +++ b/test/old/testdir/test_find_complete.vim @@ -0,0 +1,163 @@ +" Tests for the 'find' command completion. + +" Do all the tests in a separate window to avoid E211 when we recursively +" delete the Xfind directory during cleanup +func Test_find_complete() + set belloff=all + + " On windows a stale "Xfind" directory may exist, remove it so that + " we start from a clean state. + call delete("Xfind", "rf") + let cwd = getcwd() + let test_out = cwd . '/test.out' + call mkdir('Xfind') + cd Xfind + + new + set path= + call assert_fails('call feedkeys(":find \t\n", "xt")', 'E471:') + close + + new + set path=. + call assert_fails('call feedkeys(":find \t\n", "xt")', 'E471:') + close + + new + set path=.,, + call assert_fails('call feedkeys(":find \t\n", "xt")', 'E471:') + close + + new + set path=./** + call assert_fails('call feedkeys(":find \t\n", "xt")', 'E471:') + close + + " We shouldn't find any file till this point + + call mkdir('in/path', 'p') + call chdir(cwd) + call writefile(['Holy Grail'], 'Xfind/file.txt') + call writefile(['Jimmy Hoffa'], 'Xfind/in/file.txt') + call writefile(['Another Holy Grail'], 'Xfind/in/stuff.txt') + call writefile(['E.T.'], 'Xfind/in/path/file.txt') + + new + set path=Xfind/** + call feedkeys(":find file\t\n", "xt") + call assert_equal('Holy Grail', getline(1)) + call feedkeys(":find file\t\t\n", "xt") + call assert_equal('Jimmy Hoffa', getline(1)) + call feedkeys(":find file\t\t\t\n", "xt") + call assert_equal('E.T.', getline(1)) + + " Rerun the previous three find completions, using fullpath in 'path' + exec "set path=" . cwd . "/Xfind/**" + + call feedkeys(":find file\t\n", "xt") + call assert_equal('Holy Grail', getline(1)) + call feedkeys(":find file\t\t\n", "xt") + call assert_equal('Jimmy Hoffa', getline(1)) + call feedkeys(":find file\t\t\t\n", "xt") + call assert_equal('E.T.', getline(1)) + + " Same steps again, using relative and fullpath items that point to the same + " recursive location. + " This is to test that there are no duplicates in the completion list. + set path+=Xfind/** + call feedkeys(":find file\t\n", "xt") + call assert_equal('Holy Grail', getline(1)) + call feedkeys(":find file\t\t\n", "xt") + call assert_equal('Jimmy Hoffa', getline(1)) + call feedkeys(":find file\t\t\t\n", "xt") + call assert_equal('E.T.', getline(1)) + call feedkeys(":find file\t\t\n", "xt") + + " Test find completion for directory of current buffer, which at this point + " is Xfind/in/file.txt. + set path=. + call feedkeys(":find st\t\n", "xt") + call assert_equal('Another Holy Grail', getline(1)) + + " Test find completion for empty path item ",," which is the current + " directory + cd Xfind + set path=,, + call feedkeys(":find f\t\n", "xt") + call assert_equal('Holy Grail', getline(1)) + + " Test that find completion on directory appends a slash + call feedkeys(":find in/pa\tfile.txt\n", "xt") + call assert_equal('E.T.', getline(1)) + call feedkeys(":find ./i\tstuff.txt\n", "xt") + call assert_equal('Another Holy Grail', getline(1)) + + " Test shortening of + " + " foo/x/bar/voyager.txt + " foo/y/bar/voyager.txt + " + " When current directory is above foo/ they should be shortened to (in order + " of appearance): + " + " x/bar/voyager.txt + " y/bar/voyager.txt + call mkdir('foo/x/bar', 'p') + call mkdir('foo/y/bar', 'p') + call writefile(['Voyager 1'], 'foo/x/bar/voyager.txt') + call writefile(['Voyager 2'], 'foo/y/bar/voyager.txt') + + exec "set path=" . cwd . "/Xfind/**" + call feedkeys(":find voyager\t\n", "xt") + call assert_equal('Voyager 1', getline(1)) + call feedkeys(":find voyager\t\t\n", "xt") + call assert_equal('Voyager 2', getline(1)) + + " + " When current directory is .../foo/y/bar they should be shortened to (in + " order of appearance): + " + " ./voyager.txt + " x/bar/voyager.txt + cd foo/y/bar + call feedkeys(":find voyager\t\n", "xt") + call assert_equal('Voyager 2', getline(1)) + call feedkeys(":find voyager\t\t\n", "xt") + call assert_equal('Voyager 1', getline(1)) + + " Check the opposite too: + cd ../../x/bar + call feedkeys(":find voyager\t\n", "xt") + call assert_equal('Voyager 1', getline(1)) + call feedkeys(":find voyager\t\t\n", "xt") + call assert_equal('Voyager 2', getline(1)) + + " Check for correct handling of shorten_fname()'s behavior on windows + call chdir(cwd .. "/Xfind/in") + call feedkeys(":find file\t\n", "xt") + call assert_equal('Jimmy Hoffa', getline(1)) + + " Test for relative to current buffer 'path' item + call chdir(cwd . "/Xfind/") + set path=./path + " Open the file where Jimmy Hoffa is found + e in/file.txt + " Find the file containing 'E.T.' in the Xfind/in/path directory + call feedkeys(":find file\t\n", "xt") + call assert_equal('E.T.', getline(1)) + + " Test that completion works when path=.,, + set path=.,, + " Open Jimmy Hoffa file + e in/file.txt + call assert_equal('Jimmy Hoffa', getline(1)) + + " Search for the file containing Holy Grail in same directory as in/path.txt + call feedkeys(":find stu\t\n", "xt") + call assert_equal('Another Holy Grail', getline(1)) + + enew | only + call chdir(cwd) + call delete('Xfind', 'rf') + set path& +endfunc diff --git a/test/old/testdir/test_findfile.vim b/test/old/testdir/test_findfile.vim new file mode 100644 index 0000000000..0f4b30aec2 --- /dev/null +++ b/test/old/testdir/test_findfile.vim @@ -0,0 +1,255 @@ +" Test findfile() and finddir() + +let s:files = [ 'Xdir1/foo', + \ 'Xdir1/bar', + \ 'Xdir1/Xdir2/foo', + \ 'Xdir1/Xdir2/foobar', + \ 'Xdir1/Xdir2/Xdir3/bar', + \ 'Xdir1/Xdir2/Xdir3/barfoo' ] + +func CreateFiles() + call mkdir('Xdir1/Xdir2/Xdir3/Xdir2', 'p') + for f in s:files + call writefile([], f) + endfor +endfunc + +func CleanFiles() + " Safer to delete each file even if it's more verbose + " than doing a recursive delete('Xdir1', 'rf'). + for f in s:files + call delete(f) + endfor + + call delete('Xdir1/Xdir2/Xdir3/Xdir2', 'd') + call delete('Xdir1/Xdir2/Xdir3', 'd') + call delete('Xdir1/Xdir2', 'd') + call delete('Xdir1', 'd') +endfunc + +" Test findfile({name} [, {path} [, {count}]]) +func Test_findfile() + let save_path = &path + let save_shellslash = &shellslash + let save_dir = getcwd() + set shellslash + call CreateFiles() + cd Xdir1 + e Xdir2/foo + + " With ,, in path, findfile() searches in current directory. + set path=,, + call assert_equal('foo', findfile('foo')) + call assert_equal('bar', findfile('bar')) + call assert_equal('', findfile('foobar')) + + " Directories should not be found (finddir() finds them). + call assert_equal('', findfile('Xdir2')) + + " With . in 'path', findfile() searches relatively to current file. + set path=. + call assert_equal('Xdir2/foo', findfile('foo')) + call assert_equal('', findfile('bar')) + call assert_equal('Xdir2/foobar', 'foobar'->findfile()) + + " Empty {path} 2nd argument is the same as no 2nd argument. + call assert_equal('Xdir2/foo', findfile('foo', '')) + call assert_equal('', findfile('bar', '')) + + " Test with * + call assert_equal('Xdir2/foo', findfile('foo', '*')) + call assert_equal('', findfile('bar', '*')) + call assert_equal('Xdir2/Xdir3/bar', findfile('bar', '*/*')) + call assert_equal('Xdir2/Xdir3/bar', findfile('bar', 'Xdir2/*')) + call assert_equal('Xdir2/Xdir3/bar', findfile('bar', 'Xdir*/Xdir3')) + call assert_equal('Xdir2/Xdir3/bar', findfile('bar', '*2/*3')) + + " Test with ** + call assert_equal('bar', findfile('bar', '**')) + call assert_equal('Xdir2/Xdir3/bar', findfile('bar', '**/Xdir3')) + call assert_equal('Xdir2/Xdir3/bar', findfile('bar', 'Xdir2/**')) + + call assert_equal('Xdir2/Xdir3/barfoo', findfile('barfoo', '**2')) + call assert_equal('', findfile('barfoo', '**1')) + call assert_equal('Xdir2/foobar', findfile('foobar', '**1')) + + " Test with {count} 3rd argument. + call assert_equal('bar', findfile('bar', '**', 0)) + call assert_equal('bar', findfile('bar', '**', 1)) + call assert_equal('Xdir2/Xdir3/bar', findfile('bar', '**', 2)) + call assert_equal('', findfile('bar', '**', 3)) + call assert_equal(['bar', 'Xdir2/Xdir3/bar'], findfile('bar', '**', -1)) + + " Test upwards search. + cd Xdir2/Xdir3 + call assert_equal('bar', findfile('bar', ';')) + call assert_match('.*/Xdir1/Xdir2/foo', findfile('foo', ';')) + call assert_match('.*/Xdir1/Xdir2/foo', findfile('foo', ';', 1)) + call assert_match('.*/Xdir1/foo', findfile('foo', ';', 2)) + call assert_match('.*/Xdir1/foo', findfile('foo', ';', 2)) + call assert_match('.*/Xdir1/Xdir2/foo', findfile('foo', 'Xdir2;', 1)) + call assert_equal('', findfile('foo', 'Xdir2;', 2)) + + " List l should have at least 2 values (possibly more if foo file + " happens to be found upwards above Xdir1). + let l = findfile('foo', ';', -1) + call assert_match('.*/Xdir1/Xdir2/foo', l[0]) + call assert_match('.*/Xdir1/foo', l[1]) + + " Test upwards search with stop-directory. + cd Xdir2 + let l = findfile('bar', ';' . save_dir . '/Xdir1/Xdir2/', -1) + call assert_equal(1, len(l)) + call assert_match('.*/Xdir1/Xdir2/Xdir3/bar', l[0]) + + let l = findfile('bar', ';' . save_dir . '/Xdir1/', -1) + call assert_equal(2, len(l)) + call assert_match('.*/Xdir1/Xdir2/Xdir3/bar', l[0]) + call assert_match('.*/Xdir1/bar', l[1]) + + " Test combined downwards and upwards search from Xdir2/. + cd ../.. + call assert_equal('Xdir3/bar', findfile('bar', '**;', 1)) + call assert_match('.*/Xdir1/bar', findfile('bar', '**;', 2)) + + bwipe! + call chdir(save_dir) + call CleanFiles() + let &path = save_path + let &shellslash = save_shellslash +endfunc + +func Test_findfile_error() + call assert_fails('call findfile([])', 'E730:') + call assert_fails('call findfile("x", [])', 'E730:') + call assert_fails('call findfile("x", "", [])', 'E745:') + call assert_fails('call findfile("x", "**x")', 'E343:') + call assert_fails('call findfile("x", repeat("x", 5000))', 'E854:') +endfunc + +" Test finddir({name} [, {path} [, {count}]]) +func Test_finddir() + let save_path = &path + let save_shellslash = &shellslash + let save_dir = getcwd() + set path=,, + set shellslash + call CreateFiles() + cd Xdir1 + + call assert_equal('Xdir2', finddir('Xdir2')) + call assert_equal('', 'Xdir3'->finddir()) + + " Files should not be found (findfile() finds them). + call assert_equal('', finddir('foo')) + + call assert_equal('Xdir2', finddir('Xdir2', '**')) + call assert_equal('Xdir2/Xdir3', finddir('Xdir3', '**')) + + call assert_equal('Xdir2', finddir('Xdir2', '**', 1)) + call assert_equal('Xdir2/Xdir3/Xdir2', finddir('Xdir2', '**', 2)) + call assert_equal(['Xdir2', + \ 'Xdir2/Xdir3/Xdir2'], finddir('Xdir2', '**', -1)) + + call assert_equal('Xdir2', finddir('Xdir2', '**1')) + call assert_equal('Xdir2', finddir('Xdir2', '**0')) + call assert_equal('Xdir2/Xdir3', finddir('Xdir3', '**1')) + call assert_equal('', finddir('Xdir3', '**0')) + + " Test upwards dir search. + cd Xdir2/Xdir3 + call assert_match('.*/Xdir1', finddir('Xdir1', ';')) + + " Test upwards search with stop-directory. + call assert_match('.*/Xdir1', finddir('Xdir1', ';' . save_dir . '/')) + call assert_equal('', finddir('Xdir1', ';' . save_dir . '/Xdir1/')) + + " Test combined downwards and upwards dir search from Xdir2/. + cd .. + call assert_match('.*/Xdir1', finddir('Xdir1', '**;', 1)) + call assert_equal('Xdir3/Xdir2', finddir('Xdir2', '**;', 1)) + call assert_match('.*/Xdir1/Xdir2', finddir('Xdir2', '**;', 2)) + call assert_equal('Xdir3', finddir('Xdir3', '**;', 1)) + + call chdir(save_dir) + call CleanFiles() + let &path = save_path + let &shellslash = save_shellslash +endfunc + +func Test_finddir_error() + call assert_fails('call finddir([])', 'E730:') + call assert_fails('call finddir("x", [])', 'E730:') + call assert_fails('call finddir("x", "", [])', 'E745:') + call assert_fails('call finddir("x", "**x")', 'E343:') + call assert_fails('call finddir("x", repeat("x", 5000))', 'E854:') +endfunc + +" Test for the :find, :sfind and :tabfind commands +func Test_find_cmd() + new + let save_path = &path + let save_dir = getcwd() + set path=.,./**/* + call CreateFiles() + cd Xdir1 + + " Test for :find + find foo + call assert_equal('foo', expand('%:.')) + 2find foo + call assert_equal('Xdir2/foo', expand('%:.')) + call assert_fails('3find foo', 'E347:') + + " Test for :sfind + enew + sfind barfoo + call assert_equal('Xdir2/Xdir3/barfoo', expand('%:.')) + call assert_equal(3, winnr('$')) + close + call assert_fails('sfind baz', 'E345:') + call assert_equal(2, winnr('$')) + + " Test for :tabfind + enew + tabfind foobar + call assert_equal('Xdir2/foobar', expand('%:.')) + call assert_equal(2, tabpagenr('$')) + tabclose + call assert_fails('tabfind baz', 'E345:') + call assert_equal(1, tabpagenr('$')) + + call chdir(save_dir) + exe 'cd ' . save_dir + call CleanFiles() + let &path = save_path + close + + call assert_fails('find', 'E471:') + call assert_fails('sfind', 'E471:') + call assert_fails('tabfind', 'E471:') +endfunc + +func Test_find_non_existing_path() + new + let save_path = &path + let save_dir = getcwd() + call mkdir('dir1/dir2', 'p') + call writefile([], 'dir1/file.txt') + call writefile([], 'dir1/dir2/base.txt') + call chdir('dir1/dir2') + e base.txt + set path=../include + + call assert_fails(':find file.txt', 'E345:') + + call chdir(save_dir) + bw! + call delete('dir1/dir2/base.txt', 'rf') + call delete('dir1/dir2', 'rf') + call delete('dir1/file.txt', 'rf') + call delete('dir1', 'rf') + let &path = save_path +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_fixeol.vim b/test/old/testdir/test_fixeol.vim new file mode 100644 index 0000000000..41d47d6a06 --- /dev/null +++ b/test/old/testdir/test_fixeol.vim @@ -0,0 +1,118 @@ +" Tests for 'fixeol', 'eof' and 'eol' + +func Test_fixeol() + " first write two test files – with and without trailing EOL + " use Unix fileformat for consistency + set ff=unix + enew! + call setline('.', 'with eol or eof') + w! XXEol + enew! + set noeof noeol nofixeol + call setline('.', 'without eol or eof') + w! XXNoEol + set eol eof fixeol + bwipe XXEol XXNoEol + + " try editing files with 'fixeol' disabled + e! XXEol + normal ostays eol + set nofixeol + w! XXTestEol + e! XXNoEol + normal ostays without + set nofixeol + w! XXTestNoEol + bwipe! XXEol XXNoEol XXTestEol XXTestNoEol + set fixeol + + " Append "END" to each file so that we can see what the last written char + " was. + normal ggdGaEND + w >>XXEol + w >>XXNoEol + w >>XXTestEol + w >>XXTestNoEol + + call assert_equal(['with eol or eof', 'END'], readfile('XXEol')) + call assert_equal(['without eol or eofEND'], readfile('XXNoEol')) + call assert_equal(['with eol or eof', 'stays eol', 'END'], readfile('XXTestEol')) + call assert_equal(['without eol or eof', 'stays withoutEND'], + \ readfile('XXTestNoEol')) + + call delete('XXEol') + call delete('XXNoEol') + call delete('XXTestEol') + call delete('XXTestNoEol') + set ff& fixeol& eof& eol& + enew! +endfunc + +func Test_eof() + let data = 0z68656c6c6f.0d0a.776f726c64 " "hello\r\nworld" + + " 1. Eol, Eof + " read + call writefile(data + 0z0d0a.1a, 'XXEolEof') + e! XXEolEof + call assert_equal(['hello', 'world'], getline(1, 2)) + call assert_equal([1, 1], [&eol, &eof]) + " write + set fixeol + w! + call assert_equal(data + 0z0d0a, readblob('XXEolEof')) + set nofixeol + w! + call assert_equal(data + 0z0d0a.1a, readblob('XXEolEof')) + + " 2. NoEol, Eof + " read + call writefile(data + 0z1a, 'XXNoEolEof') + e! XXNoEolEof + call assert_equal(['hello', 'world'], getline(1, 2)) + call assert_equal([0, 1], [&eol, &eof]) + " write + set fixeol + w! + call assert_equal(data + 0z0d0a, readblob('XXNoEolEof')) + set nofixeol + w! + call assert_equal(data + 0z1a, readblob('XXNoEolEof')) + + " 3. Eol, NoEof + " read + call writefile(data + 0z0d0a, 'XXEolNoEof') + e! XXEolNoEof + call assert_equal(['hello', 'world'], getline(1, 2)) + call assert_equal([1, 0], [&eol, &eof]) + " write + set fixeol + w! + call assert_equal(data + 0z0d0a, readblob('XXEolNoEof')) + set nofixeol + w! + call assert_equal(data + 0z0d0a, readblob('XXEolNoEof')) + + " 4. NoEol, NoEof + " read + call writefile(data, 'XXNoEolNoEof') + e! XXNoEolNoEof + call assert_equal(['hello', 'world'], getline(1, 2)) + call assert_equal([0, 0], [&eol, &eof]) + " write + set fixeol + w! + call assert_equal(data + 0z0d0a, readblob('XXNoEolNoEof')) + set nofixeol + w! + call assert_equal(data, readblob('XXNoEolNoEof')) + + call delete('XXEolEof') + call delete('XXNoEolEof') + call delete('XXEolNoEof') + call delete('XXNoEolNoEof') + set ff& fixeol& eof& eol& + enew! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_flatten.vim b/test/old/testdir/test_flatten.vim new file mode 100644 index 0000000000..aa91060313 --- /dev/null +++ b/test/old/testdir/test_flatten.vim @@ -0,0 +1,108 @@ +" Test for flatting list. +func Test_flatten() + call assert_fails('call flatten(1)', 'E686:') + call assert_fails('call flatten({})', 'E686:') + call assert_fails('call flatten("string")', 'E686:') + call assert_fails('call flatten([], [])', 'E745:') + call assert_fails('call flatten([], -1)', 'E900: maxdepth') + + call assert_equal([], flatten([])) + call assert_equal([], flatten([[]])) + call assert_equal([], flatten([[[]]])) + + call assert_equal([1, 2, 3], flatten([1, 2, 3])) + call assert_equal([1, 2, 3], flatten([[1], 2, 3])) + call assert_equal([1, 2, 3], flatten([1, [2], 3])) + call assert_equal([1, 2, 3], flatten([1, 2, [3]])) + call assert_equal([1, 2, 3], flatten([[1], [2], 3])) + call assert_equal([1, 2, 3], flatten([1, [2], [3]])) + call assert_equal([1, 2, 3], flatten([[1], 2, [3]])) + call assert_equal([1, 2, 3], flatten([[1], [2], [3]])) + + call assert_equal([1, 2, 3], flatten([[1, 2, 3], []])) + call assert_equal([1, 2, 3], flatten([[], [1, 2, 3]])) + call assert_equal([1, 2, 3], flatten([[1, 2], [], [3]])) + call assert_equal([1, 2, 3], flatten([[], [1, 2, 3], []])) + call assert_equal([1, 2, 3, 4], flatten(range(1, 4))) + + " example in the help + call assert_equal([1, 2, 3, 4, 5], flatten([1, [2, [3, 4]], 5])) + call assert_equal([1, 2, [3, 4], 5], flatten([1, [2, [3, 4]], 5], 1)) + + call assert_equal([0, [1], 2, [3], 4], flatten([[0, [1]], 2, [[3], 4]], 1)) + call assert_equal([1, 2, 3], flatten([[[[1]]], [2], [3]], 3)) + call assert_equal([[1], [2], [3]], flatten([[[1], [2], [3]]], 1)) + call assert_equal([[1]], flatten([[1]], 0)) + + " Make it flatten if the given maxdepth is larger than actual depth. + call assert_equal([1, 2, 3], flatten([[1, 2, 3]], 1)) + call assert_equal([1, 2, 3], flatten([[1, 2, 3]], 2)) + + let l:list = [[1], [2], [3]] + call assert_equal([1, 2, 3], flatten(l:list)) + call assert_equal([1, 2, 3], l:list) + + " Tests for checking reference counter works well. + let l:x = {'foo': 'bar'} + call assert_equal([1, 2, l:x, 3], flatten([1, [2, l:x], 3])) + call test_garbagecollect_now() + call assert_equal('bar', l:x.foo) + + let l:list = [[1], [2], [3]] + call assert_equal([1, 2, 3], flatten(l:list)) + call test_garbagecollect_now() + call assert_equal([1, 2, 3], l:list) + + " Tests for checking circular reference list can be flatten. + let l:x = [1] + let l:y = [x] + let l:z = flatten(l:y) + call assert_equal([1], l:z) + call test_garbagecollect_now() + let l:x[0] = 2 + call assert_equal([2], l:x) + call assert_equal([1], l:z) " NOTE: primitive types are copied. + call assert_equal([1], l:y) + + let l:x = [2] + let l:y = [1, [l:x], 3] " [1, [[2]], 3] + let l:z = flatten(l:y, 1) + call assert_equal([1, [2], 3], l:z) + let l:x[0] = 9 + call assert_equal([1, [9], 3], l:z) " Reference to l:x is kept. + call assert_equal([1, [9], 3], l:y) + + let l:x = [1] + let l:y = [2] + call add(x, y) " l:x = [1, [2]] + call add(y, x) " l:y = [2, [1, [...]]] + call assert_equal([1, 2, 1, 2], flatten(l:x, 2)) + call assert_equal([2, l:x], l:y) + + let l4 = [ 1, [ 11, [ 101, [ 1001 ] ] ] ] + call assert_equal(l4, flatten(deepcopy(l4), 0)) + call assert_equal([1, 11, [101, [1001]]], flatten(deepcopy(l4), 1)) + call assert_equal([1, 11, 101, [1001]], flatten(deepcopy(l4), 2)) + call assert_equal([1, 11, 101, 1001], flatten(deepcopy(l4), 3)) + call assert_equal([1, 11, 101, 1001], flatten(deepcopy(l4), 4)) + call assert_equal([1, 11, 101, 1001], flatten(deepcopy(l4))) +endfunc + +func Test_flattennew() + let l = [1, [2, [3, 4]], 5] + call assert_equal([1, 2, 3, 4, 5], flattennew(l)) + call assert_equal([1, [2, [3, 4]], 5], l) + + call assert_equal([1, 2, [3, 4], 5], flattennew(l, 1)) + call assert_equal([1, [2, [3, 4]], 5], l) + + let l4 = [ 1, [ 11, [ 101, [ 1001 ] ] ] ] + call assert_equal(l4, flatten(deepcopy(l4), 0)) + call assert_equal([1, 11, [101, [1001]]], flattennew(l4, 1)) + call assert_equal([1, 11, 101, [1001]], flattennew(l4, 2)) + call assert_equal([1, 11, 101, 1001], flattennew(l4, 3)) + call assert_equal([1, 11, 101, 1001], flattennew(l4, 4)) + call assert_equal([1, 11, 101, 1001], flattennew(l4)) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_float_func.vim b/test/old/testdir/test_float_func.vim new file mode 100644 index 0000000000..f9a7251d59 --- /dev/null +++ b/test/old/testdir/test_float_func.vim @@ -0,0 +1,372 @@ +" test float functions + +source check.vim +CheckFeature float +source vim9.vim + +func Test_abs() + call assert_equal('1.23', string(abs(1.23))) + call assert_equal('1.23', string(abs(-1.23))) + eval -1.23->abs()->string()->assert_equal('1.23') + + call assert_equal('0.0', string(abs(0.0))) + call assert_equal('0.0', string(abs(1.0/(1.0/0.0)))) + call assert_equal('0.0', string(abs(-1.0/(1.0/0.0)))) + call assert_equal("str2float('inf')", string(abs(1.0/0.0))) + call assert_equal("str2float('inf')", string(abs(-1.0/0.0))) + call assert_equal("str2float('nan')", string(abs(0.0/0.0))) + call assert_equal('12', string(abs('12abc'))) + call assert_equal('12', string(abs('-12abc'))) + call assert_fails("call abs([])", 'E745:') + call assert_fails("call abs({})", 'E728:') + call assert_fails("call abs(function('string'))", 'E703:') +endfunc + +func Test_sqrt() + call assert_equal('0.0', string(sqrt(0.0))) + call assert_equal('1.414214', string(sqrt(2.0))) + eval 2.0->sqrt()->string()->assert_equal('1.414214') + call assert_equal("str2float('inf')", string(sqrt(1.0/0.0))) + call assert_equal("str2float('nan')", string(sqrt(-1.0))) + call assert_equal("str2float('nan')", string(sqrt(0.0/0.0))) + call assert_fails('call sqrt("")', 'E808:') +endfunc + +func Test_log() + call assert_equal('0.0', string(log(1.0))) + call assert_equal('-0.693147', string(log(0.5))) + eval 0.5->log()->string()->assert_equal('-0.693147') + call assert_equal("-str2float('inf')", string(log(0.0))) + call assert_equal("str2float('nan')", string(log(-1.0))) + call assert_equal("str2float('inf')", string(log(1.0/0.0))) + call assert_equal("str2float('nan')", string(log(0.0/0.0))) + call assert_fails('call log("")', 'E808:') +endfunc + +func Test_log10() + call assert_equal('0.0', string(log10(1.0))) + call assert_equal('2.0', string(log10(100.0))) + call assert_equal('2.079181', string(log10(120.0))) + eval 120.0->log10()->string()->assert_equal('2.079181') + call assert_equal("-str2float('inf')", string(log10(0.0))) + call assert_equal("str2float('nan')", string(log10(-1.0))) + call assert_equal("str2float('inf')", string(log10(1.0/0.0))) + call assert_equal("str2float('nan')", string(log10(0.0/0.0))) + call assert_fails('call log10("")', 'E808:') +endfunc + +func Test_exp() + call assert_equal('1.0', string(exp(0.0))) + call assert_equal('7.389056', string(exp(2.0))) + call assert_equal('0.367879', string(exp(-1.0))) + eval -1.0->exp()->string()->assert_equal('0.367879') + call assert_equal("str2float('inf')", string(exp(1.0/0.0))) + call assert_equal('0.0', string(exp(-1.0/0.0))) + call assert_equal("str2float('nan')", string(exp(0.0/0.0))) + call assert_fails('call exp("")', 'E808:') +endfunc + +func Test_sin() + call assert_equal('0.0', string(sin(0.0))) + call assert_equal('0.841471', string(sin(1.0))) + call assert_equal('-0.479426', string(sin(-0.5))) + eval -0.5->sin()->string()->assert_equal('-0.479426') + call assert_equal("str2float('nan')", string(sin(0.0/0.0))) + call assert_equal("str2float('nan')", string(sin(1.0/0.0))) + call assert_equal('0.0', string(sin(1.0/(1.0/0.0)))) + call assert_equal('-0.0', string(sin(-1.0/(1.0/0.0)))) + call assert_fails('call sin("")', 'E808:') +endfunc + +func Test_asin() + call assert_equal('0.0', string(asin(0.0))) + call assert_equal('1.570796', string(asin(1.0))) + eval 1.0->asin()->string()->assert_equal('1.570796') + + call assert_equal('-0.523599', string(asin(-0.5))) + call assert_equal("str2float('nan')", string(asin(1.1))) + call assert_equal("str2float('nan')", string(asin(1.0/0.0))) + call assert_equal("str2float('nan')", string(asin(0.0/0.0))) + call assert_fails('call asin("")', 'E808:') +endfunc + +func Test_sinh() + call assert_equal('0.0', string(sinh(0.0))) + call assert_equal('0.521095', string(sinh(0.5))) + call assert_equal('-1.026517', string(sinh(-0.9))) + eval -0.9->sinh()->string()->assert_equal('-1.026517') + call assert_equal("str2float('inf')", string(sinh(1.0/0.0))) + call assert_equal("-str2float('inf')", string(sinh(-1.0/0.0))) + call assert_equal("str2float('nan')", string(sinh(0.0/0.0))) + call assert_fails('call sinh("")', 'E808:') +endfunc + +func Test_cos() + call assert_equal('1.0', string(cos(0.0))) + call assert_equal('0.540302', string(cos(1.0))) + call assert_equal('0.877583', string(cos(-0.5))) + eval -0.5->cos()->string()->assert_equal('0.877583') + call assert_equal("str2float('nan')", string(cos(0.0/0.0))) + call assert_equal("str2float('nan')", string(cos(1.0/0.0))) + call assert_fails('call cos("")', 'E808:') +endfunc + +func Test_acos() + call assert_equal('1.570796', string(acos(0.0))) + call assert_equal('0.0', string(acos(1.0))) + call assert_equal('3.141593', string(acos(-1.0))) + eval -1.0->acos()->string()->assert_equal('3.141593') + call assert_equal('2.094395', string(acos(-0.5))) + call assert_equal("str2float('nan')", string(acos(1.1))) + call assert_equal("str2float('nan')", string(acos(1.0/0.0))) + call assert_equal("str2float('nan')", string(acos(0.0/0.0))) + call assert_fails('call acos("")', 'E808:') +endfunc + +func Test_cosh() + call assert_equal('1.0', string(cosh(0.0))) + call assert_equal('1.127626', string(cosh(0.5))) + eval 0.5->cosh()->string()->assert_equal('1.127626') + call assert_equal("str2float('inf')", string(cosh(1.0/0.0))) + call assert_equal("str2float('inf')", string(cosh(-1.0/0.0))) + call assert_equal("str2float('nan')", string(cosh(0.0/0.0))) + call assert_fails('call cosh("")', 'E808:') +endfunc + +func Test_tan() + call assert_equal('0.0', string(tan(0.0))) + call assert_equal('0.546302', string(tan(0.5))) + call assert_equal('-0.546302', string(tan(-0.5))) + eval -0.5->tan()->string()->assert_equal('-0.546302') + call assert_equal("str2float('nan')", string(tan(1.0/0.0))) + call assert_equal("str2float('nan')", string(cos(0.0/0.0))) + call assert_equal('0.0', string(tan(1.0/(1.0/0.0)))) + call assert_equal('-0.0', string(tan(-1.0/(1.0/0.0)))) + call assert_fails('call tan("")', 'E808:') +endfunc + +func Test_atan() + call assert_equal('0.0', string(atan(0.0))) + call assert_equal('0.463648', string(atan(0.5))) + call assert_equal('-0.785398', string(atan(-1.0))) + eval -1.0->atan()->string()->assert_equal('-0.785398') + call assert_equal('1.570796', string(atan(1.0/0.0))) + call assert_equal('-1.570796', string(atan(-1.0/0.0))) + call assert_equal("str2float('nan')", string(atan(0.0/0.0))) + call assert_fails('call atan("")', 'E808:') +endfunc + +func Test_atan2() + call assert_equal('-2.356194', string(atan2(-1, -1))) + call assert_equal('2.356194', string(atan2(1, -1))) + call assert_equal('0.0', string(atan2(1.0, 1.0/0.0))) + eval 1.0->atan2(1.0/0.0)->string()->assert_equal('0.0') + call assert_equal('1.570796', string(atan2(1.0/0.0, 1.0))) + call assert_equal("str2float('nan')", string(atan2(0.0/0.0, 1.0))) + call assert_fails('call atan2("", -1)', 'E808:') + call assert_fails('call atan2(-1, "")', 'E808:') +endfunc + +func Test_tanh() + call assert_equal('0.0', string(tanh(0.0))) + call assert_equal('0.462117', string(tanh(0.5))) + call assert_equal('-0.761594', string(tanh(-1.0))) + eval -1.0->tanh()->string()->assert_equal('-0.761594') + call assert_equal('1.0', string(tanh(1.0/0.0))) + call assert_equal('-1.0', string(tanh(-1.0/0.0))) + call assert_equal("str2float('nan')", string(tanh(0.0/0.0))) + call assert_fails('call tanh("")', 'E808:') +endfunc + +func Test_fmod() + call assert_equal('0.13', string(fmod(12.33, 1.22))) + call assert_equal('-0.13', string(fmod(-12.33, 1.22))) + call assert_equal("str2float('nan')", string(fmod(1.0/0.0, 1.0))) + eval (1.0/0.0)->fmod(1.0)->string()->assert_equal("str2float('nan')") + " On Windows we get "nan" instead of 1.0, accept both. + let res = string(fmod(1.0, 1.0/0.0)) + if res != "str2float('nan')" + call assert_equal('1.0', res) + endif + call assert_equal("str2float('nan')", string(fmod(1.0, 0.0))) + call assert_fails("call fmod('', 1.22)", 'E808:') + call assert_fails("call fmod(12.33, '')", 'E808:') +endfunc + +func Test_pow() + call assert_equal('1.0', string(pow(0.0, 0.0))) + call assert_equal('8.0', string(pow(2.0, 3.0))) + eval 2.0->pow(3.0)->string()->assert_equal('8.0') + call assert_equal("str2float('nan')", string(pow(2.0, 0.0/0.0))) + call assert_equal("str2float('nan')", string(pow(0.0/0.0, 3.0))) + call assert_equal("str2float('nan')", string(pow(0.0/0.0, 3.0))) + call assert_equal("str2float('inf')", string(pow(2.0, 1.0/0.0))) + call assert_equal("str2float('inf')", string(pow(1.0/0.0, 3.0))) + call assert_fails("call pow('', 2.0)", 'E808:') + call assert_fails("call pow(2.0, '')", 'E808:') +endfunc + +func Test_str2float() + call assert_equal('1.0', string(str2float('1'))) + call assert_equal('1.0', string(str2float(' 1 '))) + call assert_equal('1.0', string(str2float(' 1.0 '))) + call assert_equal('1.23', string(str2float('1.23'))) + call assert_equal('1.23', string(str2float('1.23abc'))) + eval '1.23abc'->str2float()->string()->assert_equal('1.23') + call assert_equal('1.0e40', string(str2float('1e40'))) + call assert_equal('-1.23', string(str2float('-1.23'))) + call assert_equal('1.23', string(str2float(' + 1.23 '))) + + call assert_equal('1.0', string(str2float('+1'))) + call assert_equal('1.0', string(str2float('+1'))) + call assert_equal('1.0', string(str2float(' +1 '))) + call assert_equal('1.0', string(str2float(' + 1 '))) + + call assert_equal('-1.0', string(str2float('-1'))) + call assert_equal('-1.0', string(str2float('-1'))) + call assert_equal('-1.0', string(str2float(' -1 '))) + call assert_equal('-1.0', string(str2float(' - 1 '))) + + call assert_equal('0.0', string(str2float('+0.0'))) + call assert_equal('-0.0', string(str2float('-0.0'))) + call assert_equal("str2float('inf')", string(str2float('1e1000'))) + call assert_equal("str2float('inf')", string(str2float('inf'))) + call assert_equal("-str2float('inf')", string(str2float('-inf'))) + call assert_equal("str2float('inf')", string(str2float('+inf'))) + call assert_equal("str2float('inf')", string(str2float('Inf'))) + call assert_equal("str2float('inf')", string(str2float(' +inf '))) + call assert_equal("str2float('nan')", string(str2float('nan'))) + call assert_equal("str2float('nan')", string(str2float('NaN'))) + call assert_equal("str2float('nan')", string(str2float(' nan '))) + + call assert_equal(1.2, str2float(1.2)) + call CheckDefExecFailure(['str2float(1.2)'], 'E1013:') + call CheckScriptFailure(['vim9script', 'str2float(1.2)'], 'E806:') + call assert_fails("call str2float([])", 'E730:') + call assert_fails("call str2float({})", 'E731:') + call assert_fails("call str2float(function('string'))", 'E729:') +endfunc + +func Test_float2nr() + call assert_equal(1, float2nr(1.234)) + call assert_equal(123, float2nr(1.234e2)) + call assert_equal(12, float2nr(123.4e-1)) + eval 123.4e-1->float2nr()->assert_equal(12) + let max_number = 1/0 + let min_number = -max_number + call assert_equal(max_number/2+1, float2nr(pow(2, 62))) + call assert_equal(max_number, float2nr(pow(2, 63))) + call assert_equal(max_number, float2nr(pow(2, 64))) + call assert_equal(min_number/2-1, float2nr(-pow(2, 62))) + call assert_equal(min_number, float2nr(-pow(2, 63))) + call assert_equal(min_number, float2nr(-pow(2, 64))) +endfunc + +func Test_floor() + call assert_equal('2.0', string(floor(2.0))) + call assert_equal('2.0', string(floor(2.11))) + call assert_equal('2.0', string(floor(2.99))) + eval 2.99->floor()->string()->assert_equal('2.0') + call assert_equal('-3.0', string(floor(-2.11))) + call assert_equal('-3.0', string(floor(-2.99))) + call assert_equal("str2float('nan')", string(floor(0.0/0.0))) + call assert_equal("str2float('inf')", string(floor(1.0/0.0))) + call assert_equal("-str2float('inf')", string(floor(-1.0/0.0))) + call assert_fails("call floor('')", 'E808:') +endfunc + +func Test_ceil() + call assert_equal('2.0', string(ceil(2.0))) + call assert_equal('3.0', string(ceil(2.11))) + call assert_equal('3.0', string(ceil(2.99))) + call assert_equal('-2.0', string(ceil(-2.11))) + eval -2.11->ceil()->string()->assert_equal('-2.0') + call assert_equal('-2.0', string(ceil(-2.99))) + call assert_equal("str2float('nan')", string(ceil(0.0/0.0))) + call assert_equal("str2float('inf')", string(ceil(1.0/0.0))) + call assert_equal("-str2float('inf')", string(ceil(-1.0/0.0))) + call assert_fails("call ceil('')", 'E808:') +endfunc + +func Test_round() + call assert_equal('2.0', string(round(2.1))) + call assert_equal('3.0', string(round(2.5))) + call assert_equal('3.0', string(round(2.9))) + eval 2.9->round()->string()->assert_equal('3.0') + call assert_equal('-2.0', string(round(-2.1))) + call assert_equal('-3.0', string(round(-2.5))) + call assert_equal('-3.0', string(round(-2.9))) + call assert_equal("str2float('nan')", string(round(0.0/0.0))) + call assert_equal("str2float('inf')", string(round(1.0/0.0))) + call assert_equal("-str2float('inf')", string(round(-1.0/0.0))) + call assert_fails("call round('')", 'E808:') +endfunc + +func Test_trunc() + call assert_equal('2.0', string(trunc(2.1))) + call assert_equal('2.0', string(trunc(2.5))) + call assert_equal('2.0', string(trunc(2.9))) + eval 2.9->trunc()->string()->assert_equal('2.0') + call assert_equal('-2.0', string(trunc(-2.1))) + call assert_equal('-2.0', string(trunc(-2.5))) + call assert_equal('-2.0', string(trunc(-2.9))) + call assert_equal("str2float('nan')", string(trunc(0.0/0.0))) + call assert_equal("str2float('inf')", string(trunc(1.0/0.0))) + call assert_equal("-str2float('inf')", string(trunc(-1.0/0.0))) + call assert_fails("call trunc('')", 'E808:') +endfunc + +func Test_isinf() + call assert_equal(1, isinf(1.0/0.0)) + call assert_equal(-1, isinf(-1.0/0.0)) + eval (-1.0/0.0)->isinf()->assert_equal(-1) + call assert_false(isinf(1.0)) + call assert_false(isinf(0.0/0.0)) + call assert_false(isinf('a')) + call assert_false(isinf([])) + call assert_false(isinf({})) +endfunc + +func Test_isnan() + call assert_true(isnan(0.0/0.0)) + call assert_false(isnan(1.0)) + call assert_false(isnan(1.0/0.0)) + eval (1.0/0.0)->isnan()->assert_false() + call assert_false(isnan(-1.0/0.0)) + call assert_false(isnan('a')) + call assert_false(isnan([])) + call assert_false(isnan({})) +endfunc + +" This was converted from test65 +func Test_float_misc() + call assert_equal('123.456000', printf('%f', 123.456)) + call assert_equal('1.234560e+02', printf('%e', 123.456)) + call assert_equal('123.456', printf('%g', 123.456)) + " += + let v = 1.234 + let v += 6.543 + call assert_equal('7.777', printf('%g', v)) + let v = 1.234 + let v += 5 + call assert_equal('6.234', printf('%g', v)) + let v = 5 + let v += 3.333 + call assert_equal('8.333', string(v)) + " == + let v = 1.234 + call assert_true(v == 1.234) + call assert_false(v == 1.2341) + " add-subtract + call assert_equal('5.234', printf('%g', 4 + 1.234)) + call assert_equal('-6.766', printf('%g', 1.234 - 8)) + " mult-div + call assert_equal('4.936', printf('%g', 4 * 1.234)) + call assert_equal('0.003241', printf('%g', 4.0 / 1234)) + " dict + call assert_equal("{'x': 1.234, 'y': -2.0e20}", string({'x': 1.234, 'y': -2.0e20})) + " list + call assert_equal('[-123.4, 2.0e-20]', string([-123.4, 2.0e-20])) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_fnameescape.vim b/test/old/testdir/test_fnameescape.vim new file mode 100644 index 0000000000..cdb96ba5ff --- /dev/null +++ b/test/old/testdir/test_fnameescape.vim @@ -0,0 +1,27 @@ + +" Test if fnameescape is correct for special chars like ! +func Test_fnameescape() + let fname = 'Xspa ce' + let status = v:false + try + exe "w! " . fnameescape(fname) + let status = v:true + endtry + call assert_true(status, "Space") + call delete(fname) + + let fname = 'Xemark!' + let status = v:false + try + exe "w! " . fname->fnameescape() + let status = v:true + endtry + call assert_true(status, "ExclamationMark") + call delete(fname) + + call assert_equal('\-', fnameescape('-')) + call assert_equal('\+', fnameescape('+')) + call assert_equal('\>', fnameescape('>')) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_fnamemodify.vim b/test/old/testdir/test_fnamemodify.vim new file mode 100644 index 0000000000..258a2093bd --- /dev/null +++ b/test/old/testdir/test_fnamemodify.vim @@ -0,0 +1,104 @@ +" Test filename modifiers. + +func Test_fnamemodify() + let save_home = $HOME + let save_shell = &shell + let save_shellslash = &shellslash + let $HOME = fnamemodify('.', ':p:h:h') + set shell=sh + set shellslash + + call assert_equal('/', fnamemodify('.', ':p')[-1:]) + call assert_equal('r', fnamemodify('.', ':p:h')[-1:]) + call assert_equal('t', fnamemodify('test.out', ':p')[-1:]) + call assert_equal($HOME .. "/foo" , fnamemodify('~/foo', ':p')) + call assert_equal('test.out', fnamemodify('test.out', ':.')) + call assert_equal('a', fnamemodify('../testdir/a', ':.')) + call assert_equal('~/testdir/test.out', fnamemodify('test.out', ':~')) + call assert_equal('~/testdir/a', fnamemodify('../testdir/a', ':~')) + call assert_equal('a', '../testdir/a'->fnamemodify(':t')) + call assert_equal('', fnamemodify('.', ':p:t')) + call assert_equal('test.out', fnamemodify('test.out', ':p:t')) + call assert_equal('out', fnamemodify('test.out', ':p:e')) + call assert_equal('out', fnamemodify('test.out', ':p:t:e')) + call assert_equal('abc.fb2.tar', fnamemodify('abc.fb2.tar.gz', ':r')) + call assert_equal('abc.fb2', fnamemodify('abc.fb2.tar.gz', ':r:r')) + call assert_equal('abc', fnamemodify('abc.fb2.tar.gz', ':r:r:r')) + call assert_equal('testdir/abc.fb2', substitute(fnamemodify('abc.fb2.tar.gz', ':p:r:r'), '.*\(testdir/.*\)', '\1', '')) + call assert_equal('gz', fnamemodify('abc.fb2.tar.gz', ':e')) + call assert_equal('tar.gz', fnamemodify('abc.fb2.tar.gz', ':e:e')) + call assert_equal('fb2.tar.gz', fnamemodify('abc.fb2.tar.gz', ':e:e:e')) + call assert_equal('fb2.tar.gz', fnamemodify('abc.fb2.tar.gz', ':e:e:e:e')) + call assert_equal('tar', fnamemodify('abc.fb2.tar.gz', ':e:e:r')) + call assert_equal(getcwd(), fnamemodify('', ':p:h')) + + let cwd = getcwd() + call chdir($HOME) + call assert_equal('foobar', fnamemodify('~/foobar', ':~:.')) + call chdir(cwd) + call mkdir($HOME . '/XXXXXXXX/a', 'p') + call mkdir($HOME . '/XXXXXXXX/b', 'p') + call chdir($HOME . '/XXXXXXXX/a/') + call assert_equal('foo', fnamemodify($HOME . '/XXXXXXXX/a/foo', ':p:~:.')) + call assert_equal('~/XXXXXXXX/b/foo', fnamemodify($HOME . '/XXXXXXXX/b/foo', ':p:~:.')) + call mkdir($HOME . '/XXXXXXXX/a.ext', 'p') + call assert_equal('~/XXXXXXXX/a.ext/foo', fnamemodify($HOME . '/XXXXXXXX/a.ext/foo', ':p:~:.')) + call chdir(cwd) + call delete($HOME . '/XXXXXXXX', 'rf') + + call assert_equal('''abc def''', fnamemodify('abc def', ':S')) + call assert_equal('''abc" "def''', fnamemodify('abc" "def', ':S')) + call assert_equal('''abc"%"def''', fnamemodify('abc"%"def', ':S')) + call assert_equal('''abc''\'''' ''\''''def''', fnamemodify('abc'' ''def', ':S')) + call assert_equal('''abc''\''''%''\''''def''', fnamemodify('abc''%''def', ':S')) + sp test_alot.vim + call assert_equal(expand('%:r:S'), shellescape(expand('%:r'))) + call assert_equal('test_alot,''test_alot'',test_alot.vim', join([expand('%:r'), expand('%:r:S'), expand('%')], ',')) + quit + + call assert_equal("'abc\ndef'", fnamemodify("abc\ndef", ':S')) + set shell=tcsh + call assert_equal("'abc\\\ndef'", fnamemodify("abc\ndef", ':S')) + + let $HOME = save_home + let &shell = save_shell + let &shellslash = save_shellslash +endfunc + +func Test_fnamemodify_er() + call assert_equal("with", fnamemodify("path/to/file.with.extensions", ':e:e:r:r')) + + call assert_equal('c', fnamemodify('a.c', ':e')) + call assert_equal('c', fnamemodify('a.c', ':e:e')) + call assert_equal('c', fnamemodify('a.c', ':e:e:r')) + call assert_equal('c', fnamemodify('a.c', ':e:e:r:r')) + + call assert_equal('rb', fnamemodify('a.spec.rb', ':e:r')) + call assert_equal('rb', fnamemodify('a.spec.rb', ':e:r')) + call assert_equal('spec.rb', fnamemodify('a.spec.rb', ':e:e')) + call assert_equal('spec', fnamemodify('a.spec.rb', ':e:e:r')) + call assert_equal('spec', fnamemodify('a.spec.rb', ':e:e:r:r')) + call assert_equal('spec', fnamemodify('a.b.spec.rb', ':e:e:r')) + call assert_equal('b.spec', fnamemodify('a.b.spec.rb', ':e:e:e:r')) + call assert_equal('b', fnamemodify('a.b.spec.rb', ':e:e:e:r:r')) + + call assert_equal('spec', fnamemodify('a.b.spec.rb', ':r:e')) + call assert_equal('b', fnamemodify('a.b.spec.rb', ':r:r:e')) + + call assert_equal('c', fnamemodify('a.b.c.d.e', ':r:r:e')) + call assert_equal('b.c', fnamemodify('a.b.c.d.e', ':r:r:e:e')) + + " :e never includes the whole filename, so "a.b":e:e:e --> "b" + call assert_equal('b.c', fnamemodify('a.b.c.d.e', ':r:r:e:e:e')) + call assert_equal('b.c', fnamemodify('a.b.c.d.e', ':r:r:e:e:e:e')) + + call assert_equal('', fnamemodify('', ':p:t')) + call assert_equal('', fnamemodify(v:_null_string, v:_null_string)) +endfunc + +func Test_fnamemodify_fail() + call assert_fails('call fnamemodify({}, ":p")', 'E731:') + call assert_fails('call fnamemodify("x", {})', 'E731:') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_fold.vim b/test/old/testdir/test_fold.vim new file mode 100644 index 0000000000..e529a94174 --- /dev/null +++ b/test/old/testdir/test_fold.vim @@ -0,0 +1,1581 @@ +" Test for folding + +source check.vim +source view_util.vim +source screendump.vim + +func PrepIndent(arg) + return [a:arg] + repeat(["\t".a:arg], 5) +endfu + +func Test_address_fold() + new + call setline(1, ['int FuncName() {/*{{{*/', 1, 2, 3, 4, 5, '}/*}}}*/', + \ 'after fold 1', 'after fold 2', 'after fold 3']) + setl fen fdm=marker + " The next commands should all copy the same part of the buffer, + " regardless of the addressing type, since the part to be copied + " is folded away + :1y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/'], getreg(0,1,1)) + :.y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/'], getreg(0,1,1)) + :.+y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/'], getreg(0,1,1)) + :.,.y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/'], getreg(0,1,1)) + :sil .1,.y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/'], getreg(0,1,1)) + " use silent to make E493 go away + :sil .+,.y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/'], getreg(0,1,1)) + :,y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/'], getreg(0,1,1)) + :,+y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/','after fold 1'], getreg(0,1,1)) + " using .+3 as second address should copy the whole folded line + the next 3 + " lines + :.,+3y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/', + \ 'after fold 1', 'after fold 2', 'after fold 3'], getreg(0,1,1)) + :sil .,-2y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3', '4', '5', '}/*}}}*/'], getreg(0,1,1)) + + " now test again with folding disabled + set nofoldenable + :1y + call assert_equal(['int FuncName() {/*{{{*/'], getreg(0,1,1)) + :.y + call assert_equal(['int FuncName() {/*{{{*/'], getreg(0,1,1)) + :.+y + call assert_equal(['1'], getreg(0,1,1)) + :.,.y + call assert_equal(['int FuncName() {/*{{{*/'], getreg(0,1,1)) + " use silent to make E493 go away + :sil .1,.y + call assert_equal(['int FuncName() {/*{{{*/', '1'], getreg(0,1,1)) + " use silent to make E493 go away + :sil .+,.y + call assert_equal(['int FuncName() {/*{{{*/', '1'], getreg(0,1,1)) + :,y + call assert_equal(['int FuncName() {/*{{{*/'], getreg(0,1,1)) + :,+y + call assert_equal(['int FuncName() {/*{{{*/', '1'], getreg(0,1,1)) + " using .+3 as second address should copy the whole folded line + the next 3 + " lines + :.,+3y + call assert_equal(['int FuncName() {/*{{{*/', '1', '2', '3'], getreg(0,1,1)) + :7 + :sil .,-2y + call assert_equal(['4', '5', '}/*}}}*/'], getreg(0,1,1)) + + quit! +endfunc + +func Test_address_offsets() + " check the help for :range-closed-fold + enew + call setline(1, [ + \ '1 one', + \ '2 two', + \ '3 three', + \ '4 four FOLDED', + \ '5 five FOLDED', + \ '6 six', + \ '7 seven', + \ '8 eight', + \]) + set foldmethod=manual + normal 4Gvjzf + 3,4+2yank + call assert_equal([ + \ '3 three', + \ '4 four FOLDED', + \ '5 five FOLDED', + \ '6 six', + \ '7 seven', + \ ], getreg(0,1,1)) + + enew! + call setline(1, [ + \ '1 one', + \ '2 two', + \ '3 three FOLDED', + \ '4 four FOLDED', + \ '5 five FOLDED', + \ '6 six FOLDED', + \ '7 seven', + \ '8 eight', + \]) + normal 3Gv3jzf + 2,4-1yank + call assert_equal([ + \ '2 two', + \ '3 three FOLDED', + \ '4 four FOLDED', + \ '5 five FOLDED', + \ '6 six FOLDED', + \ ], getreg(0,1,1)) + + bwipe! +endfunc + +func Test_indent_fold() + new + call setline(1, ['', 'a', ' b', ' c']) + setl fen fdm=indent + 2 + norm! >> + let a=map(range(1,4), 'foldclosed(v:val)') + call assert_equal([-1,-1,-1,-1], a) + bw! +endfunc + +func Test_indent_fold2() + new + call setline(1, ['', '{{{', '}}}', '{{{', '}}}']) + setl fen fdm=marker + 2 + norm! >> + let a=map(range(1,5), 'v:val->foldclosed()') + call assert_equal([-1,-1,-1,4,4], a) + bw! +endfunc + +" Test for fold indent with indents greater than 'foldnestmax' +func Test_indent_fold_max() + new + setlocal foldmethod=indent + setlocal shiftwidth=2 + " 'foldnestmax' default value is 20 + call setline(1, "\t\t\t\t\t\ta") + call assert_equal(20, foldlevel(1)) + setlocal foldnestmax=10 + call assert_equal(10, foldlevel(1)) + setlocal foldnestmax=-1 + call assert_equal(0, foldlevel(1)) + bw! +endfunc + +func Test_indent_fold_tabstop() + call setline(1, ['0', ' 1', ' 1', "\t2", "\t2"]) + setlocal shiftwidth=4 + setlocal foldcolumn=1 + setlocal foldlevel=2 + setlocal foldmethod=indent + redraw + call assert_equal('2 2', ScreenLines(5, 10)[0]) + vsplit + windo diffthis + botright new + " This 'tabstop' value should not be used for folding in other buffers. + setlocal tabstop=4 + diffoff! + redraw + call assert_equal('2 2', ScreenLines(5, 10)[0]) + + bwipe! + bwipe! +endfunc + +func Test_manual_fold_with_filter() + CheckExecutable cat + for type in ['manual', 'marker'] + exe 'set foldmethod=' . type + new + call setline(1, range(1, 20)) + 4,$fold + %foldopen + 10,$fold + %foldopen + " This filter command should not have an effect + 1,8! cat + call feedkeys('5ggzdzMGdd', 'xt') + call assert_equal(['1', '2', '3', '4', '5', '6', '7', '8', '9'], getline(1, '$')) + + bwipe! + set foldmethod& + endfor +endfunc + +func Test_indent_fold_with_read() + new + set foldmethod=indent + call setline(1, repeat(["\<Tab>a"], 4)) + for n in range(1, 4) + call assert_equal(1, foldlevel(n)) + endfor + + call writefile(["a", "", "\<Tab>a"], 'Xfile') + foldopen + 2read Xfile + %foldclose + call assert_equal(1, foldlevel(1)) + call assert_equal(2, foldclosedend(1)) + call assert_equal(0, foldlevel(3)) + call assert_equal(0, foldlevel(4)) + call assert_equal(1, foldlevel(5)) + call assert_equal(7, 5->foldclosedend()) + + bwipe! + set foldmethod& + call delete('Xfile') +endfunc + +func Test_combining_folds_indent() + new + let one = "\<Tab>a" + let zero = 'a' + call setline(1, [one, one, zero, zero, zero, one, one, one]) + set foldmethod=indent + 3,5d + %foldclose + call assert_equal(5, foldclosedend(1)) + + set foldmethod& + bwipe! +endfunc + +func Test_combining_folds_marker() + new + call setline(1, ['{{{', '}}}', '', '', '', '{{{', '', '}}}']) + set foldmethod=marker + 3,5d + %foldclose + call assert_equal(2, foldclosedend(1)) + + set foldmethod& + bwipe! +endfunc + +func Test_folds_marker_in_comment() + new + call setline(1, ['" foo', 'bar', 'baz']) + setl fen fdm=marker + setl com=sO:\"\ -,mO:\"\ \ ,eO:\"\",:\" cms=\"%s + norm! zf2j + setl nofen + :1y + call assert_equal(['" foo{{{'], getreg(0,1,1)) + :+2y + call assert_equal(['baz"}}}'], getreg(0,1,1)) + + set foldmethod& + bwipe! +endfunc + +func s:TestFoldExpr(lnum) + let thisline = getline(a:lnum) + if thisline == 'a' + return 1 + elseif thisline == 'b' + return 0 + elseif thisline == 'c' + return '<1' + elseif thisline == 'd' + return '>1' + endif + return 0 +endfunction + +func Test_update_folds_expr_read() + new + call setline(1, ['a', 'a', 'a', 'a', 'a', 'a']) + set foldmethod=expr + set foldexpr=s:TestFoldExpr(v:lnum) + 2 + foldopen + call writefile(['b', 'b', 'a', 'a', 'd', 'a', 'a', 'c'], 'Xfile') + read Xfile + %foldclose + call assert_equal(2, foldclosedend(1)) + call assert_equal(0, foldlevel(3)) + call assert_equal(0, 4->foldlevel()) + call assert_equal(6, foldclosedend(5)) + call assert_equal(10, foldclosedend(7)) + call assert_equal(14, foldclosedend(11)) + + call delete('Xfile') + bwipe! + set foldmethod& foldexpr& +endfunc + +" Test for what patch 8.1.0535 fixes. +func Test_foldexpr_no_interrupt_addsub() + new + func! FoldFunc() + call setpos('.', getcurpos()) + return '=' + endfunc + + set foldmethod=expr + set foldexpr=FoldFunc() + call setline(1, '1.2') + + exe "norm! $\<C-A>" + call assert_equal('1.3', getline(1)) + + bwipe! + delfunc FoldFunc + set foldmethod& foldexpr& +endfunc + +func Check_foldlevels(expected) + call assert_equal(a:expected, map(range(1, line('$')), 'foldlevel(v:val)')) +endfunc + +func Test_move_folds_around_manual() + new + let input = PrepIndent("a") + PrepIndent("b") + PrepIndent("c") + call setline(1, PrepIndent("a") + PrepIndent("b") + PrepIndent("c")) + let folds=[-1, 2, 2, 2, 2, 2, -1, 8, 8, 8, 8, 8, -1, 14, 14, 14, 14, 14] + " all folds closed + set foldenable foldlevel=0 fdm=indent + " needs a forced redraw + redraw! + set fdm=manual + call assert_equal(folds, map(range(1, line('$')), 'foldclosed(v:val)')) + call assert_equal(input, getline(1, '$')) + 7,12m0 + call assert_equal(PrepIndent("b") + PrepIndent("a") + PrepIndent("c"), getline(1, '$')) + call assert_equal(folds, map(range(1, line('$')), 'foldclosed(v:val)')) + 10,12m0 + call assert_equal(PrepIndent("a")[1:] + PrepIndent("b") + ["a"] + PrepIndent("c"), getline(1, '$')) + call assert_equal([1, 1, 1, 1, 1, -1, 7, 7, 7, 7, 7, -1, -1, 14, 14, 14, 14, 14], map(range(1, line('$')), 'foldclosed(v:val)')) + " moving should not close the folds + %d + call setline(1, PrepIndent("a") + PrepIndent("b") + PrepIndent("c")) + set fdm=indent + redraw! + set fdm=manual + call cursor(2, 1) + %foldopen + 7,12m0 + let folds=repeat([-1], 18) + call assert_equal(PrepIndent("b") + PrepIndent("a") + PrepIndent("c"), getline(1, '$')) + call assert_equal(folds, map(range(1, line('$')), 'foldclosed(v:val)')) + norm! zM + " folds are not corrupted and all have been closed + call assert_equal([-1, 2, 2, 2, 2, 2, -1, 8, 8, 8, 8, 8, -1, 14, 14, 14, 14, 14], map(range(1, line('$')), 'foldclosed(v:val)')) + %d + call setline(1, ["a", "\tb", "\tc", "\td", "\te"]) + set fdm=indent + redraw! + set fdm=manual + %foldopen + 3m4 + %foldclose + call assert_equal(["a", "\tb", "\td", "\tc", "\te"], getline(1, '$')) + call assert_equal([-1, 5, 5, 5, 5], map(range(1, line('$')), 'foldclosedend(v:val)')) + %d + call setline(1, ["a", "\tb", "\tc", "\td", "\te", "z", "\ty", "\tx", "\tw", "\tv"]) + set fdm=indent foldlevel=0 + set fdm=manual + %foldopen + 3m1 + %foldclose + call assert_equal(["a", "\tc", "\tb", "\td", "\te", "z", "\ty", "\tx", "\tw", "\tv"], getline(1, '$')) + call assert_equal(0, foldlevel(2)) + call assert_equal(5, foldclosedend(3)) + call assert_equal([-1, -1, 3, 3, 3, -1, 7, 7, 7, 7], map(range(1, line('$')), 'foldclosed(v:val)')) + 2,6m$ + %foldclose + call assert_equal(5, foldclosedend(2)) + call assert_equal(0, foldlevel(6)) + call assert_equal(9, foldclosedend(7)) + call assert_equal([-1, 2, 2, 2, 2, -1, 7, 7, 7, -1], map(range(1, line('$')), 'foldclosed(v:val)')) + + %d + " Ensure moving around the edges still works. + call setline(1, PrepIndent("a") + repeat(["a"], 3) + ["\ta"]) + set fdm=indent foldlevel=0 + set fdm=manual + %foldopen + 6m$ + " The first fold has been truncated to the 5'th line. + " Second fold has been moved up because the moved line is now below it. + call Check_foldlevels([0, 1, 1, 1, 1, 0, 0, 0, 1, 0]) + + %delete + set fdm=indent foldlevel=0 + call setline(1, [ + \ "a", + \ "\ta", + \ "\t\ta", + \ "\t\ta", + \ "\t\ta", + \ "a", + \ "a"]) + set fdm=manual + %foldopen! + 4,5m6 + call Check_foldlevels([0, 1, 2, 0, 0, 0, 0]) + + %delete + set fdm=indent + call setline(1, [ + \ "\ta", + \ "\t\ta", + \ "\t\ta", + \ "\t\ta", + \ "\ta", + \ "\t\ta", + \ "\t\ta", + \ "\t\ta", + \ "\ta", + \ "\t\ta", + \ "\t\ta", + \ "\t\ta", + \ "\t\ta", + \ "\ta", + \ "a"]) + set fdm=manual + %foldopen! + 13m7 + call Check_foldlevels([1, 2, 2, 2, 1, 2, 2, 1, 1, 1, 2, 2, 2, 1, 0]) + + bw! +endfunc + +func Test_move_folds_around_indent() + new + let input = PrepIndent("a") + PrepIndent("b") + PrepIndent("c") + call setline(1, PrepIndent("a") + PrepIndent("b") + PrepIndent("c")) + let folds=[-1, 2, 2, 2, 2, 2, -1, 8, 8, 8, 8, 8, -1, 14, 14, 14, 14, 14] + " all folds closed + set fdm=indent + call assert_equal(folds, map(range(1, line('$')), 'foldclosed(v:val)')) + call assert_equal(input, getline(1, '$')) + 7,12m0 + call assert_equal(PrepIndent("b") + PrepIndent("a") + PrepIndent("c"), getline(1, '$')) + call assert_equal(folds, map(range(1, line('$')), 'foldclosed(v:val)')) + 10,12m0 + call assert_equal(PrepIndent("a")[1:] + PrepIndent("b") + ["a"] + PrepIndent("c"), getline(1, '$')) + call assert_equal([1, 1, 1, 1, 1, -1, 7, 7, 7, 7, 7, -1, -1, 14, 14, 14, 14, 14], map(range(1, line('$')), 'foldclosed(v:val)')) + " moving should not close the folds + %d + call setline(1, PrepIndent("a") + PrepIndent("b") + PrepIndent("c")) + set fdm=indent + call cursor(2, 1) + %foldopen + 7,12m0 + let folds=repeat([-1], 18) + call assert_equal(PrepIndent("b") + PrepIndent("a") + PrepIndent("c"), getline(1, '$')) + call assert_equal(folds, map(range(1, line('$')), 'foldclosed(v:val)')) + norm! zM + " folds are not corrupted and all have been closed + call assert_equal([-1, 2, 2, 2, 2, 2, -1, 8, 8, 8, 8, 8, -1, 14, 14, 14, 14, 14], map(range(1, line('$')), 'foldclosed(v:val)')) + %d + call setline(1, ["a", "\tb", "\tc", "\td", "\te"]) + set fdm=indent + %foldopen + 3m4 + %foldclose + call assert_equal(["a", "\tb", "\td", "\tc", "\te"], getline(1, '$')) + call assert_equal([-1, 5, 5, 5, 5], map(range(1, line('$')), 'foldclosedend(v:val)')) + %d + call setline(1, ["a", "\tb", "\tc", "\td", "\te", "z", "\ty", "\tx", "\tw", "\tv"]) + set fdm=indent foldlevel=0 + %foldopen + 3m1 + %foldclose + call assert_equal(["a", "\tc", "\tb", "\td", "\te", "z", "\ty", "\tx", "\tw", "\tv"], getline(1, '$')) + call assert_equal(1, foldlevel(2)) + call assert_equal(5, foldclosedend(3)) + call assert_equal([-1, 2, 2, 2, 2, -1, 7, 7, 7, 7], map(range(1, line('$')), 'foldclosed(v:val)')) + 2,6m$ + %foldclose + call assert_equal(9, foldclosedend(2)) + call assert_equal(1, foldlevel(6)) + call assert_equal(9, foldclosedend(7)) + call assert_equal([-1, 2, 2, 2, 2, 2, 2, 2, 2, -1], map(range(1, line('$')), 'foldclosed(v:val)')) + " Ensure moving around the edges still works. + %d + call setline(1, PrepIndent("a") + repeat(["a"], 3) + ["\ta"]) + set fdm=indent foldlevel=0 + %foldopen + 6m$ + " The first fold has been truncated to the 5'th line. + " Second fold has been moved up because the moved line is now below it. + call Check_foldlevels([0, 1, 1, 1, 1, 0, 0, 0, 1, 1]) + bw! +endfunc + +func Test_folddoopen_folddoclosed() + new + call setline(1, range(1, 9)) + set foldmethod=manual + 1,3 fold + 6,8 fold + + " Test without range. + folddoopen s/$/o/ + folddoclosed s/$/c/ + call assert_equal(['1c', '2c', '3c', + \ '4o', '5o', + \ '6c', '7c', '8c', + \ '9o'], getline(1, '$')) + + " Test with range. + call setline(1, range(1, 9)) + 1,8 folddoopen s/$/o/ + 4,$ folddoclosed s/$/c/ + call assert_equal(['1', '2', '3', + \ '4o', '5o', + \ '6c', '7c', '8c', + \ '9'], getline(1, '$')) + + set foldmethod& + bw! +endfunc + +func Test_fold_error() + new + call setline(1, [1, 2]) + + for fm in ['indent', 'expr', 'syntax', 'diff'] + exe 'set foldmethod=' . fm + call assert_fails('norm zf', 'E350:') + call assert_fails('norm zd', 'E351:') + call assert_fails('norm zE', 'E352:') + endfor + + set foldmethod=manual + call assert_fails('norm zd', 'E490:') + call assert_fails('norm zo', 'E490:') + call assert_fails('3fold', 'E16:') + + set foldmethod=marker + set nomodifiable + call assert_fails('1,2fold', 'E21:') + + set modifiable& + set foldmethod& + bw! +endfunc + +func Test_foldtext_recursive() + new + call setline(1, ['{{{', 'some text', '}}}']) + setlocal foldenable foldmethod=marker foldtext=foldtextresult(v\:foldstart) + " This was crashing because of endless recursion. + 2foldclose + redraw + call assert_equal(1, foldlevel(2)) + call assert_equal(1, foldclosed(2)) + call assert_equal(3, foldclosedend(2)) + bwipe! +endfunc + +" Various fold related tests + +" Basic test if a fold can be created, opened, moving to the end and closed +func Test_fold_manual() + new + set fdm=manual + + let content = ['1 aa', '2 bb', '3 cc'] + call append(0, content) + call cursor(1, 1) + normal zf2j + call assert_equal('1 aa', getline(foldclosed('.'))) + normal zo + call assert_equal(-1, foldclosed('.')) + normal ]z + call assert_equal('3 cc', getline('.')) + normal zc + call assert_equal('1 aa', getline(foldclosed('.'))) + + " Create a fold inside a closed fold after setting 'foldlevel' + %d _ + call setline(1, range(1, 5)) + 1,5fold + normal zR + 2,4fold + set foldlevel=1 + 3fold + call assert_equal([1, 3, 3, 3, 1], map(range(1, 5), {->foldlevel(v:val)})) + set foldlevel& + + " Create overlapping folds (at the start and at the end) + normal zE + 2,3fold + normal zR + 3,4fold + call assert_equal([0, 2, 2, 1, 0], map(range(1, 5), {->foldlevel(v:val)})) + normal zE + 3,4fold + normal zR + 2,3fold + call assert_equal([0, 1, 2, 2, 0], map(range(1, 5), {->foldlevel(v:val)})) + + " Create a nested fold across two non-adjoining folds + %d _ + call setline(1, range(1, 7)) + 1,2fold + normal zR + 4,5fold + normal zR + 6,7fold + normal zR + 1,5fold + call assert_equal([2, 2, 1, 2, 2, 1, 1], + \ map(range(1, 7), {->foldlevel(v:val)})) + + " A newly created nested fold should be closed + %d _ + call setline(1, range(1, 6)) + 1,6fold + normal zR + 3,4fold + normal zR + 2,5fold + call assert_equal([1, 2, 3, 3, 2, 1], map(range(1, 6), {->foldlevel(v:val)})) + call assert_equal(2, foldclosed(4)) + call assert_equal(5, foldclosedend(4)) + + " Test zO, zC and zA on a line with no folds. + normal zE + call assert_fails('normal zO', 'E490:') + call assert_fails('normal zC', 'E490:') + call assert_fails('normal zA', 'E490:') + + set fdm& + bw! +endfunc + +" test folding with markers. +func Test_fold_marker() + new + set fdm=marker fdl=1 fdc=3 + + let content = ['4 dd {{{', '5 ee {{{ }}}', '6 ff }}}'] + call append(0, content) + call cursor(2, 1) + call assert_equal(2, foldlevel('.')) + normal [z + call assert_equal(1, foldlevel('.')) + exe "normal jo{{ \<Esc>r{jj" + call assert_equal(1, foldlevel('.')) + normal kYpj + call assert_equal(0, foldlevel('.')) + + " Use only closing fold marker (without and with a count) + set fdl& + %d _ + call setline(1, ['one }}}', 'two']) + call assert_equal([0, 0], [foldlevel(1), foldlevel(2)]) + %d _ + call setline(1, ['one }}}4', 'two']) + call assert_equal([4, 3], [foldlevel(1), foldlevel(2)]) + + set fdm& fdl& fdc& + bw! +endfunc + +" test create fold markers with C filetype +func Test_fold_create_marker_in_C() + bw! + set fdm=marker fdl=9 + set filetype=c + + let content =<< trim [CODE] + /* + * comment + * + * + */ + int f(int* p) { + *p = 3; + return 0; + } + [CODE] + + for c in range(len(content) - 1) + bw! + call append(0, content) + call cursor(c + 1, 1) + norm! zfG + call assert_equal(content[c] . (c < 4 ? '{{{' : '/*{{{*/'), getline(c + 1)) + endfor + + set fdm& fdl& + bw! +endfunc + +" test folding with indent +func Test_fold_indent() + new + set fdm=indent sw=2 + + let content = ['1 aa', '2 bb', '3 cc'] + call append(0, content) + call cursor(2, 1) + exe "normal i \<Esc>jI " + call assert_equal(2, foldlevel('.')) + normal k + call assert_equal(1, foldlevel('.')) + + set fdm& sw& + bw! +endfunc + +" test syntax folding +func Test_fold_syntax() + CheckFeature syntax + + new + set fdm=syntax fdl=0 + + syn region Hup start="dd" end="ii" fold contains=Fd1,Fd2,Fd3 + syn region Fd1 start="ee" end="ff" fold contained + syn region Fd2 start="gg" end="hh" fold contained + syn region Fd3 start="commentstart" end="commentend" fold contained + let content = ['3 cc', '4 dd {{{', '5 ee {{{ }}}', '{{{{', '6 ff }}}', + \ '6 ff }}}', '7 gg', '8 hh', '9 ii'] + call append(0, content) + normal Gzk + call assert_equal('9 ii', getline('.')) + normal k + call assert_equal('3 cc', getline('.')) + exe "normal jAcommentstart \<Esc>Acommentend" + set fdl=1 + normal 3j + call assert_equal('7 gg', getline('.')) + set fdl=0 + exe "normal zO\<C-L>j" + call assert_equal('8 hh', getline('.')) + syn clear Fd1 Fd2 Fd3 Hup + + set fdm& fdl& + bw! +endfunc + +func Flvl() + let l = getline(v:lnum) + if l =~ "bb$" + return 2 + elseif l =~ "gg$" + return "s1" + elseif l =~ "ii$" + return ">2" + elseif l =~ "kk$" + return "0" + endif + return "=" +endfun + +" test expression folding +func Test_fold_expr() + new + set fdm=expr fde=Flvl() + + let content = ['1 aa', + \ '2 bb', + \ '3 cc', + \ '4 dd {{{commentstart commentend', + \ '5 ee {{{ }}}', + \ '{{{', + \ '6 ff }}}', + \ '6 ff }}}', + \ ' 7 gg', + \ ' 8 hh', + \ '9 ii', + \ 'a jj', + \ 'b kk'] + call append(0, content) + call cursor(1, 1) + exe "normal /bb$\<CR>" + call assert_equal(2, foldlevel('.')) + exe "normal /hh$\<CR>" + call assert_equal(1, foldlevel('.')) + exe "normal /ii$\<CR>" + call assert_equal(2, foldlevel('.')) + exe "normal /kk$\<CR>" + call assert_equal(0, foldlevel('.')) + + set fdm& fde& + bw! +endfunc + +" Bug with fdm=indent and moving folds +" Moving a fold a few times, messes up the folds below the moved fold. +" Fixed by 7.4.700 +func Test_fold_move() + new + set fdm=indent sw=2 fdl=0 + + let content = ['', '', 'Line1', ' Line2', ' Line3', + \ 'Line4', ' Line5', ' Line6', + \ 'Line7', ' Line8', ' Line9'] + call append(0, content) + normal zM + call cursor(4, 1) + move 2 + move 1 + call assert_equal(7, foldclosed(7)) + call assert_equal(8, foldclosedend(7)) + call assert_equal(0, foldlevel(9)) + call assert_equal(10, foldclosed(10)) + call assert_equal(11, foldclosedend(10)) + call assert_equal('+-- 2 lines: Line2', foldtextresult(2)) + call assert_equal('+-- 2 lines: Line8', 10->foldtextresult()) + + set fdm& sw& fdl& + bw! +endfunc + +" test for patch 7.3.637 +" Cannot catch the error caused by a foldopen when there is no fold. +func Test_foldopen_exception() + new + let a = 'No error caught' + try + foldopen + catch + let a = matchstr(v:exception,'^[^ ]*') + endtry + call assert_equal('Vim(foldopen):E490:', a) + + let a = 'No error caught' + try + foobar + catch + let a = matchstr(v:exception,'^[^ ]*') + endtry + call assert_match('E492:', a) + bw! +endfunc + +func Test_fold_last_line_with_pagedown() + new + set fdm=manual + + let expect = '+-- 11 lines: 9---' + let content = range(1,19) + call append(0, content) + normal dd9G + normal zfG + normal zt + call assert_equal('9', getline(foldclosed('.'))) + call assert_equal('19', getline(foldclosedend('.'))) + call assert_equal(expect, ScreenLines(1, len(expect))[0]) + call feedkeys("\<C-F>", 'xt') + call assert_equal(expect, ScreenLines(1, len(expect))[0]) + call feedkeys("\<C-F>", 'xt') + call assert_equal(expect, ScreenLines(1, len(expect))[0]) + call feedkeys("\<C-B>\<C-F>\<C-F>", 'xt') + call assert_equal(expect, ScreenLines(1, len(expect))[0]) + + set fdm& + bw! +endfunc + +func Test_folds_with_rnu() + CheckScreendump + + call writefile([ + \ 'set fdm=marker rnu foldcolumn=2', + \ 'call setline(1, ["{{{1", "nline 1", "{{{1", "line 2"])', + \ ], 'Xtest_folds_with_rnu') + let buf = RunVimInTerminal('-S Xtest_folds_with_rnu', {}) + + call VerifyScreenDump(buf, 'Test_folds_with_rnu_01', {}) + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_folds_with_rnu_02', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('Xtest_folds_with_rnu') +endfunc + +func Test_folds_marker_in_comment2() + new + call setline(1, ['Lorem ipsum dolor sit', 'Lorem ipsum dolor sit', 'Lorem ipsum dolor sit']) + setl fen fdm=marker + setl commentstring=<!--%s--> + setl comments=s:<!--,m:\ \ \ \ ,e:--> + norm! zf2j + setl nofen + :1y + call assert_equal(['Lorem ipsum dolor sit<!--{{{-->'], getreg(0,1,1)) + :+2y + call assert_equal(['Lorem ipsum dolor sit<!--}}}-->'], getreg(0,1,1)) + + set foldmethod& + bwipe! +endfunc + +func Test_fold_delete_with_marker() + new + call setline(1, ['func Func() {{{1', 'endfunc']) + 1,2yank + new + set fdm=marker + call setline(1, 'x') + normal! Vp + normal! zd + call assert_equal(['func Func() ', 'endfunc'], getline(1, '$')) + + set fdm& + bwipe! + bwipe! +endfunc + +func Test_fold_delete_with_marker_and_whichwrap() + new + let content1 = [''] + let content2 = ['folded line 1 "{{{1', ' test', ' test2', ' test3', '', 'folded line 2 "{{{1', ' test', ' test2', ' test3'] + call setline(1, content1 + content2) + set fdm=marker ww+=l + normal! x + call assert_equal(content2, getline(1, '$')) + set fdm& ww& + bwipe! +endfunc + +func Test_fold_delete_first_line() + new + call setline(1, [ + \ '" x {{{1', + \ '" a', + \ '" aa', + \ '" x {{{1', + \ '" b', + \ '" bb', + \ '" x {{{1', + \ '" c', + \ '" cc', + \ ]) + set foldmethod=marker + 1 + normal dj + call assert_equal([ + \ '" x {{{1', + \ '" c', + \ '" cc', + \ ], getline(1,'$')) + bwipe! + set foldmethod& +endfunc + +" Add a test for deleting the outer fold of a nested fold and promoting the +" inner folds to one level up with already a fold at that level following the +" nested fold. +func Test_fold_delete_recursive_fold() + new + call setline(1, range(1, 7)) + 2,3fold + normal zR + 4,5fold + normal zR + 1,5fold + normal zR + 6,7fold + normal zR + normal 1Gzd + normal 1Gzj + call assert_equal(2, line('.')) + normal zj + call assert_equal(4, line('.')) + normal zj + call assert_equal(6, line('.')) + bw! +endfunc + +" Test for errors in 'foldexpr' +func Test_fold_expr_error() + new + call setline(1, ['one', 'two', 'three']) + " In a window with no folds, foldlevel() should return 0 + call assert_equal(0, foldlevel(1)) + + " Return a list from the expression + set foldexpr=[] + set foldmethod=expr + for i in range(3) + call assert_equal(0, foldlevel(i)) + endfor + + " expression error + set foldexpr=[{] + set foldmethod=expr + for i in range(3) + call assert_equal(0, foldlevel(i)) + endfor + + set foldmethod& foldexpr& + close! +endfunc + +func Test_undo_fold_deletion() + new + set fdm=marker + let lines =<< trim END + " {{{ + " }}}1 + " {{{ + END + call setline(1, lines) + 3d + g/"/d + undo + redo + eval getline(1, '$')->assert_equal(['']) + + set fdm&vim + bwipe! +endfunc + +" this was crashing +func Test_move_no_folds() + new + fold + setlocal fdm=expr + normal zj + bwipe! +endfunc + +" this was crashing +func Test_fold_create_delete_create() + new + fold + fold + normal zd + fold + bwipe! +endfunc + +" this was crashing +func Test_fold_create_delete() + new + norm zFzFzdzj + bwipe! +endfunc + +func Test_fold_relative_move() + new + set fdm=indent sw=2 wrap tw=80 + + let longtext = repeat('x', &columns + 1) + let content = [ ' foo', ' ' .. longtext, ' baz', + \ longtext, + \ ' foo', ' ' .. longtext, ' baz' + \ ] + call append(0, content) + + normal zM + + for lnum in range(1, 3) + call cursor(lnum, 1) + call assert_true(foldclosed(line('.'))) + normal gj + call assert_equal(2, winline()) + endfor + + call cursor(2, 1) + call assert_true(foldclosed(line('.'))) + normal 2gj + call assert_equal(3, winline()) + + for lnum in range(5, 7) + call cursor(lnum, 1) + call assert_true(foldclosed(line('.'))) + normal gk + call assert_equal(3, winline()) + endfor + + call cursor(6, 1) + call assert_true(foldclosed(line('.'))) + normal 2gk + call assert_equal(2, winline()) + + set fdm& sw& wrap& tw& + bw! +endfunc + +" Test for calling foldlevel() from a fold expression +let g:FoldLevels = [] +func FoldExpr1(lnum) + let f = [a:lnum] + for i in range(1, line('$')) + call add(f, foldlevel(i)) + endfor + call add(g:FoldLevels, f) + return getline(a:lnum)[0] == "\t" +endfunc + +func Test_foldexpr_foldlevel() + new + call setline(1, ['one', "\ttwo", "\tthree"]) + setlocal foldmethod=expr + setlocal foldexpr=FoldExpr1(v:lnum) + setlocal foldenable + setlocal foldcolumn=3 + redraw! + call assert_equal([[1, -1, -1, -1], [2, -1, -1, -1], [3, 0, 1, -1]], + \ g:FoldLevels) + set foldmethod& foldexpr& foldenable& foldcolumn& + bw! +endfunc + +" Test for returning different values from a fold expression +func FoldExpr2(lnum) + if a:lnum == 1 || a:lnum == 4 + return -2 + elseif a:lnum == 2 + return 'a1' + elseif a:lnum == 3 + return 's4' + endif + return '=' +endfunc + +func Test_foldexpr_2() + new + call setline(1, ['one', 'two', 'three', 'four']) + setlocal foldexpr=FoldExpr2(v:lnum) + setlocal foldmethod=expr + call assert_equal([0, 1, 1, 0], [foldlevel(1), foldlevel(2), foldlevel(3), + \ foldlevel(4)]) + bw! +endfunc + +" Test for the 'foldclose' option +func Test_foldclose_opt() + CheckScreendump + + let lines =<< trim END + set foldmethod=manual foldclose=all foldopen=all + call setline(1, ['one', 'two', 'three', 'four']) + 2,3fold + func XsaveFoldLevels() + redraw! + call writefile([json_encode([foldclosed(1), foldclosed(2), foldclosed(3), + \ foldclosed(4)])], 'Xoutput', 'a') + endfunc + END + call writefile(lines, 'Xscript') + let rows = 10 + let buf = RunVimInTerminal('-S Xscript', {'rows': rows}) + call term_wait(buf) + call term_sendkeys(buf, ":set noruler\n") + call term_wait(buf) + call term_sendkeys(buf, ":call XsaveFoldLevels()\n") + call term_sendkeys(buf, "2G") + call WaitForAssert({-> assert_equal('two', term_getline(buf, 2))}) + call term_sendkeys(buf, ":call XsaveFoldLevels()\n") + call term_sendkeys(buf, "4G") + call WaitForAssert({-> assert_equal('four', term_getline(buf, 3))}) + call term_sendkeys(buf, ":call XsaveFoldLevels()\n") + call term_sendkeys(buf, "3G") + call WaitForAssert({-> assert_equal('three', term_getline(buf, 3))}) + call term_sendkeys(buf, ":call XsaveFoldLevels()\n") + call term_sendkeys(buf, "1G") + call WaitForAssert({-> assert_equal('four', term_getline(buf, 3))}) + call term_sendkeys(buf, ":call XsaveFoldLevels()\n") + call term_sendkeys(buf, "2G") + call WaitForAssert({-> assert_equal('two', term_getline(buf, 2))}) + call term_sendkeys(buf, "k") + call WaitForAssert({-> assert_equal('four', term_getline(buf, 3))}) + + " clean up + call StopVimInTerminal(buf) + + call assert_equal(['[-1,2,2,-1]', '[-1,-1,-1,-1]', '[-1,2,2,-1]', + \ '[-1,-1,-1,-1]', '[-1,2,2,-1]'], readfile('Xoutput')) + call delete('Xscript') + call delete('Xoutput') +endfunc + +" Test for foldtextresult() +func Test_foldtextresult() + new + call assert_equal('', foldtextresult(-1)) + call assert_equal('', foldtextresult(0)) + call assert_equal('', foldtextresult(1)) + call setline(1, ['one', 'two', 'three', 'four']) + 2,3fold + call assert_equal('', foldtextresult(1)) + call assert_equal('+-- 2 lines: two', foldtextresult(2)) + setlocal foldtext= + call assert_equal('+-- 2 lines folded ', foldtextresult(2)) + + " Fold text for a C comment fold + %d _ + setlocal foldtext& + call setline(1, ['', '/*', ' * Comment', ' */', '']) + 2,4fold + call assert_equal('+-- 3 lines: Comment', foldtextresult(2)) + + bw! +endfunc + +" Test for merging two recursive folds when an intermediate line with no fold +" is removed +func Test_fold_merge_recursive() + new + call setline(1, [' one', ' two', 'xxxx', ' three', + \ ' four', "\tfive"]) + setlocal foldmethod=indent shiftwidth=2 + 3d_ + %foldclose + call assert_equal([1, 5], [foldclosed(5), foldclosedend(1)]) + bw! +endfunc + +" Test for moving a line which is the start of a fold from a recursive fold to +" outside. The fold length should reduce. +func Test_fold_move_foldlevel() + new + call setline(1, ['a{{{', 'b{{{', 'c{{{', 'd}}}', 'e}}}', 'f}}}', 'g']) + setlocal foldmethod=marker + normal zR + call assert_equal([3, 2, 1], [foldlevel(4), foldlevel(5), foldlevel(6)]) + 3move 7 + call assert_equal([2, 1, 0], [foldlevel(3), foldlevel(4), foldlevel(5)]) + call assert_equal(1, foldlevel(7)) + + " Move a line from outside a fold to inside the fold. + %d _ + call setline(1, ['a', 'b{{{', 'c}}}']) + normal zR + 1move 2 + call assert_equal([1, 1, 1], [foldlevel(1), foldlevel(2), foldlevel(3)]) + + " Move the start of one fold to inside another fold + %d _ + call setline(1, ['a', 'b{{{', 'c}}}', 'd{{{', 'e}}}']) + normal zR + call assert_equal([0, 1, 1, 1, 1], [foldlevel(1), foldlevel(2), + \ foldlevel(3), foldlevel(4), foldlevel(5)]) + 1,2move 4 + call assert_equal([0, 1, 1, 2, 2], [foldlevel(1), foldlevel(2), + \ foldlevel(3), foldlevel(4), foldlevel(5)]) + + bw! +endfunc + +" Test for using zj and zk to move downwards and upwards to the start and end +" of the next fold. +" Test for using [z and ]z in a closed fold to jump to the beginning and end +" of the fold. +func Test_fold_jump() + new + call setline(1, ["\t1", "\t2", "\t\t3", "\t\t4", "\t\t\t5", "\t\t\t6", "\t\t7", "\t\t8", "\t9", "\t10"]) + setlocal foldmethod=indent + normal zR + normal zj + call assert_equal(3, line('.')) + normal zj + call assert_equal(5, line('.')) + call assert_beeps('normal zj') + call assert_equal(5, line('.')) + call assert_beeps('normal 9Gzj') + call assert_equal(9, line('.')) + normal Gzk + call assert_equal(8, line('.')) + normal zk + call assert_equal(6, line('.')) + call assert_beeps('normal zk') + call assert_equal(6, line('.')) + call assert_beeps('normal 2Gzk') + call assert_equal(2, line('.')) + + " Using [z or ]z in a closed fold should not move the cursor + %d _ + call setline(1, ["1", "\t2", "\t3", "\t4", "\t5", "\t6", "7"]) + normal zR4Gzc + call assert_equal(4, line('.')) + call assert_beeps('normal [z') + call assert_equal(4, line('.')) + call assert_beeps('normal ]z') + call assert_equal(4, line('.')) + bw! +endfunc + +" Test for using a script-local function for 'foldexpr' +func Test_foldexpr_scriptlocal_func() + func! s:FoldFunc() + let g:FoldLnum = v:lnum + endfunc + new | only + call setline(1, 'abc') + let g:FoldLnum = 0 + set foldmethod=expr foldexpr=s:FoldFunc() + redraw! + call assert_equal(expand('<SID>') .. 'FoldFunc()', &foldexpr) + call assert_equal(expand('<SID>') .. 'FoldFunc()', &g:foldexpr) + call assert_equal(1, g:FoldLnum) + set foldmethod& foldexpr= + bw! + new | only + call setline(1, 'abc') + let g:FoldLnum = 0 + set foldmethod=expr foldexpr=<SID>FoldFunc() + redraw! + call assert_equal(expand('<SID>') .. 'FoldFunc()', &foldexpr) + call assert_equal(expand('<SID>') .. 'FoldFunc()', &g:foldexpr) + call assert_equal(1, g:FoldLnum) + bw! + call setline(1, 'abc') + setlocal foldmethod& foldexpr& + setglobal foldmethod=expr foldexpr=s:FoldFunc() + call assert_equal(expand('<SID>') .. 'FoldFunc()', &g:foldexpr) + call assert_equal('0', &foldexpr) + enew! + call setline(1, 'abc') + redraw! + call assert_equal(expand('<SID>') .. 'FoldFunc()', &foldexpr) + call assert_equal(1, g:FoldLnum) + bw! + call setline(1, 'abc') + setlocal foldmethod& foldexpr& + setglobal foldmethod=expr foldexpr=<SID>FoldFunc() + call assert_equal(expand('<SID>') .. 'FoldFunc()', &g:foldexpr) + call assert_equal('0', &foldexpr) + enew! + call setline(1, 'abc') + redraw! + call assert_equal(expand('<SID>') .. 'FoldFunc()', &foldexpr) + call assert_equal(1, g:FoldLnum) + set foldmethod& foldexpr& + delfunc s:FoldFunc + bw! +endfunc + +" Test for using a script-local function for 'foldtext' +func Test_foldtext_scriptlocal_func() + func! s:FoldText() + let g:FoldTextArgs = [v:foldstart, v:foldend] + return foldtext() + endfunc + new | only + call setline(1, range(50)) + let g:FoldTextArgs = [] + set foldtext=s:FoldText() + norm! 4Gzf4j + redraw! + call assert_equal(expand('<SID>') .. 'FoldText()', &foldtext) + call assert_equal(expand('<SID>') .. 'FoldText()', &g:foldtext) + call assert_equal([4, 8], g:FoldTextArgs) + set foldtext& + bw! + new | only + call setline(1, range(50)) + let g:FoldTextArgs = [] + set foldtext=<SID>FoldText() + norm! 8Gzf4j + redraw! + call assert_equal(expand('<SID>') .. 'FoldText()', &foldtext) + call assert_equal(expand('<SID>') .. 'FoldText()', &g:foldtext) + call assert_equal([8, 12], g:FoldTextArgs) + set foldtext& + bw! + call setline(1, range(50)) + let g:FoldTextArgs = [] + setlocal foldtext& + setglobal foldtext=s:FoldText() + call assert_equal(expand('<SID>') .. 'FoldText()', &g:foldtext) + call assert_equal('foldtext()', &foldtext) + enew! + call setline(1, range(50)) + norm! 12Gzf4j + redraw! + call assert_equal(expand('<SID>') .. 'FoldText()', &foldtext) + call assert_equal([12, 16], g:FoldTextArgs) + set foldtext& + bw! + call setline(1, range(50)) + let g:FoldTextArgs = [] + setlocal foldtext& + setglobal foldtext=<SID>FoldText() + call assert_equal(expand('<SID>') .. 'FoldText()', &g:foldtext) + call assert_equal('foldtext()', &foldtext) + enew! + call setline(1, range(50)) + norm! 16Gzf4j + redraw! + call assert_equal(expand('<SID>') .. 'FoldText()', &foldtext) + call assert_equal([16, 20], g:FoldTextArgs) + set foldtext& + bw! + delfunc s:FoldText +endfunc + +" Make sure a fold containing a nested fold is split correctly when using +" foldmethod=indent +func Test_fold_split() + new + let lines =<< trim END + line 1 + line 2 + line 3 + line 4 + line 5 + END + call setline(1, lines) + setlocal sw=2 + setlocal foldmethod=indent foldenable + call assert_equal([0, 1, 1, 2, 2], range(1, 5)->map('foldlevel(v:val)')) + call append(2, 'line 2.5') + call assert_equal([0, 1, 0, 1, 2, 2], range(1, 6)->map('foldlevel(v:val)')) + bw! +endfunc + +" Make sure that when you append under a blank line that is under a fold with +" the same indent level as your appended line, the fold expands across the +" blank line +func Test_indent_append_under_blank_line() + new + let lines =<< trim END + line 1 + line 2 + line 3 + END + call setline(1, lines) + setlocal sw=2 + setlocal foldmethod=indent foldenable + call assert_equal([0, 1, 1], range(1, 3)->map('foldlevel(v:val)')) + call append(3, '') + call append(4, ' line 5') + call assert_equal([0, 1, 1, 1, 1], range(1, 5)->map('foldlevel(v:val)')) + bw! +endfunc + +" Make sure that when you delete 1 line of a fold whose length is 2 lines, the +" fold can't be closed since its length (1) is now less than foldminlines. +func Test_indent_one_line_fold_close() + let lines =<< trim END + line 1 + line 2 + line 3 + END + + new + setlocal sw=2 foldmethod=indent + call setline(1, lines) + " open all folds, delete line, then close all folds + normal zR + 3delete + normal zM + call assert_equal(-1, foldclosed(2)) " the fold should not be closed + + " Now do the same, but delete line 2 this time; this covers different code. + " (Combining this code with the above code doesn't expose both bugs.) + 1,$delete + call setline(1, lines) + normal zR + 2delete + normal zM + call assert_equal(-1, foldclosed(2)) + bw! +endfunc + +" Make sure that when appending [an indented line then a blank line] right +" before a single indented line, the resulting extended fold can be closed +func Test_indent_append_blank_small_fold_close() + new + setlocal sw=2 foldmethod=indent + " at first, the fold at the second line can't be closed since it's smaller + " than foldminlines + let lines =<< trim END + line 1 + line 4 + END + call setline(1, lines) + call append(1, [' line 2', '']) + " close all folds + normal zM + call assert_notequal(-1, foldclosed(2)) " the fold should be closed now + bw! +endfunc + +func Test_sort_closed_fold() + CheckExecutable sort + + call setline(1, [ + \ 'Section 1', + \ ' how', + \ ' now', + \ ' brown', + \ ' cow', + \ 'Section 2', + \ ' how', + \ ' now', + \ ' brown', + \ ' cow', + \]) + setlocal foldmethod=indent sw=3 + normal 2G + + " The "!!" expands to ".,.+3" and must only sort four lines + call feedkeys("!!sort\<CR>", 'xt') + call assert_equal([ + \ 'Section 1', + \ ' brown', + \ ' cow', + \ ' how', + \ ' now', + \ 'Section 2', + \ ' how', + \ ' now', + \ ' brown', + \ ' cow', + \ ], getline(1, 10)) + + bwipe! +endfunc + +func Test_indent_with_L_command() + " The "L" command moved the cursor to line zero, causing the text saved for + " undo to use line number -1, which caused trouble for undo later. + new + sil! norm 8R
V{zf8=Lu + bwipe! +endfunc + +" Make sure that when there is a fold at the bottom of the buffer and a newline +" character is appended to the line, the fold gets expanded (instead of the new +" line not being part of the fold). +func Test_expand_fold_at_bottom_of_buffer() + new + " create a fold on the only line + fold + execute "normal A\<CR>" + call assert_equal([1, 1], range(1, 2)->map('foldlevel(v:val)')) + + bwipe! +endfunc + +func Test_fold_screenrow_motion() + call setline(1, repeat(['aaaa'], 5)) + 1,4fold + norm Ggkzo + call assert_equal(1, line('.')) +endfunc + +" This was using freed memory +func Test_foldcolumn_linebreak_control_char() + CheckFeature linebreak + + 5vnew + setlocal foldcolumn=1 linebreak + call setline(1, "aaa\<C-A>b") + redraw + call assert_equal([' aaa^', ' Ab '], ScreenLines([1, 2], 5)) + call assert_equal(screenattr(1, 5), screenattr(2, 2)) + + bwipe! +endfunc + +" This used to cause invalid memory access +func Test_foldexpr_return_empty_string() + new + setlocal foldexpr='' foldmethod=expr + redraw + + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_format.vim b/test/old/testdir/test_format.vim new file mode 100644 index 0000000000..d3578e7165 --- /dev/null +++ b/test/old/testdir/test_format.vim @@ -0,0 +1,361 @@ +" Tests for expressions. + +source check.vim +source vim9.vim + +func Test_printf_pos_misc() + let lines =<< trim END + call assert_equal('123', printf('%1$d', 123)) + call assert_equal('', printf('%1$.0d', 0)) + call assert_equal('00005', printf('%1$5.5d', 5)) + call assert_equal('00005', printf('%1$*1$.5d', 5)) + call assert_equal('00005', printf('%1$5.*1$d', 5)) + call assert_equal('00005', printf('%1$*1$.*1$d', 5)) + call assert_equal('00005', printf('%1$*10$.5d%2$.0d%3$.0d%4$.0d%5$.0d%6$.0d%7$.0d%8$.0d%9$.0d', 5, 0, 0, 0, 0, 0, 0, 0, 0, 5)) + call assert_equal('00005', printf('%1$5.*10$d%2$.0d%3$.0d%4$.0d%5$.0d%6$.0d%7$.0d%8$.0d%9$.0d', 5, 0, 0, 0, 0, 0, 0, 0, 0, 5)) + call assert_equal('123', printf('%1$i', 123)) + call assert_equal('123', printf('%1$D', 123)) + call assert_equal('123', printf('%1$U', 123)) + call assert_equal('173', printf('%1$o', 123)) + call assert_equal('173', printf('%1$O', 123)) + call assert_equal('7b', printf('%1$x', 123)) + call assert_equal('7B', printf('%1$X', 123)) + call assert_equal('Printing 1 at width 1 gives: 1', 1->printf("Printing %1$d at width %1$d gives: %1$*1$d")) + call assert_equal('Printing 2 at width 2 gives: 2', 2->printf("Printing %1$d at width %1$d gives: %1$*1$d")) + call assert_equal('Printing 3 at width 3 gives: 3', 3->printf("Printing %1$d at width %1$d gives: %1$*1$d")) + call assert_equal('Printing 1 at width/precision 1.1 gives: 1', 1->printf("Printing %1$d at width/precision %1$d.%1$d gives: %1$*1$.*1$d")) + call assert_equal('Printing 2 at width/precision 2.2 gives: 02', 2->printf("Printing %1$d at width/precision %1$d.%1$d gives: %1$*1$.*1$d")) + call assert_equal('Printing 3 at width/precision 3.3 gives: 003', 3->printf("Printing %1$d at width/precision %1$d.%1$d gives: %1$*1$.*1$d")) + + call assert_equal('123', printf('%1$hd', 123)) + call assert_equal('-123', printf('%1$hd', -123)) + call assert_equal('-1', printf('%1$hd', 0xFFFF)) + call assert_equal('-1', printf('%1$hd', 0x1FFFFF)) + + call assert_equal('123', printf('%1$hu', 123)) + call assert_equal('65413', printf('%1$hu', -123)) + call assert_equal('65535', printf('%1$hu', 0xFFFF)) + call assert_equal('65535', printf('%1$hu', 0x1FFFFF)) + + call assert_equal('123', printf('%1$ld', 123)) + call assert_equal('-123', printf('%1$ld', -123)) + call assert_equal('65535', printf('%1$ld', 0xFFFF)) + call assert_equal('131071', printf('%1$ld', 0x1FFFF)) + + call assert_equal('{', printf('%1$c', 123)) + call assert_equal('abc', printf('%1$s', 'abc')) + call assert_equal('abc', printf('%1$S', 'abc')) + + call assert_equal('+123', printf('%1$+d', 123)) + call assert_equal('-123', printf('%1$+d', -123)) + call assert_equal('+123', printf('%1$+ d', 123)) + call assert_equal(' 123', printf('%1$ d', 123)) + call assert_equal(' 123', printf('%1$ d', 123)) + call assert_equal('-123', printf('%1$ d', -123)) + + call assert_equal(' 123', printf('%2$*1$d', 5, 123)) + call assert_equal('123 ', printf('%2$*1$d', -5, 123)) + call assert_equal('00123', printf('%2$.*1$d', 5, 123)) + call assert_equal(' 123', printf('%2$ *1$d', 5, 123)) + call assert_equal(' +123', printf('%2$+ *1$d', 5, 123)) + + call assert_equal(' 123', printf('%1$*2$d', 123, 5)) + call assert_equal('123 ', printf('%1$*2$d', 123, -5)) + call assert_equal('00123', printf('%1$.*2$d', 123, 5)) + call assert_equal(' 123', printf('%1$ *2$d', 123, 5)) + call assert_equal(' +123', printf('%1$+ *2$d', 123, 5)) + + call assert_equal('foobar', printf('%2$.*1$s', 9, 'foobar')) + call assert_equal('foo', printf('%2$.*1$s', 3, 'foobar')) + call assert_equal('', printf('%2$.*1$s', 0, 'foobar')) + call assert_equal('foobar', printf('%2$.*1$s', -1, 'foobar')) + + #" Unrecognized format specifier kept as-is. + call assert_equal('_123', printf("%_%1$d", 123)) + + #" Test alternate forms. + call assert_equal('0x7b', printf('%1$#x', 123)) + call assert_equal('0X7B', printf('%1$#X', 123)) + call assert_equal('0173', printf('%1$#o', 123)) + call assert_equal('0173', printf('%1$#O', 123)) + call assert_equal('abc', printf('%1$#s', 'abc')) + call assert_equal('abc', printf('%1$#S', 'abc')) + + call assert_equal('1%', printf('%1$d%%', 1)) + call assert_notequal('', printf('%1$p', "abc")) + call assert_notequal('', printf('%2$d %1$p %3$s', "abc", 2, "abc")) + + #" Try argument re-use and argument swapping + call assert_equal('one two one', printf('%1$s %2$s %1$s', "one", "two")) + call assert_equal('Screen height: 400', printf('%1$s height: %2$d', "Screen", 400)) + call assert_equal('400 is: Screen height', printf('%2$d is: %1$s height', "Screen", 400)) + + #" Try out lots of combinations of argument types to skip + call assert_equal('9 12345 7654321', printf('%2$ld %1$d %3$lu', 12345, 9, 7654321)) + call assert_equal('9 1234567 7654321', printf('%2$d %1$ld %3$lu', 1234567, 9, 7654321)) + call assert_equal('9 1234567 7654321', printf('%2$d %1$lld %3$lu', 1234567, 9, 7654321)) + call assert_equal('9 12345 7654321', printf('%2$ld %1$u %3$lu', 12345, 9, 7654321)) + call assert_equal('9 1234567 7654321', printf('%2$d %1$lu %3$lu', 1234567, 9, 7654321)) + call assert_equal('9 1234567 7654321', printf('%2$d %1$llu %3$lu', 1234567, 9, 7654321)) + call assert_equal('9 1234567 7654321', printf('%2$d %1$llu %3$lu', 1234567, 9, 7654321)) + call assert_equal('9 deadbeef 7654321', printf('%2$d %1$x %3$lu', 0xdeadbeef, 9, 7654321)) + call assert_equal('9 c 7654321', printf('%2$ld %1$c %3$lu', 99, 9, 7654321)) + call assert_equal('9 hi 7654321', printf('%2$ld %1$s %3$lu', "hi", 9, 7654321)) + call assert_equal('9 0.000000e+00 7654321', printf('%2$ld %1$e %3$lu', 0.0, 9, 7654321)) + END + call CheckLegacyAndVim9Success(lines) + + call CheckLegacyAndVim9Failure(["call printf('%1$d%2$d', 1, 3, 4)"], "E767:") + + call CheckLegacyAndVim9Failure(["call printf('%2$d%d', 1, 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%d%2$d', 1, 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%2$*1$d%d', 1, 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%d%2$*1$d', 1, 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%2$.*1$d%d', 1, 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%d%2$.*1$d', 1, 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%1$%')"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%1$')"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%1$_')"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%1$*3$.*d', 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%1$*.*2$d', 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%1$*.*d', 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%*.*1$d', 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%*1$.*d', 3)"], "E1500:") + call CheckLegacyAndVim9Failure(["call printf('%*1$.*1$d', 3)"], "E1500:") + + call CheckLegacyAndVim9Failure(["call printf('%2$d', 3, 3)"], "E1501:") + + call CheckLegacyAndVim9Failure(["call printf('%2$*1$d %1$ld', 3, 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$s %1$*1$d', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$p %1$*1$d', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$f %1$*1$d', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$lud %1$*1$d', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$llud %1$*1$d', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$lld %1$*1$d', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$s %1$*1$d', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$c %1$*1$d', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$ld %1$*1$d', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$ld %2$*1$d', 3, 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$*1$ld', 3)"], "E1502:") + call CheckLegacyAndVim9Failure(["call printf('%1$*1$.*1$ld', 3)"], "E1502:") + + call CheckLegacyAndVim9Failure(["call printf('%1$d%2$d', 3)"], "E1503:") + + call CheckLegacyAndVim9Failure(["call printf('%1$d %1$s', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$ld %1$s', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$ud %1$d', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$s %1$f', 3.0)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$*1$d %1$ld', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$s %1$d', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$p %1$d', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$f %1$d', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$lud %1$d', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$llud %1$d', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$lld %1$d', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$s %1$d', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$c %1$d', 3)"], "E1504:") + call CheckLegacyAndVim9Failure(["call printf('%1$ld %1$d', 3)"], "E1504:") + + call CheckLegacyAndVim9Failure(["call printf('%1$.2$d', 3)"], "E1505:") + call CheckLegacyAndVim9Failure(["call printf('%01$d', 3)"], "E1505:") + call CheckLegacyAndVim9Failure(["call printf('%01$0d', 3)"], "E1505:") + call CheckLegacyAndVim9Failure(["call printf('%1$*2d', 3)"], "E1505:") + call CheckLegacyAndVim9Failure(["call printf('%1$*3.*2$d', 3)"], "E1505:") + call CheckLegacyAndVim9Failure(["call printf('%1$*3$.2$d', 3)"], "E1505:") + call CheckLegacyAndVim9Failure(["call printf('%1$*3$.*2d', 3)"], "E1505:") + call CheckLegacyAndVim9Failure(["call printf('%1$1$.5d', 5)"], "E1505:") + call CheckLegacyAndVim9Failure(["call printf('%1$5.1$d', 5)"], "E1505:") + call CheckLegacyAndVim9Failure(["call printf('%1$1$.1$d', 5)"], "E1505:") +endfunc + +func Test_printf_pos_float() + let lines =<< trim END + call assert_equal('1.000000', printf('%1$f', 1)) + call assert_equal('1.230000', printf('%1$f', 1.23)) + call assert_equal('1.230000', printf('%1$F', 1.23)) + call assert_equal('9999999.9', printf('%1$g', 9999999.9)) + call assert_equal('9999999.9', printf('%1$G', 9999999.9)) + call assert_equal('1.230000e+00', printf('%1$e', 1.23)) + call assert_equal('1.230000E+00', printf('%1$E', 1.23)) + call assert_equal('1.200000e-02', printf('%1$e', 0.012)) + call assert_equal('-1.200000e-02', printf('%1$e', -0.012)) + call assert_equal('0.33', printf('%1$.2f', 1.0 / 3.0)) + + #" When precision is 0, the dot should be omitted. + call assert_equal(' 2', printf('%1$*2$.f', 7.0 / 3.0, 3)) + call assert_equal(' 2', printf('%2$*1$.f', 3, 7.0 / 3.0)) + call assert_equal(' 2', printf('%1$*2$.g', 7.0 / 3.0, 3)) + call assert_equal(' 2', printf('%2$*1$.g', 3, 7.0 / 3.0)) + call assert_equal(' 2e+00', printf('%1$*2$.e', 7.0 / 3.0, 7)) + call assert_equal(' 2e+00', printf('%2$*1$.e', 7, 7.0 / 3.0)) + + #" Float zero can be signed. + call assert_equal('+0.000000', printf('%1$+f', 0.0)) + call assert_equal('0.000000', printf('%1$f', 1.0 / (1.0 / 0.0))) + call assert_equal('-0.000000', printf('%1$f', 1.0 / (-1.0 / 0.0))) + call assert_equal('0.0', printf('%1$s', 1.0 / (1.0 / 0.0))) + call assert_equal('-0.0', printf('%1$s', 1.0 / (-1.0 / 0.0))) + call assert_equal('0.0', printf('%1$S', 1.0 / (1.0 / 0.0))) + call assert_equal('-0.0', printf('%1$S', 1.0 / (-1.0 / 0.0))) + + #" Float infinity can be signed. + call assert_equal('inf', printf('%1$f', 1.0 / 0.0)) + call assert_equal('-inf', printf('%1$f', -1.0 / 0.0)) + call assert_equal('inf', printf('%1$g', 1.0 / 0.0)) + call assert_equal('-inf', printf('%1$g', -1.0 / 0.0)) + call assert_equal('inf', printf('%1$e', 1.0 / 0.0)) + call assert_equal('-inf', printf('%1$e', -1.0 / 0.0)) + call assert_equal('INF', printf('%1$F', 1.0 / 0.0)) + call assert_equal('-INF', printf('%1$F', -1.0 / 0.0)) + call assert_equal('INF', printf('%1$E', 1.0 / 0.0)) + call assert_equal('-INF', printf('%1$E', -1.0 / 0.0)) + call assert_equal('INF', printf('%1$E', 1.0 / 0.0)) + call assert_equal('-INF', printf('%1$G', -1.0 / 0.0)) + call assert_equal('+inf', printf('%1$+f', 1.0 / 0.0)) + call assert_equal('-inf', printf('%1$+f', -1.0 / 0.0)) + call assert_equal(' inf', printf('%1$ f', 1.0 / 0.0)) + call assert_equal(' inf', printf('%1$*2$f', 1.0 / 0.0, 6)) + call assert_equal(' -inf', printf('%1$*2$f', -1.0 / 0.0, 6)) + call assert_equal(' inf', printf('%1$*2$g', 1.0 / 0.0, 6)) + call assert_equal(' -inf', printf('%1$*2$g', -1.0 / 0.0, 6)) + call assert_equal(' +inf', printf('%1$+*2$f', 1.0 / 0.0, 6)) + call assert_equal(' inf', printf('%1$ *2$f', 1.0 / 0.0, 6)) + call assert_equal(' +inf', printf('%1$+0*2$f', 1.0 / 0.0, 6)) + call assert_equal('inf ', printf('%1$-*2$f', 1.0 / 0.0, 6)) + call assert_equal('-inf ', printf('%1$-*2$f', -1.0 / 0.0, 6)) + call assert_equal('+inf ', printf('%1$-+*2$f', 1.0 / 0.0, 6)) + call assert_equal(' inf ', printf('%1$- *2$f', 1.0 / 0.0, 6)) + call assert_equal('-INF ', printf('%1$-*2$F', -1.0 / 0.0, 6)) + call assert_equal('+INF ', printf('%1$-+*2$F', 1.0 / 0.0, 6)) + call assert_equal(' INF ', printf('%1$- *2$F', 1.0 / 0.0, 6)) + call assert_equal('INF ', printf('%1$-*2$G', 1.0 / 0.0, 6)) + call assert_equal('-INF ', printf('%1$-*2$G', -1.0 / 0.0, 6)) + call assert_equal('INF ', printf('%1$-*2$E', 1.0 / 0.0, 6)) + call assert_equal('-INF ', printf('%1$-*2$E', -1.0 / 0.0, 6)) + call assert_equal(' inf', printf('%2$*1$f', 6, 1.0 / 0.0)) + call assert_equal(' -inf', printf('%2$*1$f', 6, -1.0 / 0.0)) + call assert_equal(' inf', printf('%2$*1$g', 6, 1.0 / 0.0)) + call assert_equal(' -inf', printf('%2$*1$g', 6, -1.0 / 0.0)) + call assert_equal(' +inf', printf('%2$+*1$f', 6, 1.0 / 0.0)) + call assert_equal(' inf', printf('%2$ *1$f', 6, 1.0 / 0.0)) + call assert_equal(' +inf', printf('%2$+0*1$f', 6, 1.0 / 0.0)) + call assert_equal('inf ', printf('%2$-*1$f', 6, 1.0 / 0.0)) + call assert_equal('-inf ', printf('%2$-*1$f', 6, -1.0 / 0.0)) + call assert_equal('+inf ', printf('%2$-+*1$f', 6, 1.0 / 0.0)) + call assert_equal(' inf ', printf('%2$- *1$f', 6, 1.0 / 0.0)) + call assert_equal('-INF ', printf('%2$-*1$F', 6, -1.0 / 0.0)) + call assert_equal('+INF ', printf('%2$-+*1$F', 6, 1.0 / 0.0)) + call assert_equal(' INF ', printf('%2$- *1$F', 6, 1.0 / 0.0)) + call assert_equal('INF ', printf('%2$-*1$G', 6, 1.0 / 0.0)) + call assert_equal('-INF ', printf('%2$-*1$G', 6, -1.0 / 0.0)) + call assert_equal('INF ', printf('%2$-*1$E', 6, 1.0 / 0.0)) + call assert_equal('-INF ', printf('%2$-*1$E', 6, -1.0 / 0.0)) + call assert_equal("str2float('inf')", printf('%1$s', 1.0 / 0.0)) + call assert_equal("-str2float('inf')", printf('%1$s', -1.0 / 0.0)) + + #" Test special case where max precision is truncated at 340. + call assert_equal('1.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', printf('%1$.*2$f', 1.0, 330)) + call assert_equal('1.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', printf('%2$.*1$f', 330, 1.0)) + call assert_equal('1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', printf('%1$.*2$f', 1.0, 340)) + call assert_equal('1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', printf('%2$.*1$f', 340, 1.0)) + call assert_equal('1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', printf('%1$.*2$f', 1.0, 350)) + call assert_equal('1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', printf('%2$.*1$f', 350, 1.0)) + + #" Float nan (not a number) has no sign. + call assert_equal('nan', printf('%1$f', sqrt(-1.0))) + call assert_equal('nan', printf('%1$f', 0.0 / 0.0)) + call assert_equal('nan', printf('%1$f', -0.0 / 0.0)) + call assert_equal('nan', printf('%1$g', 0.0 / 0.0)) + call assert_equal('nan', printf('%1$e', 0.0 / 0.0)) + call assert_equal('NAN', printf('%1$F', 0.0 / 0.0)) + call assert_equal('NAN', printf('%1$G', 0.0 / 0.0)) + call assert_equal('NAN', printf('%1$E', 0.0 / 0.0)) + call assert_equal('NAN', printf('%1$F', -0.0 / 0.0)) + call assert_equal('NAN', printf('%1$G', -0.0 / 0.0)) + call assert_equal('NAN', printf('%1$E', -0.0 / 0.0)) + call assert_equal(' nan', printf('%1$*2$f', 0.0 / 0.0, 6)) + call assert_equal(' nan', printf('%1$0*2$f', 0.0 / 0.0, 6)) + call assert_equal('nan ', printf('%1$-*2$f', 0.0 / 0.0, 6)) + call assert_equal('nan ', printf('%1$- *2$f', 0.0 / 0.0, 6)) + call assert_equal(' nan', printf('%2$*1$f', 6, 0.0 / 0.0)) + call assert_equal(' nan', printf('%2$0*1$f', 6, 0.0 / 0.0)) + call assert_equal('nan ', printf('%2$-*1$f', 6, 0.0 / 0.0)) + call assert_equal('nan ', printf('%2$- *1$f', 6, 0.0 / 0.0)) + call assert_equal("str2float('nan')", printf('%1$s', 0.0 / 0.0)) + call assert_equal("str2float('nan')", printf('%1$s', -0.0 / 0.0)) + call assert_equal("str2float('nan')", printf('%1$S', 0.0 / 0.0)) + call assert_equal("str2float('nan')", printf('%1$S', -0.0 / 0.0)) + END + call CheckLegacyAndVim9Success(lines) + + call CheckLegacyAndVim9Failure(['echo printf("%f", "a")'], 'E807:') +endfunc + +func Test_printf_pos_errors() + call CheckLegacyAndVim9Failure(['echo printf("%1$d", {})'], 'E728:') + call CheckLegacyAndVim9Failure(['echo printf("%1$d", [])'], 'E745:') + call CheckLegacyAndVim9Failure(['echo printf("%1$d", 1, 2)'], 'E767:') + call CheckLegacyAndVim9Failure(['echo printf("%*d", 1)'], 'E766:') + call CheckLegacyAndVim9Failure(['echo printf("%1$s")'], 'E1503:') + call CheckLegacyAndVim9Failure(['echo printf("%1$d", 1.2)'], 'E805:') + call CheckLegacyAndVim9Failure(['echo printf("%1$f")'], 'E1503:') +endfunc + +func Test_printf_pos_64bit() + let lines =<< trim END + call assert_equal("123456789012345", printf('%1$d', 123456789012345)) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_printf_pos_spec_s() + let lines =<< trim END + #" number + call assert_equal("1234567890", printf('%1$s', 1234567890)) + + #" string + call assert_equal("abcdefgi", printf('%1$s', "abcdefgi")) + + #" float + call assert_equal("1.23", printf('%1$s', 1.23)) + + #" list + VAR lvalue = [1, 'two', ['three', 4]] + call assert_equal(string(lvalue), printf('%1$s', lvalue)) + + #" dict + VAR dvalue = {'key1': 'value1', 'key2': ['list', 'lvalue'], 'key3': {'dict': 'lvalue'}} + call assert_equal(string(dvalue), printf('%1$s', dvalue)) + + #" funcref + call assert_equal('printf', printf('%1$s', 'printf'->function())) + + #" partial + call assert_equal(string(function('printf', ['%1$s'])), printf('%1$s', function('printf', ['%1$s']))) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_printf_pos_spec_b() + let lines =<< trim END + call assert_equal("0", printf('%1$b', 0)) + call assert_equal("00001100", printf('%1$0*2$b', 12, 8)) + call assert_equal("11111111", printf('%1$0*2$b', 0xff, 8)) + call assert_equal(" 1111011", printf('%1$*2$b', 123, 10)) + call assert_equal("0001111011", printf('%1$0*2$b', 123, 10)) + call assert_equal(" 0b1111011", printf('%1$#*2$b', 123, 10)) + call assert_equal("0B01111011", printf('%1$#0*2$B', 123, 10)) + call assert_equal("00001100", printf('%2$0*1$b', 8, 12)) + call assert_equal("11111111", printf('%2$0*1$b', 8, 0xff)) + call assert_equal(" 1111011", printf('%2$*1$b', 10, 123)) + call assert_equal("0001111011", printf('%2$0*1$b', 10, 123)) + call assert_equal(" 0b1111011", printf('%2$#*1$b', 10, 123)) + call assert_equal("0B01111011", printf('%2$#0*1$B', 10, 123)) + call assert_equal("1001001100101100000001011010010", printf('%1$b', 1234567890)) + call assert_equal("11100000100100010000110000011011101111101111001", printf('%1$b', 123456789012345)) + call assert_equal("1111111111111111111111111111111111111111111111111111111111111111", printf('%1$b', -1)) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_functions.vim b/test/old/testdir/test_functions.vim new file mode 100644 index 0000000000..88a29968fe --- /dev/null +++ b/test/old/testdir/test_functions.vim @@ -0,0 +1,3423 @@ +" Tests for various functions. + +source shared.vim +source check.vim +source term_util.vim +source screendump.vim +source vim9.vim + +" Must be done first, since the alternate buffer must be unset. +func Test_00_bufexists() + call assert_equal(0, bufexists('does_not_exist')) + call assert_equal(1, bufexists(bufnr('%'))) + call assert_equal(0, bufexists(0)) + new Xfoo + let bn = bufnr('%') + call assert_equal(1, bufexists(bn)) + call assert_equal(1, bufexists('Xfoo')) + call assert_equal(1, bufexists(getcwd() . '/Xfoo')) + call assert_equal(1, bufexists(0)) + bw + call assert_equal(0, bufexists(bn)) + call assert_equal(0, bufexists('Xfoo')) +endfunc + +func Test_has() + throw 'Skipped: Nvim has removed some features' + call assert_equal(1, has('eval')) + call assert_equal(1, has('eval', 1)) + + if has('unix') + call assert_equal(1, or(has('ttyin'), 1)) + call assert_equal(0, and(has('ttyout'), 0)) + call assert_equal(1, has('multi_byte_encoding')) + call assert_equal(0, has(':tearoff')) + endif + call assert_equal(1, has('vcon', 1)) + call assert_equal(1, has('mouse_gpm_enabled', 1)) + + call assert_equal(has('gui_win32') && has('menu'), has(':tearoff')) + + call assert_equal(0, has('nonexistent')) + call assert_equal(0, has('nonexistent', 1)) + + " Will we ever have patch 9999? + let ver = 'patch-' .. v:version / 100 .. '.' .. v:version % 100 .. '.9999' + call assert_equal(0, has(ver)) +endfunc + +func Test_empty() + call assert_equal(1, empty('')) + call assert_equal(0, empty('a')) + + call assert_equal(1, empty(0)) + call assert_equal(1, empty(-0)) + call assert_equal(0, empty(1)) + call assert_equal(0, empty(-1)) + + if has('float') + call assert_equal(1, empty(0.0)) + call assert_equal(1, empty(-0.0)) + call assert_equal(0, empty(1.0)) + call assert_equal(0, empty(-1.0)) + call assert_equal(0, empty(1.0/0.0)) + call assert_equal(0, empty(0.0/0.0)) + endif + + call assert_equal(1, empty([])) + call assert_equal(0, empty(['a'])) + + call assert_equal(1, empty({})) + call assert_equal(0, empty({'a':1})) + + call assert_equal(1, empty(v:null)) + " call assert_equal(1, empty(v:none)) + call assert_equal(1, empty(v:false)) + call assert_equal(0, empty(v:true)) + + if has('channel') + call assert_equal(1, empty(test_null_channel())) + endif + if has('job') + call assert_equal(1, empty(test_null_job())) + endif + + call assert_equal(0, empty(function('Test_empty'))) + call assert_equal(0, empty(function('Test_empty', [0]))) +endfunc + +func Test_err_teapot() + throw 'Skipped: Nvim does not have err_teapot()' + call assert_fails('call err_teapot()', "E418: I'm a teapot") + call assert_fails('call err_teapot(0)', "E418: I'm a teapot") + call assert_fails('call err_teapot(v:false)', "E418: I'm a teapot") + + call assert_fails('call err_teapot("1")', "E503: Coffee is currently not available") + call assert_fails('call err_teapot(v:true)', "E503: Coffee is currently not available") + let expr = 1 + call assert_fails('call err_teapot(expr)', "E503: Coffee is currently not available") +endfunc + +func Test_len() + call assert_equal(1, len(0)) + call assert_equal(2, len(12)) + + call assert_equal(0, len('')) + call assert_equal(2, len('ab')) + + call assert_equal(0, len([])) + call assert_equal(0, len(v:_null_list)) + call assert_equal(2, len([2, 1])) + + call assert_equal(0, len({})) + call assert_equal(0, len(v:_null_dict)) + call assert_equal(2, len({'a': 1, 'b': 2})) + + " call assert_fails('call len(v:none)', 'E701:') + call assert_fails('call len({-> 0})', 'E701:') +endfunc + +func Test_max() + call assert_equal(0, max([])) + call assert_equal(2, max([2])) + call assert_equal(2, max([1, 2])) + call assert_equal(2, max([1, 2, v:null])) + + call assert_equal(0, max({})) + call assert_equal(2, max({'a':1, 'b':2})) + + call assert_fails('call max(1)', 'E712:') + " call assert_fails('call max(v:none)', 'E712:') + + " check we only get one error + call assert_fails('call max([#{}, [1]])', ['E728:', 'E728:']) + call assert_fails('call max(#{a: {}, b: [1]})', ['E728:', 'E728:']) +endfunc + +func Test_min() + call assert_equal(0, min([])) + call assert_equal(2, min([2])) + call assert_equal(1, min([1, 2])) + call assert_equal(0, min([1, 2, v:null])) + + call assert_equal(0, min({})) + call assert_equal(1, min({'a':1, 'b':2})) + + call assert_fails('call min(1)', 'E712:') + " call assert_fails('call min(v:none)', 'E712:') + call assert_fails('call min([1, {}])', 'E728:') + + " check we only get one error + call assert_fails('call min([[1], #{}])', ['E745:', 'E745:']) + call assert_fails('call min(#{a: [1], b: #{}})', ['E745:', 'E745:']) +endfunc + +func Test_strwidth() + for aw in ['single', 'double'] + exe 'set ambiwidth=' . aw + call assert_equal(0, strwidth('')) + call assert_equal(1, strwidth("\t")) + call assert_equal(3, strwidth('Vim')) + call assert_equal(4, strwidth(1234)) + call assert_equal(5, strwidth(-1234)) + + call assert_equal(2, strwidth('😉')) + call assert_equal(17, strwidth('Eĥoŝanĝo ĉiuĵaŭde')) + call assert_equal((aw == 'single') ? 6 : 7, strwidth('Straße')) + + call assert_fails('call strwidth({->0})', 'E729:') + call assert_fails('call strwidth([])', 'E730:') + call assert_fails('call strwidth({})', 'E731:') + endfor + + if has('float') + call assert_equal(3, strwidth(1.2)) + call CheckDefExecAndScriptFailure(['echo strwidth(1.2)'], 'E806:') + endif + + set ambiwidth& +endfunc + +func Test_str2nr() + call assert_equal(0, str2nr('')) + call assert_equal(1, str2nr('1')) + call assert_equal(1, str2nr(' 1 ')) + + call assert_equal(1, str2nr('+1')) + call assert_equal(1, str2nr('+ 1')) + call assert_equal(1, str2nr(' + 1 ')) + + call assert_equal(-1, str2nr('-1')) + call assert_equal(-1, str2nr('- 1')) + call assert_equal(-1, str2nr(' - 1 ')) + + call assert_equal(123456789, str2nr('123456789')) + call assert_equal(-123456789, str2nr('-123456789')) + + call assert_equal(5, str2nr('101', 2)) + call assert_equal(5, '0b101'->str2nr(2)) + call assert_equal(5, str2nr('0B101', 2)) + call assert_equal(-5, str2nr('-101', 2)) + call assert_equal(-5, str2nr('-0b101', 2)) + call assert_equal(-5, str2nr('-0B101', 2)) + + call assert_equal(65, str2nr('101', 8)) + call assert_equal(65, str2nr('0101', 8)) + call assert_equal(-65, str2nr('-101', 8)) + call assert_equal(-65, str2nr('-0101', 8)) + call assert_equal(65, str2nr('0o101', 8)) + call assert_equal(65, str2nr('0O0101', 8)) + call assert_equal(-65, str2nr('-0O101', 8)) + call assert_equal(-65, str2nr('-0o0101', 8)) + + call assert_equal(11259375, str2nr('abcdef', 16)) + call assert_equal(11259375, str2nr('ABCDEF', 16)) + call assert_equal(-11259375, str2nr('-ABCDEF', 16)) + call assert_equal(11259375, str2nr('0xabcdef', 16)) + call assert_equal(11259375, str2nr('0Xabcdef', 16)) + call assert_equal(11259375, str2nr('0XABCDEF', 16)) + call assert_equal(-11259375, str2nr('-0xABCDEF', 16)) + + call assert_equal(1, str2nr("1'000'000", 10, 0)) + call assert_equal(256, str2nr("1'0000'0000", 2, 1)) + call assert_equal(262144, str2nr("1'000'000", 8, 1)) + call assert_equal(1000000, str2nr("1'000'000", 10, 1)) + call assert_equal(1000, str2nr("1'000''000", 10, 1)) + call assert_equal(65536, str2nr("1'00'00", 16, 1)) + + call assert_equal(0, str2nr('0x10')) + call assert_equal(0, str2nr('0b10')) + call assert_equal(0, str2nr('0o10')) + call assert_equal(1, str2nr('12', 2)) + call assert_equal(1, str2nr('18', 8)) + call assert_equal(1, str2nr('1g', 16)) + + call assert_equal(0, str2nr(v:null)) + " call assert_equal(0, str2nr(v:none)) + + call assert_fails('call str2nr([])', 'E730:') + call assert_fails('call str2nr({->2})', 'E729:') + if has('float') + call assert_equal(1, str2nr(1.2)) + call CheckDefExecFailure(['echo str2nr(1.2)'], 'E1013:') + call CheckScriptFailure(['vim9script', 'echo str2nr(1.2)'], 'E806:') + endif + call assert_fails('call str2nr(10, [])', 'E745:') +endfunc + +func Test_strftime() + CheckFunction strftime + + " Format of strftime() depends on system. We assume + " that basic formats tested here are available and + " identical on all systems which support strftime(). + " + " The 2nd parameter of strftime() is a local time, so the output day + " of strftime() can be 17 or 18, depending on timezone. + call assert_match('^2017-01-1[78]$', strftime('%Y-%m-%d', 1484695512)) + " + call assert_match('^\d\d\d\d-\(0\d\|1[012]\)-\([012]\d\|3[01]\) \([01]\d\|2[0-3]\):[0-5]\d:\([0-5]\d\|60\)$', '%Y-%m-%d %H:%M:%S'->strftime()) + + call assert_fails('call strftime([])', 'E730:') + call assert_fails('call strftime("%Y", [])', 'E745:') + + " Check that the time changes after we change the timezone + " Save previous timezone value, if any + if exists('$TZ') + let tz = $TZ + endif + + " Force EST and then UTC, save the current hour (24-hour clock) for each + let $TZ = 'EST' | let est = strftime('%H') + let $TZ = 'UTC' | let utc = strftime('%H') + + " Those hours should be two bytes long, and should not be the same; if they + " are, a tzset(3) call may have failed somewhere + call assert_equal(strlen(est), 2) + call assert_equal(strlen(utc), 2) + " TODO: this fails on MS-Windows + if has('unix') + call assert_notequal(est, utc) + endif + + " If we cached a timezone value, put it back, otherwise clear it + if exists('tz') + let $TZ = tz + else + unlet $TZ + endif +endfunc + +func Test_strptime() + CheckFunction strptime + CheckNotBSD + CheckNotMSWindows + + if exists('$TZ') + let tz = $TZ + endif + let $TZ = 'UTC' + + call assert_equal(1484653763, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23')) + + " Force DST and check that it's considered + let $TZ = 'WINTER0SUMMER,J1,J365' + call assert_equal(1484653763 - 3600, strptime('%Y-%m-%d %T', '2017-01-17 11:49:23')) + + call assert_fails('call strptime()', 'E119:') + call assert_fails('call strptime("xxx")', 'E119:') + " This fails on BSD 14 and returns + " -2209078800 instead of 0 + call assert_equal(0, strptime("%Y", '')) + call assert_equal(0, strptime("%Y", "xxx")) + + if exists('tz') + let $TZ = tz + else + unlet $TZ + endif +endfunc + +func Test_resolve_unix() + if !has('unix') + return + endif + + " Xlink1 -> Xlink2 + " Xlink2 -> Xlink3 + silent !ln -s -f Xlink2 Xlink1 + silent !ln -s -f Xlink3 Xlink2 + call assert_equal('Xlink3', resolve('Xlink1')) + call assert_equal('./Xlink3', resolve('./Xlink1')) + call assert_equal('Xlink3/', resolve('Xlink2/')) + " FIXME: these tests result in things like "Xlink2/" instead of "Xlink3/"?! + "call assert_equal('Xlink3/', resolve('Xlink1/')) + "call assert_equal('./Xlink3/', resolve('./Xlink1/')) + "call assert_equal(getcwd() . '/Xlink3/', resolve(getcwd() . '/Xlink1/')) + call assert_equal(getcwd() . '/Xlink3', resolve(getcwd() . '/Xlink1')) + + " Test resolve() with a symlink cycle. + " Xlink1 -> Xlink2 + " Xlink2 -> Xlink3 + " Xlink3 -> Xlink1 + silent !ln -s -f Xlink1 Xlink3 + call assert_fails('call resolve("Xlink1")', 'E655:') + call assert_fails('call resolve("./Xlink1")', 'E655:') + call assert_fails('call resolve("Xlink2")', 'E655:') + call assert_fails('call resolve("Xlink3")', 'E655:') + call delete('Xlink1') + call delete('Xlink2') + call delete('Xlink3') + + silent !ln -s -f Xdir//Xfile Xlink + call assert_equal('Xdir/Xfile', resolve('Xlink')) + call delete('Xlink') + + silent !ln -s -f Xlink2/ Xlink1 + call assert_equal('Xlink2', 'Xlink1'->resolve()) + call assert_equal('Xlink2/', resolve('Xlink1/')) + call delete('Xlink1') + + silent !ln -s -f ./Xlink2 Xlink1 + call assert_equal('Xlink2', resolve('Xlink1')) + call assert_equal('./Xlink2', resolve('./Xlink1')) + call delete('Xlink1') + + call assert_equal('/', resolve('/')) +endfunc + +func s:normalize_fname(fname) + let ret = substitute(a:fname, '\', '/', 'g') + let ret = substitute(ret, '//', '/', 'g') + return ret->tolower() +endfunc + +func Test_simplify() + call assert_equal('', simplify('')) + call assert_equal('/', simplify('/')) + call assert_equal('/', simplify('/.')) + call assert_equal('/', simplify('/..')) + call assert_equal('/...', simplify('/...')) + call assert_equal('./dir/file', './dir/file'->simplify()) + call assert_equal('./dir/file', simplify('.///dir//file')) + call assert_equal('./dir/file', simplify('./dir/./file')) + call assert_equal('./file', simplify('./dir/../file')) + call assert_equal('../dir/file', simplify('dir/../../dir/file')) + call assert_equal('./file', simplify('dir/.././file')) + call assert_equal('../dir', simplify('./../dir')) + call assert_equal('..', simplify('../testdir/..')) + call mkdir('Xdir') + call assert_equal('.', simplify('Xdir/../.')) + call delete('Xdir', 'd') + + call assert_fails('call simplify({->0})', 'E729:') + call assert_fails('call simplify([])', 'E730:') + call assert_fails('call simplify({})', 'E731:') + if has('float') + call assert_equal('1.2', simplify(1.2)) + call CheckDefExecAndScriptFailure(['echo simplify(1.2)'], 'E806:') + endif +endfunc + +func Test_pathshorten() + call assert_equal('', pathshorten('')) + call assert_equal('foo', pathshorten('foo')) + call assert_equal('/foo', '/foo'->pathshorten()) + call assert_equal('f/', pathshorten('foo/')) + call assert_equal('f/bar', pathshorten('foo/bar')) + call assert_equal('f/b/foobar', 'foo/bar/foobar'->pathshorten()) + call assert_equal('/f/b/foobar', pathshorten('/foo/bar/foobar')) + call assert_equal('.f/bar', pathshorten('.foo/bar')) + call assert_equal('~f/bar', pathshorten('~foo/bar')) + call assert_equal('~.f/bar', pathshorten('~.foo/bar')) + call assert_equal('.~f/bar', pathshorten('.~foo/bar')) + call assert_equal('~/f/bar', pathshorten('~/foo/bar')) + call assert_fails('call pathshorten([])', 'E730:') + + " test pathshorten with optional variable to set preferred size of shortening + call assert_equal('', pathshorten('', 2)) + call assert_equal('foo', pathshorten('foo', 2)) + call assert_equal('/foo', pathshorten('/foo', 2)) + call assert_equal('fo/', pathshorten('foo/', 2)) + call assert_equal('fo/bar', pathshorten('foo/bar', 2)) + call assert_equal('fo/ba/foobar', pathshorten('foo/bar/foobar', 2)) + call assert_equal('/fo/ba/foobar', pathshorten('/foo/bar/foobar', 2)) + call assert_equal('.fo/bar', pathshorten('.foo/bar', 2)) + call assert_equal('~fo/bar', pathshorten('~foo/bar', 2)) + call assert_equal('~.fo/bar', pathshorten('~.foo/bar', 2)) + call assert_equal('.~fo/bar', pathshorten('.~foo/bar', 2)) + call assert_equal('~/fo/bar', pathshorten('~/foo/bar', 2)) + call assert_fails('call pathshorten([],2)', 'E730:') + call assert_notequal('~/fo/bar', pathshorten('~/foo/bar', 3)) + call assert_equal('~/foo/bar', pathshorten('~/foo/bar', 3)) + call assert_equal('~/f/bar', pathshorten('~/foo/bar', 0)) +endfunc + +func Test_strpart() + call assert_equal('de', strpart('abcdefg', 3, 2)) + call assert_equal('ab', strpart('abcdefg', -2, 4)) + call assert_equal('abcdefg', 'abcdefg'->strpart(-2)) + call assert_equal('fg', strpart('abcdefg', 5, 4)) + call assert_equal('defg', strpart('abcdefg', 3)) + call assert_equal('', strpart('abcdefg', 10)) + call assert_fails("let s=strpart('abcdef', [])", 'E745:') + + call assert_equal('lép', strpart('éléphant', 2, 4)) + call assert_equal('léphant', strpart('éléphant', 2)) + + call assert_equal('é', strpart('éléphant', 0, 1, 1)) + call assert_equal('ép', strpart('éléphant', 3, 2, v:true)) + call assert_equal('ó', strpart('cómposed', 1, 1, 1)) +endfunc + +func Test_tolower() + call assert_equal("", tolower("")) + + " Test with all printable ASCII characters. + call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\]^_`abcdefghijklmnopqrstuvwxyz{|}~', + \ tolower(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~')) + + " Test with a few uppercase diacritics. + call assert_equal("aàáâãäåāăąǎǟǡả", tolower("AÀÁÂÃÄÅĀĂĄǍǞǠẢ")) + call assert_equal("bḃḇ", tolower("BḂḆ")) + call assert_equal("cçćĉċč", tolower("CÇĆĈĊČ")) + call assert_equal("dďđḋḏḑ", tolower("DĎĐḊḎḐ")) + call assert_equal("eèéêëēĕėęěẻẽ", tolower("EÈÉÊËĒĔĖĘĚẺẼ")) + call assert_equal("fḟ ", tolower("FḞ ")) + call assert_equal("gĝğġģǥǧǵḡ", tolower("GĜĞĠĢǤǦǴḠ")) + call assert_equal("hĥħḣḧḩ", tolower("HĤĦḢḦḨ")) + call assert_equal("iìíîïĩīĭįiǐỉ", tolower("IÌÍÎÏĨĪĬĮİǏỈ")) + call assert_equal("jĵ", tolower("JĴ")) + call assert_equal("kķǩḱḵ", tolower("KĶǨḰḴ")) + call assert_equal("lĺļľŀłḻ", tolower("LĹĻĽĿŁḺ")) + call assert_equal("mḿṁ", tolower("MḾṀ")) + call assert_equal("nñńņňṅṉ", tolower("NÑŃŅŇṄṈ")) + call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ")) + call assert_equal("pṕṗ", tolower("PṔṖ")) + call assert_equal("q", tolower("Q")) + call assert_equal("rŕŗřṙṟ", tolower("RŔŖŘṘṞ")) + call assert_equal("sśŝşšṡ", tolower("SŚŜŞŠṠ")) + call assert_equal("tţťŧṫṯ", tolower("TŢŤŦṪṮ")) + call assert_equal("uùúûüũūŭůűųưǔủ", tolower("UÙÚÛÜŨŪŬŮŰŲƯǓỦ")) + call assert_equal("vṽ", tolower("VṼ")) + call assert_equal("wŵẁẃẅẇ", tolower("WŴẀẂẄẆ")) + call assert_equal("xẋẍ", tolower("XẊẌ")) + call assert_equal("yýŷÿẏỳỷỹ", tolower("YÝŶŸẎỲỶỸ")) + call assert_equal("zźżžƶẑẕ", tolower("ZŹŻŽƵẐẔ")) + + " Test with a few lowercase diacritics, which should remain unchanged. + call assert_equal("aàáâãäåāăąǎǟǡả", tolower("aàáâãäåāăąǎǟǡả")) + call assert_equal("bḃḇ", tolower("bḃḇ")) + call assert_equal("cçćĉċč", tolower("cçćĉċč")) + call assert_equal("dďđḋḏḑ", tolower("dďđḋḏḑ")) + call assert_equal("eèéêëēĕėęěẻẽ", tolower("eèéêëēĕėęěẻẽ")) + call assert_equal("fḟ", tolower("fḟ")) + call assert_equal("gĝğġģǥǧǵḡ", tolower("gĝğġģǥǧǵḡ")) + call assert_equal("hĥħḣḧḩẖ", tolower("hĥħḣḧḩẖ")) + call assert_equal("iìíîïĩīĭįǐỉ", tolower("iìíîïĩīĭįǐỉ")) + call assert_equal("jĵǰ", tolower("jĵǰ")) + call assert_equal("kķǩḱḵ", tolower("kķǩḱḵ")) + call assert_equal("lĺļľŀłḻ", tolower("lĺļľŀłḻ")) + call assert_equal("mḿṁ ", tolower("mḿṁ ")) + call assert_equal("nñńņňʼnṅṉ", tolower("nñńņňʼnṅṉ")) + call assert_equal("oòóôõöøōŏőơǒǫǭỏ", tolower("oòóôõöøōŏőơǒǫǭỏ")) + call assert_equal("pṕṗ", tolower("pṕṗ")) + call assert_equal("q", tolower("q")) + call assert_equal("rŕŗřṙṟ", tolower("rŕŗřṙṟ")) + call assert_equal("sśŝşšṡ", tolower("sśŝşšṡ")) + call assert_equal("tţťŧṫṯẗ", tolower("tţťŧṫṯẗ")) + call assert_equal("uùúûüũūŭůűųưǔủ", tolower("uùúûüũūŭůűųưǔủ")) + call assert_equal("vṽ", tolower("vṽ")) + call assert_equal("wŵẁẃẅẇẘ", tolower("wŵẁẃẅẇẘ")) + call assert_equal("ẋẍ", tolower("ẋẍ")) + call assert_equal("yýÿŷẏẙỳỷỹ", tolower("yýÿŷẏẙỳỷỹ")) + call assert_equal("zźżžƶẑẕ", tolower("zźżžƶẑẕ")) + + " According to https://twitter.com/jifa/status/625776454479970304 + " Ⱥ (U+023A) and Ⱦ (U+023E) are the *only* code points to increase + " in length (2 to 3 bytes) when lowercased. So let's test them. + call assert_equal("ⱥ ⱦ", tolower("Ⱥ Ⱦ")) + + " This call to tolower with invalid utf8 sequence used to cause access to + " invalid memory. + call tolower("\xC0\x80\xC0") + call tolower("123\xC0\x80\xC0") + + " Test in latin1 encoding + let save_enc = &encoding + " set encoding=latin1 + call assert_equal("abc", tolower("ABC")) + let &encoding = save_enc +endfunc + +func Test_toupper() + call assert_equal("", toupper("")) + + " Test with all printable ASCII characters. + call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~', + \ toupper(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~')) + + " Test with a few lowercase diacritics. + call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", "aàáâãäåāăąǎǟǡả"->toupper()) + call assert_equal("BḂḆ", toupper("bḃḇ")) + call assert_equal("CÇĆĈĊČ", toupper("cçćĉċč")) + call assert_equal("DĎĐḊḎḐ", toupper("dďđḋḏḑ")) + call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("eèéêëēĕėęěẻẽ")) + call assert_equal("FḞ", toupper("fḟ")) + call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("gĝğġģǥǧǵḡ")) + call assert_equal("HĤĦḢḦḨẖ", toupper("hĥħḣḧḩẖ")) + call assert_equal("IÌÍÎÏĨĪĬĮǏỈ", toupper("iìíîïĩīĭįǐỉ")) + call assert_equal("JĴǰ", toupper("jĵǰ")) + call assert_equal("KĶǨḰḴ", toupper("kķǩḱḵ")) + call assert_equal("LĹĻĽĿŁḺ", toupper("lĺļľŀłḻ")) + call assert_equal("MḾṀ ", toupper("mḿṁ ")) + call assert_equal("NÑŃŅŇʼnṄṈ", toupper("nñńņňʼnṅṉ")) + call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("oòóôõöøōŏőơǒǫǭỏ")) + call assert_equal("PṔṖ", toupper("pṕṗ")) + call assert_equal("Q", toupper("q")) + call assert_equal("RŔŖŘṘṞ", toupper("rŕŗřṙṟ")) + call assert_equal("SŚŜŞŠṠ", toupper("sśŝşšṡ")) + call assert_equal("TŢŤŦṪṮẗ", toupper("tţťŧṫṯẗ")) + call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("uùúûüũūŭůűųưǔủ")) + call assert_equal("VṼ", toupper("vṽ")) + call assert_equal("WŴẀẂẄẆẘ", toupper("wŵẁẃẅẇẘ")) + call assert_equal("ẊẌ", toupper("ẋẍ")) + call assert_equal("YÝŸŶẎẙỲỶỸ", toupper("yýÿŷẏẙỳỷỹ")) + call assert_equal("ZŹŻŽƵẐẔ", toupper("zźżžƶẑẕ")) + + " Test that uppercase diacritics, which should remain unchanged. + call assert_equal("AÀÁÂÃÄÅĀĂĄǍǞǠẢ", toupper("AÀÁÂÃÄÅĀĂĄǍǞǠẢ")) + call assert_equal("BḂḆ", toupper("BḂḆ")) + call assert_equal("CÇĆĈĊČ", toupper("CÇĆĈĊČ")) + call assert_equal("DĎĐḊḎḐ", toupper("DĎĐḊḎḐ")) + call assert_equal("EÈÉÊËĒĔĖĘĚẺẼ", toupper("EÈÉÊËĒĔĖĘĚẺẼ")) + call assert_equal("FḞ ", toupper("FḞ ")) + call assert_equal("GĜĞĠĢǤǦǴḠ", toupper("GĜĞĠĢǤǦǴḠ")) + call assert_equal("HĤĦḢḦḨ", toupper("HĤĦḢḦḨ")) + call assert_equal("IÌÍÎÏĨĪĬĮİǏỈ", toupper("IÌÍÎÏĨĪĬĮİǏỈ")) + call assert_equal("JĴ", toupper("JĴ")) + call assert_equal("KĶǨḰḴ", toupper("KĶǨḰḴ")) + call assert_equal("LĹĻĽĿŁḺ", toupper("LĹĻĽĿŁḺ")) + call assert_equal("MḾṀ", toupper("MḾṀ")) + call assert_equal("NÑŃŅŇṄṈ", toupper("NÑŃŅŇṄṈ")) + call assert_equal("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ", toupper("OÒÓÔÕÖØŌŎŐƠǑǪǬỎ")) + call assert_equal("PṔṖ", toupper("PṔṖ")) + call assert_equal("Q", toupper("Q")) + call assert_equal("RŔŖŘṘṞ", toupper("RŔŖŘṘṞ")) + call assert_equal("SŚŜŞŠṠ", toupper("SŚŜŞŠṠ")) + call assert_equal("TŢŤŦṪṮ", toupper("TŢŤŦṪṮ")) + call assert_equal("UÙÚÛÜŨŪŬŮŰŲƯǓỦ", toupper("UÙÚÛÜŨŪŬŮŰŲƯǓỦ")) + call assert_equal("VṼ", toupper("VṼ")) + call assert_equal("WŴẀẂẄẆ", toupper("WŴẀẂẄẆ")) + call assert_equal("XẊẌ", toupper("XẊẌ")) + call assert_equal("YÝŶŸẎỲỶỸ", toupper("YÝŶŸẎỲỶỸ")) + call assert_equal("ZŹŻŽƵẐẔ", toupper("ZŹŻŽƵẐẔ")) + + call assert_equal("Ⱥ Ⱦ", toupper("ⱥ ⱦ")) + + " This call to toupper with invalid utf8 sequence used to cause access to + " invalid memory. + call toupper("\xC0\x80\xC0") + call toupper("123\xC0\x80\xC0") + + " Test in latin1 encoding + let save_enc = &encoding + " set encoding=latin1 + call assert_equal("ABC", toupper("abc")) + let &encoding = save_enc +endfunc + +func Test_tr() + call assert_equal('foo', tr('bar', 'bar', 'foo')) + call assert_equal('zxy', 'cab'->tr('abc', 'xyz')) + call assert_fails("let s=tr([], 'abc', 'def')", 'E730:') + call assert_fails("let s=tr('abc', [], 'def')", 'E730:') + call assert_fails("let s=tr('abc', 'abc', [])", 'E730:') + call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:') + " set encoding=latin1 + call assert_fails("let s=tr('abcd', 'abcd', 'def')", 'E475:') + call assert_equal('hEllO', tr('hello', 'eo', 'EO')) + call assert_equal('hello', tr('hello', 'xy', 'ab')) + call assert_fails('call tr("abc", "123", "₁₂")', 'E475:') + set encoding=utf8 +endfunc + +" Tests for the mode() function +let current_modes = '' +func Save_mode() + let g:current_modes = mode(0) . '-' . mode(1) + return '' +endfunc + +" Test for the mode() function +func Test_mode() + new + call append(0, ["Blue Ball Black", "Brown Band Bowl", ""]) + + " Only complete from the current buffer. + set complete=. + + noremap! <F2> <C-R>=Save_mode()<CR> + xnoremap <F2> <Cmd>call Save_mode()<CR> + + normal! 3G + exe "normal i\<F2>\<Esc>" + call assert_equal('i-i', g:current_modes) + " i_CTRL-P: Multiple matches + exe "normal i\<C-G>uBa\<C-P>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + " i_CTRL-P: Single match + exe "normal iBro\<C-P>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + " i_CTRL-X + exe "normal iBa\<C-X>\<F2>\<Esc>u" + call assert_equal('i-ix', g:current_modes) + " i_CTRL-X CTRL-P: Multiple matches + exe "normal iBa\<C-X>\<C-P>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + " i_CTRL-X CTRL-P: Single match + exe "normal iBro\<C-X>\<C-P>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + " i_CTRL-X CTRL-P + CTRL-P: Single match + exe "normal iBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + " i_CTRL-X CTRL-L: Multiple matches + exe "normal i\<C-X>\<C-L>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + " i_CTRL-X CTRL-L: Single match + exe "normal iBlu\<C-X>\<C-L>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + " i_CTRL-P: No match + exe "normal iCom\<C-P>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + " i_CTRL-X CTRL-P: No match + exe "normal iCom\<C-X>\<C-P>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + " i_CTRL-X CTRL-L: No match + exe "normal iabc\<C-X>\<C-L>\<F2>\<Esc>u" + call assert_equal('i-ic', g:current_modes) + + exe "normal R\<F2>\<Esc>" + call assert_equal('R-R', g:current_modes) + " R_CTRL-P: Multiple matches + exe "normal RBa\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + " R_CTRL-P: Single match + exe "normal RBro\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + " R_CTRL-X + exe "normal RBa\<C-X>\<F2>\<Esc>u" + call assert_equal('R-Rx', g:current_modes) + " R_CTRL-X CTRL-P: Multiple matches + exe "normal RBa\<C-X>\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + " R_CTRL-X CTRL-P: Single match + exe "normal RBro\<C-X>\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + " R_CTRL-X CTRL-P + CTRL-P: Single match + exe "normal RBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + " R_CTRL-X CTRL-L: Multiple matches + exe "normal R\<C-X>\<C-L>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + " R_CTRL-X CTRL-L: Single match + exe "normal RBlu\<C-X>\<C-L>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + " R_CTRL-P: No match + exe "normal RCom\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + " R_CTRL-X CTRL-P: No match + exe "normal RCom\<C-X>\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + " R_CTRL-X CTRL-L: No match + exe "normal Rabc\<C-X>\<C-L>\<F2>\<Esc>u" + call assert_equal('R-Rc', g:current_modes) + + exe "normal gR\<F2>\<Esc>" + call assert_equal('R-Rv', g:current_modes) + " gR_CTRL-P: Multiple matches + exe "normal gRBa\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + " gR_CTRL-P: Single match + exe "normal gRBro\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + " gR_CTRL-X + exe "normal gRBa\<C-X>\<F2>\<Esc>u" + call assert_equal('R-Rvx', g:current_modes) + " gR_CTRL-X CTRL-P: Multiple matches + exe "normal gRBa\<C-X>\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + " gR_CTRL-X CTRL-P: Single match + exe "normal gRBro\<C-X>\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + " gR_CTRL-X CTRL-P + CTRL-P: Single match + exe "normal gRBro\<C-X>\<C-P>\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + " gR_CTRL-X CTRL-L: Multiple matches + exe "normal gR\<C-X>\<C-L>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + " gR_CTRL-X CTRL-L: Single match + exe "normal gRBlu\<C-X>\<C-L>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + " gR_CTRL-P: No match + exe "normal gRCom\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + " gR_CTRL-X CTRL-P: No match + exe "normal gRCom\<C-X>\<C-P>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + " gR_CTRL-X CTRL-L: No match + exe "normal gRabc\<C-X>\<C-L>\<F2>\<Esc>u" + call assert_equal('R-Rvc', g:current_modes) + + call assert_equal('n', 0->mode()) + call assert_equal('n', 1->mode()) + + " i_CTRL-O + exe "normal i\<C-O>:call Save_mode()\<Cr>\<Esc>" + call assert_equal("n-niI", g:current_modes) + + " R_CTRL-O + exe "normal R\<C-O>:call Save_mode()\<Cr>\<Esc>" + call assert_equal("n-niR", g:current_modes) + + " gR_CTRL-O + exe "normal gR\<C-O>:call Save_mode()\<Cr>\<Esc>" + call assert_equal("n-niV", g:current_modes) + + " How to test operator-pending mode? + + call feedkeys("v", 'xt') + call assert_equal('v', mode()) + call assert_equal('v', mode(1)) + call feedkeys("\<Esc>V", 'xt') + call assert_equal('V', mode()) + call assert_equal('V', mode(1)) + call feedkeys("\<Esc>\<C-V>", 'xt') + call assert_equal("\<C-V>", mode()) + call assert_equal("\<C-V>", mode(1)) + call feedkeys("\<Esc>", 'xt') + + call feedkeys("gh", 'xt') + call assert_equal('s', mode()) + call assert_equal('s', mode(1)) + call feedkeys("\<Esc>gH", 'xt') + call assert_equal('S', mode()) + call assert_equal('S', mode(1)) + call feedkeys("\<Esc>g\<C-H>", 'xt') + call assert_equal("\<C-S>", mode()) + call assert_equal("\<C-S>", mode(1)) + call feedkeys("\<Esc>", 'xt') + + " v_CTRL-O + exe "normal gh\<C-O>\<F2>\<Esc>" + call assert_equal("v-vs", g:current_modes) + exe "normal gH\<C-O>\<F2>\<Esc>" + call assert_equal("V-Vs", g:current_modes) + exe "normal g\<C-H>\<C-O>\<F2>\<Esc>" + call assert_equal("\<C-V>-\<C-V>s", g:current_modes) + + call feedkeys(":\<F2>\<CR>", 'xt') + call assert_equal('c-c', g:current_modes) + call feedkeys(":\<Insert>\<F2>\<CR>", 'xt') + call assert_equal("c-cr", g:current_modes) + call feedkeys("gQ\<F2>vi\<CR>", 'xt') + call assert_equal('c-cv', g:current_modes) + call feedkeys("gQ\<Insert>\<F2>vi\<CR>", 'xt') + call assert_equal("c-cvr", g:current_modes) + + " Executing commands in Vim Ex mode should return "cv", never "cvr", + " as Cmdline editing has already ended. + call feedkeys("gQcall Save_mode()\<CR>vi\<CR>", 'xt') + call assert_equal('c-cv', g:current_modes) + call feedkeys("gQ\<Insert>call Save_mode()\<CR>vi\<CR>", 'xt') + call assert_equal('c-cv', g:current_modes) + + " call feedkeys("Qcall Save_mode()\<CR>vi\<CR>", 'xt') + " call assert_equal('c-ce', g:current_modes) + + " Test mode in operatorfunc (it used to be Operator-pending). + set operatorfunc=OperatorFunc + function OperatorFunc(_) + call Save_mode() + endfunction + execute "normal! g@l\<Esc>" + call assert_equal('n-n', g:current_modes) + execute "normal! i\<C-o>g@l\<Esc>" + call assert_equal('n-niI', g:current_modes) + execute "normal! R\<C-o>g@l\<Esc>" + call assert_equal('n-niR', g:current_modes) + execute "normal! gR\<C-o>g@l\<Esc>" + call assert_equal('n-niV', g:current_modes) + + " Test statusline updates for overstrike mode + if CanRunVimInTerminal() + let buf = RunVimInTerminal('', {'rows': 12}) + call term_sendkeys(buf, ":set laststatus=2 statusline=%!mode(1)\<CR>") + call term_sendkeys(buf, ":") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_mode_1', {}) + call term_sendkeys(buf, "\<Insert>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_mode_2', {}) + call StopVimInTerminal(buf) + endif + + if has('terminal') + term + call feedkeys("\<C-W>N", 'xt') + call assert_equal('n', mode()) + call assert_equal('nt', mode(1)) + call feedkeys("aexit\<CR>", 'xt') + endif + + bwipe! + unmap! <F2> + xunmap <F2> + set complete& + set operatorfunc& + delfunction OperatorFunc +endfunc + +" Test for append() +func Test_append() + enew! + split + call assert_equal(0, append(1, [])) + call assert_equal(0, append(1, v:_null_list)) + call assert_equal(0, append(0, ["foo"])) + call assert_equal(0, append(1, [])) + call assert_equal(0, append(1, v:_null_list)) + call assert_equal(0, append(8, [])) + call assert_equal(0, append(9, v:_null_list)) + call assert_equal(['foo', ''], getline(1, '$')) + split + only + undo + undo + + " Using $ instead of '$' must give an error + call assert_fails("call append($, 'foobar')", 'E116:') + + call assert_fails("call append({}, '')", ['E728:', 'E728:']) +endfunc + +" Test for setline() +func Test_setline() + new + call setline(0, ["foo"]) + call setline(0, []) + call setline(0, v:_null_list) + call setline(1, ["bar"]) + call setline(1, []) + call setline(1, v:_null_list) + call setline(2, []) + call setline(2, v:_null_list) + call setline(3, []) + call setline(3, v:_null_list) + call setline(2, ["baz"]) + call assert_equal(['bar', 'baz'], getline(1, '$')) + close! +endfunc + +func Test_getbufvar() + let bnr = bufnr('%') + let b:var_num = '1234' + let def_num = '5678' + call assert_equal('1234', getbufvar(bnr, 'var_num')) + call assert_equal('1234', getbufvar(bnr, 'var_num', def_num)) + + let bd = getbufvar(bnr, '') + call assert_equal('1234', bd['var_num']) + call assert_true(exists("bd['changedtick']")) + call assert_equal(2, len(bd)) + + let bd2 = getbufvar(bnr, '', def_num) + call assert_equal(bd, bd2) + + unlet b:var_num + call assert_equal(def_num, getbufvar(bnr, 'var_num', def_num)) + call assert_equal('', getbufvar(bnr, 'var_num')) + + let bd = getbufvar(bnr, '') + call assert_equal(1, len(bd)) + let bd = getbufvar(bnr, '',def_num) + call assert_equal(1, len(bd)) + + call assert_equal('', getbufvar(9999, '')) + call assert_equal(def_num, getbufvar(9999, '', def_num)) + unlet def_num + + call assert_equal(0, getbufvar(bnr, '&autoindent')) + call assert_equal(0, getbufvar(bnr, '&autoindent', 1)) + + " Set and get a buffer-local variable + call setbufvar(bnr, 'bufvar_test', ['one', 'two']) + call assert_equal(['one', 'two'], getbufvar(bnr, 'bufvar_test')) + + " Open new window with forced option values + set fileformats=unix,dos + new ++ff=dos ++bin ++enc=iso-8859-2 + call assert_equal('dos', getbufvar(bufnr('%'), '&fileformat')) + call assert_equal(1, getbufvar(bufnr('%'), '&bin')) + call assert_equal('iso-8859-2', getbufvar(bufnr('%'), '&fenc')) + close + + " Get the b: dict. + let b:testvar = 'one' + new + let b:testvar = 'two' + let thebuf = bufnr() + wincmd w + call assert_equal('two', getbufvar(thebuf, 'testvar')) + call assert_equal('two', getbufvar(thebuf, '').testvar) + bwipe! + + set fileformats& +endfunc + +func Test_last_buffer_nr() + call assert_equal(bufnr('$'), last_buffer_nr()) +endfunc + +func Test_stridx() + call assert_equal(-1, stridx('', 'l')) + call assert_equal(0, stridx('', '')) + call assert_equal(0, 'hello'->stridx('')) + call assert_equal(-1, stridx('hello', 'L')) + call assert_equal(2, stridx('hello', 'l', -1)) + call assert_equal(2, stridx('hello', 'l', 0)) + call assert_equal(2, 'hello'->stridx('l', 1)) + call assert_equal(3, stridx('hello', 'l', 3)) + call assert_equal(-1, stridx('hello', 'l', 4)) + call assert_equal(-1, stridx('hello', 'l', 10)) + call assert_equal(2, stridx('hello', 'll')) + call assert_equal(-1, stridx('hello', 'hello world')) + call assert_fails("let n=stridx('hello', [])", 'E730:') + call assert_fails("let n=stridx([], 'l')", 'E730:') +endfunc + +func Test_strridx() + call assert_equal(-1, strridx('', 'l')) + call assert_equal(0, strridx('', '')) + call assert_equal(5, strridx('hello', '')) + call assert_equal(-1, strridx('hello', 'L')) + call assert_equal(3, 'hello'->strridx('l')) + call assert_equal(3, strridx('hello', 'l', 10)) + call assert_equal(3, strridx('hello', 'l', 3)) + call assert_equal(2, strridx('hello', 'l', 2)) + call assert_equal(-1, strridx('hello', 'l', 1)) + call assert_equal(-1, strridx('hello', 'l', 0)) + call assert_equal(-1, strridx('hello', 'l', -1)) + call assert_equal(2, strridx('hello', 'll')) + call assert_equal(-1, strridx('hello', 'hello world')) + call assert_fails("let n=strridx('hello', [])", 'E730:') + call assert_fails("let n=strridx([], 'l')", 'E730:') +endfunc + +func Test_match_func() + call assert_equal(4, match('testing', 'ing')) + call assert_equal(4, 'testing'->match('ing', 2)) + call assert_equal(-1, match('testing', 'ing', 5)) + call assert_equal(-1, match('testing', 'ing', 8)) + call assert_equal(1, match(['vim', 'testing', 'execute'], 'ing')) + call assert_equal(-1, match(['vim', 'testing', 'execute'], 'img')) + call assert_fails("let x=match('vim', [])", 'E730:') + call assert_equal(3, match(['a', 'b', 'c', 'a'], 'a', 1)) + call assert_equal(-1, match(['a', 'b', 'c', 'a'], 'a', 5)) + call assert_equal(4, match('testing', 'ing', -1)) + call assert_fails("let x=match('testing', 'ing', 0, [])", 'E745:') + call assert_equal(-1, match(v:_null_list, 2)) + call assert_equal(-1, match('abc', '\\%(')) +endfunc + +func Test_matchend() + call assert_equal(7, matchend('testing', 'ing')) + call assert_equal(7, 'testing'->matchend('ing', 2)) + call assert_equal(-1, matchend('testing', 'ing', 5)) + call assert_equal(-1, matchend('testing', 'ing', 8)) + call assert_equal(match(['vim', 'testing', 'execute'], 'ing'), matchend(['vim', 'testing', 'execute'], 'ing')) + call assert_equal(match(['vim', 'testing', 'execute'], 'img'), matchend(['vim', 'testing', 'execute'], 'img')) +endfunc + +func Test_matchlist() + call assert_equal(['acd', 'a', '', 'c', 'd', '', '', '', '', ''], matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)')) + call assert_equal(['d', '', '', '', 'd', '', '', '', '', ''], 'acd'->matchlist('\(a\)\?\(b\)\?\(c\)\?\(.*\)', 2)) + call assert_equal([], matchlist('acd', '\(a\)\?\(b\)\?\(c\)\?\(.*\)', 4)) +endfunc + +func Test_matchstr() + call assert_equal('ing', matchstr('testing', 'ing')) + call assert_equal('ing', 'testing'->matchstr('ing', 2)) + call assert_equal('', matchstr('testing', 'ing', 5)) + call assert_equal('', matchstr('testing', 'ing', 8)) + call assert_equal('testing', matchstr(['vim', 'testing', 'execute'], 'ing')) + call assert_equal('', matchstr(['vim', 'testing', 'execute'], 'img')) +endfunc + +func Test_matchstrpos() + call assert_equal(['ing', 4, 7], matchstrpos('testing', 'ing')) + call assert_equal(['ing', 4, 7], 'testing'->matchstrpos('ing', 2)) + call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 5)) + call assert_equal(['', -1, -1], matchstrpos('testing', 'ing', 8)) + call assert_equal(['ing', 1, 4, 7], matchstrpos(['vim', 'testing', 'execute'], 'ing')) + call assert_equal(['', -1, -1, -1], matchstrpos(['vim', 'testing', 'execute'], 'img')) + call assert_equal(['', -1, -1], matchstrpos(v:_null_list, '\a')) +endfunc + +func Test_nextnonblank_prevnonblank() + new +insert +This + + +is + +a +Test +. + call assert_equal(0, nextnonblank(-1)) + call assert_equal(0, nextnonblank(0)) + call assert_equal(1, nextnonblank(1)) + call assert_equal(4, 2->nextnonblank()) + call assert_equal(4, nextnonblank(3)) + call assert_equal(4, nextnonblank(4)) + call assert_equal(6, nextnonblank(5)) + call assert_equal(6, nextnonblank(6)) + call assert_equal(7, nextnonblank(7)) + call assert_equal(0, 8->nextnonblank()) + + call assert_equal(0, prevnonblank(-1)) + call assert_equal(0, prevnonblank(0)) + call assert_equal(1, 1->prevnonblank()) + call assert_equal(1, prevnonblank(2)) + call assert_equal(1, prevnonblank(3)) + call assert_equal(4, prevnonblank(4)) + call assert_equal(4, 5->prevnonblank()) + call assert_equal(6, prevnonblank(6)) + call assert_equal(7, prevnonblank(7)) + call assert_equal(0, prevnonblank(8)) + bw! +endfunc + +func Test_byte2line_line2byte() + new + set endofline + call setline(1, ['a', 'bc', 'd']) + + set fileformat=unix + call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1], + \ map(range(-1, 8), 'byte2line(v:val)')) + call assert_equal([-1, -1, 1, 3, 6, 8, -1], + \ map(range(-1, 5), 'line2byte(v:val)')) + + set fileformat=mac + call assert_equal([-1, -1, 1, 1, 2, 2, 2, 3, 3, -1], + \ map(range(-1, 8), 'v:val->byte2line()')) + call assert_equal([-1, -1, 1, 3, 6, 8, -1], + \ map(range(-1, 5), 'v:val->line2byte()')) + + set fileformat=dos + call assert_equal([-1, -1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, -1], + \ map(range(-1, 11), 'byte2line(v:val)')) + call assert_equal([-1, -1, 1, 4, 8, 11, -1], + \ map(range(-1, 5), 'line2byte(v:val)')) + + bw! + set noendofline nofixendofline + normal a- + for ff in ["unix", "mac", "dos"] + let &fileformat = ff + call assert_equal(1, line2byte(1)) + call assert_equal(2, line2byte(2)) " line2byte(line("$") + 1) is the buffer size plus one (as per :help line2byte). + endfor + + set endofline& fixendofline& fileformat& + bw! +endfunc + +" Test for byteidx() using a character index +func Test_byteidx() + let a = '.é.' " one char of two bytes + call assert_equal(0, byteidx(a, 0)) + call assert_equal(1, byteidx(a, 1)) + call assert_equal(3, byteidx(a, 2)) + call assert_equal(4, byteidx(a, 3)) + call assert_equal(-1, byteidx(a, 4)) + + let b = '.é.' " normal e with composing char + call assert_equal(0, b->byteidx(0)) + call assert_equal(1, b->byteidx(1)) + call assert_equal(4, b->byteidx(2)) + call assert_equal(5, b->byteidx(3)) + call assert_equal(-1, b->byteidx(4)) + + " string with multiple composing characters + let str = '-ą́-ą́' + call assert_equal(0, byteidx(str, 0)) + call assert_equal(1, byteidx(str, 1)) + call assert_equal(6, byteidx(str, 2)) + call assert_equal(7, byteidx(str, 3)) + call assert_equal(12, byteidx(str, 4)) + call assert_equal(-1, byteidx(str, 5)) + + " empty string + call assert_equal(0, byteidx('', 0)) + call assert_equal(-1, byteidx('', 1)) + + " error cases + call assert_fails("call byteidx([], 0)", 'E730:') + call assert_fails("call byteidx('abc', [])", 'E745:') + call assert_fails("call byteidx('abc', 0, {})", ['E728:', 'E728:']) + call assert_fails("call byteidx('abc', 0, -1)", ['E1023:', 'E1023:']) +endfunc + +" Test for byteidxcomp() using a character index +func Test_byteidxcomp() + let a = '.é.' " one char of two bytes + call assert_equal(0, byteidxcomp(a, 0)) + call assert_equal(1, byteidxcomp(a, 1)) + call assert_equal(3, byteidxcomp(a, 2)) + call assert_equal(4, byteidxcomp(a, 3)) + call assert_equal(-1, byteidxcomp(a, 4)) + + let b = '.é.' " normal e with composing char + call assert_equal(0, b->byteidxcomp(0)) + call assert_equal(1, b->byteidxcomp(1)) + call assert_equal(2, b->byteidxcomp(2)) + call assert_equal(4, b->byteidxcomp(3)) + call assert_equal(5, b->byteidxcomp(4)) + call assert_equal(-1, b->byteidxcomp(5)) + + " string with multiple composing characters + let str = '-ą́-ą́' + call assert_equal(0, byteidxcomp(str, 0)) + call assert_equal(1, byteidxcomp(str, 1)) + call assert_equal(2, byteidxcomp(str, 2)) + call assert_equal(4, byteidxcomp(str, 3)) + call assert_equal(6, byteidxcomp(str, 4)) + call assert_equal(7, byteidxcomp(str, 5)) + call assert_equal(8, byteidxcomp(str, 6)) + call assert_equal(10, byteidxcomp(str, 7)) + call assert_equal(12, byteidxcomp(str, 8)) + call assert_equal(-1, byteidxcomp(str, 9)) + + " empty string + call assert_equal(0, byteidxcomp('', 0)) + call assert_equal(-1, byteidxcomp('', 1)) + + " error cases + call assert_fails("call byteidxcomp([], 0)", 'E730:') + call assert_fails("call byteidxcomp('abc', [])", 'E745:') + call assert_fails("call byteidxcomp('abc', 0, {})", ['E728:', 'E728:']) + call assert_fails("call byteidxcomp('abc', 0, -1)", ['E1023:', 'E1023:']) +endfunc + +" Test for byteidx() using a UTF-16 index +func Test_byteidx_from_utf16_index() + " string with single byte characters + let str = "abc" + for i in range(3) + call assert_equal(i, byteidx(str, i, v:true)) + endfor + call assert_equal(3, byteidx(str, 3, v:true)) + call assert_equal(-1, byteidx(str, 4, v:true)) + + " string with two byte characters + let str = "a©©b" + call assert_equal(0, byteidx(str, 0, v:true)) + call assert_equal(1, byteidx(str, 1, v:true)) + call assert_equal(3, byteidx(str, 2, v:true)) + call assert_equal(5, byteidx(str, 3, v:true)) + call assert_equal(6, byteidx(str, 4, v:true)) + call assert_equal(-1, byteidx(str, 5, v:true)) + + " string with two byte characters + let str = "a😊😊b" + call assert_equal(0, byteidx(str, 0, v:true)) + call assert_equal(1, byteidx(str, 1, v:true)) + call assert_equal(1, byteidx(str, 2, v:true)) + call assert_equal(5, byteidx(str, 3, v:true)) + call assert_equal(5, byteidx(str, 4, v:true)) + call assert_equal(9, byteidx(str, 5, v:true)) + call assert_equal(10, byteidx(str, 6, v:true)) + call assert_equal(-1, byteidx(str, 7, v:true)) + + " string with composing characters + let str = '-á-b́' + call assert_equal(0, byteidx(str, 0, v:true)) + call assert_equal(1, byteidx(str, 1, v:true)) + call assert_equal(4, byteidx(str, 2, v:true)) + call assert_equal(5, byteidx(str, 3, v:true)) + call assert_equal(8, byteidx(str, 4, v:true)) + call assert_equal(-1, byteidx(str, 5, v:true)) + + " string with multiple composing characters + let str = '-ą́-ą́' + call assert_equal(0, byteidx(str, 0, v:true)) + call assert_equal(1, byteidx(str, 1, v:true)) + call assert_equal(6, byteidx(str, 2, v:true)) + call assert_equal(7, byteidx(str, 3, v:true)) + call assert_equal(12, byteidx(str, 4, v:true)) + call assert_equal(-1, byteidx(str, 5, v:true)) + + " empty string + call assert_equal(0, byteidx('', 0, v:true)) + call assert_equal(-1, byteidx('', 1, v:true)) + + " error cases + call assert_fails('call byteidx(str, 0, [])', 'E745:') +endfunc + +" Test for byteidxcomp() using a UTF-16 index +func Test_byteidxcomp_from_utf16_index() + " string with single byte characters + let str = "abc" + for i in range(3) + call assert_equal(i, byteidxcomp(str, i, v:true)) + endfor + call assert_equal(3, byteidxcomp(str, 3, v:true)) + call assert_equal(-1, byteidxcomp(str, 4, v:true)) + + " string with two byte characters + let str = "a©©b" + call assert_equal(0, byteidxcomp(str, 0, v:true)) + call assert_equal(1, byteidxcomp(str, 1, v:true)) + call assert_equal(3, byteidxcomp(str, 2, v:true)) + call assert_equal(5, byteidxcomp(str, 3, v:true)) + call assert_equal(6, byteidxcomp(str, 4, v:true)) + call assert_equal(-1, byteidxcomp(str, 5, v:true)) + + " string with two byte characters + let str = "a😊😊b" + call assert_equal(0, byteidxcomp(str, 0, v:true)) + call assert_equal(1, byteidxcomp(str, 1, v:true)) + call assert_equal(1, byteidxcomp(str, 2, v:true)) + call assert_equal(5, byteidxcomp(str, 3, v:true)) + call assert_equal(5, byteidxcomp(str, 4, v:true)) + call assert_equal(9, byteidxcomp(str, 5, v:true)) + call assert_equal(10, byteidxcomp(str, 6, v:true)) + call assert_equal(-1, byteidxcomp(str, 7, v:true)) + + " string with composing characters + let str = '-á-b́' + call assert_equal(0, byteidxcomp(str, 0, v:true)) + call assert_equal(1, byteidxcomp(str, 1, v:true)) + call assert_equal(2, byteidxcomp(str, 2, v:true)) + call assert_equal(4, byteidxcomp(str, 3, v:true)) + call assert_equal(5, byteidxcomp(str, 4, v:true)) + call assert_equal(6, byteidxcomp(str, 5, v:true)) + call assert_equal(8, byteidxcomp(str, 6, v:true)) + call assert_equal(-1, byteidxcomp(str, 7, v:true)) + call assert_fails('call byteidxcomp(str, 0, [])', 'E745:') + + " string with multiple composing characters + let str = '-ą́-ą́' + call assert_equal(0, byteidxcomp(str, 0, v:true)) + call assert_equal(1, byteidxcomp(str, 1, v:true)) + call assert_equal(2, byteidxcomp(str, 2, v:true)) + call assert_equal(4, byteidxcomp(str, 3, v:true)) + call assert_equal(6, byteidxcomp(str, 4, v:true)) + call assert_equal(7, byteidxcomp(str, 5, v:true)) + call assert_equal(8, byteidxcomp(str, 6, v:true)) + call assert_equal(10, byteidxcomp(str, 7, v:true)) + call assert_equal(12, byteidxcomp(str, 8, v:true)) + call assert_equal(-1, byteidxcomp(str, 9, v:true)) + + " empty string + call assert_equal(0, byteidxcomp('', 0, v:true)) + call assert_equal(-1, byteidxcomp('', 1, v:true)) + + " error cases + call assert_fails('call byteidxcomp(str, 0, [])', 'E745:') +endfunc + +" Test for charidx() using a byte index +func Test_charidx() + let a = 'xáb́y' + call assert_equal(0, charidx(a, 0)) + call assert_equal(1, charidx(a, 3)) + call assert_equal(2, charidx(a, 4)) + call assert_equal(3, charidx(a, 7)) + call assert_equal(4, charidx(a, 8)) + call assert_equal(-1, charidx(a, 9)) + call assert_equal(-1, charidx(a, -1)) + + " count composing characters + call assert_equal(0, a->charidx(0, 1)) + call assert_equal(2, a->charidx(2, 1)) + call assert_equal(3, a->charidx(4, 1)) + call assert_equal(5, a->charidx(7, 1)) + call assert_equal(6, a->charidx(8, 1)) + call assert_equal(-1, a->charidx(9, 1)) + + " empty string + call assert_equal(0, charidx('', 0)) + call assert_equal(-1, charidx('', 1)) + call assert_equal(0, charidx('', 0, 1)) + call assert_equal(-1, charidx('', 1, 1)) + + " error cases + call assert_equal(0, charidx(v:_null_string, 0)) + call assert_equal(-1, charidx(v:_null_string, 1)) + call assert_fails('let x = charidx([], 1)', 'E1174:') + call assert_fails('let x = charidx("abc", [])', 'E1210:') + call assert_fails('let x = charidx("abc", 1, [])', 'E1212:') + call assert_fails('let x = charidx("abc", 1, -1)', 'E1212:') + call assert_fails('let x = charidx("abc", 1, 2)', 'E1212:') +endfunc + +" Test for charidx() using a UTF-16 index +func Test_charidx_from_utf16_index() + " string with single byte characters + let str = "abc" + for i in range(4) + call assert_equal(i, charidx(str, i, v:false, v:true)) + endfor + call assert_equal(-1, charidx(str, 4, v:false, v:true)) + + " string with two byte characters + let str = "a©©b" + call assert_equal(0, charidx(str, 0, v:false, v:true)) + call assert_equal(1, charidx(str, 1, v:false, v:true)) + call assert_equal(2, charidx(str, 2, v:false, v:true)) + call assert_equal(3, charidx(str, 3, v:false, v:true)) + call assert_equal(4, charidx(str, 4, v:false, v:true)) + call assert_equal(-1, charidx(str, 5, v:false, v:true)) + + " string with four byte characters + let str = "a😊😊b" + call assert_equal(0, charidx(str, 0, v:false, v:true)) + call assert_equal(1, charidx(str, 1, v:false, v:true)) + call assert_equal(1, charidx(str, 2, v:false, v:true)) + call assert_equal(2, charidx(str, 3, v:false, v:true)) + call assert_equal(2, charidx(str, 4, v:false, v:true)) + call assert_equal(3, charidx(str, 5, v:false, v:true)) + call assert_equal(4, charidx(str, 6, v:false, v:true)) + call assert_equal(-1, charidx(str, 7, v:false, v:true)) + + " string with composing characters + let str = '-á-b́' + for i in str->strcharlen()->range() + call assert_equal(i, charidx(str, i, v:false, v:true)) + endfor + call assert_equal(4, charidx(str, 4, v:false, v:true)) + call assert_equal(-1, charidx(str, 5, v:false, v:true)) + for i in str->strchars()->range() + call assert_equal(i, charidx(str, i, v:true, v:true)) + endfor + call assert_equal(6, charidx(str, 6, v:true, v:true)) + call assert_equal(-1, charidx(str, 7, v:true, v:true)) + + " string with multiple composing characters + let str = '-ą́-ą́' + for i in str->strcharlen()->range() + call assert_equal(i, charidx(str, i, v:false, v:true)) + endfor + call assert_equal(4, charidx(str, 4, v:false, v:true)) + call assert_equal(-1, charidx(str, 5, v:false, v:true)) + for i in str->strchars()->range() + call assert_equal(i, charidx(str, i, v:true, v:true)) + endfor + call assert_equal(8, charidx(str, 8, v:true, v:true)) + call assert_equal(-1, charidx(str, 9, v:true, v:true)) + + " empty string + call assert_equal(0, charidx('', 0, v:false, v:true)) + call assert_equal(-1, charidx('', 1, v:false, v:true)) + call assert_equal(0, charidx('', 0, v:true, v:true)) + call assert_equal(-1, charidx('', 1, v:true, v:true)) + + " error cases + call assert_equal(0, charidx('', 0, v:false, v:true)) + call assert_equal(-1, charidx('', 1, v:false, v:true)) + call assert_equal(0, charidx('', 0, v:true, v:true)) + call assert_equal(-1, charidx('', 1, v:true, v:true)) + call assert_equal(0, charidx(v:_null_string, 0, v:false, v:true)) + call assert_equal(-1, charidx(v:_null_string, 1, v:false, v:true)) + call assert_fails('let x = charidx("abc", 1, v:false, [])', 'E1212:') + call assert_fails('let x = charidx("abc", 1, v:true, [])', 'E1212:') +endfunc + +" Test for utf16idx() using a byte index +func Test_utf16idx_from_byteidx() + " UTF-16 index of a string with single byte characters + let str = "abc" + for i in range(4) + call assert_equal(i, utf16idx(str, i)) + endfor + call assert_equal(-1, utf16idx(str, 4)) + + " UTF-16 index of a string with two byte characters + let str = 'a©©b' + call assert_equal(0, str->utf16idx(0)) + call assert_equal(1, str->utf16idx(1)) + call assert_equal(1, str->utf16idx(2)) + call assert_equal(2, str->utf16idx(3)) + call assert_equal(2, str->utf16idx(4)) + call assert_equal(3, str->utf16idx(5)) + call assert_equal(4, str->utf16idx(6)) + call assert_equal(-1, str->utf16idx(7)) + + " UTF-16 index of a string with four byte characters + let str = 'a😊😊b' + call assert_equal(0, utf16idx(str, 0)) + call assert_equal(1, utf16idx(str, 1)) + call assert_equal(1, utf16idx(str, 2)) + call assert_equal(1, utf16idx(str, 3)) + call assert_equal(1, utf16idx(str, 4)) + call assert_equal(3, utf16idx(str, 5)) + call assert_equal(3, utf16idx(str, 6)) + call assert_equal(3, utf16idx(str, 7)) + call assert_equal(3, utf16idx(str, 8)) + call assert_equal(5, utf16idx(str, 9)) + call assert_equal(6, utf16idx(str, 10)) + call assert_equal(-1, utf16idx(str, 11)) + + " UTF-16 index of a string with composing characters + let str = '-á-b́' + call assert_equal(0, utf16idx(str, 0)) + call assert_equal(1, utf16idx(str, 1)) + call assert_equal(1, utf16idx(str, 2)) + call assert_equal(1, utf16idx(str, 3)) + call assert_equal(2, utf16idx(str, 4)) + call assert_equal(3, utf16idx(str, 5)) + call assert_equal(3, utf16idx(str, 6)) + call assert_equal(3, utf16idx(str, 7)) + call assert_equal(4, utf16idx(str, 8)) + call assert_equal(-1, utf16idx(str, 9)) + call assert_equal(0, utf16idx(str, 0, v:true)) + call assert_equal(1, utf16idx(str, 1, v:true)) + call assert_equal(2, utf16idx(str, 2, v:true)) + call assert_equal(2, utf16idx(str, 3, v:true)) + call assert_equal(3, utf16idx(str, 4, v:true)) + call assert_equal(4, utf16idx(str, 5, v:true)) + call assert_equal(5, utf16idx(str, 6, v:true)) + call assert_equal(5, utf16idx(str, 7, v:true)) + call assert_equal(6, utf16idx(str, 8, v:true)) + call assert_equal(-1, utf16idx(str, 9, v:true)) + + " string with multiple composing characters + let str = '-ą́-ą́' + call assert_equal(0, utf16idx(str, 0)) + call assert_equal(1, utf16idx(str, 1)) + call assert_equal(1, utf16idx(str, 2)) + call assert_equal(1, utf16idx(str, 3)) + call assert_equal(1, utf16idx(str, 4)) + call assert_equal(1, utf16idx(str, 5)) + call assert_equal(2, utf16idx(str, 6)) + call assert_equal(3, utf16idx(str, 7)) + call assert_equal(3, utf16idx(str, 8)) + call assert_equal(3, utf16idx(str, 9)) + call assert_equal(3, utf16idx(str, 10)) + call assert_equal(3, utf16idx(str, 11)) + call assert_equal(4, utf16idx(str, 12)) + call assert_equal(-1, utf16idx(str, 13)) + call assert_equal(0, utf16idx(str, 0, v:true)) + call assert_equal(1, utf16idx(str, 1, v:true)) + call assert_equal(2, utf16idx(str, 2, v:true)) + call assert_equal(2, utf16idx(str, 3, v:true)) + call assert_equal(3, utf16idx(str, 4, v:true)) + call assert_equal(3, utf16idx(str, 5, v:true)) + call assert_equal(4, utf16idx(str, 6, v:true)) + call assert_equal(5, utf16idx(str, 7, v:true)) + call assert_equal(6, utf16idx(str, 8, v:true)) + call assert_equal(6, utf16idx(str, 9, v:true)) + call assert_equal(7, utf16idx(str, 10, v:true)) + call assert_equal(7, utf16idx(str, 11, v:true)) + call assert_equal(8, utf16idx(str, 12, v:true)) + call assert_equal(-1, utf16idx(str, 13, v:true)) + + " empty string + call assert_equal(0, utf16idx('', 0)) + call assert_equal(-1, utf16idx('', 1)) + call assert_equal(0, utf16idx('', 0, v:true)) + call assert_equal(-1, utf16idx('', 1, v:true)) + + " error cases + call assert_equal(0, utf16idx("", 0)) + call assert_equal(-1, utf16idx("", 1)) + call assert_equal(-1, utf16idx("abc", -1)) + call assert_equal(0, utf16idx(v:_null_string, 0)) + call assert_equal(-1, utf16idx(v:_null_string, 1)) + call assert_fails('let l = utf16idx([], 0)', 'E1174:') + call assert_fails('let l = utf16idx("ab", [])', 'E1210:') + call assert_fails('let l = utf16idx("ab", 0, [])', 'E1212:') +endfunc + +" Test for utf16idx() using a character index +func Test_utf16idx_from_charidx() + let str = "abc" + for i in str->strcharlen()->range() + call assert_equal(i, utf16idx(str, i, v:false, v:true)) + endfor + call assert_equal(3, utf16idx(str, 3, v:false, v:true)) + call assert_equal(-1, utf16idx(str, 4, v:false, v:true)) + + " UTF-16 index of a string with two byte characters + let str = "a©©b" + for i in str->strcharlen()->range() + call assert_equal(i, utf16idx(str, i, v:false, v:true)) + endfor + call assert_equal(4, utf16idx(str, 4, v:false, v:true)) + call assert_equal(-1, utf16idx(str, 5, v:false, v:true)) + + " UTF-16 index of a string with four byte characters + let str = "a😊😊b" + call assert_equal(0, utf16idx(str, 0, v:false, v:true)) + call assert_equal(1, utf16idx(str, 1, v:false, v:true)) + call assert_equal(3, utf16idx(str, 2, v:false, v:true)) + call assert_equal(5, utf16idx(str, 3, v:false, v:true)) + call assert_equal(6, utf16idx(str, 4, v:false, v:true)) + call assert_equal(-1, utf16idx(str, 5, v:false, v:true)) + + " UTF-16 index of a string with composing characters + let str = '-á-b́' + for i in str->strcharlen()->range() + call assert_equal(i, utf16idx(str, i, v:false, v:true)) + endfor + call assert_equal(4, utf16idx(str, 4, v:false, v:true)) + call assert_equal(-1, utf16idx(str, 5, v:false, v:true)) + for i in str->strchars()->range() + call assert_equal(i, utf16idx(str, i, v:true, v:true)) + endfor + call assert_equal(6, utf16idx(str, 6, v:true, v:true)) + call assert_equal(-1, utf16idx(str, 7, v:true, v:true)) + + " string with multiple composing characters + let str = '-ą́-ą́' + for i in str->strcharlen()->range() + call assert_equal(i, utf16idx(str, i, v:false, v:true)) + endfor + call assert_equal(4, utf16idx(str, 4, v:false, v:true)) + call assert_equal(-1, utf16idx(str, 5, v:false, v:true)) + for i in str->strchars()->range() + call assert_equal(i, utf16idx(str, i, v:true, v:true)) + endfor + call assert_equal(8, utf16idx(str, 8, v:true, v:true)) + call assert_equal(-1, utf16idx(str, 9, v:true, v:true)) + + " empty string + call assert_equal(0, utf16idx('', 0, v:false, v:true)) + call assert_equal(-1, utf16idx('', 1, v:false, v:true)) + call assert_equal(0, utf16idx('', 0, v:true, v:true)) + call assert_equal(-1, utf16idx('', 1, v:true, v:true)) + + " error cases + call assert_equal(0, utf16idx(v:_null_string, 0, v:true, v:true)) + call assert_equal(-1, utf16idx(v:_null_string, 1, v:true, v:true)) + call assert_fails('let l = utf16idx("ab", 0, v:false, [])', 'E1212:') +endfunc + +" Test for strutf16len() +func Test_strutf16len() + call assert_equal(3, strutf16len('abc')) + call assert_equal(3, 'abc'->strutf16len(v:true)) + call assert_equal(4, strutf16len('a©©b')) + call assert_equal(4, strutf16len('a©©b', v:true)) + call assert_equal(6, strutf16len('a😊😊b')) + call assert_equal(6, strutf16len('a😊😊b', v:true)) + call assert_equal(4, strutf16len('-á-b́')) + call assert_equal(6, strutf16len('-á-b́', v:true)) + call assert_equal(4, strutf16len('-ą́-ą́')) + call assert_equal(8, strutf16len('-ą́-ą́', v:true)) + call assert_equal(0, strutf16len('')) + + " error cases + call assert_fails('let l = strutf16len([])', 'E1174:') + call assert_fails('let l = strutf16len("a", [])', 'E1212:') + call assert_equal(0, strutf16len(v:_null_string)) +endfunc + +func Test_count() + let l = ['a', 'a', 'A', 'b'] + call assert_equal(2, count(l, 'a')) + call assert_equal(1, count(l, 'A')) + call assert_equal(1, count(l, 'b')) + call assert_equal(0, count(l, 'B')) + + call assert_equal(2, count(l, 'a', 0)) + call assert_equal(1, count(l, 'A', 0)) + call assert_equal(1, count(l, 'b', 0)) + call assert_equal(0, count(l, 'B', 0)) + + call assert_equal(3, count(l, 'a', 1)) + call assert_equal(3, count(l, 'A', 1)) + call assert_equal(1, count(l, 'b', 1)) + call assert_equal(1, count(l, 'B', 1)) + call assert_equal(0, count(l, 'c', 1)) + + call assert_equal(1, count(l, 'a', 0, 1)) + call assert_equal(2, count(l, 'a', 1, 1)) + call assert_fails('call count(l, "a", 0, 10)', 'E684:') + call assert_fails('call count(l, "a", [])', 'E745:') + + let d = {1: 'a', 2: 'a', 3: 'A', 4: 'b'} + call assert_equal(2, count(d, 'a')) + call assert_equal(1, count(d, 'A')) + call assert_equal(1, count(d, 'b')) + call assert_equal(0, count(d, 'B')) + + call assert_equal(2, count(d, 'a', 0)) + call assert_equal(1, count(d, 'A', 0)) + call assert_equal(1, count(d, 'b', 0)) + call assert_equal(0, count(d, 'B', 0)) + + call assert_equal(3, count(d, 'a', 1)) + call assert_equal(3, count(d, 'A', 1)) + call assert_equal(1, count(d, 'b', 1)) + call assert_equal(1, count(d, 'B', 1)) + call assert_equal(0, count(d, 'c', 1)) + + call assert_fails('call count(d, "a", 0, 1)', 'E474:') + + call assert_equal(0, count("foo", "bar")) + call assert_equal(1, count("foo", "oo")) + call assert_equal(2, count("foo", "o")) + call assert_equal(0, count("foo", "O")) + call assert_equal(2, count("foo", "O", 1)) + call assert_equal(2, count("fooooo", "oo")) + call assert_equal(0, count("foo", "")) + + call assert_fails('call count(0, 0)', 'E706:') + call assert_fails('call count("", "", {})', ['E728:', 'E728:']) +endfunc + +func Test_changenr() + new Xchangenr + call assert_equal(0, changenr()) + norm ifoo + call assert_equal(1, changenr()) + set undolevels=10 + norm Sbar + call assert_equal(2, changenr()) + undo + call assert_equal(1, changenr()) + redo + call assert_equal(2, changenr()) + bw! + set undolevels& +endfunc + +func Test_filewritable() + new Xfilewritable + write! + call assert_equal(1, filewritable('Xfilewritable')) + + call assert_notequal(0, setfperm('Xfilewritable', 'r--r-----')) + call assert_equal(0, filewritable('Xfilewritable')) + + call assert_notequal(0, setfperm('Xfilewritable', 'rw-r-----')) + call assert_equal(1, 'Xfilewritable'->filewritable()) + + call assert_equal(0, filewritable('doesnotexist')) + + call mkdir('Xdir') + call assert_equal(2, filewritable('Xdir')) + call delete('Xdir', 'd') + + call delete('Xfilewritable') + bw! +endfunc + +func Test_Executable() + if has('win32') + call assert_equal(1, executable('notepad')) + call assert_equal(1, 'notepad.exe'->executable()) + call assert_equal(0, executable('notepad.exe.exe')) + call assert_equal(0, executable('shell32.dll')) + call assert_equal(0, executable('win.ini')) + elseif has('unix') + call assert_equal(1, 'cat'->executable()) + call assert_equal(0, executable('nodogshere')) + + " get "cat" path and remove the leading / + let catcmd = exepath('cat')[1:] + new + " check that the relative path works in / + lcd / + call assert_equal(1, executable(catcmd)) + let result = catcmd->exepath() + " when using chroot looking for sbin/cat can return bin/cat, that is OK + if catcmd =~ '\<sbin\>' && result =~ '\<bin\>' + call assert_equal('/' .. substitute(catcmd, '\<sbin\>', 'bin', ''), result) + else + " /bin/cat and /usr/bin/cat may be hard linked, we could get either + let result = substitute(result, '/usr/bin/cat', '/bin/cat', '') + let catcmd = substitute(catcmd, 'usr/bin/cat', 'bin/cat', '') + call assert_equal('/' .. catcmd, result) + endif + bwipe + else + throw 'Skipped: does not work on this platform' + endif +endfunc + +func Test_executable_longname() + if !has('win32') + return + endif + + let fname = 'X' . repeat('あ', 200) . '.bat' + call writefile([], fname) + call assert_equal(1, executable(fname)) + call delete(fname) +endfunc + +func Test_hostname() + let hostname_vim = hostname() + if has('unix') + let hostname_system = systemlist('uname -n')[0] + call assert_equal(hostname_vim, hostname_system) + endif +endfunc + +func Test_getpid() + " getpid() always returns the same value within a vim instance. + call assert_equal(getpid(), getpid()) + if has('unix') + call assert_equal(systemlist('echo $PPID')[0], string(getpid())) + endif +endfunc + +func Test_hlexists() + call assert_equal(0, hlexists('does_not_exist')) + " call assert_equal(0, 'Number'->hlexists()) + call assert_equal(0, highlight_exists('does_not_exist')) + " call assert_equal(0, highlight_exists('Number')) + syntax on + call assert_equal(0, hlexists('does_not_exist')) + " call assert_equal(1, hlexists('Number')) + call assert_equal(0, highlight_exists('does_not_exist')) + " call assert_equal(1, highlight_exists('Number')) + syntax off +endfunc + +" Test for the col() function +func Test_col() + new + call setline(1, 'abcdef') + norm gg4|mx6|mY2| + call assert_equal(2, col('.')) + call assert_equal(7, col('$')) + call assert_equal(2, col('v')) + call assert_equal(4, col("'x")) + call assert_equal(6, col("'Y")) + call assert_equal(2, [1, 2]->col()) + call assert_equal(7, col([1, '$'])) + + call assert_equal(0, col('')) + call assert_equal(0, col('x')) + call assert_equal(0, col([2, '$'])) + call assert_equal(0, col([1, 100])) + call assert_equal(0, col([1])) + call assert_equal(0, col(v:_null_list)) + call assert_fails('let c = col({})', 'E1222:') + call assert_fails('let c = col(".", [])', 'E1210:') + + " test for getting the visual start column + func T() + let g:Vcol = col('v') + return '' + endfunc + let g:Vcol = 0 + xmap <expr> <F2> T() + exe "normal gg3|ve\<F2>" + call assert_equal(3, g:Vcol) + xunmap <F2> + delfunc T + + " Test for the visual line start and end marks '< and '> + call setline(1, ['one', 'one two', 'one two three']) + "normal! ggVG + call feedkeys("ggVG\<Esc>", 'xt') + call assert_equal(1, col("'<")) + call assert_equal(14, col("'>")) + " Delete the last line of the visually selected region + $d + call assert_notequal(14, col("'>")) + + " Test with 'virtualedit' + set virtualedit=all + call cursor(1, 10) + call assert_equal(4, col('.')) + set virtualedit& + + " Test for getting the column number in another window + let winid = win_getid() + new + call win_execute(winid, 'normal 1G$') + call assert_equal(3, col('.', winid)) + call win_execute(winid, 'normal 2G') + call assert_equal(8, col('$', winid)) + call assert_equal(0, col('.', 5001)) + + bw! +endfunc + +" Test for input() +func Test_input_func() + " Test for prompt with multiple lines + redir => v + call feedkeys(":let c = input(\"A\\nB\\nC\\n? \")\<CR>B\<CR>", 'xt') + redir END + call assert_equal("B", c) + call assert_equal(['A', 'B', 'C'], split(v, "\n")) + + " Test for default value + call feedkeys(":let c = input('color? ', 'red')\<CR>\<CR>", 'xt') + call assert_equal('red', c) + + " Test for completion at the input prompt + func! Tcomplete(arglead, cmdline, pos) + return "item1\nitem2\nitem3" + endfunc + call feedkeys(":let c = input('Q? ', '', 'custom,Tcomplete')\<CR>" + \ .. "\<C-A>\<CR>", 'xt') + delfunc Tcomplete + call assert_equal('item1 item2 item3', c) + + " Test for using special characters as default input + call feedkeys(":let c = input('name? ', \"x\\<BS>y\")\<CR>\<CR>", 'xt') + call assert_equal('y', c) + + " Test for using text with composing characters as default input + call feedkeys(":let c = input('name? ', \"ã̳\")\<CR>\<CR>", 'xt') + call assert_equal('ã̳', c) + + " Test for using <CR> as default input + call feedkeys(":let c = input('name? ', \"\\<CR>\")\<CR>x\<CR>", 'xt') + call assert_equal(' x', c) + + call assert_fails("call input('F:', '', 'invalid')", 'E180:') + call assert_fails("call input('F:', '', [])", 'E730:') +endfunc + +" Test for the inputdialog() function +func Test_inputdialog() + if has('gui_running') + call assert_fails('let v=inputdialog([], "xx")', 'E730:') + call assert_fails('let v=inputdialog("Q", [])', 'E730:') + else + call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<CR>", 'xt') + call assert_equal('xx', v) + call feedkeys(":let v=inputdialog('Q:', 'xx', 'yy')\<CR>\<Esc>", 'xt') + call assert_equal('yy', v) + endif +endfunc + +" Test for inputlist() +func Test_inputlist() + call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<cr>", 'tx') + call assert_equal(1, c) + call feedkeys(":let c = ['Select color:', '1. red', '2. green', '3. blue']->inputlist()\<cr>2\<cr>", 'tx') + call assert_equal(2, c) + call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>3\<cr>", 'tx') + call assert_equal(3, c) + + " CR to cancel + call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<cr>", 'tx') + call assert_equal(0, c) + + " Esc to cancel + call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<Esc>", 'tx') + call assert_equal(0, c) + + " q to cancel + call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>q", 'tx') + call assert_equal(0, c) + + " Cancel after inputting a number + call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>5q", 'tx') + call assert_equal(0, c) + + " Use backspace to delete characters in the prompt + call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>1\<BS>3\<BS>2\<cr>", 'tx') + call assert_equal(2, c) + + " Use mouse to make a selection + call Ntest_setmouse(&lines - 3, 2) + call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx') + call assert_equal(1, c) + " Mouse click outside of the list + call Ntest_setmouse(&lines - 6, 2) + call feedkeys(":let c = inputlist(['Select color:', '1. red', '2. green', '3. blue'])\<cr>\<LeftMouse>", 'tx') + call assert_equal(-2, c) + + call assert_fails('call inputlist("")', 'E686:') + " Nvim accepts null list as empty list + " call assert_fails('call inputlist(v:_null_list)', 'E686:') +endfunc + +func Test_range_inputlist() + " flush out any garbage left in the buffer + while getchar(0) + endwhile + + call feedkeys(":let result = inputlist(range(10))\<CR>1\<CR>", 'x') + call assert_equal(1, result) + call feedkeys(":let result = inputlist(range(3, 10))\<CR>1\<CR>", 'x') + call assert_equal(1, result) + + unlet result +endfunc + +func Test_balloon_show() + CheckFeature balloon_eval + + " This won't do anything but must not crash either. + call balloon_show('hi!') + if !has('gui_running') + call balloon_show(range(3)) + call balloon_show([]) + endif +endfunc + +func Test_shellescape() + let save_shell = &shell + set shell=bash + call assert_equal("'text'", shellescape('text')) + call assert_equal("'te\"xt'", 'te"xt'->shellescape()) + call assert_equal("'te'\\''xt'", shellescape("te'xt")) + + call assert_equal("'te%xt'", shellescape("te%xt")) + call assert_equal("'te\\%xt'", shellescape("te%xt", 1)) + call assert_equal("'te#xt'", shellescape("te#xt")) + call assert_equal("'te\\#xt'", shellescape("te#xt", 1)) + call assert_equal("'te!xt'", shellescape("te!xt")) + call assert_equal("'te\\!xt'", shellescape("te!xt", 1)) + + call assert_equal("'te\nxt'", shellescape("te\nxt")) + call assert_equal("'te\\\nxt'", shellescape("te\nxt", 1)) + set shell=tcsh + call assert_equal("'te\\!xt'", shellescape("te!xt")) + call assert_equal("'te\\\\!xt'", shellescape("te!xt", 1)) + call assert_equal("'te\\\nxt'", shellescape("te\nxt")) + call assert_equal("'te\\\\\nxt'", shellescape("te\nxt", 1)) + + set shell=fish + call assert_equal("'text'", shellescape('text')) + call assert_equal("'te\"xt'", shellescape('te"xt')) + call assert_equal("'te'\\''xt'", shellescape("te'xt")) + + call assert_equal("'te%xt'", shellescape("te%xt")) + call assert_equal("'te\\%xt'", shellescape("te%xt", 1)) + call assert_equal("'te#xt'", shellescape("te#xt")) + call assert_equal("'te\\#xt'", shellescape("te#xt", 1)) + call assert_equal("'te!xt'", shellescape("te!xt")) + call assert_equal("'te\\!xt'", shellescape("te!xt", 1)) + + call assert_equal("'te\\\\xt'", shellescape("te\\xt")) + call assert_equal("'te\\\\xt'", shellescape("te\\xt", 1)) + call assert_equal("'te\\\\'\\''xt'", shellescape("te\\'xt")) + call assert_equal("'te\\\\'\\''xt'", shellescape("te\\'xt", 1)) + call assert_equal("'te\\\\!xt'", shellescape("te\\!xt")) + call assert_equal("'te\\\\\\!xt'", shellescape("te\\!xt", 1)) + call assert_equal("'te\\\\%xt'", shellescape("te\\%xt")) + call assert_equal("'te\\\\\\%xt'", shellescape("te\\%xt", 1)) + call assert_equal("'te\\\\#xt'", shellescape("te\\#xt")) + call assert_equal("'te\\\\\\#xt'", shellescape("te\\#xt", 1)) + + let &shell = save_shell +endfunc + +func Test_setbufvar_options() + " This tests that aucmd_prepbuf() and aucmd_restbuf() properly restore the + " window layout and cursor position. + call assert_equal(1, winnr('$')) + split dummy_preview + resize 2 + set winfixheight winfixwidth + let prev_id = win_getid() + + wincmd j + let wh = winheight(0) + let dummy_buf = bufnr('dummy_buf1', v:true) + call setbufvar(dummy_buf, '&buftype', 'nofile') + execute 'belowright vertical split #' . dummy_buf + call assert_equal(wh, winheight(0)) + let dum1_id = win_getid() + call setline(1, 'foo') + normal! V$ + call assert_equal(4, col('.')) + call setbufvar('dummy_preview', '&buftype', 'nofile') + call assert_equal(4, col('.')) + + wincmd h + let wh = winheight(0) + call setline(1, 'foo') + normal! V$ + call assert_equal(4, col('.')) + let dummy_buf = bufnr('dummy_buf2', v:true) + eval 'nofile'->setbufvar(dummy_buf, '&buftype') + call assert_equal(4, col('.')) + execute 'belowright vertical split #' . dummy_buf + call assert_equal(wh, winheight(0)) + + bwipe! + call win_gotoid(prev_id) + bwipe! + call win_gotoid(dum1_id) + bwipe! +endfunc + +func Test_setbufvar_keep_window_title() + CheckRunVimInTerminal + if !has('title') || empty(&t_ts) + throw "Skipped: can't get/set title" + endif + + let lines =<< trim END + set title + edit Xa.txt + let g:buf = bufadd('Xb.txt') + inoremap <F2> <C-R>=setbufvar(g:buf, '&autoindent', 1) ?? ''<CR> + END + call writefile(lines, 'Xsetbufvar') + let buf = RunVimInTerminal('-S Xsetbufvar', {}) + call WaitForAssert({-> assert_match('Xa.txt', term_gettitle(buf))}, 1000) + + call term_sendkeys(buf, "i\<F2>") + call TermWait(buf) + call term_sendkeys(buf, "\<Esc>") + call TermWait(buf) + call assert_match('Xa.txt', term_gettitle(buf)) + + call StopVimInTerminal(buf) + call delete('Xsetbufvar') +endfunc + +func Test_redo_in_nested_functions() + nnoremap g. :set opfunc=Operator<CR>g@ + function Operator( type, ... ) + let @x = 'XXX' + execute 'normal! g`[' . (a:type ==# 'line' ? 'V' : 'v') . 'g`]' . '"xp' + endfunction + + function! Apply() + 5,6normal! . + endfunction + + new + call setline(1, repeat(['some "quoted" text', 'more "quoted" text'], 3)) + 1normal g.i" + call assert_equal('some "XXX" text', getline(1)) + 3,4normal . + call assert_equal('some "XXX" text', getline(3)) + call assert_equal('more "XXX" text', getline(4)) + call Apply() + call assert_equal('some "XXX" text', getline(5)) + call assert_equal('more "XXX" text', getline(6)) + bwipe! + + nunmap g. + delfunc Operator + delfunc Apply +endfunc + +func Test_trim() + call assert_equal("Testing", trim(" \t\r\r\x0BTesting \t\n\r\n\t\x0B\x0B")) + call assert_equal("Testing", " \t \r\r\n\n\x0BTesting \t\n\r\n\t\x0B\x0B"->trim()) + call assert_equal("RESERVE", trim("xyz \twwRESERVEzyww \t\t", " wxyz\t")) + call assert_equal("wRE \tSERVEzyww", trim("wRE \tSERVEzyww")) + call assert_equal("abcd\t xxxx tail", trim(" \tabcd\t xxxx tail")) + call assert_equal("\tabcd\t xxxx tail", trim(" \tabcd\t xxxx tail", " ")) + call assert_equal(" \tabcd\t xxxx tail", trim(" \tabcd\t xxxx tail", "abx")) + call assert_equal("RESERVE", trim("你RESERVE好", "你好")) + call assert_equal("您R E SER V E早", trim("你好您R E SER V E早好你你", "你好")) + call assert_equal("你好您R E SER V E早好你你", trim(" \n\r\r 你好您R E SER V E早好你你 \t \x0B", )) + call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" 你好您R E SER V E早好你你 \t \x0B", " 你好")) + call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" tteesstttt你好您R E SER V E早好你你 \t \x0B ttestt", " 你好tes")) + call assert_equal("您R E SER V E早好你你 \t \x0B", trim(" tteesstttt你好您R E SER V E早好你你 \t \x0B ttestt", " 你你你好好好tttsses")) + call assert_equal("留下", trim("这些些不要这些留下这些", "这些不要")) + call assert_equal("", trim("", "")) + call assert_equal("a", trim("a", "")) + call assert_equal("", trim("", "a")) + call assert_equal("vim", trim(" vim ", " ", 0)) + call assert_equal("vim ", trim(" vim ", " ", 1)) + call assert_equal(" vim", trim(" vim ", " ", 2)) + call assert_fails('eval trim(" vim ", " ", [])', 'E745:') + call assert_fails('eval trim(" vim ", " ", -1)', 'E475:') + call assert_fails('eval trim(" vim ", " ", 3)', 'E475:') + call assert_fails('eval trim(" vim ", 0)', 'E1174:') + + let chars = join(map(range(1, 0x20) + [0xa0], {n -> n->nr2char()}), '') + call assert_equal("x", trim(chars . "x" . chars)) + + call assert_equal("x", trim(chars . "x" . chars, '', 0)) + call assert_equal("x" . chars, trim(chars . "x" . chars, '', 1)) + call assert_equal(chars . "x", trim(chars . "x" . chars, '', 2)) + + call assert_fails('let c=trim([])', 'E730:') +endfunc + +" Test for reg_recording() and reg_executing() +func Test_reg_executing_and_recording() + let s:reg_stat = '' + func s:save_reg_stat() + let s:reg_stat = reg_recording() . ':' . reg_executing() + return '' + endfunc + + new + call s:save_reg_stat() + call assert_equal(':', s:reg_stat) + call feedkeys("qa\"=s:save_reg_stat()\<CR>pq", 'xt') + call assert_equal('a:', s:reg_stat) + call feedkeys("@a", 'xt') + call assert_equal(':a', s:reg_stat) + call feedkeys("qb@aq", 'xt') + call assert_equal('b:a', s:reg_stat) + call feedkeys("q\"\"=s:save_reg_stat()\<CR>pq", 'xt') + call assert_equal('":', s:reg_stat) + + " :normal command saves and restores reg_executing + let s:reg_stat = '' + let @q = ":call TestFunc()\<CR>:call s:save_reg_stat()\<CR>" + func TestFunc() abort + normal! ia + endfunc + call feedkeys("@q", 'xt') + call assert_equal(':q', s:reg_stat) + delfunc TestFunc + + " getchar() command saves and restores reg_executing + map W :call TestFunc()<CR> + let @q = "W" + let g:typed = '' + let g:regs = [] + func TestFunc() abort + let g:regs += [reg_executing()] + let g:typed = getchar(0) + let g:regs += [reg_executing()] + endfunc + call feedkeys("@qy", 'xt') + call assert_equal(char2nr("y"), g:typed) + call assert_equal(['q', 'q'], g:regs) + delfunc TestFunc + unmap W + unlet g:typed + unlet g:regs + + " input() command saves and restores reg_executing + map W :call TestFunc()<CR> + let @q = "W" + let g:typed = '' + let g:regs = [] + func TestFunc() abort + let g:regs += [reg_executing()] + let g:typed = '?'->input() + let g:regs += [reg_executing()] + endfunc + call feedkeys("@qy\<CR>", 'xt') + call assert_equal("y", g:typed) + call assert_equal(['q', 'q'], g:regs) + delfunc TestFunc + unmap W + unlet g:typed + unlet g:regs + + bwipe! + delfunc s:save_reg_stat + unlet s:reg_stat +endfunc + +func Test_inputsecret() + map W :call TestFunc()<CR> + let @q = "W" + let g:typed1 = '' + let g:typed2 = '' + let g:regs = [] + func TestFunc() abort + let g:typed1 = '?'->inputsecret() + let g:typed2 = inputsecret('password: ') + endfunc + call feedkeys("@qsomething\<CR>else\<CR>", 'xt') + call assert_equal("something", g:typed1) + call assert_equal("else", g:typed2) + delfunc TestFunc + unmap W + unlet g:typed1 + unlet g:typed2 +endfunc + +func Test_getchar() + call feedkeys('a', '') + call assert_equal(char2nr('a'), getchar()) + call assert_equal(0, getchar(0)) + call assert_equal(0, getchar(1)) + + call feedkeys('a', '') + call assert_equal('a', getcharstr()) + call assert_equal('', getcharstr(0)) + call assert_equal('', getcharstr(1)) + + call feedkeys("\<M-F2>", '') + call assert_equal("\<M-F2>", getchar(0)) + call assert_equal(0, getchar(0)) + + call setline(1, 'xxxx') + call Ntest_setmouse(1, 3) + let v:mouse_win = 9 + let v:mouse_winid = 9 + let v:mouse_lnum = 9 + let v:mouse_col = 9 + call feedkeys("\<S-LeftMouse>", '') + call assert_equal("\<S-LeftMouse>", getchar()) + call assert_equal(1, v:mouse_win) + call assert_equal(win_getid(1), v:mouse_winid) + call assert_equal(1, v:mouse_lnum) + call assert_equal(3, v:mouse_col) + enew! +endfunc + +func Test_libcall_libcallnr() + if !has('libcall') + return + endif + + if has('win32') + let libc = 'msvcrt.dll' + elseif has('mac') + let libc = 'libSystem.B.dylib' + elseif executable('ldd') + let libc = matchstr(split(system('ldd ' . GetVimProg())), '/libc\.so\>') + endif + if get(l:, 'libc', '') ==# '' + " On Unix, libc.so can be in various places. + if has('linux') + " There is not documented but regarding the 1st argument of glibc's + " dlopen an empty string and nullptr are equivalent, so using an empty + " string for the 1st argument of libcall allows to call functions. + let libc = '' + elseif has('sun') + " Set the path to libc.so according to the architecture. + let test_bits = system('file ' . GetVimProg()) + let test_arch = system('uname -p') + if test_bits =~ '64-bit' && test_arch =~ 'sparc' + let libc = '/usr/lib/sparcv9/libc.so' + elseif test_bits =~ '64-bit' && test_arch =~ 'i386' + let libc = '/usr/lib/amd64/libc.so' + else + let libc = '/usr/lib/libc.so' + endif + else + " Unfortunately skip this test until a good way is found. + return + endif + endif + + if has('win32') + call assert_equal($USERPROFILE, 'USERPROFILE'->libcall(libc, 'getenv')) + else + call assert_equal($HOME, 'HOME'->libcall(libc, 'getenv')) + endif + + " If function returns NULL, libcall() should return an empty string. + call assert_equal('', libcall(libc, 'getenv', 'X_ENV_DOES_NOT_EXIT')) + + " Test libcallnr() with string and integer argument. + call assert_equal(4, 'abcd'->libcallnr(libc, 'strlen')) + call assert_equal(char2nr('A'), char2nr('a')->libcallnr(libc, 'toupper')) + + call assert_fails("call libcall(libc, 'Xdoesnotexist_', '')", ['', 'E364:']) + call assert_fails("call libcallnr(libc, 'Xdoesnotexist_', '')", ['', 'E364:']) + + call assert_fails("call libcall('Xdoesnotexist_', 'getenv', 'HOME')", ['', 'E364:']) + call assert_fails("call libcallnr('Xdoesnotexist_', 'strlen', 'abcd')", ['', 'E364:']) +endfunc + +sandbox function Fsandbox() + normal ix +endfunc + +func Test_func_sandbox() + sandbox let F = {-> 'hello'} + call assert_equal('hello', F()) + + sandbox let F = {-> "normal ix\<Esc>"->execute()} + call assert_fails('call F()', 'E48:') + unlet F + + call assert_fails('call Fsandbox()', 'E48:') + delfunc Fsandbox + + " From a sandbox try to set a predefined variable (which cannot be modified + " from a sandbox) + call assert_fails('sandbox let v:lnum = 10', 'E794:') +endfunc + +func EditAnotherFile() + let word = expand('<cword>') + edit Xfuncrange2 +endfunc + +func Test_func_range_with_edit() + " Define a function that edits another buffer, then call it with a range that + " is invalid in that buffer. + call writefile(['just one line'], 'Xfuncrange2') + new + eval 10->range()->setline(1) + write Xfuncrange1 + call assert_fails('5,8call EditAnotherFile()', 'E16:') + + call delete('Xfuncrange1') + call delete('Xfuncrange2') + bwipe! +endfunc + +func Test_func_exists_on_reload() + call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists') + call assert_equal(0, exists('*ExistingFunction')) + source Xfuncexists + call assert_equal(1, '*ExistingFunction'->exists()) + " Redefining a function when reloading a script is OK. + source Xfuncexists + call assert_equal(1, exists('*ExistingFunction')) + + " But redefining in another script is not OK. + call writefile(['func ExistingFunction()', 'echo "yes"', 'endfunc'], 'Xfuncexists2') + call assert_fails('source Xfuncexists2', 'E122:') + + delfunc ExistingFunction + call assert_equal(0, exists('*ExistingFunction')) + call writefile([ + \ 'func ExistingFunction()', 'echo "yes"', 'endfunc', + \ 'func ExistingFunction()', 'echo "no"', 'endfunc', + \ ], 'Xfuncexists') + call assert_fails('source Xfuncexists', 'E122:') + call assert_equal(1, exists('*ExistingFunction')) + + call delete('Xfuncexists2') + call delete('Xfuncexists') + delfunc ExistingFunction +endfunc + +func Test_platform_name() + " The system matches at most only one name. + let names = ['amiga', 'beos', 'bsd', 'hpux', 'linux', 'mac', 'qnx', 'sun', 'vms', 'win32', 'win32unix'] + call assert_inrange(0, 1, len(filter(copy(names), 'has(v:val)'))) + + " Is Unix? + call assert_equal(has('beos'), has('beos') && has('unix')) + call assert_equal(has('bsd'), has('bsd') && has('unix')) + call assert_equal(has('hpux'), has('hpux') && has('unix')) + call assert_equal(has('linux'), has('linux') && has('unix')) + call assert_equal(has('mac'), has('mac') && has('unix')) + call assert_equal(has('qnx'), has('qnx') && has('unix')) + call assert_equal(has('sun'), has('sun') && has('unix')) + call assert_equal(has('win32'), has('win32') && !has('unix')) + call assert_equal(has('win32unix'), has('win32unix') && has('unix')) + + if has('unix') && executable('uname') + let uname = system('uname') + call assert_equal(uname =~? 'BeOS', has('beos')) + " GNU userland on BSD kernels (e.g., GNU/kFreeBSD) don't have BSD defined + call assert_equal(uname =~? '\%(GNU/k\w\+\)\@<!BSD\|DragonFly', has('bsd')) + call assert_equal(uname =~? 'HP-UX', has('hpux')) + call assert_equal(uname =~? 'Linux', has('linux')) + call assert_equal(uname =~? 'Darwin', has('mac')) + call assert_equal(uname =~? 'QNX', has('qnx')) + call assert_equal(uname =~? 'SunOS', has('sun')) + call assert_equal(uname =~? 'CYGWIN\|MSYS', has('win32unix')) + endif +endfunc + +" Test confirm({msg} [, {choices} [, {default} [, {type}]]]) +func Test_confirm() + " requires a UI to be active + throw 'Skipped: use test/functional/vimscript/input_spec.lua' + CheckUnix + CheckNotGui + + call feedkeys('o', 'L') + let a = confirm('Press O to proceed') + call assert_equal(1, a) + + call feedkeys('y', 'L') + let a = 'Are you sure?'->confirm("&Yes\n&No") + call assert_equal(1, a) + + call feedkeys('n', 'L') + let a = confirm('Are you sure?', "&Yes\n&No") + call assert_equal(2, a) + + " confirm() should return 0 when pressing CTRL-C. + call feedkeys("\<C-C>", 'L') + let a = confirm('Are you sure?', "&Yes\n&No") + call assert_equal(0, a) + + " <Esc> requires another character to avoid it being seen as the start of an + " escape sequence. Zero should be harmless. + eval "\<Esc>0"->feedkeys('L') + let a = confirm('Are you sure?', "&Yes\n&No") + call assert_equal(0, a) + + " Default choice is returned when pressing <CR>. + call feedkeys("\<CR>", 'L') + let a = confirm('Are you sure?', "&Yes\n&No") + call assert_equal(1, a) + + call feedkeys("\<CR>", 'L') + let a = confirm('Are you sure?', "&Yes\n&No", 2) + call assert_equal(2, a) + + call feedkeys("\<CR>", 'L') + let a = confirm('Are you sure?', "&Yes\n&No", 0) + call assert_equal(0, a) + + " Test with the {type} 4th argument + for type in ['Error', 'Question', 'Info', 'Warning', 'Generic'] + call feedkeys('y', 'L') + let a = confirm('Are you sure?', "&Yes\n&No\n", 1, type) + call assert_equal(1, a) + endfor + + call assert_fails('call confirm([])', 'E730:') + call assert_fails('call confirm("Are you sure?", [])', 'E730:') + call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", [])', 'E745:') + call assert_fails('call confirm("Are you sure?", "&Yes\n&No\n", 0, [])', 'E730:') +endfunc + +func Test_readdir() + call mkdir('Xdir') + call writefile([], 'Xdir/foo.txt') + call writefile([], 'Xdir/bar.txt') + call mkdir('Xdir/dir') + + " All results + let files = readdir('Xdir') + call assert_equal(['bar.txt', 'dir', 'foo.txt'], sort(files)) + + " Only results containing "f" + let files = 'Xdir'->readdir({ x -> stridx(x, 'f') !=- 1 }) + call assert_equal(['foo.txt'], sort(files)) + + " Only .txt files + let files = readdir('Xdir', { x -> x =~ '.txt$' }) + call assert_equal(['bar.txt', 'foo.txt'], sort(files)) + + " Only .txt files with string + let files = readdir('Xdir', 'v:val =~ ".txt$"') + call assert_equal(['bar.txt', 'foo.txt'], sort(files)) + + " Limit to 1 result. + let l = [] + let files = readdir('Xdir', {x -> len(add(l, x)) == 2 ? -1 : 1}) + call assert_equal(1, len(files)) + + eval 'Xdir'->delete('rf') +endfunc + +func Test_delete_rf() + call mkdir('Xdir') + call writefile([], 'Xdir/foo.txt') + call writefile([], 'Xdir/bar.txt') + call mkdir('Xdir/[a-1]') " issue #696 + call writefile([], 'Xdir/[a-1]/foo.txt') + call writefile([], 'Xdir/[a-1]/bar.txt') + call assert_true(filereadable('Xdir/foo.txt')) + call assert_true('Xdir/[a-1]/foo.txt'->filereadable()) + + call assert_equal(0, delete('Xdir', 'rf')) + call assert_false(filereadable('Xdir/foo.txt')) + call assert_false(filereadable('Xdir/[a-1]/foo.txt')) + + if has('unix') + call mkdir('Xdir/Xdir2', 'p') + silent !chmod 555 Xdir + call assert_equal(-1, delete('Xdir/Xdir2', 'rf')) + call assert_equal(-1, delete('Xdir', 'rf')) + silent !chmod 755 Xdir + call assert_equal(0, delete('Xdir', 'rf')) + endif +endfunc + +func Test_call() + call assert_equal(3, call('len', [123])) + call assert_equal(3, 'len'->call([123])) + call assert_fails("call call('len', 123)", 'E714:') + call assert_equal(0, call('', [])) + call assert_equal(0, call('len', v:_null_list)) + + function Mylen() dict + return len(self.data) + endfunction + let mydict = {'data': [0, 1, 2, 3], 'len': function("Mylen")} + eval mydict.len->call([], mydict)->assert_equal(4) + call assert_fails("call call('Mylen', [], 0)", 'E1206:') + call assert_fails('call foo', 'E107:') + + " These once caused a crash. + " Nvim doesn't have null functions + " call call(test_null_function(), []) + " Nvim doesn't have null partials + " call call(test_null_partial(), []) + " Nvim doesn't have null functions + " call assert_fails('call test_null_function()()', 'E1192:') + " Nvim doesn't have null partials + " call assert_fails('call test_null_partial()()', 'E117:') + + let lines =<< trim END + let Time = 'localtime' + call Time() + END + call CheckScriptFailure(lines, 'E1085:') +endfunc + +func Test_char2nr() + call assert_equal(12354, char2nr('あ', 1)) + call assert_equal(120, 'x'->char2nr()) + " set encoding=latin1 + call assert_equal(120, 'x'->char2nr()) + set encoding=utf-8 +endfunc + +func Test_charclass() + call assert_equal(0, charclass(' ')) + call assert_equal(1, charclass('.')) + call assert_equal(2, charclass('x')) + call assert_equal(3, charclass("\u203c")) + " this used to crash vim + call assert_equal(0, "xxx"[-1]->charclass()) +endfunc + +func Test_eventhandler() + call assert_equal(0, eventhandler()) +endfunc + +func Test_bufadd_bufload() + call assert_equal(0, bufexists('someName')) + let buf = bufadd('someName') + call assert_notequal(0, buf) + call assert_equal(1, bufexists('someName')) + call assert_equal(0, getbufvar(buf, '&buflisted')) + call assert_equal(0, bufloaded(buf)) + call bufload(buf) + call assert_equal(1, bufloaded(buf)) + call assert_equal([''], getbufline(buf, 1, '$')) + + let curbuf = bufnr('') + eval ['some', 'text']->writefile('XotherName') + let buf = 'XotherName'->bufadd() + call assert_notequal(0, buf) + eval 'XotherName'->bufexists()->assert_equal(1) + call assert_equal(0, getbufvar(buf, '&buflisted')) + call assert_equal(0, bufloaded(buf)) + eval buf->bufload() + call assert_equal(1, bufloaded(buf)) + call assert_equal(['some', 'text'], getbufline(buf, 1, '$')) + call assert_equal(curbuf, bufnr('')) + + let buf1 = bufadd('') + let buf2 = bufadd('') + call assert_notequal(0, buf1) + call assert_notequal(0, buf2) + call assert_notequal(buf1, buf2) + call assert_equal(1, bufexists(buf1)) + call assert_equal(1, bufexists(buf2)) + call assert_equal(0, bufloaded(buf1)) + exe 'bwipe ' .. buf1 + call assert_equal(0, bufexists(buf1)) + call assert_equal(1, bufexists(buf2)) + exe 'bwipe ' .. buf2 + call assert_equal(0, bufexists(buf2)) + + " When 'buftype' is "nofile" then bufload() does not read the file. + " Other values too. + for val in [['nofile', 0], + \ ['nowrite', 1], + \ ['acwrite', 1], + \ ['quickfix', 0], + \ ['help', 1], + "\ ['terminal', 0], + \ ['prompt', 0], + "\ ['popup', 0], + \ ] + bwipe! XotherName + let buf = bufadd('XotherName') + call setbufvar(buf, '&bt', val[0]) + call bufload(buf) + call assert_equal(val[1] ? ['some', 'text'] : [''], getbufline(buf, 1, '$'), val[0]) + endfor + + bwipe someName + bwipe XotherName + call assert_equal(0, bufexists('someName')) + call delete('XotherName') +endfunc + +func Test_state() + CheckRunVimInTerminal + + let getstate = ":echo 'state: ' .. g:state .. '; mode: ' .. g:mode\<CR>" + + let lines =<< trim END + call setline(1, ['one', 'two', 'three']) + map ;; gg + set complete=. + func RunTimer() + call timer_start(10, {id -> execute('let g:state = state()') .. execute('let g:mode = mode()')}) + endfunc + au Filetype foobar let g:state = state()|let g:mode = mode() + END + call writefile(lines, 'XState') + let buf = RunVimInTerminal('-S XState', #{rows: 6}) + + " Using a ":" command Vim is busy, thus "S" is returned + call term_sendkeys(buf, ":echo 'state: ' .. state() .. '; mode: ' .. mode()\<CR>") + call WaitForAssert({-> assert_match('state: S; mode: n', term_getline(buf, 6))}, 1000) + call term_sendkeys(buf, ":\<CR>") + + " Using a timer callback + call term_sendkeys(buf, ":call RunTimer()\<CR>") + call TermWait(buf, 25) + call term_sendkeys(buf, getstate) + call WaitForAssert({-> assert_match('state: c; mode: n', term_getline(buf, 6))}, 1000) + + " Halfway a mapping + call term_sendkeys(buf, ":call RunTimer()\<CR>;") + call TermWait(buf, 25) + call term_sendkeys(buf, ";") + call term_sendkeys(buf, getstate) + call WaitForAssert({-> assert_match('state: mSc; mode: n', term_getline(buf, 6))}, 1000) + + " An operator is pending + call term_sendkeys(buf, ":call RunTimer()\<CR>y") + call TermWait(buf, 25) + call term_sendkeys(buf, "y") + call term_sendkeys(buf, getstate) + call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000) + + " A register was specified + call term_sendkeys(buf, ":call RunTimer()\<CR>\"r") + call TermWait(buf, 25) + call term_sendkeys(buf, "yy") + call term_sendkeys(buf, getstate) + call WaitForAssert({-> assert_match('state: oSc; mode: n', term_getline(buf, 6))}, 1000) + + " Insert mode completion (bit slower on Mac) + call term_sendkeys(buf, ":call RunTimer()\<CR>Got\<C-N>") + call TermWait(buf, 25) + call term_sendkeys(buf, "\<Esc>") + call term_sendkeys(buf, getstate) + call WaitForAssert({-> assert_match('state: aSc; mode: i', term_getline(buf, 6))}, 1000) + + " Autocommand executing + call term_sendkeys(buf, ":set filetype=foobar\<CR>") + call TermWait(buf, 25) + call term_sendkeys(buf, getstate) + call WaitForAssert({-> assert_match('state: xS; mode: n', term_getline(buf, 6))}, 1000) + + " Todo: "w" - waiting for ch_evalexpr() + + " messages scrolled + call term_sendkeys(buf, ":call RunTimer()\<CR>:echo \"one\\ntwo\\nthree\"\<CR>") + call TermWait(buf, 25) + call term_sendkeys(buf, "\<CR>") + call term_sendkeys(buf, getstate) + call WaitForAssert({-> assert_match('state: Scs; mode: r', term_getline(buf, 6))}, 1000) + + call StopVimInTerminal(buf) + call delete('XState') +endfunc + +func Test_range() + " destructuring + let [x, y] = range(2) + call assert_equal([0, 1], [x, y]) + + " index + call assert_equal(4, range(1, 10)[3]) + + " add() + call assert_equal([0, 1, 2, 3], add(range(3), 3)) + call assert_equal([0, 1, 2, [0, 1, 2]], add([0, 1, 2], range(3))) + call assert_equal([0, 1, 2, [0, 1, 2]], add(range(3), range(3))) + + " append() + new + call append('.', range(5)) + call assert_equal(['', '0', '1', '2', '3', '4'], getline(1, '$')) + bwipe! + + " appendbufline() + new + call appendbufline(bufnr(''), '.', range(5)) + call assert_equal(['0', '1', '2', '3', '4', ''], getline(1, '$')) + bwipe! + + " call() + func TwoArgs(a, b) + return [a:a, a:b] + endfunc + call assert_equal([0, 1], call('TwoArgs', range(2))) + + " col() + new + call setline(1, ['foo', 'bar']) + call assert_equal(2, col(range(1, 2))) + bwipe! + + " complete() + execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>" + " complete_info() + execute "normal! a\<C-r>=[complete(col('.'), range(10)), ''][1]\<CR>\<C-r>=[complete_info(range(5)), ''][1]\<CR>" + + " copy() + call assert_equal([1, 2, 3], copy(range(1, 3))) + + " count() + call assert_equal(0, count(range(0), 3)) + call assert_equal(0, count(range(2), 3)) + call assert_equal(1, count(range(5), 3)) + + " cursor() + new + call setline(1, ['aaa', 'bbb', 'ccc']) + call cursor(range(1, 2)) + call assert_equal([2, 1], [col('.'), line('.')]) + bwipe! + + " deepcopy() + call assert_equal([1, 2, 3], deepcopy(range(1, 3))) + + " empty() + call assert_true(empty(range(0))) + call assert_false(empty(range(2))) + + " execute() + new + call setline(1, ['aaa', 'bbb', 'ccc']) + call execute(range(3)) + call assert_equal(2, line('.')) + bwipe! + + " extend() + call assert_equal([1, 2, 3, 4], extend([1], range(2, 4))) + call assert_equal([1, 2, 3, 4], extend(range(1, 1), range(2, 4))) + call assert_equal([1, 2, 3, 4], extend(range(1, 1), [2, 3, 4])) + + " filter() + call assert_equal([1, 3], filter(range(5), 'v:val % 2')) + + " funcref() + call assert_equal([0, 1], funcref('TwoArgs', range(2))()) + + " function() + call assert_equal([0, 1], function('TwoArgs', range(2))()) + + " garbagecollect() + let thelist = [1, range(2), 3] + let otherlist = range(3) + call test_garbagecollect_now() + + " get() + call assert_equal(4, get(range(1, 10), 3)) + call assert_equal(-1, get(range(1, 10), 42, -1)) + + " index() + call assert_equal(1, index(range(1, 5), 2)) + call assert_fails("echo index([1, 2], 1, [])", 'E745:') + + " insert() + call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42)) + call assert_equal([42, 1, 2, 3, 4, 5], insert(range(1, 5), 42, 0)) + call assert_equal([1, 42, 2, 3, 4, 5], insert(range(1, 5), 42, 1)) + call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, 4)) + call assert_equal([1, 2, 3, 4, 42, 5], insert(range(1, 5), 42, -1)) + call assert_equal([1, 2, 3, 4, 5, 42], insert(range(1, 5), 42, 5)) + + " join() + call assert_equal('0 1 2 3 4', join(range(5))) + + " json_encode() + " call assert_equal('[0,1,2,3]', json_encode(range(4))) + call assert_equal('[0, 1, 2, 3]', json_encode(range(4))) + + " len() + call assert_equal(0, len(range(0))) + call assert_equal(2, len(range(2))) + call assert_equal(5, len(range(0, 12, 3))) + call assert_equal(4, len(range(3, 0, -1))) + + " list2str() + call assert_equal('ABC', list2str(range(65, 67))) + call assert_fails('let s = list2str(5)', 'E474:') + + " lock() + let thelist = range(5) + lockvar thelist + + " map() + call assert_equal([0, 2, 4, 6, 8], map(range(5), 'v:val * 2')) + + " match() + call assert_equal(3, match(range(5), 3)) + + " matchaddpos() + highlight MyGreenGroup ctermbg=green guibg=green + call matchaddpos('MyGreenGroup', range(line('.'), line('.'))) + + " matchend() + call assert_equal(4, matchend(range(5), '4')) + call assert_equal(3, matchend(range(1, 5), '4')) + call assert_equal(-1, matchend(range(1, 5), '42')) + + " matchstrpos() + call assert_equal(['4', 4, 0, 1], matchstrpos(range(5), '4')) + call assert_equal(['4', 3, 0, 1], matchstrpos(range(1, 5), '4')) + call assert_equal(['', -1, -1, -1], matchstrpos(range(1, 5), '42')) + + " max() reverse() + call assert_equal(0, max(range(0))) + call assert_equal(0, max(range(10, 9))) + call assert_equal(9, max(range(10))) + call assert_equal(18, max(range(0, 20, 3))) + call assert_equal(20, max(range(20, 0, -3))) + call assert_equal(99999, max(range(100000))) + call assert_equal(99999, max(range(99999, 0, -1))) + call assert_equal(99999, max(reverse(range(100000)))) + call assert_equal(99999, max(reverse(range(99999, 0, -1)))) + + " min() reverse() + call assert_equal(0, min(range(0))) + call assert_equal(0, min(range(10, 9))) + call assert_equal(5, min(range(5, 10))) + call assert_equal(5, min(range(5, 10, 3))) + call assert_equal(2, min(range(20, 0, -3))) + call assert_equal(0, min(range(100000))) + call assert_equal(0, min(range(99999, 0, -1))) + call assert_equal(0, min(reverse(range(100000)))) + call assert_equal(0, min(reverse(range(99999, 0, -1)))) + + " remove() + call assert_equal(1, remove(range(1, 10), 0)) + call assert_equal(2, remove(range(1, 10), 1)) + call assert_equal(9, remove(range(1, 10), 8)) + call assert_equal(10, remove(range(1, 10), 9)) + call assert_equal(10, remove(range(1, 10), -1)) + call assert_equal([3, 4, 5], remove(range(1, 10), 2, 4)) + + " repeat() + call assert_equal([0, 1, 2, 0, 1, 2], repeat(range(3), 2)) + call assert_equal([0, 1, 2], repeat(range(3), 1)) + call assert_equal([], repeat(range(3), 0)) + call assert_equal([], repeat(range(5, 4), 2)) + call assert_equal([], repeat(range(5, 4), 0)) + + " reverse() + call assert_equal([2, 1, 0], reverse(range(3))) + call assert_equal([0, 1, 2, 3], reverse(range(3, 0, -1))) + call assert_equal([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], reverse(range(10))) + call assert_equal([20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], reverse(range(10, 20))) + call assert_equal([16, 13, 10], reverse(range(10, 18, 3))) + call assert_equal([19, 16, 13, 10], reverse(range(10, 19, 3))) + call assert_equal([19, 16, 13, 10], reverse(range(10, 20, 3))) + call assert_equal([11, 14, 17, 20], reverse(range(20, 10, -3))) + call assert_equal([], reverse(range(0))) + + " TODO: setpos() + " new + " call setline(1, repeat([''], bufnr(''))) + " call setline(bufnr('') + 1, repeat('x', bufnr('') * 2 + 6)) + " call setpos('x', range(bufnr(''), bufnr('') + 3)) + " bwipe! + + " setreg() + call setreg('a', range(3)) + call assert_equal("0\n1\n2\n", getreg('a')) + + " settagstack() + call settagstack(1, #{items : range(4)}) + + " sign_define() + call assert_fails("call sign_define(range(5))", "E715:") + call assert_fails("call sign_placelist(range(5))", "E715:") + + " sign_undefine() + " call assert_fails("call sign_undefine(range(5))", "E908:") + call assert_fails("call sign_undefine(range(5))", "E155:") + + " sign_unplacelist() + call assert_fails("call sign_unplacelist(range(5))", "E715:") + + " sort() + call assert_equal([0, 1, 2, 3, 4, 5], sort(range(5, 0, -1))) + + " string() + call assert_equal('[0, 1, 2, 3, 4]', string(range(5))) + + " taglist() with 'tagfunc' + func TagFunc(pattern, flags, info) + return range(10) + endfunc + set tagfunc=TagFunc + call assert_fails("call taglist('asdf')", 'E987:') + set tagfunc= + + " term_start() + if has('terminal') && has('termguicolors') + call assert_fails('call term_start(range(3, 4))', 'E474:') + let g:terminal_ansi_colors = range(16) + if has('win32') + let cmd = "cmd /c dir" + else + let cmd = "ls" + endif + call assert_fails('call term_start("' .. cmd .. '", #{term_finish: "close"})', 'E475:') + unlet g:terminal_ansi_colors + endif + + " type() + call assert_equal(v:t_list, type(range(5))) + + " uniq() + call assert_equal([0, 1, 2, 3, 4], uniq(range(5))) + + " errors + call assert_fails('let x=range(2, 8, 0)', 'E726:') + call assert_fails('let x=range(3, 1)', 'E727:') + call assert_fails('let x=range(1, 3, -2)', 'E727:') + call assert_fails('let x=range([])', 'E745:') + call assert_fails('let x=range(1, [])', 'E745:') + call assert_fails('let x=range(1, 4, [])', 'E745:') +endfunc + +func Test_garbagecollect_now_fails() + let v:testing = 0 + call assert_fails('call test_garbagecollect_now()', 'E1142:') + let v:testing = 1 +endfunc + +" Test for echo highlighting +func Test_echohl() + echohl Search + echo 'Vim' + call assert_equal('Vim', Screenline(&lines)) + " TODO: How to check the highlight group used by echohl? + " ScreenAttrs() returns all zeros. + echohl None +endfunc + +" Test for the eval() function +func Test_eval() + call assert_fails("call eval('5 a')", 'E488:') +endfunc + +" Test for the keytrans() function +func Test_keytrans() + call assert_equal('<Space>', keytrans(' ')) + call assert_equal('<lt>', keytrans('<')) + call assert_equal('<lt>Tab>', keytrans('<Tab>')) + call assert_equal('<Tab>', keytrans("\<Tab>")) + call assert_equal('<C-V>', keytrans("\<C-V>")) + call assert_equal('<BS>', keytrans("\<BS>")) + call assert_equal('<Home>', keytrans("\<Home>")) + call assert_equal('<C-Home>', keytrans("\<C-Home>")) + call assert_equal('<M-Home>', keytrans("\<M-Home>")) + call assert_equal('<C-Space>', keytrans("\<C-Space>")) + call assert_equal('<M-Space>', keytrans("\<*M-Space>")) + call assert_equal('<M-x>', "\<*M-x>"->keytrans()) + call assert_equal('<C-I>', "\<*C-I>"->keytrans()) + call assert_equal('<S-3>', "\<*S-3>"->keytrans()) + call assert_equal('π', 'π'->keytrans()) + call assert_equal('<M-π>', "\<M-π>"->keytrans()) + call assert_equal('ě', 'ě'->keytrans()) + call assert_equal('<M-ě>', "\<M-ě>"->keytrans()) + call assert_equal('', ''->keytrans()) + call assert_equal('', v:_null_string->keytrans()) + call assert_fails('call keytrans(1)', 'E1174:') + call assert_fails('call keytrans()', 'E119:') +endfunc + +" Test for the nr2char() function +func Test_nr2char() + " set encoding=latin1 + call assert_equal('@', nr2char(64)) + set encoding=utf8 + call assert_equal('a', nr2char(97, 1)) + call assert_equal('a', nr2char(97, 0)) + + call assert_equal("\x80\xfc\b" .. nr2char(0x100000), eval('"\<M-' .. nr2char(0x100000) .. '>"')) + call assert_equal("\x80\xfc\b" .. nr2char(0x40000000), eval('"\<M-' .. nr2char(0x40000000) .. '>"')) +endfunc + +" Test for screenattr(), screenchar() and screenchars() functions +func Test_screen_functions() + call assert_equal(-1, screenattr(-1, -1)) + call assert_equal(-1, screenchar(-1, -1)) + call assert_equal([], screenchars(-1, -1)) + + " Run this in a separate Vim instance to avoid messing up. + let after =<< trim [CODE] + scriptencoding utf-8 + call setline(1, '口') + redraw + call assert_equal(0, screenattr(1, 1)) + call assert_equal(char2nr('口'), screenchar(1, 1)) + call assert_equal([char2nr('口')], screenchars(1, 1)) + call assert_equal('口', screenstring(1, 1)) + call writefile(v:errors, 'Xresult') + qall! + [CODE] + + let encodings = ['utf-8', 'cp932', 'cp936', 'cp949', 'cp950'] + if !has('win32') + let encodings += ['euc-jp'] + endif + if has('nvim') + let encodings = ['utf-8'] + endif + for enc in encodings + let msg = 'enc=' .. enc + if RunVim([], after, $'--clean --cmd "set encoding={enc}"') + call assert_equal([], readfile('Xresult'), msg) + endif + call delete('Xresult') + endfor +endfunc + +" Test for getcurpos() and setpos() +func Test_getcurpos_setpos() + new + call setline(1, ['012345678', '012345678']) + normal gg6l + let sp = getcurpos() + normal 0 + call setpos('.', sp) + normal jyl + call assert_equal('6', @") + call assert_equal(-1, setpos('.', v:_null_list)) + call assert_equal(-1, setpos('.', {})) + + let winid = win_getid() + normal G$ + let pos = getcurpos() + wincmd w + call assert_equal(pos, getcurpos(winid)) + + wincmd w + close! + + call assert_equal(getcurpos(), getcurpos(0)) + call assert_equal([0, 0, 0, 0, 0], getcurpos(-1)) + call assert_equal([0, 0, 0, 0, 0], getcurpos(1999)) +endfunc + +func Test_getmousepos() + enew! + call setline(1, "\t\t\t1234") + call Ntest_setmouse(1, 1) + call assert_equal(#{ + \ screenrow: 1, + \ screencol: 1, + \ winid: win_getid(), + \ winrow: 1, + \ wincol: 1, + \ line: 1, + \ column: 1, + \ coladd: 0, + \ }, getmousepos()) + call Ntest_setmouse(1, 2) + call assert_equal(#{ + \ screenrow: 1, + \ screencol: 2, + \ winid: win_getid(), + \ winrow: 1, + \ wincol: 2, + \ line: 1, + \ column: 1, + \ coladd: 1, + \ }, getmousepos()) + call Ntest_setmouse(1, 8) + call assert_equal(#{ + \ screenrow: 1, + \ screencol: 8, + \ winid: win_getid(), + \ winrow: 1, + \ wincol: 8, + \ line: 1, + \ column: 1, + \ coladd: 7, + \ }, getmousepos()) + call Ntest_setmouse(1, 9) + call assert_equal(#{ + \ screenrow: 1, + \ screencol: 9, + \ winid: win_getid(), + \ winrow: 1, + \ wincol: 9, + \ line: 1, + \ column: 2, + \ coladd: 0, + \ }, getmousepos()) + call Ntest_setmouse(1, 12) + call assert_equal(#{ + \ screenrow: 1, + \ screencol: 12, + \ winid: win_getid(), + \ winrow: 1, + \ wincol: 12, + \ line: 1, + \ column: 2, + \ coladd: 3, + \ }, getmousepos()) + call Ntest_setmouse(1, 25) + call assert_equal(#{ + \ screenrow: 1, + \ screencol: 25, + \ winid: win_getid(), + \ winrow: 1, + \ wincol: 25, + \ line: 1, + \ column: 4, + \ coladd: 0, + \ }, getmousepos()) + call Ntest_setmouse(1, 28) + call assert_equal(#{ + \ screenrow: 1, + \ screencol: 28, + \ winid: win_getid(), + \ winrow: 1, + \ wincol: 28, + \ line: 1, + \ column: 7, + \ coladd: 0, + \ }, getmousepos()) + call Ntest_setmouse(1, 29) + call assert_equal(#{ + \ screenrow: 1, + \ screencol: 29, + \ winid: win_getid(), + \ winrow: 1, + \ wincol: 29, + \ line: 1, + \ column: 8, + \ coladd: 0, + \ }, getmousepos()) + call Ntest_setmouse(1, 50) + call assert_equal(#{ + \ screenrow: 1, + \ screencol: 50, + \ winid: win_getid(), + \ winrow: 1, + \ wincol: 50, + \ line: 1, + \ column: 8, + \ coladd: 21, + \ }, getmousepos()) + + " If the mouse is positioned past the last buffer line, "line" and "column" + " should act like it's positioned on the last buffer line. + call Ntest_setmouse(2, 25) + call assert_equal(#{ + \ screenrow: 2, + \ screencol: 25, + \ winid: win_getid(), + \ winrow: 2, + \ wincol: 25, + \ line: 1, + \ column: 4, + \ coladd: 0, + \ }, getmousepos()) + call Ntest_setmouse(2, 50) + call assert_equal(#{ + \ screenrow: 2, + \ screencol: 50, + \ winid: win_getid(), + \ winrow: 2, + \ wincol: 50, + \ line: 1, + \ column: 8, + \ coladd: 21, + \ }, getmousepos()) + bwipe! +endfunc + +" Test for glob() +func Test_glob() + call assert_equal('', glob(v:_null_string)) + call assert_equal('', globpath(v:_null_string, v:_null_string)) + call assert_fails("let x = globpath(&rtp, 'syntax/c.vim', [])", 'E745:') + + call writefile([], 'Xglob1') + call writefile([], 'XGLOB2') + set wildignorecase + " Sort output of glob() otherwise we end up with different + " ordering depending on whether file system is case-sensitive. + call assert_equal(['XGLOB2', 'Xglob1'], sort(glob('Xglob[12]', 0, 1))) + " wildignorecase shall be applied even when the pattern contains no wildcards. + call assert_equal('XGLOB2', glob('xglob2')) + set wildignorecase& + + call delete('Xglob1') + call delete('XGLOB2') + + call assert_fails("call glob('*', 0, {})", 'E728:') +endfunc + +" Test for browse() +func Test_browse() + CheckFeature browse + call assert_fails('call browse([], "open", "x", "a.c")', 'E745:') +endfunc + +" Test for browsedir() +func Test_browsedir() + CheckFeature browse + call assert_fails('call browsedir("open", [])', 'E730:') +endfunc + +func HasDefault(msg = 'msg') + return a:msg +endfunc + +func Test_default_arg_value() + call assert_equal('msg', HasDefault()) +endfunc + +" Test for gettext() +func Test_gettext() + call assert_fails('call gettext(1)', 'E1174:') +endfunc + +func Test_builtin_check() + call assert_fails('let g:["trim"] = {x -> " " .. x}', 'E704:') + call assert_fails('let g:.trim = {x -> " " .. x}', 'E704:') + call assert_fails('let l:["trim"] = {x -> " " .. x}', 'E704:') + call assert_fails('let l:.trim = {x -> " " .. x}', 'E704:') + let lines =<< trim END + vim9script + var trim = (x) => " " .. x + END + call CheckScriptFailure(lines, 'E704:') + + call assert_fails('call extend(g:, #{foo: { -> "foo" }})', 'E704:') + let g:bar = 123 + call extend(g:, #{bar: { -> "foo" }}, "keep") + call assert_fails('call extend(g:, #{bar: { -> "foo" }}, "force")', 'E704:') + unlet g:bar + + call assert_fails('call extend(l:, #{foo: { -> "foo" }})', 'E704:') + let bar = 123 + call extend(l:, #{bar: { -> "foo" }}, "keep") + call assert_fails('call extend(l:, #{bar: { -> "foo" }}, "force")', 'E704:') + unlet bar + + call assert_fails('call extend(g:, #{foo: function("extend")})', 'E704:') + let g:bar = 123 + call extend(g:, #{bar: function("extend")}, "keep") + call assert_fails('call extend(g:, #{bar: function("extend")}, "force")', 'E704:') + unlet g:bar + + call assert_fails('call extend(l:, #{foo: function("extend")})', 'E704:') + let bar = 123 + call extend(l:, #{bar: function("extend")}, "keep") + call assert_fails('call extend(l:, #{bar: function("extend")}, "force")', 'E704:') + unlet bar +endfunc + + +" Test for virtcol() +func Test_virtcol() + new + call setline(1, "the\tquick\tbrown\tfox") + norm! 4| + call assert_equal(8, virtcol('.')) + call assert_equal(8, virtcol('.', v:false)) + call assert_equal([4, 8], virtcol('.', v:true)) + + let w = winwidth(0) + call setline(2, repeat('a', w + 2)) + let win_nosbr = win_getid() + split + setlocal showbreak=!! + let win_sbr = win_getid() + call assert_equal([w, w], virtcol([2, w], v:true, win_nosbr)) + call assert_equal([w + 1, w + 1], virtcol([2, w + 1], v:true, win_nosbr)) + call assert_equal([w + 2, w + 2], virtcol([2, w + 2], v:true, win_nosbr)) + call assert_equal([w, w], virtcol([2, w], v:true, win_sbr)) + call assert_equal([w + 3, w + 3], virtcol([2, w + 1], v:true, win_sbr)) + call assert_equal([w + 4, w + 4], virtcol([2, w + 2], v:true, win_sbr)) + close + + call assert_equal(0, virtcol('')) + call assert_equal([0, 0], virtcol('', v:true)) + call assert_equal(0, virtcol('.', v:false, 5001)) + call assert_equal([0, 0], virtcol('.', v:true, 5001)) + + bwipe! +endfunc + +func Test_delfunc_while_listing() + CheckRunVimInTerminal + + let lines =<< trim END + set nocompatible + for i in range(1, 999) + exe 'func ' .. 'MyFunc' .. i .. '()' + endfunc + endfor + au CmdlineLeave : call timer_start(0, {-> execute('delfunc MyFunc622')}) + END + call writefile(lines, 'Xfunctionclear', 'D') + let buf = RunVimInTerminal('-S Xfunctionclear', {'rows': 12}) + + " This was using freed memory. The height of the terminal must be so that + " the next function to be listed with "j" is the one that is deleted in the + " timer callback, tricky! + call term_sendkeys(buf, ":func /MyFunc\<CR>") + call TermWait(buf, 50) + call term_sendkeys(buf, "j") + call TermWait(buf, 50) + call term_sendkeys(buf, "\<CR>") + + call StopVimInTerminal(buf) +endfunc + +" Test for the reverse() function with a string +func Test_string_reverse() + let lines =<< trim END + call assert_equal('', reverse(v:_null_string)) + for [s1, s2] in [['', ''], ['a', 'a'], ['ab', 'ba'], ['abc', 'cba'], + \ ['abcd', 'dcba'], ['«-«-»-»', '»-»-«-«'], + \ ['🇦', '🇦'], ['🇦🇧', '🇧🇦'], ['🇦🇧🇨', '🇨🇧🇦'], + \ ['🇦«🇧-🇨»🇩', '🇩»🇨-🇧«🇦']] + call assert_equal(s2, reverse(s1)) + endfor + END + call CheckLegacyAndVim9Success(lines) + + " test in latin1 encoding + let save_enc = &encoding + " set encoding=latin1 + call assert_equal('dcba', reverse('abcd')) + let &encoding = save_enc +endfunc + +func Test_fullcommand() + " this used to crash vim + call assert_equal('', fullcommand(10)) +endfunc + +" Test for glob() with shell special patterns +func Test_glob_extended_bash() + CheckExecutable bash + CheckNotMSWindows + CheckNotMac " The default version of bash is old on macOS. + + let _shell = &shell + set shell=bash + + call mkdir('Xtestglob/foo/bar/src', 'p') + call writefile([], 'Xtestglob/foo/bar/src/foo.sh') + call writefile([], 'Xtestglob/foo/bar/src/foo.h') + call writefile([], 'Xtestglob/foo/bar/src/foo.cpp') + + " Sort output of glob() otherwise we end up with different + " ordering depending on whether file system is case-sensitive. + let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h'] + call assert_equal(expected, sort(glob('Xtestglob/**/foo.{h,cpp}', 0, 1))) + call delete('Xtestglob', 'rf') + let &shell=_shell +endfunc + +" Test for glob() with extended patterns (MS-Windows) +" Vim doesn't use 'shell' to expand wildcards on MS-Windows. +" Unlike bash, it doesn't support {,} expansion. +func Test_glob_extended_mswin() + CheckMSWindows + + call mkdir('Xtestglob/foo/bar/src', 'p') + call writefile([], 'Xtestglob/foo/bar/src/foo.sh') + call writefile([], 'Xtestglob/foo/bar/src/foo.h') + call writefile([], 'Xtestglob/foo/bar/src/foo.cpp') + + " Sort output of glob() otherwise we end up with different + " ordering depending on whether file system is case-sensitive. + let expected = ['Xtestglob/foo/bar/src/foo.cpp', 'Xtestglob/foo/bar/src/foo.h', 'Xtestglob/foo/bar/src/foo.sh'] + call assert_equal(expected, sort(glob('Xtestglob/**/foo.*', 0, 1))) + call delete('Xtestglob', 'rf') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_ga.vim b/test/old/testdir/test_ga.vim new file mode 100644 index 0000000000..ce31edfc7a --- /dev/null +++ b/test/old/testdir/test_ga.vim @@ -0,0 +1,43 @@ +" Test ga normal command, and :ascii Ex command. +func Do_ga(c) + call setline(1, a:c) + let l:a = execute("norm 1goga") + let l:b = execute("ascii") + call assert_equal(l:a, l:b) + return l:a +endfunc + +func Test_ga_command() + new + set display=uhex + call assert_equal("\nNUL", Do_ga('')) + call assert_equal("\n<<01>> 1, Hex 01, Oct 001, Digr SH", Do_ga("\x01")) + call assert_equal("\n<<09>> 9, Hex 09, Oct 011, Digr HT", Do_ga("\t")) + + set display= + call assert_equal("\nNUL", Do_ga('')) + call assert_equal("\n<^A> 1, Hex 01, Oct 001, Digr SH", Do_ga("\x01")) + call assert_equal("\n<^I> 9, Hex 09, Oct 011, Digr HT", Do_ga("\t")) + call assert_equal("\n<^@> 0, Hex 00, Octal 000", Do_ga("\n")) + + call assert_equal("\n<e> 101, Hex 65, Octal 145", Do_ga('e')) + + " Test a few multi-bytes characters. + call assert_equal("\n<é> 233, Hex 00e9, Oct 351, Digr e'", Do_ga('é')) + call assert_equal("\n<ẻ> 7867, Hex 1ebb, Oct 17273, Digr e2", Do_ga('ẻ')) + call assert_equal("\n<\U00012345> 74565, Hex 00012345, Octal 221505", Do_ga("\U00012345")) + + " Test with combining characters. + call assert_equal("\n<e> 101, Hex 65, Octal 145 < ́> 769, Hex 0301, Octal 1401", Do_ga("e\u0301")) + call assert_equal("\n<e> 101, Hex 65, Octal 145 < ́> 769, Hex 0301, Octal 1401 < ̱> 817, Hex 0331, Octal 1461", Do_ga("e\u0301\u0331")) + call assert_equal("\n<e> 101, Hex 65, Octal 145 < ́> 769, Hex 0301, Octal 1401 < ̱> 817, Hex 0331, Octal 1461 < ̸> 824, Hex 0338, Octal 1470", Do_ga("e\u0301\u0331\u0338")) + + " When using Mac fileformat, CR instead of NL is used for line termination + enew! + set fileformat=mac + call assert_equal("\n<^J> 10, Hex 0a, Oct 012, Digr NU", Do_ga("\r")) + + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_getcwd.vim b/test/old/testdir/test_getcwd.vim new file mode 100644 index 0000000000..073f8303dc --- /dev/null +++ b/test/old/testdir/test_getcwd.vim @@ -0,0 +1,112 @@ +func GetCwdInfo(win, tab) + let tab_changed = 0 + let mod = ":t" + if a:tab > 0 && a:tab != tabpagenr() + let tab_changed = 1 + exec "tabnext " . a:tab + endif + let bufname = fnamemodify(bufname(winbufnr(a:win)), mod) + if tab_changed + tabprevious + endif + if a:win == 0 && a:tab == 0 + let dirname = fnamemodify(getcwd(), mod) + let lflag = haslocaldir() + elseif a:tab == 0 + let dirname = fnamemodify(getcwd(a:win), mod) + let lflag = haslocaldir(a:win) + else + let dirname = fnamemodify(getcwd(a:win, a:tab), mod) + let lflag = a:win->haslocaldir(a:tab) + endif + return bufname . ' ' . dirname . ' ' . lflag +endfunc + +" Do all test in a separate window to avoid E211 when we recursively +" delete the Xtopdir directory during cleanup +func SetUp() + set visualbell + set nocp viminfo+=nviminfo + + " On windows a swapfile in Xtopdir prevents it from being cleaned up. + set noswapfile + + " On windows a stale "Xtopdir" directory may exist, remove it so that + " we start from a clean state. + call delete("Xtopdir", "rf") + new + eval 'Xtopdir'->mkdir() + cd Xtopdir + let g:topdir = getcwd() + call mkdir('Xdir1') + call mkdir('Xdir2') + call mkdir('Xdir3') +endfunction + +let g:cwd=getcwd() +function TearDown() + q + call chdir(g:cwd) + call delete("Xtopdir", "rf") +endfunction + +function Test_GetCwd() + new a + new b + new c + 3wincmd w + lcd Xdir1 + call assert_equal("a Xdir1 1", GetCwdInfo(0, 0)) + call assert_equal(g:topdir, getcwd(-1)) + wincmd W + call assert_equal("b Xtopdir 0", GetCwdInfo(0, 0)) + call assert_equal(g:topdir, getcwd(-1)) + wincmd W + lcd Xdir3 + call assert_equal("c Xdir3 1", GetCwdInfo(0, 0)) + call assert_equal("a Xdir1 1", GetCwdInfo(bufwinnr("a"), 0)) + call assert_equal("b Xtopdir 0", GetCwdInfo(bufwinnr("b"), 0)) + call assert_equal("c Xdir3 1", GetCwdInfo(bufwinnr("c"), 0)) + call assert_equal(g:topdir, getcwd(-1)) + wincmd W + call assert_equal("a Xdir1 1", GetCwdInfo(bufwinnr("a"), tabpagenr())) + call assert_equal("b Xtopdir 0", GetCwdInfo(bufwinnr("b"), tabpagenr())) + call assert_equal("c Xdir3 1", GetCwdInfo(bufwinnr("c"), tabpagenr())) + call assert_equal(g:topdir, getcwd(-1)) + + tabnew x + new y + new z + 3wincmd w + call assert_equal("x Xtopdir 0", GetCwdInfo(0, 0)) + call assert_equal(g:topdir, getcwd(-1)) + wincmd W + lcd Xdir2 + call assert_equal("y Xdir2 1", GetCwdInfo(0, 0)) + call assert_equal(g:topdir, getcwd(-1)) + wincmd W + lcd Xdir3 + call assert_equal("z Xdir3 1", GetCwdInfo(0, 0)) + call assert_equal("x Xtopdir 0", GetCwdInfo(bufwinnr("x"), 0)) + call assert_equal("y Xdir2 1", GetCwdInfo(bufwinnr("y"), 0)) + call assert_equal("z Xdir3 1", GetCwdInfo(bufwinnr("z"), 0)) + call assert_equal(g:topdir, getcwd(-1)) + let tp_nr = tabpagenr() + tabrewind + call assert_equal("x Xtopdir 0", GetCwdInfo(3, tp_nr)) + call assert_equal("y Xdir2 1", GetCwdInfo(2, tp_nr)) + call assert_equal("z Xdir3 1", GetCwdInfo(1, tp_nr)) + call assert_equal(g:topdir, getcwd(-1)) +endfunc + +function Test_GetCwd_lcd_shellslash() + new + let root = fnamemodify('/', ':p') + exe 'lcd '.root + let cwd = getcwd() + if !exists('+shellslash') || &shellslash + call assert_equal(cwd[-1:], '/') + else + call assert_equal(cwd[-1:], '\') + endif +endfunc diff --git a/test/old/testdir/test_getvar.vim b/test/old/testdir/test_getvar.vim new file mode 100644 index 0000000000..331f3cfe8a --- /dev/null +++ b/test/old/testdir/test_getvar.vim @@ -0,0 +1,161 @@ +" Tests for getwinvar(), gettabvar(), gettabwinvar() and get(). + +func Test_var() + " Use strings to test for memory leaks. First, check that in an empty + " window, gettabvar() returns the correct value + let t:testvar='abcd' + call assert_equal('abcd', gettabvar(1, 'testvar')) + call assert_equal('abcd', gettabvar(1, 'testvar')) + + " test for getwinvar() + let w:var_str = "Dance" + let def_str = "Chance" + call assert_equal('Dance', getwinvar(1, 'var_str')) + call assert_equal('Dance', getwinvar(1, 'var_str', def_str)) + call assert_equal({'var_str': 'Dance'}, 1->getwinvar('')) + call assert_equal({'var_str': 'Dance'}, 1->getwinvar('', def_str)) + unlet w:var_str + call assert_equal('Chance', getwinvar(1, 'var_str', def_str)) + call assert_equal({}, getwinvar(1, '')) + call assert_equal({}, getwinvar(1, '', def_str)) + call assert_equal('', getwinvar(9, '')) + call assert_equal('Chance', getwinvar(9, '', def_str)) + call assert_equal(0, getwinvar(1, '&nu')) + call assert_equal(0, getwinvar(1, '&nu', 1)) + unlet def_str + + " test for gettabvar() + tabnew + tabnew + let t:var_list = [1, 2, 3] + let t:other = 777 + let def_list = [4, 5, 6, 7] + tabrewind + call assert_equal([1, 2, 3], 3->gettabvar('var_list')) + call assert_equal([1, 2, 3], gettabvar(3, 'var_list', def_list)) + call assert_equal({'var_list': [1, 2, 3], 'other': 777}, gettabvar(3, '')) + call assert_equal({'var_list': [1, 2, 3], 'other': 777}, + \ gettabvar(3, '', def_list)) + + tablast + unlet t:var_list + tabrewind + call assert_equal([4, 5, 6, 7], gettabvar(3, 'var_list', def_list)) + call assert_equal('', gettabvar(9, '')) + call assert_equal([4, 5, 6, 7], gettabvar(9, '', def_list)) + call assert_equal('', gettabvar(3, '&nu')) + call assert_equal([4, 5, 6, 7], gettabvar(3, '&nu', def_list)) + unlet def_list + tabonly + + " test for gettabwinvar() + tabnew + tabnew + tabprev + split + split + wincmd w + vert split + wincmd w + let w:var_dict = {'dict': 'tabwin'} + let def_dict = {'dict2': 'newval'} + wincmd b + tabrewind + call assert_equal({'dict': 'tabwin'}, 2->gettabwinvar(3, 'var_dict')) + call assert_equal({'dict': 'tabwin'}, + \ gettabwinvar(2, 3, 'var_dict', def_dict)) + call assert_equal({'var_dict': {'dict': 'tabwin'}}, gettabwinvar(2, 3, '')) + call assert_equal({'var_dict': {'dict': 'tabwin'}}, + \ gettabwinvar(2, 3, '', def_dict)) + + tabnext + 3wincmd w + unlet w:var_dict + tabrewind + call assert_equal({'dict2': 'newval'}, + \ gettabwinvar(2, 3, 'var_dict', def_dict)) + call assert_equal({}, gettabwinvar(2, 3, '')) + call assert_equal({}, gettabwinvar(2, 3, '', def_dict)) + call assert_equal("", gettabwinvar(2, 9, '')) + call assert_equal({'dict2': 'newval'}, gettabwinvar(2, 9, '', def_dict)) + call assert_equal('', gettabwinvar(9, 3, '')) + call assert_equal({'dict2': 'newval'}, gettabwinvar(9, 3, '', def_dict)) + + unlet def_dict + + call assert_equal('', gettabwinvar(2, 3, '&nux')) + call assert_equal(1, gettabwinvar(2, 3, '&nux', 1)) + tabonly +endfunc + +" It was discovered that "gettabvar()" would fail if called from within the +" tabline when the user closed a window. This test confirms the fix. +func Test_gettabvar_in_tabline() + let t:var_str = 'value' + + set tabline=%{assert_equal('value',gettabvar(1,'var_str'))} + set showtabline=2 + + " Simulate the user opening a split (which becomes window #1) and then + " closing the split, which triggers the redrawing of the tabline. + leftabove split + redrawstatus! + close + redrawstatus! +endfunc + +" Test get() function using default value. + +" get({dict}, {key} [, {default}]) +func Test_get_dict() + let d = {'foo': 42} + call assert_equal(42, get(d, 'foo', 99)) + call assert_equal(999, get(d, 'bar', 999)) +endfunc + +" get({list}, {idx} [, {default}]) +func Test_get_list() + let l = [1,2,3] + call assert_equal(1, get(l, 0, 999)) + call assert_equal(3, get(l, -1, 999)) + call assert_equal(999, get(l, 3, 999)) +endfunc + +" get({blob}, {idx} [, {default}]) - in test_blob.vim + +" get({lambda}, {what} [, {default}]) +func Test_get_lambda() + let l:L = {-> 42} + call assert_match('^<lambda>', get(l:L, 'name')) + call assert_equal(l:L, get(l:L, 'func')) + call assert_equal({'lambda has': 'no dict'}, get(l:L, 'dict', {'lambda has': 'no dict'})) + call assert_equal(0, get(l:L, 'dict')) + call assert_equal([], get(l:L, 'args')) +endfunc + +func s:FooBar() +endfunc + +" get({func}, {what} [, {default}]) +func Test_get_func() + let l:F = function('tr') + call assert_equal('tr', get(l:F, 'name')) + call assert_equal(l:F, get(l:F, 'func')) + + let Fb_func = function('s:FooBar') + call assert_match('<SNR>\d\+_FooBar', get(Fb_func, 'name')) + let Fb_ref = funcref('s:FooBar') + call assert_match('<SNR>\d\+_FooBar', get(Fb_ref, 'name')) + + call assert_equal({'func has': 'no dict'}, get(l:F, 'dict', {'func has': 'no dict'})) + call assert_equal(0, get(l:F, 'dict')) + call assert_equal([], get(l:F, 'args')) + " Nvim doesn't have null functions + " let NF = test_null_function() + " call assert_equal('', get(NF, 'name')) + " call assert_equal(NF, get(NF, 'func')) + " call assert_equal(0, get(NF, 'dict')) + " call assert_equal([], get(NF, 'args')) +endfunc + +" get({partial}, {what} [, {default}]) - in test_partial.vim diff --git a/test/old/testdir/test_gf.vim b/test/old/testdir/test_gf.vim new file mode 100644 index 0000000000..9824c8276e --- /dev/null +++ b/test/old/testdir/test_gf.vim @@ -0,0 +1,364 @@ +" Test for the gf and gF (goto file) commands + +" This is a test if a URL is recognized by "gf", with the cursor before and +" after the "://". Also test ":\\". +func Test_gf_url() + enew! + call append(0, [ + \ "first test for URL://machine.name/tmp/vimtest2a and other text", + \ "second test for URL://machine.name/tmp/vimtest2b. And other text", + \ "third test for URL:\\\\machine.name\\vimtest2c and other text", + \ "fourth test for URL:\\\\machine.name\\tmp\\vimtest2d, and other text", + \ "fifth test for URL://machine.name/tmp?q=vim&opt=yes and other text", + \ "sixth test for URL://machine.name:1234?q=vim and other text", + \ ]) + call cursor(1,1) + call search("^first") + call search("tmp") + call assert_equal("URL://machine.name/tmp/vimtest2a", expand("<cfile>")) + call search("^second") + call search("URL") + call assert_equal("URL://machine.name/tmp/vimtest2b", expand("<cfile>")) + set isf=@,48-57,/,.,-,_,+,,,$,~,\ + call search("^third") + call search("name") + call assert_equal("URL:\\\\machine.name\\vimtest2c", expand("<cfile>")) + call search("^fourth") + call search("URL") + call assert_equal("URL:\\\\machine.name\\tmp\\vimtest2d", expand("<cfile>")) + + call search("^fifth") + call search("URL") + call assert_equal("URL://machine.name/tmp?q=vim&opt=yes", expand("<cfile>")) + + call search("^sixth") + call search("URL") + call assert_equal("URL://machine.name:1234?q=vim", expand("<cfile>")) + + %d + call setline(1, "demo://remote_file") + wincmd f + call assert_equal('demo://remote_file', @%) + call assert_equal(2, winnr('$')) + close! + + set isf&vim + enew! +endfunc + +func Test_gF() + new + call setline(1, ['111', '222', '333', '444']) + w! Xfile + close + new + set isfname-=: + call setline(1, ['one', 'Xfile:3', 'three']) + 2 + call assert_fails('normal gF', 'E37:') + call assert_equal(2, getcurpos()[1]) + w! Xfile2 + normal gF + call assert_equal('Xfile', bufname('%')) + call assert_equal(3, getcurpos()[1]) + + enew! + call setline(1, ['one', 'the Xfile line 2, and more', 'three']) + w! Xfile2 + normal 2GfX + normal gF + call assert_equal('Xfile', bufname('%')) + call assert_equal(2, getcurpos()[1]) + + " jumping to the file/line with CTRL-W_F + %bw! + edit Xfile1 + call setline(1, ['one', 'Xfile:4', 'three']) + exe "normal 2G\<C-W>F" + call assert_equal('Xfile', bufname('%')) + call assert_equal(4, getcurpos()[1]) + + set isfname& + call delete('Xfile') + call delete('Xfile2') + %bw! +endfunc + +" Test for invoking 'gf' on a ${VAR} variable +func Test_gf() + set isfname=@,48-57,/,.,-,_,+,,,$,:,~,{,} + + call writefile(["Test for gf command"], "Xtest1") + if has("unix") + call writefile([" ${CDIR}/Xtest1"], "Xtestgf") + else + call writefile([" $TDIR/Xtest1"], "Xtestgf") + endif + new Xtestgf + if has("unix") + let $CDIR = "." + /CDIR + else + if has("amiga") + let $TDIR = "/testdir" + else + let $TDIR = "." + endif + /TDIR + endif + + normal gf + call assert_equal('Xtest1', fnamemodify(bufname(''), ":t")) + close! + + call delete('Xtest1') + call delete('Xtestgf') +endfunc + +func Test_gf_visual() + call writefile(['one', 'two', 'three', 'four'], "Xtest_gf_visual") + new + call setline(1, 'XXXtest_gf_visualXXX') + set hidden + + " Visually select Xtest_gf_visual and use gf to go to that file + norm! ttvtXgf + call assert_equal('Xtest_gf_visual', bufname('%')) + + " if multiple lines are selected, then gf should fail + call setline(1, ["one", "two"]) + normal VGgf + call assert_equal('Xtest_gf_visual', @%) + + " following line number is used for gF + bwipe! + new + call setline(1, 'XXXtest_gf_visual:3XXX') + norm! 0ttvt:gF + call assert_equal('Xtest_gf_visual', bufname('%')) + call assert_equal(3, getcurpos()[1]) + + " do not include the NUL at the end + call writefile(['x'], 'X') + let save_enc = &enc + " for enc in ['latin1', 'utf-8'] + for enc in ['utf-8'] + exe "set enc=" .. enc + new + call setline(1, 'X') + set nomodified + exe "normal \<C-V>$gf" + call assert_equal('X', bufname()) + bwipe! + endfor + let &enc = save_enc + call delete('X') + + " line number in visual area is used for file name + if has('unix') + bwipe! + call writefile([], "Xtest_gf_visual:3") + new + call setline(1, 'XXXtest_gf_visual:3XXX') + norm! 0ttvtXgF + call assert_equal('Xtest_gf_visual:3', bufname('%')) + call delete('Xtest_gf_visual:3') + endif + + bwipe! + call delete('Xtest_gf_visual') + set hidden& +endfunc + +func Test_gf_error() + new + call assert_fails('normal gf', 'E446:') + call assert_fails('normal gF', 'E446:') + call setline(1, '/doesnotexist') + call assert_fails('normal gf', 'E447:') + call assert_fails('normal gF', 'E447:') + call assert_fails('normal [f', 'E447:') + + " gf is not allowed when text is locked + au InsertCharPre <buffer> normal! gF<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 + + bwipe! + + " gf is not allowed when buffer is locked + new + augroup Test_gf + au! + au OptionSet diff norm! gf + augroup END + call setline(1, ['Xfile1', 'line2', 'line3', 'line4']) + " Nvim does not support test_override() + " call test_override('starting', 1) + " call assert_fails('diffthis', 'E788:') + " call test_override('starting', 0) + augroup Test_gf + au! + augroup END + bw! +endfunc + +" If a file is not found by 'gf', then 'includeexpr' should be used to locate +" the file. +func Test_gf_includeexpr() + new + let g:Inc_fname = '' + func IncFunc() + let g:Inc_fname = v:fname + return v:fname + endfunc + setlocal includeexpr=IncFunc() + call setline(1, 'somefile.java') + call assert_fails('normal gf', 'E447:') + call assert_equal('somefile.java', g:Inc_fname) + close! + delfunc IncFunc +endfunc + +" Test for using a script-local function for 'includeexpr' +func Test_includeexpr_scriptlocal_func() + func! s:IncludeFunc() + let g:IncludeFname = v:fname + return '' + endfunc + set includeexpr=s:IncludeFunc() + call assert_equal(expand('<SID>') .. 'IncludeFunc()', &includeexpr) + call assert_equal(expand('<SID>') .. 'IncludeFunc()', &g:includeexpr) + new | only + call setline(1, 'TestFile1') + let g:IncludeFname = '' + call assert_fails('normal! gf', 'E447:') + call assert_equal('TestFile1', g:IncludeFname) + bw! + set includeexpr=<SID>IncludeFunc() + call assert_equal(expand('<SID>') .. 'IncludeFunc()', &includeexpr) + call assert_equal(expand('<SID>') .. 'IncludeFunc()', &g:includeexpr) + new | only + call setline(1, 'TestFile2') + let g:IncludeFname = '' + call assert_fails('normal! gf', 'E447:') + call assert_equal('TestFile2', g:IncludeFname) + bw! + setlocal includeexpr= + setglobal includeexpr=s:IncludeFunc() + call assert_equal(expand('<SID>') .. 'IncludeFunc()', &g:includeexpr) + call assert_equal('', &includeexpr) + new + call assert_equal(expand('<SID>') .. 'IncludeFunc()', &includeexpr) + call setline(1, 'TestFile3') + let g:IncludeFname = '' + call assert_fails('normal! gf', 'E447:') + call assert_equal('TestFile3', g:IncludeFname) + bw! + setlocal includeexpr= + setglobal includeexpr=<SID>IncludeFunc() + call assert_equal(expand('<SID>') .. 'IncludeFunc()', &g:includeexpr) + call assert_equal('', &includeexpr) + new + call assert_equal(expand('<SID>') .. 'IncludeFunc()', &includeexpr) + call setline(1, 'TestFile4') + let g:IncludeFname = '' + call assert_fails('normal! gf', 'E447:') + call assert_equal('TestFile4', g:IncludeFname) + bw! + set includeexpr& + delfunc s:IncludeFunc + bw! +endfunc + +" Check that expanding directories can handle more than 255 entries. +func Test_gf_subdirs_wildcard() + let cwd = getcwd() + let dir = 'Xtestgf_dir' + call mkdir(dir) + call chdir(dir) + for i in range(300) + call mkdir(i) + call writefile([], i .. '/' .. i, 'S') + endfor + set path=./** + + new | only + call setline(1, '99') + w! Xtest1 + normal gf + call assert_equal('99', fnamemodify(bufname(''), ":t")) + + call chdir(cwd) + call delete(dir, 'rf') + set path& +endfunc + +" Test for 'switchbuf' with gf and gF commands +func Test_gf_switchbuf() + call writefile(repeat(["aaa"], 10), "Xtest1", 'D') + edit Xtest1 + new + call setline(1, ['Xtest1']) + + " Test for 'useopen' + set switchbuf=useopen + call cursor(1, 1) + exe "normal \<C-W>f" + call assert_equal([2, 2], [winnr(), winnr('$')]) + close + + " If the file is opened in another tabpage, then it should not be considered + tabedit Xtest1 + tabfirst + exe "normal \<C-W>f" + call assert_equal([1, 2], [winnr(), winnr('$')]) + call assert_equal([1, 2], [tabpagenr(), tabpagenr('$')]) + close + + " Test for 'usetab' + set switchbuf=usetab + exe "normal \<C-W>f" + call assert_equal([1, 1], [winnr(), winnr('$')]) + call assert_equal([2, 2], [tabpagenr(), tabpagenr('$')]) + %bw! + + " Test for CTRL-W_F with 'useopen' + set isfname-=: + call setline(1, ['Xtest1:5']) + set switchbuf=useopen + split +1 Xtest1 + wincmd b + exe "normal \<C-W>F" + call assert_equal([1, 2], [winnr(), winnr('$')]) + call assert_equal(5, line('.')) + close + + " If the file is opened in another tabpage, then it should not be considered + tabedit +1 Xtest1 + tabfirst + exe "normal \<C-W>F" + call assert_equal([1, 2], [winnr(), winnr('$')]) + call assert_equal(5, line('.')) + call assert_equal([1, 2], [tabpagenr(), tabpagenr('$')]) + close + + " Test for CTRL_W_F with 'usetab' + set switchbuf=usetab + exe "normal \<C-W>F" + call assert_equal([2, 2], [tabpagenr(), tabpagenr('$')]) + call assert_equal([1, 1], [winnr(), winnr('$')]) + call assert_equal(5, line('.')) + + set switchbuf= + set isfname& + %bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_glob2regpat.vim b/test/old/testdir/test_glob2regpat.vim new file mode 100644 index 0000000000..b9c4c12059 --- /dev/null +++ b/test/old/testdir/test_glob2regpat.vim @@ -0,0 +1,35 @@ +" Test glob2regpat() + +source vim9.vim + +func Test_glob2regpat_invalid() + if has('float') + call assert_equal('^1\.33$', glob2regpat(1.33)) + call CheckDefExecAndScriptFailure(['echo glob2regpat(1.33)'], 'E806:') + endif + call assert_fails('call glob2regpat("}")', 'E219:') + call assert_fails('call glob2regpat("{")', 'E220:') +endfunc + +func Test_glob2regpat_valid() + call assert_equal('^foo\.', glob2regpat('foo.*')) + call assert_equal('^foo.$', 'foo?'->glob2regpat()) + call assert_equal('\.vim$', glob2regpat('*.vim')) + call assert_equal('^[abc]$', glob2regpat('[abc]')) + call assert_equal('^foo bar$', glob2regpat('foo\ bar')) + call assert_equal('^foo,bar$', glob2regpat('foo,bar')) + call assert_equal('^\(foo\|bar\)$', glob2regpat('{foo,bar}')) + call assert_equal('.*', glob2regpat('**')) + + if exists('+shellslash') + call assert_equal('^foo[\/].$', glob2regpat('foo\?')) + call assert_equal('^\(foo[\/]\|bar\|foobar\)$', glob2regpat('{foo\,bar,foobar}')) + call assert_equal('^[\/]\(foo\|bar[\/]\)$', glob2regpat('\{foo,bar\}')) + call assert_equal('^[\/][\/]\(foo\|bar[\/][\/]\)$', glob2regpat('\\{foo,bar\\}')) + else + call assert_equal('^foo?$', glob2regpat('foo\?')) + call assert_equal('^\(foo,bar\|foobar\)$', glob2regpat('{foo\,bar,foobar}')) + call assert_equal('^{foo,bar}$', glob2regpat('\{foo,bar\}')) + call assert_equal('^\\\(foo\|bar\\\)$', glob2regpat('\\{foo,bar\\}')) + endif +endfunc diff --git a/test/old/testdir/test_global.vim b/test/old/testdir/test_global.vim new file mode 100644 index 0000000000..44a8784348 --- /dev/null +++ b/test/old/testdir/test_global.vim @@ -0,0 +1,131 @@ +" Test for :global and :vglobal + +source check.vim +source term_util.vim + +func Test_yank_put_clipboard() + new + call setline(1, ['a', 'b', 'c']) + set clipboard=unnamed + g/^/normal yyp + call assert_equal(['a', 'a', 'b', 'b', 'c', 'c'], getline(1, 6)) + set clipboard=unnamed,unnamedplus + call setline(1, ['a', 'b', 'c']) + g/^/normal yyp + call assert_equal(['a', 'a', 'b', 'b', 'c', 'c'], getline(1, 6)) + set clipboard& + bwipe! +endfunc + +func Test_global_set_clipboard() + CheckFeature clipboard_working + new + set clipboard=unnamedplus + let @+='clipboard' | g/^/set cb= | let @" = 'unnamed' | put + call assert_equal(['','unnamed'], getline(1, '$')) + set clipboard& + bwipe! +endfunc + +func Test_nested_global() + new + call setline(1, ['nothing', 'found', 'found bad', 'bad']) + call assert_fails('g/found/3v/bad/s/^/++/', 'E147') + g/found/v/bad/s/^/++/ + call assert_equal(['nothing', '++found', 'found bad', 'bad'], getline(1, 4)) + bwipe! +endfunc + +func Test_global_error() + call assert_fails('g\\a', 'E10:') + call assert_fails('g', 'E148:') + call assert_fails('g/\(/y', 'E54:') +endfunc + +" Test for printing lines using :g with different search patterns +func Test_global_print() + new + call setline(1, ['foo', 'bar', 'foo', 'foo']) + let @/ = 'foo' + let t = execute("g/")->trim()->split("\n") + call assert_equal(['foo', 'foo', 'foo'], t) + + " Test for Vi compatible patterns + let @/ = 'bar' + let t = execute('g\/')->trim()->split("\n") + call assert_equal(['bar'], t) + + normal gg + s/foo/foo/ + let t = execute('g\&')->trim()->split("\n") + call assert_equal(['foo', 'foo', 'foo'], t) + + let @/ = 'bar' + let t = execute('g?')->trim()->split("\n") + call assert_equal(['bar'], t) + + " Test for the 'Pattern found in every line' message + let v:statusmsg = '' + v/foo\|bar/p + call assert_notequal('', v:statusmsg) + + close! +endfunc + +func Test_global_empty_pattern() + " populate history + silent g/hello/ + + redir @a + g// + redir END + + call assert_match('Pattern not found: hello', @a) + " ^~~~~ this was previously empty +endfunc + +" Test for global command with newline character +func Test_global_newline() + new + call setline(1, ['foo']) + exe "g/foo/s/f/h/\<NL>s/o$/w/" + call assert_equal('how', getline(1)) + call setline(1, ["foo\<NL>bar"]) + exe "g/foo/s/foo\\\<NL>bar/xyz/" + call assert_equal('xyz', getline(1)) + close! +endfunc + +func Test_wrong_delimiter() + call assert_fails('g x^bxd', 'E146:') +endfunc + +" Test for interrupting :global using Ctrl-C +func Test_interrupt_global() + CheckRunVimInTerminal + + let lines =<< trim END + cnoremap ; <Cmd>sleep 10<CR> + call setline(1, repeat(['foo'], 5)) + END + call writefile(lines, 'Xtest_interrupt_global') + let buf = RunVimInTerminal('-S Xtest_interrupt_global', {'rows': 6}) + + call term_sendkeys(buf, ":g/foo/norm :\<C-V>;\<CR>") + " Wait for :sleep to start + call TermWait(buf, 100) + call term_sendkeys(buf, "\<C-C>") + call WaitForAssert({-> assert_match('Interrupted', term_getline(buf, 6))}, 1000) + + " Also test in Ex mode + call term_sendkeys(buf, "gQg/foo/norm :\<C-V>;\<CR>") + " Wait for :sleep to start + call TermWait(buf, 100) + call term_sendkeys(buf, "\<C-C>") + call WaitForAssert({-> assert_match('Interrupted', term_getline(buf, 5))}, 1000) + + call StopVimInTerminal(buf) + call delete('Xtest_interrupt_global') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_gn.vim b/test/old/testdir/test_gn.vim new file mode 100644 index 0000000000..c4a41a6742 --- /dev/null +++ b/test/old/testdir/test_gn.vim @@ -0,0 +1,221 @@ +" Test for gn command + +func Test_gn_command() + noautocmd new + " replace a single char by itself quoted: + call setline('.', 'abc x def x ghi x jkl') + let @/ = 'x' + exe "norm! cgn'x'\<esc>.." + call assert_equal("abc 'x' def 'x' ghi 'x' jkl", getline('.')) + sil! %d_ + + " simple search match + call setline('.', 'foobar') + let @/ = 'foobar' + exe "norm! gncsearchmatch" + call assert_equal('searchmatch', getline('.')) + sil! %d _ + + " replace a multi-line match + call setline('.', ['', 'one', 'two']) + let @/ = 'one\_s*two\_s' + exe "norm! gnceins\<CR>zwei" + call assert_equal(['','eins','zwei'], getline(1,'$')) + sil! %d _ + + " test count argument + call setline('.', ['', 'abcdx | abcdx | abcdx']) + let @/ = '[a]bcdx' + exe "norm! 2gnd" + call assert_equal(['','abcdx | | abcdx'], getline(1,'$')) + sil! %d _ + + " join lines + call setline('.', ['join ', 'lines']) + let @/ = '$' + exe "norm! 0gnd" + call assert_equal(['join lines'], getline(1,'$')) + sil! %d _ + + " zero-width match + call setline('.', ['', 'zero width pattern']) + let @/ = '\>\zs' + exe "norm! 0gnd" + call assert_equal(['', 'zerowidth pattern'], getline(1,'$')) + sil! %d _ + + " delete first and last chars + call setline('.', ['delete first and last chars']) + let @/ = '^' + exe "norm! 0gnd$" + let @/ = '\zs' + exe "norm! gnd" + call assert_equal(['elete first and last char'], getline(1,'$')) + sil! %d _ + + " using visual mode + call setline('.', ['', 'uniquepattern uniquepattern']) + exe "norm! /[u]niquepattern/s\<cr>vlgnd" + call assert_equal(['', ' uniquepattern'], getline(1,'$')) + sil! %d _ + + " backwards search + call setline('.', ['my very excellent mother just served us nachos']) + let @/ = 'mother' + exe "norm! $cgNmongoose" + call assert_equal(['my very excellent mongoose just served us nachos'], getline(1,'$')) + sil! %d _ + + " search for single char + call setline('.', ['','for (i=0; i<=10; i++)']) + let @/ = 'i' + exe "norm! cgnj" + call assert_equal(['','for (j=0; i<=10; i++)'], getline(1,'$')) + sil! %d _ + + " search hex char + call setline('.', ['','Y']) + set noignorecase + let @/ = '\%x59' + exe "norm! gnd" + call assert_equal(['',''], getline(1,'$')) + sil! %d _ + + " test repeating gdn + call setline('.', ['', '1', 'Johnny', '2', 'Johnny', '3']) + let @/ = 'Johnny' + exe "norm! dgn." + call assert_equal(['','1', '', '2', '', '3'], getline(1,'$')) + sil! %d _ + + " test repeating gUgn + call setline('.', ['', '1', 'Depp', '2', 'Depp', '3']) + let @/ = 'Depp' + exe "norm! gUgn." + call assert_equal(['', '1', 'DEPP', '2', 'DEPP', '3'], getline(1,'$')) + sil! %d _ + + " test using look-ahead assertions + call setline('.', ['a:10', '', 'a:1', '', 'a:20']) + let @/ = 'a:0\@!\zs\d\+' + exe "norm! 2nygno\<esc>p" + call assert_equal(['a:10', '', 'a:1', '1', '', 'a:20'], getline(1,'$')) + sil! %d _ + + " test using nowrapscan + set nowrapscan + call setline(1, 'foo bar baz') + exe "norm! /bar/e\<cr>" + exe "norm! gnd" + call assert_equal(['foo baz'], getline(1,'$')) + sil! %d_ + + " search upwards with nowrapscan set + call setline('.', ['foo', 'bar', 'foo', 'baz']) + set nowrapscan + let @/ = 'foo' + $ + norm! dgN + call assert_equal(['foo', 'bar', '', 'baz'], getline(1,'$')) + sil! %d_ + + " search using the \zs atom + call setline(1, [' nnoremap', '' , 'nnoremap']) + set wrapscan&vim + let @/ = '\_s\zsnnoremap' + $ + norm! cgnmatch + call assert_equal([' nnoremap', '', 'match'], getline(1,'$')) + sil! %d_ + + " make sure it works correctly for one-char wide search items + call setline('.', ['abcdefghi']) + let @/ = 'a' + exe "norm! 0fhvhhgNgU" + call assert_equal(['ABCDEFGHi'], getline(1,'$')) + call setline('.', ['abcdefghi']) + let @/ = 'b' + " this gn wraps around the end of the file + exe "norm! 0fhvhhgngU" + call assert_equal(['aBCDEFGHi'], getline(1,'$')) + sil! %d _ + call setline('.', ['abcdefghi']) + let @/ = 'f' + exe "norm! 0vllgngU" + call assert_equal(['ABCDEFghi'], getline(1,'$')) + sil! %d _ + call setline('.', ['12345678']) + let @/ = '5' + norm! gg0f7vhhhhgnd + call assert_equal(['12348'], getline(1,'$')) + sil! %d _ + call setline('.', ['12345678']) + let @/ = '5' + norm! gg0f2vf7gNd + call assert_equal(['1678'], getline(1,'$')) + sil! %d _ + set wrapscan&vim + + " Without 'wrapscan', in visual mode, running gn without a match should fail + " but the visual mode should be kept. + set nowrapscan + call setline('.', 'one two') + let @/ = 'one' + call assert_beeps('normal 0wvlgn') + exe "normal y" + call assert_equal('tw', @") + + " with exclusive selection, run gn and gN + set selection=exclusive + normal 0gny + call assert_equal('one', @") + normal 0wgNy + call assert_equal('one', @") + set selection& +endfunc + +func Test_gN_repeat() + new + call setline(1, 'this list is a list with a list of a list.') + /list + normal $gNgNgNx + call assert_equal('list with a list of a list', @") + bwipe! +endfunc + +func Test_gN_then_gn() + new + + call setline(1, 'this list is a list with a list of a last.') + /l.st + normal $gNgNgnx + call assert_equal('last', @") + + call setline(1, 'this list is a list with a lust of a last.') + /l.st + normal $gNgNgNgnx + call assert_equal('lust of a last', @") + + bwipe! +endfunc + +func Test_gn_multi_line() + new + call setline(1, [ + \ 'func Tm1()', + \ ' echo "one"', + \ 'endfunc', + \ 'func Tm2()', + \ ' echo "two"', + \ 'endfunc', + \ 'func Tm3()', + \ ' echo "three"', + \ 'endfunc', + \]) + /\v^func Tm\d\(\)\n.*\zs".*"\ze$ + normal jgnrx + call assert_equal(' echo xxxxx', getline(5)) + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_goto.vim b/test/old/testdir/test_goto.vim new file mode 100644 index 0000000000..6d029ffda2 --- /dev/null +++ b/test/old/testdir/test_goto.vim @@ -0,0 +1,442 @@ +" Test commands that jump somewhere. + +" Create a new buffer using "lines" and place the cursor on the word after the +" first occurrence of return and invoke "cmd". The cursor should now be +" positioned at the given line and col. +func XTest_goto_decl(cmd, lines, line, col) + new + call setline(1, a:lines) + /return/ + normal! W + execute 'norm! ' . a:cmd + call assert_equal(a:line, line('.')) + call assert_equal(a:col, col('.')) + quit! +endfunc + +func Test_gD() + let lines =<< trim [CODE] + int x; + + int func(void) + { + return x; + } + [CODE] + + call XTest_goto_decl('gD', lines, 1, 5) +endfunc + +func Test_gD_too() + let lines =<< trim [CODE] + Filename x; + + int Filename + int func() { + Filename x; + return x; + [CODE] + + call XTest_goto_decl('gD', lines, 1, 10) +endfunc + +func Test_gD_comment() + let lines =<< trim [CODE] + /* int x; */ + int x; + + int func(void) + { + return x; + } + [CODE] + + call XTest_goto_decl('gD', lines, 2, 5) +endfunc + +func Test_gD_inline_comment() + let lines =<< trim [CODE] + int y /* , x */; + int x; + + int func(void) + { + return x; + } + [CODE] + + call XTest_goto_decl('gD', lines, 2, 5) +endfunc + +func Test_gD_string() + let lines =<< trim [CODE] + char *s[] = "x"; + int x = 1; + + int func(void) + { + return x; + } + [CODE] + + call XTest_goto_decl('gD', lines, 2, 5) +endfunc + +func Test_gD_string_same_line() + let lines =<< trim [CODE] + char *s[] = "x", int x = 1; + + int func(void) + { + return x; + } + [CODE] + + call XTest_goto_decl('gD', lines, 1, 22) +endfunc + +func Test_gD_char() + let lines =<< trim [CODE] + char c = 'x'; + int x = 1; + + int func(void) + { + return x; + } + [CODE] + + call XTest_goto_decl('gD', lines, 2, 5) +endfunc + +func Test_gd() + let lines =<< trim [CODE] + int x; + + int func(int x) + { + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 3, 14) +endfunc + +" Using gd to jump to a declaration in a fold +func Test_gd_with_fold() + new + let lines =<< trim END + #define ONE 1 + #define TWO 2 + #define THREE 3 + + TWO + END + call setline(1, lines) + 1,3fold + call feedkeys('Ggd', 'xt') + call assert_equal(2, line('.')) + call assert_equal(-1, foldclosedend(2)) + bw! +endfunc + +func Test_gd_not_local() + let lines =<< trim [CODE] + int func1(void) + { + return x; + } + + int func2(int x) + { + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 3, 10) +endfunc + +func Test_gd_kr_style() + let lines =<< trim [CODE] + int func(x) + int x; + { + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 2, 7) +endfunc + +func Test_gd_missing_braces() + let lines =<< trim [CODE] + def func1(a) + a + 1 + end + + a = 1 + + def func2() + return a + end + [CODE] + + call XTest_goto_decl('gd', lines, 1, 11) +endfunc + +func Test_gd_comment() + let lines =<< trim [CODE] + int func(void) + { + /* int x; */ + int x; + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 4, 7) +endfunc + +func Test_gd_comment_in_string() + let lines =<< trim [CODE] + int func(void) + { + char *s ="//"; int x; + int x; + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 3, 22) +endfunc + +func Test_gd_string_in_comment() + set comments= + let lines =<< trim [CODE] + int func(void) + { + /* " */ int x; + int x; + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 3, 15) + set comments& +endfunc + +func Test_gd_inline_comment() + let lines =<< trim [CODE] + int func(/* x is an int */ int x) + { + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 1, 32) +endfunc + +func Test_gd_inline_comment_only() + let lines =<< trim [CODE] + int func(void) /* one lonely x */ + { + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 3, 10) +endfunc + +func Test_gd_inline_comment_body() + let lines =<< trim [CODE] + int func(void) + { + int y /* , x */; + + for (/* int x = 0 */; y < 2; y++); + + int x = 0; + + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 7, 7) +endfunc + +func Test_gd_trailing_multiline_comment() + let lines =<< trim [CODE] + int func(int x) /* x is an int */ + { + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 1, 14) +endfunc + +func Test_gd_trailing_comment() + let lines =<< trim [CODE] + int func(int x) // x is an int + { + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 1, 14) +endfunc + +func Test_gd_string() + let lines =<< trim [CODE] + int func(void) + { + char *s = "x"; + int x = 1; + + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 4, 7) +endfunc + +func Test_gd_string_only() + let lines =<< trim [CODE] + int func(void) + { + char *s = "x"; + + return x; + } + [CODE] + + call XTest_goto_decl('gd', lines, 5, 10) +endfunc + +" Check that setting 'cursorline' does not change curswant +func Test_cursorline_keep_col() + new + call setline(1, ['long long long line', 'short line']) + normal ggfi + let pos = getcurpos() + normal j + set cursorline + normal k + call assert_equal(pos, getcurpos()) + bwipe! + set nocursorline +endfunc + +func Test_gd_local_block() + let lines =<< trim [CODE] + int main() + { + char *a = "NOT NULL"; + if(a) + { + char *b = a; + printf("%s\n", b); + } + else + { + char *b = "NULL"; + return b; + } + + return 0; + } + [CODE] + + call XTest_goto_decl('1gd', lines, 11, 11) +endfunc + +func Test_motion_if_elif_else_endif() + new + let lines =<< trim END + /* Test pressing % on #if, #else #elsif and #endif, + * with nested #if + */ + #if FOO + /* ... */ + # if BAR + /* ... */ + # endif + #elif BAR + /* ... */ + #else + /* ... */ + #endif + + #define FOO 1 + END + call setline(1, lines) + /#if FOO + norm % + call assert_equal([9, 1], getpos('.')[1:2]) + norm % + call assert_equal([11, 1], getpos('.')[1:2]) + norm % + call assert_equal([13, 1], getpos('.')[1:2]) + norm % + call assert_equal([4, 1], getpos('.')[1:2]) + /# if BAR + norm $% + call assert_equal([8, 1], getpos('.')[1:2]) + norm $% + call assert_equal([6, 1], getpos('.')[1:2]) + + " Test for [# and ]# command + call cursor(5, 1) + normal [# + call assert_equal([4, 1], getpos('.')[1:2]) + call cursor(5, 1) + normal ]# + call assert_equal([9, 1], getpos('.')[1:2]) + call cursor(10, 1) + normal [# + call assert_equal([9, 1], getpos('.')[1:2]) + call cursor(10, 1) + normal ]# + call assert_equal([11, 1], getpos('.')[1:2]) + + " Finding a match before the first line or after the last line should fail + normal gg + call assert_beeps('normal [#') + normal G + call assert_beeps('normal ]#') + + " Finding a match for a macro definition (#define) should fail + normal G + call assert_beeps('normal %') + + bw! +endfunc + +func Test_motion_c_comment() + new + a +/* + * Test pressing % on beginning/end + * of C comments. + */ +/* Another comment */ +. + norm gg0% + call assert_equal([4, 3], getpos('.')[1:2]) + norm % + call assert_equal([1, 1], getpos('.')[1:2]) + norm gg0l% + call assert_equal([4, 3], getpos('.')[1:2]) + norm h% + call assert_equal([1, 1], getpos('.')[1:2]) + + norm G^ + norm % + call assert_equal([5, 21], getpos('.')[1:2]) + norm % + call assert_equal([5, 1], getpos('.')[1:2]) + + bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_gui.vim b/test/old/testdir/test_gui.vim new file mode 100644 index 0000000000..c3f1f3163a --- /dev/null +++ b/test/old/testdir/test_gui.vim @@ -0,0 +1,43 @@ + +func Test_colorscheme() + " call assert_equal('16777216', &t_Co) + + let colorscheme_saved = exists('g:colors_name') ? g:colors_name : 'default' + let g:color_count = 0 + augroup TestColors + au! + au ColorScheme * let g:color_count += 1 + \ | let g:after_colors = g:color_count + \ | let g:color_after = expand('<amatch>') + au ColorSchemePre * let g:color_count += 1 + \ | let g:before_colors = g:color_count + \ | let g:color_pre = expand('<amatch>') + augroup END + + colorscheme torte + redraw! + call assert_equal('dark', &background) + call assert_equal(1, g:before_colors) + call assert_equal(2, g:after_colors) + call assert_equal('torte', g:color_pre) + call assert_equal('torte', g:color_after) + call assert_equal("\ntorte", execute('colorscheme')) + + let a = substitute(execute('hi Search'), "\n\\s\\+", ' ', 'g') + " FIXME: temporarily check less while the colorscheme changes + " call assert_match("\nSearch xxx term=reverse cterm=reverse ctermfg=196 ctermbg=16 gui=reverse guifg=#ff0000 guibg=#000000", a) + " call assert_match("\nSearch xxx term=reverse ", a) + + call assert_fails('colorscheme does_not_exist', 'E185:') + call assert_equal('does_not_exist', g:color_pre) + call assert_equal('torte', g:color_after) + + exec 'colorscheme' colorscheme_saved + augroup TestColors + au! + augroup END + unlet g:color_count g:after_colors g:before_colors + redraw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_help.vim b/test/old/testdir/test_help.vim new file mode 100644 index 0000000000..08dd3dcb9a --- /dev/null +++ b/test/old/testdir/test_help.vim @@ -0,0 +1,229 @@ +" Tests for :help + +source check.vim +source vim9.vim + +func SetUp() + let s:vimruntime = $VIMRUNTIME + let s:runtimepath = &runtimepath + " Set $VIMRUNTIME to $BUILD_DIR/runtime and remove the original $VIMRUNTIME + " path from &runtimepath so that ":h local-additions" won't pick up builtin + " help files. + let $VIMRUNTIME = expand($BUILD_DIR) .. '/runtime' + set runtimepath-=../../../runtime +endfunc + +func TearDown() + let $VIMRUNTIME = s:vimruntime + let &runtimepath = s:runtimepath +endfunc + +func Test_help_restore_snapshot() + help + set buftype= + help + edit x + help + helpclose +endfunc + +func Test_help_restore_snapshot_split() + " Squeeze the unnamed buffer, Xfoo and the help one side-by-side and focus + " the first one before calling :help. + let bnr = bufnr() + botright vsp Xfoo + wincmd h + help + wincmd L + let g:did_bufenter = v:false + augroup T + au! + au BufEnter Xfoo let g:did_bufenter = v:true + augroup END + helpclose + augroup! T + " We're back to the unnamed buffer. + call assert_equal(bnr, bufnr()) + " No BufEnter was triggered for Xfoo. + call assert_equal(v:false, g:did_bufenter) + + close! + bwipe! +endfunc + +func Test_help_errors() + call assert_fails('help doesnotexist', 'E149:') + call assert_fails('help!', 'E478:') + if has('multi_lang') + call assert_fails('help help@xy', 'E661:') + endif + + let save_hf = &helpfile + set helpfile=help_missing + help + call assert_equal(1, winnr('$')) + call assert_notequal('help', &buftype) + let &helpfile = save_hf + + call assert_fails('help ' . repeat('a', 1048), 'E149:') + + new + set keywordprg=:help + call setline(1, " ") + call assert_fails('normal VK', 'E349:') + bwipe! +endfunc + +func Test_help_expr() + help expr-!~? + call assert_equal('eval.txt', expand('%:t')) + close +endfunc + +func Test_help_keyword() + new + set keywordprg=:help + call setline(1, " Visual ") + normal VK + call assert_match('^Visual mode', getline('.')) + call assert_equal('help', &ft) + close + bwipe! +endfunc + +func Test_help_local_additions() + call mkdir('Xruntime/doc', 'p') + call writefile(['*mydoc.txt* my awesome doc'], 'Xruntime/doc/mydoc.txt') + call writefile(['*mydoc-ext.txt* my extended awesome doc'], 'Xruntime/doc/mydoc-ext.txt') + let rtp_save = &rtp + set rtp+=./Xruntime + help local-additions + let lines = getline(line(".") + 1, search("^$") - 1) + call assert_equal([ + \ '|mydoc-ext.txt| my extended awesome doc', + \ '|mydoc.txt| my awesome doc' + \ ], lines) + call delete('Xruntime/doc/mydoc-ext.txt') + close + + call mkdir('Xruntime-ja/doc', 'p') + call writefile(["local-additions\thelp.jax\t/*local-additions*"], 'Xruntime-ja/doc/tags-ja') + call writefile(['*help.txt* This is jax file', '', + \ 'LOCAL ADDITIONS: *local-additions*', ''], 'Xruntime-ja/doc/help.jax') + call writefile(['*work.txt* This is jax file'], 'Xruntime-ja/doc/work.jax') + call writefile(['*work2.txt* This is jax file'], 'Xruntime-ja/doc/work2.jax') + set rtp+=./Xruntime-ja + + help local-additions@en + let lines = getline(line(".") + 1, search("^$") - 1) + call assert_equal([ + \ '|mydoc.txt| my awesome doc' + \ ], lines) + close + + help local-additions@ja + let lines = getline(line(".") + 1, search("^$") - 1) + call assert_equal([ + \ '|mydoc.txt| my awesome doc', + \ '|help.txt| This is jax file', + \ '|work.txt| This is jax file', + \ '|work2.txt| This is jax file', + \ ], lines) + close + + call delete('Xruntime', 'rf') + call delete('Xruntime-ja', 'rf') + let &rtp = rtp_save +endfunc + +func Test_help_completion() + call feedkeys(":help :undo\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"help :undo :undoj :undol :undojoin :undolist', @:) +endfunc + +" Test for the :helptags command +" NOTE: if you run tests as root this will fail. Don't run tests as root! +func Test_helptag_cmd() + call mkdir('Xdir/a/doc', 'p') + + " No help file to process in the directory + call assert_fails('helptags Xdir', 'E151:') + + call writefile([], 'Xdir/a/doc/sample.txt') + + " Test for ++t argument + helptags ++t Xdir + call assert_equal(["help-tags\ttags\t1"], readfile('Xdir/tags')) + call delete('Xdir/tags') + + " Test parsing tags + call writefile(['*tag1*', 'Example: >', ' *notag*', 'Example end: *tag2*'], + \ 'Xdir/a/doc/sample.txt') + helptags Xdir + call assert_equal(["tag1\ta/doc/sample.txt\t/*tag1*", + \ "tag2\ta/doc/sample.txt\t/*tag2*"], readfile('Xdir/tags')) + + " Duplicate tags in the help file + call writefile(['*tag1*', '*tag1*', '*tag2*'], 'Xdir/a/doc/sample.txt') + call assert_fails('helptags Xdir', 'E154:') + + call delete('Xdir', 'rf') +endfunc + +func Test_helptag_cmd_readonly() + CheckUnix + CheckNotRoot + + " Read-only tags file + call mkdir('Xdir/doc', 'p') + call writefile([''], 'Xdir/doc/tags') + call writefile([], 'Xdir/doc/sample.txt') + call setfperm('Xdir/doc/tags', 'r-xr--r--') + call assert_fails('helptags Xdir/doc', 'E152:', getfperm('Xdir/doc/tags')) + + let rtp = &rtp + let &rtp = 'Xdir' + helptags ALL + let &rtp = rtp + + call delete('Xdir/doc/tags') + + " No permission to read the help file + call mkdir('Xdir/b/doc', 'p') + call writefile([], 'Xdir/b/doc/sample.txt') + call setfperm('Xdir/b/doc/sample.txt', '-w-------') + call assert_fails('helptags Xdir', 'E153:', getfperm('Xdir/b/doc/sample.txt')) + call delete('Xdir', 'rf') +endfunc + +" Test for setting the 'helpheight' option in the help window +func Test_help_window_height() + let &cmdheight = &lines - 23 + set helpheight=10 + help + set helpheight=14 + call assert_equal(14, winheight(0)) + set helpheight& cmdheight=1 + close +endfunc + +func Test_help_long_argument() + try + exe 'help \%' .. repeat('0', 1021) + catch + call assert_match("E149:", v:exception) + endtry +endfunc + +func Test_help_using_visual_match() + let lines =<< trim END + call setline(1, ' ') + /^ + exe "normal \<C-V>\<C-V>" + h5\%V] + END + call CheckScriptFailure(lines, 'E149:') +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_help_tagjump.vim b/test/old/testdir/test_help_tagjump.vim new file mode 100644 index 0000000000..31310d1e77 --- /dev/null +++ b/test/old/testdir/test_help_tagjump.vim @@ -0,0 +1,320 @@ +" Tests for :help! {subject} + +func Test_help_tagjump() + help + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*help.txt\*') + helpclose + + help | + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*bar\*') + helpclose + + help " + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*quote\*') + helpclose + + help * + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*star\*') + helpclose + + help "* + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*quotestar\*') + helpclose + + " help sm?le + help ch?ckhealth + call assert_equal("help", &filetype) + " call assert_true(getline('.') =~ '\*:smile\*') + call assert_true(getline('.') =~ '\*:checkhealth\*') + helpclose + + help ?? + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*??\*') + helpclose + + help :? + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*:?\*') + helpclose + + help q? + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*q?\*') + call assert_true(expand('<cword>') == 'q?') + helpclose + + help -? + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*-?\*') + helpclose + + help v_g? + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*v_g?\*') + helpclose + + help expr-!=? + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*expr-!=?\*') + call assert_true(expand('<cword>') == 'expr-!=?') + helpclose + + help expr-isnot? + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*expr-isnot?\*') + call assert_true(expand('<cword>') == 'expr-isnot?') + helpclose + + help FileW*Post + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*FileWritePost\*') + helpclose + + help `ls` + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*:ls\*') + helpclose + + help ^X + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*CTRL-X\*') + helpclose + + help i_^_CTRL-D + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*i_^_CTRL-D\*') + helpclose + + help i^x^y + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*i_CTRL-X_CTRL-Y\*') + helpclose + + exe "help i\<C-\>\<C-G>" + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*i_CTRL-\\_CTRL-G\*') + helpclose + + exec "help \<C-V>" + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*CTRL-V\*') + helpclose + + help /\| + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*/\\bar\*') + helpclose + + help \_$ + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*/\\_$\*') + helpclose + + help CTRL-\_CTRL-N + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*CTRL-\\_CTRL-N\*') + helpclose + + help `:pwd`, + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*:pwd\*') + helpclose + + help `:ls`. + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*:ls\*') + helpclose + + exec "help! ('textwidth'" + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ "\\*'textwidth'\\*") + helpclose + + exec "help! ('buflisted')," + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ "\\*'buflisted'\\*") + helpclose + + exec "help! abs({expr})" + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*abs()\*') + helpclose + + exec "help! arglistid([{winnr})" + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*arglistid()\*') + helpclose + + exec "help! 'autoindent'." + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ "\\*'autoindent'\\*") + helpclose + + exec "help! {address}." + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*{address}\*') + helpclose + + " Use special patterns in the help tag + for h in ['/\w', '/\%^', '/\%(', '/\zs', '/\@<=', '/\_$', '[++opt]', '/\{'] + exec "help! " . h + call assert_equal("help", &filetype) + let pat = '\*' . escape(h, '\$[') . '\*' + call assert_true(getline('.') =~ pat, pat) + helpclose + endfor + + exusage + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*:index\*') + helpclose + + viusage + call assert_equal("help", &filetype) + call assert_true(getline('.') =~ '\*normal-index\*') + helpclose +endfunc + +let s:langs = ['en', 'ab', 'ja'] + +func s:doc_config_setup() + let s:helpfile_save = &helpfile + let &helpfile="Xdocdir1/doc-en/doc/testdoc.txt" + let s:rtp_save = &rtp + let &rtp="Xdocdir1/doc-en" + if has('multi_lang') + let s:helplang_save=&helplang + endif + + call delete('Xdocdir1', 'rf') + + for lang in s:langs + if lang ==# 'en' + let tagfname = 'tags' + let docfname = 'testdoc.txt' + else + let tagfname = 'tags-' . lang + let docfname = 'testdoc.' . lang . 'x' + endif + let docdir = "Xdocdir1/doc-" . lang . "/doc" + call mkdir(docdir, "p") + call writefile(["\t*test-char*", "\t*test-col*"], docdir . '/' . docfname) + call writefile(["test-char\t" . docfname . "\t/*test-char*", + \ "test-col\t" . docfname . "\t/*test-col*"], + \ docdir . '/' . tagfname) + endfor +endfunc + +func s:doc_config_teardown() + call delete('Xdocdir1', 'rf') + + let &helpfile = s:helpfile_save + let &rtp = s:rtp_save + if has('multi_lang') + let &helplang = s:helplang_save + endif +endfunc + +func s:get_help_compl_list(cmd) + return getcompletion(a:cmd, 'help') +endfunc + +func Test_help_complete() + try + let list = [] + call s:doc_config_setup() + + " 'helplang=' and help file lang is 'en' + if has('multi_lang') + set helplang= + endif + let list = s:get_help_compl_list("test") + call assert_equal(['test-col', 'test-char'], list) + + if has('multi_lang') + " 'helplang=ab' and help file lang is 'en' + set helplang=ab + let list = s:get_help_compl_list("test") + call assert_equal(['test-col', 'test-char'], list) + + " 'helplang=' and help file lang is 'en' and 'ab' + set rtp+=Xdocdir1/doc-ab + set helplang= + let list = s:get_help_compl_list("test") + call assert_equal(sort(['test-col@en', 'test-col@ab', + \ 'test-char@en', 'test-char@ab']), sort(list)) + + " 'helplang=ab' and help file lang is 'en' and 'ab' + set helplang=ab + let list = s:get_help_compl_list("test") + call assert_equal(sort(['test-col', 'test-col@en', + \ 'test-char', 'test-char@en']), sort(list)) + + " 'helplang=' and help file lang is 'en', 'ab' and 'ja' + set rtp+=Xdocdir1/doc-ja + set helplang= + let list = s:get_help_compl_list("test") + call assert_equal(sort(['test-col@en', 'test-col@ab', + \ 'test-col@ja', 'test-char@en', + \ 'test-char@ab', 'test-char@ja']), sort(list)) + + " 'helplang=ab' and help file lang is 'en', 'ab' and 'ja' + set helplang=ab + let list = s:get_help_compl_list("test") + call assert_equal(sort(['test-col', 'test-col@en', + \ 'test-col@ja', 'test-char', + \ 'test-char@en', 'test-char@ja']), sort(list)) + + " 'helplang=ab,ja' and help file lang is 'en', 'ab' and 'ja' + set helplang=ab,ja + let list = s:get_help_compl_list("test") + call assert_equal(sort(['test-col', 'test-col@ja', + \ 'test-col@en', 'test-char', + \ 'test-char@ja', 'test-char@en']), sort(list)) + endif + catch + call assert_exception('X') + finally + call s:doc_config_teardown() + endtry +endfunc + +func Test_help_respect_current_file_lang() + try + let list = [] + call s:doc_config_setup() + + if has('multi_lang') + function s:check_help_file_ext(help_keyword, ext) + exec 'help ' . a:help_keyword + call assert_equal(a:ext, expand('%:e')) + call feedkeys("\<C-]>", 'tx') + call assert_equal(a:ext, expand('%:e')) + pop + helpclose + endfunc + + set rtp+=Xdocdir1/doc-ab + set rtp+=Xdocdir1/doc-ja + + set helplang=ab + call s:check_help_file_ext('test-char', 'abx') + call s:check_help_file_ext('test-char@ja', 'jax') + set helplang=ab,ja + call s:check_help_file_ext('test-char@ja', 'jax') + call s:check_help_file_ext('test-char@en', 'txt') + endif + catch + call assert_exception('X') + finally + call s:doc_config_teardown() + endtry +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_hide.vim b/test/old/testdir/test_hide.vim new file mode 100644 index 0000000000..b3ce395523 --- /dev/null +++ b/test/old/testdir/test_hide.vim @@ -0,0 +1,97 @@ +" Tests for :hide command/modifier and 'hidden' option + +func SetUp() + let s:save_hidden = &hidden + let s:save_bufhidden = &bufhidden + let s:save_autowrite = &autowrite + set nohidden + set bufhidden= + set noautowrite +endfunc + +function TearDown() + let &hidden = s:save_hidden + let &bufhidden = s:save_bufhidden + let &autowrite = s:save_autowrite +endfunc + +function Test_hide() + let orig_bname = bufname('') + let orig_winnr = winnr('$') + + new Xf1 + set modified + call assert_fails('edit Xf2') + bwipeout! Xf1 + + new Xf1 + set modified + edit! Xf2 + call assert_equal(['Xf2', 2], [bufname(''), winnr('$')]) + call assert_equal([1, 0], [buflisted('Xf1'), bufloaded('Xf1')]) + bwipeout! Xf1 + bwipeout! Xf2 + + new Xf1 + set modified + " :hide as a command + hide + call assert_equal([orig_bname, orig_winnr], [bufname(''), winnr('$')]) + call assert_equal([1, 1], ['Xf1'->buflisted(), 'Xf1'->bufloaded()]) + bwipeout! Xf1 + + new Xf1 + set modified + " :hide as a command with trailing comment + hide " comment + call assert_equal([orig_bname, orig_winnr], [bufname(''), winnr('$')]) + call assert_equal([1, 1], [buflisted('Xf1'), bufloaded('Xf1')]) + bwipeout! Xf1 + + new Xf1 + set modified + " :hide as a command with bar + hide | new Xf2 " comment + call assert_equal(['Xf2', 2], [bufname(''), winnr('$')]) + call assert_equal([1, 1], [buflisted('Xf1'), bufloaded('Xf1')]) + bwipeout! Xf1 + bwipeout! Xf2 + + new Xf1 + set modified + " :hide as a modifier with trailing comment + hide edit Xf2 " comment + call assert_equal(['Xf2', 2], [bufname(''), winnr('$')]) + call assert_equal([1, 1], [buflisted('Xf1'), bufloaded('Xf1')]) + bwipeout! Xf1 + bwipeout! Xf2 + + new Xf1 + set modified + " To check that the bar is not recognized to separate commands + hide echo "one|two" + call assert_equal(['Xf1', 2], [bufname(''), winnr('$')]) + call assert_equal([1, 1], [buflisted('Xf1'), bufloaded('Xf1')]) + bwipeout! Xf1 + + " set hidden + new Xf1 + set hidden + set modified + edit Xf2 " comment + call assert_equal(['Xf2', 2], [bufname(''), winnr('$')]) + call assert_equal([1, 1], [buflisted('Xf1'), bufloaded('Xf1')]) + bwipeout! Xf1 + bwipeout! Xf2 + + " set hidden bufhidden=wipe + new Xf1 + set bufhidden=wipe + set modified + hide edit! Xf2 " comment + call assert_equal(['Xf2', 2], [bufname(''), winnr('$')]) + call assert_equal([0, 0], [buflisted('Xf1'), bufloaded('Xf1')]) + bwipeout! Xf2 +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_highlight.vim b/test/old/testdir/test_highlight.vim new file mode 100644 index 0000000000..a83dc34063 --- /dev/null +++ b/test/old/testdir/test_highlight.vim @@ -0,0 +1,940 @@ +" Tests for ":highlight" and highlighting. + +source view_util.vim +source screendump.vim +source check.vim +source script_util.vim + +func Test_highlight() + " basic test if ":highlight" doesn't crash + highlight + hi Search + + " test setting colors. + " test clearing one color and all doesn't generate error or warning + silent! hi NewGroup term=bold cterm=italic ctermfg=DarkBlue ctermbg=Grey gui= guifg=#00ff00 guibg=Cyan + silent! hi Group2 term= cterm= + hi Group3 term=underline cterm=bold + + let res = split(execute("hi NewGroup"), "\n")[0] + " filter ctermfg and ctermbg, the numbers depend on the terminal + let res = substitute(res, 'ctermfg=\d*', 'ctermfg=2', '') + let res = substitute(res, 'ctermbg=\d*', 'ctermbg=3', '') + call assert_equal("NewGroup xxx cterm=italic ctermfg=2 ctermbg=3", + \ res) + call assert_equal("Group2 xxx cleared", + \ split(execute("hi Group2"), "\n")[0]) + call assert_equal("Group3 xxx cterm=bold", + \ split(execute("hi Group3"), "\n")[0]) + + hi clear NewGroup + call assert_equal("NewGroup xxx cleared", + \ split(execute("hi NewGroup"), "\n")[0]) + call assert_equal("Group2 xxx cleared", + \ split(execute("hi Group2"), "\n")[0]) + hi Group2 NONE + call assert_equal("Group2 xxx cleared", + \ split(execute("hi Group2"), "\n")[0]) + hi clear + call assert_equal("Group3 xxx cleared", + \ split(execute("hi Group3"), "\n")[0]) + call assert_fails("hi Crash term='asdf", "E475:") +endfunc + +func HighlightArgs(name) + return 'hi ' . substitute(split(execute('hi ' . a:name), '\n')[0], '\<xxx\>', '', '') +endfunc + +func IsColorable() + return has('gui_running') || str2nr(&t_Co) >= 8 +endfunc + +func HiCursorLine() + let hiCursorLine = HighlightArgs('CursorLine') + if has('gui_running') + let guibg = matchstr(hiCursorLine, 'guibg=\w\+') + let hi_ul = 'hi CursorLine gui=underline guibg=NONE' + let hi_bg = 'hi CursorLine gui=NONE ' . guibg + else + let hi_ul = 'hi CursorLine cterm=underline ctermbg=NONE' + let hi_bg = 'hi CursorLine cterm=NONE ctermbg=Gray' + endif + return [hiCursorLine, hi_ul, hi_bg] +endfunc + +func Check_lcs_eol_attrs(attrs, row, col) + let save_lcs = &lcs + set list + + call assert_equal(a:attrs, ScreenAttrs(a:row, a:col)[0]) + + set nolist + let &lcs = save_lcs +endfunc + +func Test_highlight_eol_with_cursorline() + let [hiCursorLine, hi_ul, hi_bg] = HiCursorLine() + + call NewWindow('topleft 5', 20) + call setline(1, 'abcd') + call matchadd('Search', '\n') + + " expected: + " 'abcd ' + " ^^^^ ^^^^^ no highlight + " ^ 'Search' highlight + let attrs0 = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs0[0]], 4), attrs0[0:3]) + call assert_equal(repeat([attrs0[0]], 5), attrs0[5:9]) + call assert_notequal(attrs0[0], attrs0[4]) + + setlocal cursorline + + " underline + exe hi_ul + + " expected: + " 'abcd ' + " ^^^^ underline + " ^ 'Search' highlight with underline + " ^^^^^ underline + let attrs = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs[0]], 4), attrs[0:3]) + call assert_equal([attrs[4]] + repeat([attrs[5]], 5), attrs[4:9]) + call assert_notequal(attrs[0], attrs[4]) + call assert_notequal(attrs[4], attrs[5]) + call assert_notequal(attrs0[0], attrs[0]) + call assert_notequal(attrs0[4], attrs[4]) + call Check_lcs_eol_attrs(attrs, 1, 10) + + if IsColorable() + " bg-color + exe hi_bg + + " expected: + " 'abcd ' + " ^^^^ bg-color of 'CursorLine' + " ^ 'Search' highlight + " ^^^^^ bg-color of 'CursorLine' + let attrs = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs[0]], 4), attrs[0:3]) + call assert_equal(repeat([attrs[5]], 5), attrs[5:9]) + call assert_equal(attrs0[4], attrs[4]) + call assert_notequal(attrs[0], attrs[4]) + call assert_notequal(attrs[4], attrs[5]) + call assert_notequal(attrs0[0], attrs[0]) + call assert_notequal(attrs0[5], attrs[5]) + call Check_lcs_eol_attrs(attrs, 1, 10) + endif + + call CloseWindow() + exe hiCursorLine +endfunc + +func Test_highlight_eol_with_cursorline_vertsplit() + let [hiCursorLine, hi_ul, hi_bg] = HiCursorLine() + + call NewWindow('topleft 5', 5) + call setline(1, 'abcd') + call matchadd('Search', '\n') + + let expected = "abcd |abcd " + let actual = ScreenLines(1, 15)[0] + call assert_equal(expected, actual) + + " expected: + " 'abcd |abcd ' + " ^^^^ ^^^^^^^^^ no highlight + " ^ 'Search' highlight + " ^ 'WinSeparator' highlight + let attrs0 = ScreenAttrs(1, 15)[0] + call assert_equal(repeat([attrs0[0]], 4), attrs0[0:3]) + call assert_equal(repeat([attrs0[0]], 9), attrs0[6:14]) + call assert_notequal(attrs0[0], attrs0[4]) + call assert_notequal(attrs0[0], attrs0[5]) + call assert_notequal(attrs0[4], attrs0[5]) + + setlocal cursorline + + " expected: + " 'abcd |abcd ' + " ^^^^ underline + " ^ 'Search' highlight with underline + " ^ 'WinSeparator' highlight + " ^^^^^^^^^ no highlight + + " underline + exe hi_ul + + let actual = ScreenLines(1, 15)[0] + call assert_equal(expected, actual) + + let attrs = ScreenAttrs(1, 15)[0] + call assert_equal(repeat([attrs[0]], 4), attrs[0:3]) + call assert_equal(repeat([attrs[6]], 9), attrs[6:14]) + call assert_equal(attrs0[5:14], attrs[5:14]) + call assert_notequal(attrs[0], attrs[4]) + call assert_notequal(attrs[0], attrs[5]) + call assert_notequal(attrs[0], attrs[6]) + call assert_notequal(attrs[4], attrs[5]) + call assert_notequal(attrs[5], attrs[6]) + call assert_notequal(attrs0[0], attrs[0]) + call assert_notequal(attrs0[4], attrs[4]) + call Check_lcs_eol_attrs(attrs, 1, 15) + + if IsColorable() + " bg-color + exe hi_bg + + let actual = ScreenLines(1, 15)[0] + call assert_equal(expected, actual) + + let attrs = ScreenAttrs(1, 15)[0] + call assert_equal(repeat([attrs[0]], 4), attrs[0:3]) + call assert_equal(repeat([attrs[6]], 9), attrs[6:14]) + call assert_equal(attrs0[5:14], attrs[5:14]) + call assert_notequal(attrs[0], attrs[4]) + call assert_notequal(attrs[0], attrs[5]) + call assert_notequal(attrs[0], attrs[6]) + call assert_notequal(attrs[4], attrs[5]) + call assert_notequal(attrs[5], attrs[6]) + call assert_notequal(attrs0[0], attrs[0]) + call assert_equal(attrs0[4], attrs[4]) + call Check_lcs_eol_attrs(attrs, 1, 15) + endif + + call CloseWindow() + exe hiCursorLine +endfunc + +func Test_highlight_eol_with_cursorline_rightleft() + if !has('rightleft') + return + endif + + let [hiCursorLine, hi_ul, hi_bg] = HiCursorLine() + + call NewWindow('topleft 5', 10) + setlocal rightleft + call setline(1, 'abcd') + call matchadd('Search', '\n') + let attrs0 = ScreenAttrs(1, 10)[0] + + setlocal cursorline + + " underline + exe hi_ul + + " expected: + " ' dcba' + " ^^^^ underline + " ^ 'Search' highlight with underline + " ^^^^^ underline + let attrs = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs[9]], 4), attrs[6:9]) + call assert_equal(repeat([attrs[4]], 5) + [attrs[5]], attrs[0:5]) + call assert_notequal(attrs[9], attrs[5]) + call assert_notequal(attrs[4], attrs[5]) + call assert_notequal(attrs0[9], attrs[9]) + call assert_notequal(attrs0[5], attrs[5]) + call Check_lcs_eol_attrs(attrs, 1, 10) + + if IsColorable() + " bg-color + exe hi_bg + + " expected: + " ' dcba' + " ^^^^ bg-color of 'CursorLine' + " ^ 'Search' highlight + " ^^^^^ bg-color of 'CursorLine' + let attrs = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs[9]], 4), attrs[6:9]) + call assert_equal(repeat([attrs[4]], 5), attrs[0:4]) + call assert_equal(attrs0[5], attrs[5]) + call assert_notequal(attrs[9], attrs[5]) + call assert_notequal(attrs[5], attrs[4]) + call assert_notequal(attrs0[9], attrs[9]) + call assert_notequal(attrs0[4], attrs[4]) + call Check_lcs_eol_attrs(attrs, 1, 10) + endif + + call CloseWindow() + exe hiCursorLine +endfunc + +func Test_highlight_eol_with_cursorline_linewrap() + let [hiCursorLine, hi_ul, hi_bg] = HiCursorLine() + + call NewWindow('topleft 5', 10) + call setline(1, [repeat('a', 51) . 'bcd', '']) + call matchadd('Search', '\n') + + setlocal wrap + normal! gg$ + let attrs0 = ScreenAttrs(5, 10)[0] + setlocal cursorline + + " underline + exe hi_ul + + " expected: + " 'abcd ' + " ^^^^ underline + " ^ 'Search' highlight with underline + " ^^^^^ underline + let attrs = ScreenAttrs(5, 10)[0] + call assert_equal(repeat([attrs[0]], 4), attrs[0:3]) + call assert_equal([attrs[4]] + repeat([attrs[5]], 5), attrs[4:9]) + call assert_notequal(attrs[0], attrs[4]) + call assert_notequal(attrs[4], attrs[5]) + call assert_notequal(attrs0[0], attrs[0]) + call assert_notequal(attrs0[4], attrs[4]) + call Check_lcs_eol_attrs(attrs, 5, 10) + + if IsColorable() + " bg-color + exe hi_bg + + " expected: + " 'abcd ' + " ^^^^ bg-color of 'CursorLine' + " ^ 'Search' highlight + " ^^^^^ bg-color of 'CursorLine' + let attrs = ScreenAttrs(5, 10)[0] + call assert_equal(repeat([attrs[0]], 4), attrs[0:3]) + call assert_equal(repeat([attrs[5]], 5), attrs[5:9]) + call assert_equal(attrs0[4], attrs[4]) + call assert_notequal(attrs[0], attrs[4]) + call assert_notequal(attrs[4], attrs[5]) + call assert_notequal(attrs0[0], attrs[0]) + call assert_notequal(attrs0[5], attrs[5]) + call Check_lcs_eol_attrs(attrs, 5, 10) + endif + + setlocal nocursorline nowrap + normal! gg$ + let attrs0 = ScreenAttrs(1, 10)[0] + setlocal cursorline + + " underline + exe hi_ul + + " expected: + " 'aaabcd ' + " ^^^^^^ underline + " ^ 'Search' highlight with underline + " ^^^ underline + let attrs = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs[0]], 6), attrs[0:5]) + call assert_equal([attrs[6]] + repeat([attrs[7]], 3), attrs[6:9]) + call assert_notequal(attrs[0], attrs[6]) + call assert_notequal(attrs[6], attrs[7]) + call assert_notequal(attrs0[0], attrs[0]) + call assert_notequal(attrs0[6], attrs[6]) + call Check_lcs_eol_attrs(attrs, 1, 10) + + if IsColorable() + " bg-color + exe hi_bg + + " expected: + " 'aaabcd ' + " ^^^^^^ bg-color of 'CursorLine' + " ^ 'Search' highlight + " ^^^ bg-color of 'CursorLine' + let attrs = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs[0]], 6), attrs[0:5]) + call assert_equal(repeat([attrs[7]], 3), attrs[7:9]) + call assert_equal(attrs0[6], attrs[6]) + call assert_notequal(attrs[0], attrs[6]) + call assert_notequal(attrs[6], attrs[7]) + call assert_notequal(attrs0[0], attrs[0]) + call assert_notequal(attrs0[7], attrs[7]) + call Check_lcs_eol_attrs(attrs, 1, 10) + endif + + call CloseWindow() + exe hiCursorLine +endfunc + +func Test_highlight_eol_with_cursorline_sign() + if !has('signs') + return + endif + + let [hiCursorLine, hi_ul, hi_bg] = HiCursorLine() + + call NewWindow('topleft 5', 10) + call setline(1, 'abcd') + call matchadd('Search', '\n') + + sign define Sign text=>> + exe 'sign place 1 line=1 name=Sign buffer=' . bufnr('') + let attrs0 = ScreenAttrs(1, 10)[0] + setlocal cursorline + + " underline + exe hi_ul + + " expected: + " '>>abcd ' + " ^^ sign + " ^^^^ underline + " ^ 'Search' highlight with underline + " ^^^ underline + let attrs = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs[2]], 4), attrs[2:5]) + call assert_equal([attrs[6]] + repeat([attrs[7]], 3), attrs[6:9]) + call assert_notequal(attrs[2], attrs[6]) + call assert_notequal(attrs[6], attrs[7]) + call assert_notequal(attrs0[2], attrs[2]) + call assert_notequal(attrs0[6], attrs[6]) + call Check_lcs_eol_attrs(attrs, 1, 10) + + if IsColorable() + " bg-color + exe hi_bg + + " expected: + " '>>abcd ' + " ^^ sign + " ^^^^ bg-color of 'CursorLine' + " ^ 'Search' highlight + " ^^^ bg-color of 'CursorLine' + let attrs = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs[2]], 4), attrs[2:5]) + call assert_equal(repeat([attrs[7]], 3), attrs[7:9]) + call assert_equal(attrs0[6], attrs[6]) + call assert_notequal(attrs[2], attrs[6]) + call assert_notequal(attrs[6], attrs[7]) + call assert_notequal(attrs0[2], attrs[2]) + call assert_notequal(attrs0[7], attrs[7]) + call Check_lcs_eol_attrs(attrs, 1, 10) + endif + + sign unplace 1 + call CloseWindow() + exe hiCursorLine +endfunc + +func Test_highlight_eol_with_cursorline_breakindent() + if !has('linebreak') + return + endif + + let [hiCursorLine, hi_ul, hi_bg] = HiCursorLine() + + call NewWindow('topleft 5', 10) + set showbreak=xxx + setlocal breakindent breakindentopt=min:0,shift:1 showbreak=> + call setline(1, ' ' . repeat('a', 9) . 'bcd') + call matchadd('Search', '\n') + let attrs0 = ScreenAttrs(2, 10)[0] + setlocal cursorline + + " underline + exe hi_ul + + " expected: + " ' >bcd ' + " ^^^ breakindent and showbreak + " ^^^ underline + " ^ 'Search' highlight with underline + " ^^^ underline + let attrs = ScreenAttrs(2, 10)[0] + call assert_equal(repeat([attrs[0]], 2), attrs[0:1]) + call assert_equal(repeat([attrs[3]], 3), attrs[3:5]) + call assert_equal([attrs[6]] + repeat([attrs[7]], 3), attrs[6:9]) + call assert_equal(attrs0[0], attrs[0]) + call assert_notequal(attrs[0], attrs[2]) + call assert_notequal(attrs[2], attrs[3]) + call assert_notequal(attrs[3], attrs[6]) + call assert_notequal(attrs[6], attrs[7]) + call assert_notequal(attrs0[2], attrs[2]) + call assert_notequal(attrs0[3], attrs[3]) + call assert_notequal(attrs0[6], attrs[6]) + call Check_lcs_eol_attrs(attrs, 2, 10) + + if IsColorable() + " bg-color + exe hi_bg + + " expected: + " ' >bcd ' + " ^^^ breakindent and showbreak + " ^^^ bg-color of 'CursorLine' + " ^ 'Search' highlight + " ^^^ bg-color of 'CursorLine' + let attrs = ScreenAttrs(2, 10)[0] + call assert_equal(repeat([attrs[0]], 2), attrs[0:1]) + call assert_equal(repeat([attrs[3]], 3), attrs[3:5]) + call assert_equal(repeat([attrs[7]], 3), attrs[7:9]) + call assert_equal(attrs0[0], attrs[0]) + call assert_equal(attrs0[6], attrs[6]) + call assert_notequal(attrs[0], attrs[2]) + call assert_notequal(attrs[2], attrs[3]) + call assert_notequal(attrs[3], attrs[6]) + call assert_notequal(attrs[6], attrs[7]) + call assert_notequal(attrs0[2], attrs[2]) + call assert_notequal(attrs0[3], attrs[3]) + call assert_notequal(attrs0[7], attrs[7]) + call Check_lcs_eol_attrs(attrs, 2, 10) + endif + + call CloseWindow() + set showbreak= + setlocal showbreak= + exe hiCursorLine +endfunc + +func Test_highlight_eol_on_diff() + call setline(1, ['abcd', '']) + call matchadd('Search', '\n') + let attrs0 = ScreenAttrs(1, 10)[0] + + diffthis + botright new + diffthis + + " expected: + " ' abcd ' + " ^^ sign + " ^^^^ ^^^ 'DiffAdd' highlight + " ^ 'Search' highlight + let attrs = ScreenAttrs(1, 10)[0] + call assert_equal(repeat([attrs[0]], 2), attrs[0:1]) + call assert_equal(repeat([attrs[2]], 4), attrs[2:5]) + call assert_equal(repeat([attrs[2]], 3), attrs[7:9]) + call assert_equal(attrs0[4], attrs[6]) + call assert_notequal(attrs[0], attrs[2]) + call assert_notequal(attrs[0], attrs[6]) + call assert_notequal(attrs[2], attrs[6]) + call Check_lcs_eol_attrs(attrs, 1, 10) + + bwipe! + diffoff +endfunc + +func Test_termguicolors() + if !exists('+termguicolors') + return + endif + if has('vtp') && !has('vcon') && !has('gui_running') + " Win32: 'guicolors' doesn't work without virtual console. + call assert_fails('set termguicolors', 'E954:') + return + endif + + " Basic test that setting 'termguicolors' works with one color. + set termguicolors + redraw + set t_Co=1 + redraw + set t_Co=0 + redraw +endfunc + +func Test_cursorline_after_yank() + CheckScreendump + + call writefile([ + \ 'set cul rnu', + \ 'call setline(1, ["","1","2","3",""])', + \ ], 'Xtest_cursorline_yank') + let buf = RunVimInTerminal('-S Xtest_cursorline_yank', {'rows': 8}) + call TermWait(buf) + call term_sendkeys(buf, "Gy3k") + call TermWait(buf) + call term_sendkeys(buf, "jj") + + call VerifyScreenDump(buf, 'Test_cursorline_yank_01', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('Xtest_cursorline_yank') +endfunc + +" test for issue https://github.com/vim/vim/issues/4862 +func Test_put_before_cursorline() + new + only! + call setline(1, 'A') + redraw + let std_attr = screenattr(1, 1) + set cursorline + redraw + let cul_attr = screenattr(1, 1) + normal yyP + redraw + " Line 1 has cursor so it should be highlighted with CursorLine. + call assert_equal(cul_attr, screenattr(1, 1)) + " And CursorLine highlighting from the second line should be gone. + call assert_equal(std_attr, screenattr(2, 1)) + set nocursorline + bwipe! +endfunc + +func Test_cursorline_with_visualmode() + CheckScreendump + + call writefile([ + \ 'set cul', + \ 'call setline(1, repeat(["abc"], 50))', + \ ], 'Xtest_cursorline_with_visualmode') + let buf = RunVimInTerminal('-S Xtest_cursorline_with_visualmode', {'rows': 12}) + call TermWait(buf) + call term_sendkeys(buf, "V\<C-f>kkkjk") + + call VerifyScreenDump(buf, 'Test_cursorline_with_visualmode_01', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('Xtest_cursorline_with_visualmode') +endfunc + +func Test_wincolor() + CheckScreendump + " make sure the width is enough for the test + set columns=80 + + let lines =<< trim END + set cursorline cursorcolumn rnu + call setline(1, ["","1111111111","22222222222","3 here 3","","the cat is out of the bag"]) + set wincolor=Pmenu + hi CatLine guifg=green ctermfg=green + hi Reverse gui=reverse cterm=reverse + syn match CatLine /^the.*/ + call prop_type_add("foo", {"highlight": "Reverse", "combine": 1}) + call prop_add(6, 12, {"type": "foo", "end_col": 15}) + /here + END + call writefile(lines, 'Xtest_wincolor') + let buf = RunVimInTerminal('-S Xtest_wincolor', {'rows': 8}) + call TermWait(buf) + call term_sendkeys(buf, "2G5lvj") + call TermWait(buf) + + call VerifyScreenDump(buf, 'Test_wincolor_01', {}) + + " clean up + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) + call delete('Xtest_wincolor') +endfunc + +func Test_wincolor_listchars() + CheckScreendump + CheckFeature conceal + + let lines =<< trim END + call setline(1, ["one","\t\tsome random text enough long to show 'extends' and 'precedes' includingnbsps, preceding tabs and trailing spaces ","three"]) + set wincolor=Todo + set nowrap cole=1 cocu+=n + set list lcs=eol:$,tab:>-,space:.,trail:_,extends:>,precedes:<,conceal:*,nbsp:# + call matchadd('Conceal', 'text') + normal 2G5zl + END + call writefile(lines, 'Xtest_wincolorlcs') + let buf = RunVimInTerminal('-S Xtest_wincolorlcs', {'rows': 8}) + + call VerifyScreenDump(buf, 'Test_wincolor_lcs', {}) + + " clean up + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) + call delete('Xtest_wincolorlcs') +endfunc + +func Test_cursorcolumn_insert_on_tab() + CheckScreendump + + let lines =<< trim END + call setline(1, ['123456789', "a\tb"]) + set cursorcolumn + call cursor(2, 2) + END + call writefile(lines, 'Xcuc_insert_on_tab') + + let buf = RunVimInTerminal('-S Xcuc_insert_on_tab', #{rows: 8}) + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_cursorcolumn_insert_on_tab_1', {}) + + call term_sendkeys(buf, 'i') + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_cursorcolumn_insert_on_tab_2', {}) + + call term_sendkeys(buf, "\<C-O>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_cursorcolumn_insert_on_tab_3', {}) + + call term_sendkeys(buf, 'i') + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_cursorcolumn_insert_on_tab_2', {}) + + call StopVimInTerminal(buf) + call delete('Xcuc_insert_on_tab') +endfunc + +func Test_cursorcolumn_callback() + CheckScreendump + CheckFeature timers + + let lines =<< trim END + call setline(1, ['aaaaa', 'bbbbb', 'ccccc', 'ddddd']) + set cursorcolumn + call cursor(4, 5) + + func Func(timer) + call cursor(1, 1) + endfunc + + call timer_start(300, 'Func') + END + call writefile(lines, 'Xcuc_timer') + + let buf = RunVimInTerminal('-S Xcuc_timer', #{rows: 8}) + call TermWait(buf, 310) + call VerifyScreenDump(buf, 'Test_cursorcolumn_callback_1', {}) + + call StopVimInTerminal(buf) + call delete('Xcuc_timer') +endfunc + +func Test_colorcolumn() + CheckScreendump + + " check that setting 'colorcolumn' when entering a buffer works + let lines =<< trim END + split + edit X + call setline(1, ["1111111111","22222222222","3333333333"]) + set nomodified + set colorcolumn=3,9 + set number cursorline cursorlineopt=number + wincmd w + buf X + END + call writefile(lines, 'Xtest_colorcolumn') + let buf = RunVimInTerminal('-S Xtest_colorcolumn', {'rows': 10}) + call term_sendkeys(buf, ":\<CR>") + call VerifyScreenDump(buf, 'Test_colorcolumn_1', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('Xtest_colorcolumn') +endfunc + +func Test_colorcolumn_bri() + CheckScreendump + + " check 'colorcolumn' when 'breakindent' is set + let lines =<< trim END + call setline(1, 'The quick brown fox jumped over the lazy dogs') + END + call writefile(lines, 'Xtest_colorcolumn_bri') + let buf = RunVimInTerminal('-S Xtest_colorcolumn_bri', {'rows': 10,'columns': 40}) + call term_sendkeys(buf, ":set co=40 linebreak bri briopt=shift:2 cc=40,41,43\<CR>") + call VerifyScreenDump(buf, 'Test_colorcolumn_2', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('Xtest_colorcolumn_bri') +endfunc + +func Test_colorcolumn_sbr() + CheckScreendump + + " check 'colorcolumn' when 'showbreak' is set + let lines =<< trim END + call setline(1, 'The quick brown fox jumped over the lazy dogs') + END + call writefile(lines, 'Xtest_colorcolumn_sbr', 'D') + let buf = RunVimInTerminal('-S Xtest_colorcolumn_sbr', {'rows': 10,'columns': 40}) + call term_sendkeys(buf, ":set co=40 showbreak=+++>\\ cc=40,41,43\<CR>") + call VerifyScreenDump(buf, 'Test_colorcolumn_3', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_visual_sbr() + CheckScreendump + + " check Visual highlight when 'showbreak' is set + let lines =<< trim END + set showbreak=> + call setline(1, 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.') + exe "normal! z1\<CR>" + END + call writefile(lines, 'Xtest_visual_sbr', 'D') + let buf = RunVimInTerminal('-S Xtest_visual_sbr', {'rows': 6,'columns': 60}) + + call term_sendkeys(buf, "v$") + call VerifyScreenDump(buf, 'Test_visual_sbr_1', {}) + + " clean up + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) +endfunc + +" This test must come before the Test_cursorline test, as it appears this +" defines the Normal highlighting group anyway. +func Test_1_highlight_Normalgroup_exists() + let hlNormal = HighlightArgs('Normal') + if !has('gui_running') + call assert_match('hi Normal\s*clear', hlNormal) + elseif has('gui_gtk2') || has('gui_gnome') || has('gui_gtk3') + " expect is DEFAULT_FONT of gui_gtk_x11.c + call assert_match('hi Normal\s*font=Monospace 10', hlNormal) + elseif has('gui_motif') + " expect is DEFAULT_FONT of gui_x11.c + call assert_match('hi Normal\s*font=7x13', hlNormal) + elseif has('win32') + " expect any font + call assert_match('hi Normal\s*font=.*', hlNormal) + endif +endfunc + +" Do this test last, sometimes restoring the columns doesn't work +func Test_z_no_space_before_xxx() + " Note: we need to create this highlight group in the test because it does not exist in Neovim + execute('hi StatusLineTermNC ctermfg=green') + let l:org_columns = &columns + set columns=17 + let l:hi_StatusLineTermNC = join(split(execute('hi StatusLineTermNC'))) + call assert_match('StatusLineTermNC xxx', l:hi_StatusLineTermNC) + let &columns = l:org_columns +endfunc + +" Test for :highlight command errors +func Test_highlight_cmd_errors() + if has('gui_running') || has('nvim') + " This test doesn't fail in the MS-Windows console version. + call assert_fails('hi Xcomment ctermfg=fg', 'E419:') + call assert_fails('hi Xcomment ctermfg=bg', 'E420:') + call assert_fails('hi ' .. repeat('a', 201) .. ' ctermfg=black', 'E1249:') + endif + + " Try using a very long terminal code. Define a dummy terminal code for this + " test. + let &t_fo = "\<Esc>1;" + let c = repeat("t_fo,", 100) . "t_fo" + " call assert_fails('exe "hi Xgroup1 start=" . c', 'E422:') + let &t_fo = "" +endfunc + +" Test for using RGB color values in a highlight group +func Test_xxlast_highlight_RGB_color() + CheckCanRunGui + gui -f + hi MySearch guifg=#110000 guibg=#001100 guisp=#000011 + call assert_equal('#110000', synIDattr(synIDtrans(hlID('MySearch')), 'fg#')) + call assert_equal('#001100', synIDattr(synIDtrans(hlID('MySearch')), 'bg#')) + call assert_equal('#000011', synIDattr(synIDtrans(hlID('MySearch')), 'sp#')) + hi clear +endfunc + +func Test_highlight_clear_restores_links() + let aaa_id = hlID('aaa') + call assert_equal(aaa_id, 0) + + " create default link aaa --> bbb + hi def link aaa bbb + let id_aaa = hlID('aaa') + let hl_aaa_bbb = HighlightArgs('aaa') + + " try to redefine default link aaa --> ccc; check aaa --> bbb + hi def link aaa ccc + call assert_equal(HighlightArgs('aaa'), hl_aaa_bbb) + + " clear aaa; check aaa --> bbb + hi clear aaa + call assert_equal(HighlightArgs('aaa'), hl_aaa_bbb) + + " link aaa --> ccc; clear aaa; check aaa --> bbb + hi link aaa ccc + let id_ccc = hlID('ccc') + call assert_equal(synIDtrans(id_aaa), id_ccc) + hi clear aaa + call assert_equal(HighlightArgs('aaa'), hl_aaa_bbb) + + " forcibly set default link aaa --> ddd + hi! def link aaa ddd + let id_ddd = hlID('ddd') + let hl_aaa_ddd = HighlightArgs('aaa') + call assert_equal(synIDtrans(id_aaa), id_ddd) + + " link aaa --> eee; clear aaa; check aaa --> ddd + hi link aaa eee + let eee_id = hlID('eee') + call assert_equal(synIDtrans(id_aaa), eee_id) + hi clear aaa + call assert_equal(HighlightArgs('aaa'), hl_aaa_ddd) +endfunc + +func Test_highlight_clear_restores_context() + func FuncContextDefault() + hi def link Context ContextDefault + endfun + + func FuncContextRelink() + " Dummy line + hi link Context ContextRelink + endfunc + + let scriptContextDefault = MakeScript("FuncContextDefault") + let scriptContextRelink = MakeScript("FuncContextRelink") + let patContextDefault = fnamemodify(scriptContextDefault, ':t') .. ' line 1' + let patContextRelink = fnamemodify(scriptContextRelink, ':t') .. ' line 2' + + exec 'source ' .. scriptContextDefault + let hlContextDefault = execute("verbose hi Context") + call assert_match(patContextDefault, hlContextDefault) + + exec 'source ' .. scriptContextRelink + let hlContextRelink = execute("verbose hi Context") + call assert_match(patContextRelink, hlContextRelink) + + hi clear + let hlContextAfterClear = execute("verbose hi Context") + call assert_match(patContextDefault, hlContextAfterClear) + + delfunc FuncContextDefault + delfunc FuncContextRelink + call delete(scriptContextDefault) + call delete(scriptContextRelink) +endfunc + +func Test_highlight_default_colorscheme_restores_links() + hi link TestLink Identifier + hi TestHi ctermbg=red + + let hlTestLinkPre = HighlightArgs('TestLink') + let hlTestHiPre = HighlightArgs('TestHi') + + " Test colorscheme + call assert_equal("\ndefault", execute('colorscheme')) + hi clear + if exists('syntax_on') + syntax reset + endif + let g:colors_name = 'test' + call assert_equal("\ntest", execute('colorscheme')) + hi link TestLink ErrorMsg + hi TestHi ctermbg=green + + " Restore default highlighting + colorscheme default + " 'default' should work no matter if highlight group was cleared + call assert_equal("\ndefault", execute('colorscheme')) + hi def link TestLink Identifier + hi def TestHi ctermbg=red + let hlTestLinkPost = HighlightArgs('TestLink') + let hlTestHiPost = HighlightArgs('TestHi') + call assert_equal(hlTestLinkPre, hlTestLinkPost) + call assert_equal(hlTestHiPre, hlTestHiPost) + hi clear +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_history.vim b/test/old/testdir/test_history.vim new file mode 100644 index 0000000000..482328ab4a --- /dev/null +++ b/test/old/testdir/test_history.vim @@ -0,0 +1,265 @@ +" Tests for the history functions + +source check.vim +CheckFeature cmdline_hist + +set history=7 + +function History_Tests(hist) + " First clear the history + call histadd(a:hist, 'dummy') + call assert_true(histdel(a:hist)) + call assert_equal(-1, histnr(a:hist)) + call assert_equal('', histget(a:hist)) + + call assert_true('ls'->histadd(a:hist)) + call assert_true(histadd(a:hist, 'buffers')) + call assert_equal('buffers', histget(a:hist)) + call assert_equal('ls', histget(a:hist, -2)) + call assert_equal('ls', histget(a:hist, 1)) + call assert_equal('', histget(a:hist, 5)) + call assert_equal('', histget(a:hist, -5)) + call assert_equal(2, histnr(a:hist)) + call assert_true(histdel(a:hist, 2)) + call assert_false(a:hist->histdel(7)) + call assert_equal(1, histnr(a:hist)) + call assert_equal('ls', histget(a:hist, -1)) + + call assert_true(histadd(a:hist, 'buffers')) + call assert_true(histadd(a:hist, 'ls')) + call assert_equal('ls', a:hist->histget(-1)) + call assert_equal(4, a:hist->histnr()) + + let a=execute('history ' . a:hist) + call assert_match("^\n # \\S* history\n 3 buffers\n> 4 ls$", a) + let a=execute('history all') + call assert_match("^\n # .* history\n 3 buffers\n> 4 ls", a) + + if len(a:hist) > 0 + let a=execute('history ' . a:hist . ' 2') + call assert_match("^\n # \\S* history$", a) + let a=execute('history ' . a:hist . ' 3') + call assert_match("^\n # \\S* history\n 3 buffers$", a) + let a=execute('history ' . a:hist . ' 4') + call assert_match("^\n # \\S* history\n> 4 ls$", a) + let a=execute('history ' . a:hist . ' 3,4') + call assert_match("^\n # \\S* history\n 3 buffers\n> 4 ls$", a) + let a=execute('history ' . a:hist . ' -1') + call assert_match("^\n # \\S* history\n> 4 ls$", a) + let a=execute('history ' . a:hist . ' -2') + call assert_match("^\n # \\S* history\n 3 buffers$", a) + let a=execute('history ' . a:hist . ' -2,') + call assert_match("^\n # \\S* history\n 3 buffers\n> 4 ls$", a) + let a=execute('history ' . a:hist . ' -3') + call assert_match("^\n # \\S* history$", a) + endif + + " Test for removing entries matching a pattern + for i in range(1, 3) + call histadd(a:hist, 'text_' . i) + endfor + call assert_true(histdel(a:hist, 'text_\d\+')) + call assert_equal('ls', histget(a:hist, -1)) + + " Test for freeing the entire history list + for i in range(1, 7) + call histadd(a:hist, 'text_' . i) + endfor + call histdel(a:hist) + for i in range(1, 7) + call assert_equal('', histget(a:hist, i)) + call assert_equal('', histget(a:hist, i - 7 - 1)) + endfor + + " Test for freeing an entry at the beginning of the history list + for i in range(1, 4) + call histadd(a:hist, 'text_' . i) + endfor + call histdel(a:hist, 1) + call assert_equal('', histget(a:hist, 1)) + call assert_equal('text_4', histget(a:hist, 4)) +endfunction + +function Test_History() + for h in ['cmd', ':', '', 'search', '/', '?', 'expr', '=', 'input', '@', 'debug', '>'] + call History_Tests(h) + endfor + + " Negative tests + call assert_false(histdel('abc')) + call assert_equal('', histget('abc')) + call assert_fails('call histdel([])', 'E730:') + call assert_equal('', histget(10)) + call assert_fails('call histget([])', 'E730:') + call assert_equal(-1, histnr('abc')) + call assert_fails('call histnr([])', 'E730:') + call assert_fails('history xyz', 'E488:') + call assert_fails('history ,abc', 'E488:') + call assert_fails('call histdel(":", "\\%(")', 'E53:') +endfunction + +function Test_history_truncates_long_entry() + " History entry short enough to fit on the screen should not be truncated. + call histadd(':', 'echo x' .. repeat('y', &columns - 17) .. 'z') + let a = execute('history : -1') + + call assert_match("^\n # cmd history\n" + \ .. "> *\\d\\+ echo x" .. repeat('y', &columns - 17) .. 'z$', a) + + " Long history entry should be truncated to fit on the screen, with, '...' + " inserted in the string to indicate the that there is truncation. + call histadd(':', 'echo x' .. repeat('y', &columns - 16) .. 'z') + let a = execute('history : -1') + call assert_match("^\n # cmd history\n" + \ .. "> *\\d\\+ echo xy\\+\.\.\.y\\+z$", a) +endfunction + +function Test_Search_history_window() + new + call setline(1, ['a', 'b', 'a', 'b']) + 1 + call feedkeys("/a\<CR>", 'xt') + call assert_equal('a', getline('.')) + 1 + call feedkeys("/b\<CR>", 'xt') + call assert_equal('b', getline('.')) + 1 + " select the previous /a command + call feedkeys("q/kk\<CR>", 'x!') + call assert_equal('a', getline('.')) + call assert_equal('a', @/) + bwipe! +endfunc + +" Test for :history command option completion +function Test_history_completion() + call feedkeys(":history \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"history / : = > ? @ all cmd debug expr input search', @:) +endfunc + +" Test for increasing the 'history' option value +func Test_history_size() + let save_histsz = &history + set history=10 + call histadd(':', 'ls') + call histdel(':') + for i in range(1, 5) + call histadd(':', 'cmd' .. i) + endfor + call assert_equal(5, histnr(':')) + call assert_equal('cmd5', histget(':', -1)) + + set history=15 + for i in range(6, 10) + call histadd(':', 'cmd' .. i) + endfor + call assert_equal(10, histnr(':')) + call assert_equal('cmd1', histget(':', 1)) + call assert_equal('cmd10', histget(':', -1)) + + set history=5 + call histadd(':', 'abc') + call assert_equal('', histget(':', 6)) + call assert_equal('', histget(':', 12)) + call assert_equal('cmd7', histget(':', 7)) + call assert_equal('abc', histget(':', -1)) + + " This test works only when the language is English + if v:lang == "C" || v:lang =~ '^[Ee]n' + set history=0 + redir => v + call feedkeys(":history\<CR>", 'xt') + redir END + call assert_equal(["'history' option is zero"], split(v, "\n")) + endif + + let &history=save_histsz +endfunc + +" Test for recalling old search patterns in / +func Test_history_search() + call histdel('/') + let g:pat = [] + func SavePat() + call add(g:pat, getcmdline()) + return '' + endfunc + cnoremap <F2> <C-\>eSavePat()<CR> + call histadd('/', 'pat1') + call histadd('/', 'pat2') + let @/ = '' + call feedkeys("/\<Up>\<F2>\<Up>\<F2>\<Down>\<Down>\<F2>\<Esc>", 'xt') + call assert_equal(['pat2', 'pat1', ''], g:pat) + cunmap <F2> + delfunc SavePat + + " Search for a pattern that is not present in the history + call assert_beeps('call feedkeys("/a1b2\<Up>\<CR>", "xt")') + + " Recall patterns with 'history' set to 0 + set history=0 + let @/ = 'abc' + let cmd = 'call feedkeys("/\<Up>\<Down>\<S-Up>\<S-Down>\<CR>", "xt")' + call assert_fails(cmd, 'E486:') + set history& + + " Recall patterns till the end of history + set history=4 + call histadd('/', 'pat') + call histdel('/') + call histadd('/', 'pat1') + call histadd('/', 'pat2') + call assert_beeps('call feedkeys("/\<Up>\<Up>\<Up>\<C-U>\<cr>", "xt")') + call assert_beeps('call feedkeys("/\<Down><cr>", "xt")') + + " Test for wrapping around the history list + for i in range(3, 7) + call histadd('/', 'pat' .. i) + endfor + let upcmd = "\<up>\<up>\<up>\<up>\<up>" + let downcmd = "\<down>\<down>\<down>\<down>\<down>" + try + call feedkeys("/" .. upcmd .. "\<cr>", 'xt') + catch /E486:/ + endtry + call assert_equal('pat4', @/) + try + call feedkeys("/" .. upcmd .. downcmd .. "\<cr>", 'xt') + catch /E486:/ + endtry + call assert_equal('pat4', @/) + + " Test for changing the search command separator in the history + call assert_fails('call feedkeys("/def/\<cr>", "xt")', 'E486:') + call assert_fails('call feedkeys("?\<up>\<cr>", "xt")', 'E486:') + call assert_equal('def?', histget('/', -1)) + + call assert_fails('call feedkeys("/ghi?\<cr>", "xt")', 'E486:') + call assert_fails('call feedkeys("?\<up>\<cr>", "xt")', 'E486:') + call assert_equal('ghi\?', histget('/', -1)) + + set history& +endfunc + +" Test for making sure the key value is not stored in history +func Test_history_crypt_key() + CheckFeature cryptv + + call feedkeys(":set bs=2 key=abc ts=8\<CR>", 'xt') + call assert_equal('set bs=2 key= ts=8', histget(':')) + + call assert_fails("call feedkeys(':set bs=2 key-=abc ts=8\<CR>', 'xt')") + call assert_equal('set bs=2 key-= ts=8', histget(':')) + + set key& bs& ts& +endfunc + +" The following used to overflow and causing an use-after-free +func Test_history_max_val() + + set history=10 + call assert_fails(':history 2147483648', 'E1510:') + set history& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_hlsearch.vim b/test/old/testdir/test_hlsearch.vim new file mode 100644 index 0000000000..fb1695220a --- /dev/null +++ b/test/old/testdir/test_hlsearch.vim @@ -0,0 +1,107 @@ +" Test for v:hlsearch + +source check.vim +source screendump.vim + +func Test_hlsearch() + new + call setline(1, repeat(['aaa'], 10)) + set hlsearch nolazyredraw + " redraw is needed to make hlsearch highlight the matches + exe "normal! /aaa\<CR>" | redraw + let r1 = screenattr(1, 1) + nohlsearch | redraw + call assert_notequal(r1, screenattr(1,1)) + let v:hlsearch=1 | redraw + call assert_equal(r1, screenattr(1,1)) + let v:hlsearch=0 | redraw + call assert_notequal(r1, screenattr(1,1)) + set hlsearch | redraw + call assert_equal(r1, screenattr(1,1)) + let v:hlsearch=0 | redraw + call assert_notequal(r1, screenattr(1,1)) + exe "normal! n" | redraw + call assert_equal(r1, screenattr(1,1)) + let v:hlsearch=0 | redraw + call assert_notequal(r1, screenattr(1,1)) + exe "normal! /\<CR>" | redraw + call assert_equal(r1, screenattr(1,1)) + set nohls + exe "normal! /\<CR>" | redraw + call assert_notequal(r1, screenattr(1,1)) + call assert_fails('let v:hlsearch=[]', 'E745') + call garbagecollect(1) + call getchar(1) + enew! +endfunc + +func Test_hlsearch_hangs() + if !has('reltime') || !has('float') + return + endif + + " This pattern takes a long time to match, it should timeout. + new + call setline(1, ['aaa', repeat('abc ', 100000), 'ccc']) + let start = reltime() + set hlsearch nolazyredraw redrawtime=101 + let @/ = '\%#=1a*.*X\@<=b*' + redraw + let elapsed = reltimefloat(reltime(start)) + call assert_true(elapsed > 0.1) + call assert_true(elapsed < 1.0) + set nohlsearch redrawtime& + bwipe! +endfunc + +func Test_hlsearch_eol_highlight() + new + call append(1, repeat([''], 9)) + set hlsearch nolazyredraw + exe "normal! /$\<CR>" | redraw + let attr = screenattr(1, 1) + for row in range(2, 10) + call assert_equal(attr, screenattr(row, 1), 'in line ' . row) + endfor + set nohlsearch + bwipe! +endfunc + +func Test_hlsearch_Ctrl_R() + CheckRunVimInTerminal + + let lines =<< trim END + set incsearch hlsearch + let @" = "text" + put + END + call writefile(lines, 'XhlsearchCtrlR', 'D') + let buf = RunVimInTerminal('-S XhlsearchCtrlR', #{rows: 6, cols: 60}) + + call term_sendkeys(buf, "/\<C-R>\<C-R>\"") + call VerifyScreenDump(buf, 'Test_hlsearch_ctrlr_1', {}) + + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) +endfunc + +func Test_hlsearch_clipboard() + CheckRunVimInTerminal + CheckFeature clipboard_working + + let lines =<< trim END + set incsearch hlsearch + let @* = "text" + put * + END + call writefile(lines, 'XhlsearchClipboard', 'D') + let buf = RunVimInTerminal('-S XhlsearchClipboard', #{rows: 6, cols: 60}) + + call term_sendkeys(buf, "/\<C-R>*") + call VerifyScreenDump(buf, 'Test_hlsearch_ctrlr_1', {}) + + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_increment.vim b/test/old/testdir/test_increment.vim new file mode 100644 index 0000000000..433b2b4471 --- /dev/null +++ b/test/old/testdir/test_increment.vim @@ -0,0 +1,913 @@ +" Tests for using Ctrl-A/Ctrl-X + +func SetUp() + new dummy + set nrformats&vim + set nrformats+=octal +endfunc + +func TearDown() + bwipe! +endfunc + +" 1) Ctrl-A on visually selected number +" Text: +" foobar-10 +" Expected: +" 1) Ctrl-A on start of line: +" foobar-9 +" 2) Ctrl-A on visually selected "-10": +" foobar-9 +" 3) Ctrl-A on visually selected "10": +" foobar-11 +" 4) Ctrl-X on visually selected "-10" +" foobar-11 +" 5) Ctrl-X on visually selected "10" +" foobar-9 +func Test_visual_increment_01() + call setline(1, repeat(["foobaar-10"], 5)) + + call cursor(1, 1) + exec "norm! \<C-A>" + call assert_equal("foobaar-9", getline('.')) + call assert_equal([0, 1, 9, 0], getpos('.')) + + call cursor(2, 1) + exec "norm! f-v$\<C-A>" + call assert_equal("foobaar-9", getline('.')) + call assert_equal([0, 2, 8, 0], getpos('.')) + + call cursor(3, 1) + exec "norm! f1v$\<C-A>" + call assert_equal("foobaar-11", getline('.')) + call assert_equal([0, 3, 9, 0], getpos('.')) + + call cursor(4, 1) + exec "norm! f-v$\<C-X>" + call assert_equal("foobaar-11", getline('.')) + call assert_equal([0, 4, 8, 0], getpos('.')) + + call cursor(5, 1) + exec "norm! f1v$\<C-X>" + call assert_equal("foobaar-9", getline('.')) + call assert_equal([0, 5, 9, 0], getpos('.')) +endfunc + +" 2) Ctrl-A on visually selected lines +" Text: +" 10 +" 20 +" 30 +" 40 +" +" Expected: +" 1) Ctrl-A on visually selected lines: +" 11 +" 21 +" 31 +" 41 +" +" 2) Ctrl-X on visually selected lines: +" 9 +" 19 +" 29 +" 39 +func Test_visual_increment_02() + call setline(1, ["10", "20", "30", "40"]) + exec "norm! GV3k$\<C-A>" + call assert_equal(["11", "21", "31", "41"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + call setline(1, ["10", "20", "30", "40"]) + exec "norm! GV3k$\<C-X>" + call assert_equal(["9", "19", "29", "39"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 3) g Ctrl-A on visually selected lines, with non-numbers in between +" Text: +" 10 +" +" 20 +" +" 30 +" +" 40 +" +" Expected: +" 1) 2 g Ctrl-A on visually selected lines: +" 12 +" +" 24 +" +" 36 +" +" 48 +" 2) 2 g Ctrl-X on visually selected lines +" 8 +" +" 16 +" +" 24 +" +" 32 +func Test_visual_increment_03() + call setline(1, ["10", "", "20", "", "30", "", "40"]) + exec "norm! GV6k2g\<C-A>" + call assert_equal(["12", "", "24", "", "36", "", "48"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + call setline(1, ["10", "", "20", "", "30", "", "40"]) + exec "norm! GV6k2g\<C-X>" + call assert_equal(["8", "", "16", "", "24", "", "32"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 4) Ctrl-A on non-number +" Text: +" foobar-10 +" Expected: +" 1) visually select foobar: +" foobar-10 +func Test_visual_increment_04() + call setline(1, ["foobar-10"]) + exec "norm! vf-\<C-A>" + call assert_equal(["foobar-10"], getline(1, '$')) + " NOTE: I think this is correct behavior... + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 5) g<Ctrl-A> on letter +" Test: +" a +" a +" a +" a +" Expected: +" 1) g Ctrl-A on visually selected lines +" b +" c +" d +" e +func Test_visual_increment_05() + set nrformats+=alpha + call setline(1, repeat(["a"], 4)) + exec "norm! GV3kg\<C-A>" + call assert_equal(["b", "c", "d", "e"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 6) g<Ctrl-A> on letter +" Test: +" z +" z +" z +" z +" Expected: +" 1) g Ctrl-X on visually selected lines +" y +" x +" w +" v +func Test_visual_increment_06() + set nrformats+=alpha + call setline(1, repeat(["z"], 4)) + exec "norm! GV3kg\<C-X>" + call assert_equal(["y", "x", "w", "v"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 7) <Ctrl-A> on letter +" Test: +" 2 +" 1 +" 0 +" -1 +" -2 +" +" Expected: +" 1) Ctrl-A on visually selected lines +" 3 +" 2 +" 1 +" 0 +" -1 +" +" 2) Ctrl-X on visually selected lines +" 1 +" 0 +" -1 +" -2 +" -3 +func Test_visual_increment_07() + call setline(1, ["2", "1", "0", "-1", "-2"]) + exec "norm! GV4k\<C-A>" + call assert_equal(["3", "2", "1", "0", "-1"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + call setline(1, ["2", "1", "0", "-1", "-2"]) + exec "norm! GV4k\<C-X>" + call assert_equal(["1", "0", "-1", "-2", "-3"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 8) Block increment on 0x9 +" Text: +" 0x9 +" 0x9 +" Expected: +" 1) Ctrl-A on visually block selected region (cursor at beginning): +" 0xa +" 0xa +" 2) Ctrl-A on visually block selected region (cursor at end) +" 0xa +" 0xa +func Test_visual_increment_08() + call setline(1, repeat(["0x9"], 2)) + exec "norm! \<C-V>j$\<C-A>" + call assert_equal(["0xa", "0xa"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + call setline(1, repeat(["0x9"], 2)) + exec "norm! gg$\<C-V>+\<C-A>" + call assert_equal(["0xa", "0xa"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 9) Increment and redo +" Text: +" 2 +" 2 +" +" 3 +" 3 +" +" Expected: +" 1) 2 Ctrl-A on first 2 visually selected lines +" 4 +" 4 +" 2) redo (.) on 3 +" 5 +" 5 +func Test_visual_increment_09() + call setline(1, ["2", "2", "", "3", "3", ""]) + exec "norm! ggVj2\<C-A>" + call assert_equal(["4", "4", "", "3", "3", ""], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + exec "norm! 3j." + call assert_equal(["4", "4", "", "5", "5", ""], getline(1, '$')) + call assert_equal([0, 4, 1, 0], getpos('.')) +endfunc + +" 10) sequentially decrement 1 +" Text: +" 1 +" 1 +" 1 +" 1 +" Expected: +" 1) g Ctrl-X on visually selected lines +" 0 +" -1 +" -2 +" -3 +func Test_visual_increment_10() + call setline(1, repeat(["1"], 4)) + exec "norm! GV3kg\<C-X>" + call assert_equal(["0", "-1", "-2", "-3"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 11) visually block selected indented lines +" Text: +" 1 +" 1 +" 1 +" 1 +" Expected: +" 1) g Ctrl-A on block selected indented lines +" 2 +" 1 +" 3 +" 4 +func Test_visual_increment_11() + call setline(1, [" 1", "1", " 1", " 1"]) + exec "norm! f1\<C-V>3jg\<C-A>" + call assert_equal([" 2", "1", " 3", " 4"], getline(1, '$')) + call assert_equal([0, 1, 5, 0], getpos('.')) +endfunc + +" 12) visually selected several columns +" Text: +" 0 0 +" 0 0 +" 0 0 +" Expected: +" 1) 'v' select last zero and first zeroes +" 0 1 +" 1 0 +" 1 0 +func Test_visual_increment_12() + call setline(1, repeat(["0 0"], 3)) + exec "norm! $v++\<C-A>" + call assert_equal(["0 1", "1 0", "1 0"], getline(1, '$')) + call assert_equal([0, 1, 3, 0], getpos('.')) +endfunc + +" 13) visually selected part of columns +" Text: +" max: 100px +" max: 200px +" max: 300px +" max: 400px +" Expected: +" 1) 'v' on first two numbers Ctrl-A +" max: 110px +" max: 220px +" max: 330px +" max: 400px +" 2) 'v' on first two numbers Ctrl-X +" max: 90px +" max: 190px +" max: 290px +" max: 400px +func Test_visual_increment_13() + call setline(1, ["max: 100px", "max: 200px", "max: 300px", "max: 400px"]) + exec "norm! f1\<C-V>l2j\<C-A>" + call assert_equal(["max: 110px", "max: 210px", "max: 310px", "max: 400px"], getline(1, '$')) + call assert_equal([0, 1, 6, 0], getpos('.')) + + call setline(1, ["max: 100px", "max: 200px", "max: 300px", "max: 400px"]) + exec "norm! ggf1\<C-V>l2j\<C-X>" + call assert_equal(["max: 90px", "max: 190px", "max: 290px", "max: 400px"], getline(1, '$')) + call assert_equal([0, 1, 6, 0], getpos('.')) +endfunc + +" 14) redo in block mode +" Text: +" 1 1 +" 1 1 +" Expected: +" 1) Ctrl-a on first column, redo on second column +" 2 2 +" 2 2 +func Test_visual_increment_14() + call setline(1, repeat(["1 1"], 2)) + exec "norm! G\<C-V>k\<C-A>w." + call assert_equal(["2 2", "2 2"], getline(1, '$')) + call assert_equal([0, 1, 3, 0], getpos('.')) +endfunc + +" 15) block select single numbers +" Text: +" 101 +" Expected: +" 1) Ctrl-a on visually selected zero +" 111 +" +" Also: 019 with "01" selected increments to "029". +func Test_visual_increment_15() + call setline(1, ["101"]) + exec "norm! lv\<C-A>" + call assert_equal(["111"], getline(1, '$')) + call assert_equal([0, 1, 2, 0], getpos('.')) + + call setline(1, ["019"]) + exec "norm! 0vl\<C-A>" + call assert_equal("029", getline(1)) + + call setline(1, ["01239"]) + exec "norm! 0vlll\<C-A>" + call assert_equal("01249", getline(1)) + + call setline(1, ["01299"]) + exec "norm! 0vlll\<C-A>" + call assert_equal("1309", getline(1)) +endfunc + +" 16) increment right aligned numbers +" Text: +" 1 +" 19 +" 119 +" Expected: +" 1) Ctrl-a on line selected region +" 2 +" 20 +" 120 +func Test_visual_increment_16() + call setline(1, [" 1", " 19", " 119"]) + exec "norm! VG\<C-A>" + call assert_equal([" 2", " 20", " 120"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 17) block-wise increment and redo +" Text: +" 100 +" 1 +" +" 100 +" 1 +" +" Expected: +" 1) Ctrl-V j $ on first block, afterwards '.' on second +" 101 +" 2 +" +" 101 +" 2 +func Test_visual_increment_17() + call setline(1, [" 100", " 1", "", " 100", " 1"]) + exec "norm! \<C-V>j$\<C-A>2j." + call assert_equal([" 101", " 2", "", " 101", " 1"], getline(1, '$')) + call assert_equal([0, 3, 1, 0], getpos('.')) +endfunc + +" 18) repeat of g<Ctrl-a> +" Text: +" 0 +" 0 +" 0 +" 0 +" +" Expected: +" 1) V 4j g<ctrl-a>, repeat twice afterwards with . +" 3 +" 6 +" 9 +" 12 +func Test_visual_increment_18() + call setline(1, repeat(["0"], 4)) + exec "norm! GV3kg\<C-A>" + exec "norm! .." + call assert_equal(["3", "6", "9", "12"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 19) increment on number with nrformat including alpha +" Text: +" 1 +" 1a +" +" Expected: +" 1) <Ctrl-V>j$ <ctrl-a> +" 2 +" 2a +func Test_visual_increment_19() + set nrformats+=alpha + call setline(1, ["1", "1a"]) + exec "norm! \<C-V>G$\<C-A>" + call assert_equal(["2", "2a"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 20) increment a single letter +" Text: +" a +" +" Expected: +" 1) <Ctrl-a> and cursor is on a +" b +func Test_visual_increment_20() + set nrformats+=alpha + call setline(1, ["a"]) + exec "norm! \<C-A>" + call assert_equal(["b"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + " decrement a and A and increment z and Z + call setline(1, ['a', 'A', 'z', 'Z']) + exe "normal 1G\<C-X>2G\<C-X>3G\<C-A>4G\<C-A>" + call assert_equal(['a', 'A', 'z', 'Z'], getline(1, '$')) +endfunc + +" 21) block-wise increment on part of hexadecimal +" Text: +" 0x123456 +" +" Expected: +" 1) Ctrl-V f3 <ctrl-a> +" 0x124456 +func Test_visual_increment_21() + call setline(1, ["0x123456"]) + exec "norm! \<C-V>f3\<C-A>" + call assert_equal(["0x124456"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 22) Block increment on 0b0 +" Text: +" 0b1 +" 0b1 +" Expected: +" 1) Ctrl-A on visually block selected region (cursor at beginning): +" 0b10 +" 0b10 +" 2) Ctrl-A on visually block selected region (cursor at end) +" 0b10 +" 0b10 +func Test_visual_increment_22() + call setline(1, repeat(["0b1"], 2)) + exec "norm! \<C-V>j$\<C-A>" + call assert_equal(repeat(["0b10"], 2), getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + call setline(1, repeat(["0b1"], 2)) + exec "norm! $\<C-V>+\<C-A>" + call assert_equal(repeat(["0b10"], 2), getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 23) block-wise increment on part of binary +" Text: +" 0b1001 +" +" Expected: +" 1) Ctrl-V 5l <ctrl-a> +" 0b1011 +func Test_visual_increment_23() + call setline(1, ["0b1001"]) + exec "norm! \<C-V>4l\<C-A>" + call assert_equal(["0b1011"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 24) increment hexadecimal +" Text: +" 0x0b1001 +" +" Expected: +" 1) <ctrl-a> +" 0x0b1002 +func Test_visual_increment_24() + call setline(1, ["0x0b1001"]) + exec "norm! \<C-V>$\<C-A>" + call assert_equal(["0x0b1002"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 25) increment binary with nrformats including alpha +" Text: +" 0b1001a +" +" Expected: +" 1) <ctrl-a> +" 0b1010a +func Test_visual_increment_25() + set nrformats+=alpha + call setline(1, ["0b1001a"]) + exec "norm! \<C-V>$\<C-A>" + call assert_equal(["0b1010a"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" 26) increment binary with 32 bits +" Text: +" 0b11111111111111111111111111111110 +" +" Expected: +" 1) <ctrl-a> +" 0b11111111111111111111111111111111 +func Test_visual_increment_26() + set nrformats+=bin + call setline(1, ["0b11111111111111111111111111111110"]) + exec "norm! \<C-V>$\<C-A>" + call assert_equal(["0b11111111111111111111111111111111"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + exec "norm! \<C-V>$\<C-X>" + call assert_equal(["0b11111111111111111111111111111110"], getline(1, '$')) + set nrformats-=bin +endfunc + +" 27) increment with 'rightreft', if supported +func Test_visual_increment_27() + if exists('+rightleft') + set rightleft + call setline(1, ["1234 56"]) + + exec "norm! $\<C-A>" + call assert_equal(["1234 57"], getline(1, '$')) + call assert_equal([0, 1, 7, 0], getpos('.')) + + exec "norm! \<C-A>" + call assert_equal(["1234 58"], getline(1, '$')) + call assert_equal([0, 1, 7, 0], getpos('.')) + set norightleft + endif +endfunc + +" Tab code and linewise-visual inc/dec +func Test_visual_increment_28() + call setline(1, ["x\<TAB>10", "\<TAB>-1"]) + exec "norm! Vj\<C-A>" + call assert_equal(["x\<TAB>11", "\<TAB>0"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + call setline(1, ["x\<TAB>10", "\<TAB>-1"]) + exec "norm! ggVj\<C-X>" + call assert_equal(["x\<TAB>9", "\<TAB>-2"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" Tab code and linewise-visual inc/dec with 'nrformats'+=alpha +func Test_visual_increment_29() + set nrformats+=alpha + call setline(1, ["x\<TAB>10", "\<TAB>-1"]) + exec "norm! Vj\<C-A>" + call assert_equal(["y\<TAB>10", "\<TAB>0"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + call setline(1, ["x\<TAB>10", "\<TAB>-1"]) + exec "norm! ggVj\<C-X>" + call assert_equal(["w\<TAB>10", "\<TAB>-2"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" Tab code and character-visual inc/dec +func Test_visual_increment_30() + call setline(1, ["x\<TAB>10", "\<TAB>-1"]) + exec "norm! f1vjf1\<C-A>" + call assert_equal(["x\<TAB>11", "\<TAB>0"], getline(1, '$')) + call assert_equal([0, 1, 3, 0], getpos('.')) + + call setline(1, ["x\<TAB>10", "\<TAB>-1"]) + exec "norm! ggf1vjf1\<C-X>" + call assert_equal(["x\<TAB>9", "\<TAB>-2"], getline(1, '$')) + call assert_equal([0, 1, 3, 0], getpos('.')) +endfunc + +" Tab code and blockwise-visual inc/dec +func Test_visual_increment_31() + call setline(1, ["x\<TAB>10", "\<TAB>-1"]) + exec "norm! f1\<C-V>jl\<C-A>" + call assert_equal(["x\<TAB>11", "\<TAB>0"], getline(1, '$')) + call assert_equal([0, 1, 3, 0], getpos('.')) + + call setline(1, ["x\<TAB>10", "\<TAB>-1"]) + exec "norm! ggf1\<C-V>jl\<C-X>" + call assert_equal(["x\<TAB>9", "\<TAB>-2"], getline(1, '$')) + call assert_equal([0, 1, 3, 0], getpos('.')) +endfunc + +" Tab code and blockwise-visual decrement with 'linebreak' and 'showbreak' +func Test_visual_increment_32() + 28vnew dummy_31 + set linebreak showbreak=+ + call setline(1, ["x\<TAB>\<TAB>\<TAB>10", "\<TAB>\<TAB>\<TAB>\<TAB>-1"]) + exec "norm! ggf0\<C-V>jg_\<C-X>" + call assert_equal(["x\<TAB>\<TAB>\<TAB>1-1", "\<TAB>\<TAB>\<TAB>\<TAB>-2"], getline(1, '$')) + call assert_equal([0, 1, 6, 0], getpos('.')) + bwipe! +endfunc + +" Tab code and blockwise-visual increment with $ +func Test_visual_increment_33() + call setline(1, ["\<TAB>123", "456"]) + exec "norm! gg0\<C-V>j$\<C-A>" + call assert_equal(["\<TAB>124", "457"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" Tab code and blockwise-visual increment and redo +func Test_visual_increment_34() + call setline(1, ["\<TAB>123", " 456789"]) + exec "norm! gg0\<C-V>j\<C-A>" + call assert_equal(["\<TAB>123", " 457789"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + exec "norm! .." + call assert_equal(["\<TAB>123", " 459789"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" Tab code, spaces and character-visual increment and redo +func Test_visual_increment_35() + call setline(1, ["\<TAB>123", " 123", "\<TAB>123", "\<TAB>123"]) + exec "norm! ggvjf3\<C-A>..." + call assert_equal(["\<TAB>127", " 127", "\<TAB>123", "\<TAB>123"], getline(1, '$')) + call assert_equal([0, 1, 2, 0], getpos('.')) +endfunc + +" Tab code, spaces and blockwise-visual increment and redo +func Test_visual_increment_36() + call setline(1, [" 123", "\<TAB>456789"]) + exec "norm! G0\<C-V>kl\<C-A>" + call assert_equal([" 123", "\<TAB>556789"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) + + exec "norm! ..." + call assert_equal([" 123", "\<TAB>856789"], getline(1, '$')) + call assert_equal([0, 1, 1, 0], getpos('.')) +endfunc + +" block-wise increment and dot-repeat +" Text: +" 1 23 +" 4 56 +" +" Expected: +" 1) f2 Ctrl-V jl <ctrl-a>, repeat twice afterwards with . +" 1 26 +" 4 59 +" +" Try with and without indent. +func Test_visual_increment_37() + call setline(1, [" 1 23", " 4 56"]) + exec "norm! ggf2\<C-V>jl\<C-A>.." + call assert_equal([" 1 26", " 4 59"], getline(1, 2)) + + call setline(1, ["1 23", "4 56"]) + exec "norm! ggf2\<C-V>jl\<C-A>.." + call assert_equal(["1 26", "4 59"], getline(1, 2)) +endfunc + +" Check redo after the normal mode increment +func Test_visual_increment_38() + exec "norm! i10\<ESC>5\<C-A>." + call assert_equal(["20"], getline(1, '$')) + call assert_equal([0, 1, 2, 0], getpos('.')) +endfunc + +" Test what patch 7.3.414 fixed. Ctrl-A on "000" drops the leading zeros. +func Test_normal_increment_01() + call setline(1, "000") + exec "norm! gg0\<C-A>" + call assert_equal("001", getline(1)) + + call setline(1, "000") + exec "norm! gg$\<C-A>" + call assert_equal("001", getline(1)) + + call setline(1, "001") + exec "norm! gg0\<C-A>" + call assert_equal("002", getline(1)) + + call setline(1, "001") + exec "norm! gg$\<C-A>" + call assert_equal("002", getline(1)) +endfunc + +" Test a regression of patch 7.4.1087 fixed. +func Test_normal_increment_02() + call setline(1, ["hello 10", "world"]) + exec "norm! ggl\<C-A>jx" + call assert_equal(["hello 11", "worl"], getline(1, '$')) + call assert_equal([0, 2, 4, 0], getpos('.')) +endfunc + +" The test35 unified to this file. +func Test_normal_increment_03() + call setline(1, ["100 0x100 077 0", + \ "100 0x100 077 ", + \ "100 0x100 077 0xfF 0xFf", + \ "100 0x100 077 "]) + set nrformats=octal,hex + exec "norm! gg\<C-A>102\<C-X>\<C-A>l\<C-X>l\<C-A>64\<C-A>128\<C-X>$\<C-X>" + set nrformats=octal + exec "norm! j0\<C-A>102\<C-X>\<C-A>l\<C-X>2\<C-A>w65\<C-A>129\<C-X>blx6lD" + set nrformats=hex + exec "norm! j0101\<C-X>l257\<C-X>\<C-A>Txldt \<C-A> \<C-X> \<C-X>" + set nrformats= + exec "norm! j0200\<C-X>l100\<C-X>w78\<C-X>\<C-A>k" + call assert_equal(["0 0x0ff 0000 -1", + \ "0 1x100 0777777", + \ "-1 0x0 078 0xFE 0xfe", + \ "-100 -100x100 000 "], getline(1, '$')) + call assert_equal([0, 3, 25, 0], getpos('.')) +endfunc + +func Test_increment_empty_line() + call setline(1, ['0', '0', '0', '0', '0', '0', '']) + exe "normal Gvgg\<C-A>" + call assert_equal(['1', '1', '1', '1', '1', '1', ''], getline(1, 7)) + + " Ctrl-A/Ctrl-X should do nothing in operator pending mode + %d + call setline(1, 'one two') + exe "normal! c\<C-A>l" + exe "normal! c\<C-X>l" + call assert_equal('one two', getline(1)) +endfunc + +" Try incrementing/decrementing a non-digit/alpha character +func Test_increment_special_char() + call setline(1, '!') + call assert_beeps("normal \<C-A>") + call assert_beeps("normal \<C-X>") +endfunc + +" Try incrementing/decrementing a number when nrformats contains unsigned +func Test_increment_unsigned() + set nrformats+=unsigned + + call setline(1, '0') + exec "norm! gg0\<C-X>" + call assert_equal('0', getline(1)) + + call setline(1, '3') + exec "norm! gg010\<C-X>" + call assert_equal('0', getline(1)) + + call setline(1, '-0') + exec "norm! gg0\<C-X>" + call assert_equal("-0", getline(1)) + + call setline(1, '-11') + exec "norm! gg08\<C-X>" + call assert_equal('-3', getline(1)) + + " NOTE: 18446744073709551615 == 2^64 - 1 + call setline(1, '18446744073709551615') + exec "norm! gg0\<C-A>" + call assert_equal('18446744073709551615', getline(1)) + + call setline(1, '-18446744073709551615') + exec "norm! gg0\<C-A>" + call assert_equal('-18446744073709551615', getline(1)) + + call setline(1, '-18446744073709551614') + exec "norm! gg08\<C-A>" + call assert_equal('-18446744073709551615', getline(1)) + + call setline(1, '-1') + exec "norm! gg0\<C-A>" + call assert_equal('-2', getline(1)) + + call setline(1, '-3') + exec "norm! gg08\<C-A>" + call assert_equal('-11', getline(1)) + + set nrformats-=unsigned +endfunc + +func Test_in_decrement_large_number() + " NOTE: 18446744073709551616 == 2^64 + call setline(1, '18446744073709551616') + exec "norm! gg0\<C-X>" + call assert_equal('18446744073709551615', getline(1)) + + exec "norm! gg0\<C-X>" + call assert_equal('18446744073709551614', getline(1)) + + exec "norm! gg0\<C-A>" + call assert_equal('18446744073709551615', getline(1)) + + exec "norm! gg0\<C-A>" + call assert_equal('-18446744073709551615', getline(1)) +endfunc + +func Test_normal_increment_with_virtualedit() + set virtualedit=all + + call setline(1, ["\<TAB>1"]) + exec "norm! 0\<C-A>" + call assert_equal("\<TAB>2", getline(1)) + call assert_equal([0, 1, 2, 0], getpos('.')) + + call setline(1, ["\<TAB>1"]) + exec "norm! 0l\<C-A>" + call assert_equal("\<TAB>2", getline(1)) + call assert_equal([0, 1, 2, 0], getpos('.')) + + call setline(1, ["\<TAB>1"]) + exec "norm! 07l\<C-A>" + call assert_equal("\<TAB>2", getline(1)) + call assert_equal([0, 1, 2, 0], getpos('.')) + + call setline(1, ["\<TAB>1"]) + exec "norm! 0w\<C-A>" + call assert_equal("\<TAB>2", getline(1)) + call assert_equal([0, 1, 2, 0], getpos('.')) + + call setline(1, ["\<TAB>1"]) + exec "norm! 0wl\<C-A>" + call assert_equal("\<TAB>1", getline(1)) + call assert_equal([0, 1, 3, 0], getpos('.')) + + call setline(1, ["\<TAB>1"]) + exec "norm! 0w30l\<C-A>" + call assert_equal("\<TAB>1", getline(1)) + call assert_equal([0, 1, 3, 29], getpos('.')) + + set virtualedit& +endfunc + +" Test for incrementing a signed hexadecimal and octal number +func Test_normal_increment_signed_hexoct_nr() + new + " negative sign before a hex number should be ignored + call setline(1, ["-0x9"]) + exe "norm \<C-A>" + call assert_equal(["-0xa"], getline(1, '$')) + exe "norm \<C-X>" + call assert_equal(["-0x9"], getline(1, '$')) + call setline(1, ["-007"]) + exe "norm \<C-A>" + call assert_equal(["-010"], getline(1, '$')) + exe "norm \<C-X>" + call assert_equal(["-007"], getline(1, '$')) + bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_increment_dbcs.vim b/test/old/testdir/test_increment_dbcs.vim new file mode 100644 index 0000000000..e5d5ccffb3 --- /dev/null +++ b/test/old/testdir/test_increment_dbcs.vim @@ -0,0 +1,31 @@ +" Tests for using Ctrl-A/Ctrl-X using DBCS. +" neovim needs an iconv to handle cp932. Please do not remove the following +" conditions. +if !has('iconv') + finish +endif +scriptencoding cp932 + +func SetUp() + new + set nrformats& +endfunc + +func TearDown() + bwipe! +endfunc + +func Test_increment_dbcs_1() + set nrformats+=alpha + call setline(1, ["R1"]) + exec "norm! 0\<C-A>" + call assert_equal(["R2"], getline(1, '$')) + call assert_equal([0, 1, 4, 0], getpos('.')) + + call setline(1, ["`ab0xDEe"]) + exec "norm! 0\<C-X>" + call assert_equal(["`ab0xDDe"], getline(1, '$')) + call assert_equal([0, 1, 13, 0], getpos('.')) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_indent.vim b/test/old/testdir/test_indent.vim new file mode 100644 index 0000000000..3b5b643177 --- /dev/null +++ b/test/old/testdir/test_indent.vim @@ -0,0 +1,279 @@ +" Test for various indent options + +func Test_preserveindent() + new + " Test for autoindent copying indent from the previous line + setlocal autoindent + call setline(1, [repeat(' ', 16) .. 'line1']) + call feedkeys("A\nline2", 'xt') + call assert_equal("\t\tline2", getline(2)) + setlocal autoindent& + + " Test for using CTRL-T with and without 'preserveindent' + set shiftwidth=4 + call cursor(1, 1) + call setline(1, " \t ") + call feedkeys("Al\<C-T>", 'xt') + call assert_equal("\t\tl", getline(1)) + set preserveindent + call setline(1, " \t ") + call feedkeys("Al\<C-T>", 'xt') + call assert_equal(" \t \tl", getline(1)) + set pi& sw& + + " Test for using CTRL-T with 'expandtab' and 'preserveindent' + call cursor(1, 1) + call setline(1, "\t \t") + set shiftwidth=4 expandtab preserveindent + call feedkeys("Al\<C-T>", 'xt') + call assert_equal("\t \t l", getline(1)) + set sw& et& pi& + + close! +endfunc + +" Test for indent() +func Test_indent_func() + call assert_equal(-1, indent(-1)) + new + call setline(1, "\tabc") + call assert_equal(8, indent(1)) + call setline(1, " abc") + call assert_equal(4, indent(1)) + call setline(1, " \t abc") + call assert_equal(12, indent(1)) + close! +endfunc + +" Test for reindenting a line using the '=' operator +func Test_reindent() + new + call setline(1, 'abc') + set nomodifiable + call assert_fails('normal ==', 'E21:') + set modifiable + + call setline(1, ['foo', 'bar']) + call feedkeys('ggVG=', 'xt') + call assert_equal(['foo', 'bar'], getline(1, 2)) + close! +endfunc + +" Test indent operator creating one undo entry +func Test_indent_operator_undo() + enew + call setline(1, range(12)->map('"\t" .. v:val')) + func FoldExpr() + let g:foldcount += 1 + return '=' + endfunc + set foldmethod=expr foldexpr=FoldExpr() + let g:foldcount = 0 + redraw + call assert_equal(12, g:foldcount) + normal gg=G + call assert_equal(24, g:foldcount) + undo + call assert_equal(38, g:foldcount) + + bwipe! + set foldmethod& foldexpr= + delfunc FoldExpr + unlet g:foldcount +endfunc + +" Test for shifting a line with a preprocessor directive ('#') +func Test_preproc_indent() + new + set sw=4 + call setline(1, '#define FOO 1') + normal >> + call assert_equal(' #define FOO 1', getline(1)) + + " with 'smartindent' + call setline(1, '#define FOO 1') + set smartindent + normal >> + call assert_equal('#define FOO 1', getline(1)) + set smartindent& + + " with 'cindent' + set cindent + normal >> + call assert_equal('#define FOO 1', getline(1)) + set cindent& + + close! +endfunc + +" Test for 'copyindent' +func Test_copyindent() + new + set shiftwidth=4 autoindent expandtab copyindent + call setline(1, " \t abc") + call feedkeys("ol", 'xt') + call assert_equal(" \t l", getline(2)) + set noexpandtab + call setline(1, " \t abc") + call feedkeys("ol", 'xt') + call assert_equal(" \t l", getline(2)) + set sw& ai& et& ci& + close! +endfunc + +" Test for changing multiple lines with lisp indent +func Test_lisp_indent_change_multiline() + new + setlocal lisp autoindent + call setline(1, ['(if a', ' (if b', ' (return 5)))']) + normal! jc2j(return 4)) + call assert_equal(' (return 4))', getline(2)) + close! +endfunc + +func Test_lisp_indent() + new + setlocal lisp autoindent + call setline(1, ['(if a', ' ;; comment', ' \ abc', '', ' " str1\', ' " st\b', ' (return 5)']) + normal! jo;; comment + normal! jo\ abc + normal! jo;; ret + normal! jostr1" + normal! jostr2" + call assert_equal([' ;; comment', ' ;; comment', ' \ abc', ' \ abc', '', ' ;; ret', ' " str1\', ' str1"', ' " st\b', ' str2"'], getline(2, 11)) + close! +endfunc + +func Test_lisp_indent_quoted() + " This was going past the end of the line + new + setlocal lisp autoindent + call setline(1, ['"[', '=']) + normal Gvk= + + bwipe! +endfunc + +" Test for setting the 'indentexpr' from a modeline +func Test_modeline_indent_expr() + let modeline = &modeline + set modeline + func GetIndent() + return line('.') * 2 + endfunc + call writefile(['# vim: indentexpr=GetIndent()'], 'Xfile.txt') + set modelineexpr + new Xfile.txt + call assert_equal('GetIndent()', &indentexpr) + exe "normal Oa\nb\n" + call assert_equal([' a', ' b'], getline(1, 2)) + + set modelineexpr& + delfunc GetIndent + let &modeline = modeline + close! + call delete('Xfile.txt') +endfunc + +func Test_indent_func_with_gq() + + function GetTeXIndent() + " Sample indent expression for TeX files + let lnum = prevnonblank(v:lnum - 1) + " At the start of the file use zero indent. + if lnum == 0 + return 0 + endif + let line = getline(lnum) + let ind = indent(lnum) + " Add a 'shiftwidth' after beginning of environments. + if line =~ '\\begin{center}' + let ind = ind + shiftwidth() + endif + return ind + endfunction + + new + setl et sw=2 sts=2 ts=2 tw=50 indentexpr=GetTeXIndent() + put =[ '\documentclass{article}', '', '\begin{document}', '', + \ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ut enim non', + \ 'libero efficitur aliquet. Maecenas metus justo, facilisis convallis blandit', + \ 'non, semper eu urna. Suspendisse diam diam, iaculis faucibus lorem eu,', + \ 'fringilla condimentum lectus. Quisque euismod diam at convallis vulputate.', + \ 'Pellentesque laoreet tortor sit amet mauris euismod ornare. Sed varius', + \ 'bibendum orci vel vehicula. Pellentesque tempor, ipsum et auctor accumsan,', + \ 'metus lectus ultrices odio, sed elementum mi ante at arcu.', '', '\begin{center}', '', + \ 'Proin nec risus consequat nunc dapibus consectetur. Mauris lacinia est a augue', + \ 'tristique accumsan. Morbi pretium, felis molestie eleifend condimentum, arcu', + \ 'ipsum congue nisl, quis euismod purus libero in ante.', '', + \ 'Donec id semper purus.', + \ 'Suspendisse eget aliquam nunc. Maecenas fringilla mauris vitae maximus', + \ 'condimentum. Cras a quam in mi dictum eleifend at a lorem. Sed convallis', + \ 'ante a commodo facilisis. Nam suscipit vulputate odio, vel dapibus nisl', + \ 'dignissim facilisis. Vestibulum ante ipsum primis in faucibus orci luctus et', + \ 'ultrices posuere cubilia curae;', '', ''] + 1d_ + call cursor(5, 1) + ka + call cursor(14, 1) + kb + norm! 'agqap + norm! 'bgqG + let expected = [ '\documentclass{article}', '', '\begin{document}', '', + \ 'Lorem ipsum dolor sit amet, consectetur adipiscing', + \ 'elit. Fusce ut enim non libero efficitur aliquet.', + \ 'Maecenas metus justo, facilisis convallis blandit', + \ 'non, semper eu urna. Suspendisse diam diam,', + \ 'iaculis faucibus lorem eu, fringilla condimentum', + \ 'lectus. Quisque euismod diam at convallis', + \ 'vulputate. Pellentesque laoreet tortor sit amet', + \ 'mauris euismod ornare. Sed varius bibendum orci', + \ 'vel vehicula. Pellentesque tempor, ipsum et auctor', + \ 'accumsan, metus lectus ultrices odio, sed', + \ 'elementum mi ante at arcu.', '', '\begin{center}', '', + \ ' Proin nec risus consequat nunc dapibus', + \ ' consectetur. Mauris lacinia est a augue', + \ ' tristique accumsan. Morbi pretium, felis', + \ ' molestie eleifend condimentum, arcu ipsum congue', + \ ' nisl, quis euismod purus libero in ante.', + \ '', + \ ' Donec id semper purus. Suspendisse eget aliquam', + \ ' nunc. Maecenas fringilla mauris vitae maximus', + \ ' condimentum. Cras a quam in mi dictum eleifend', + \ ' at a lorem. Sed convallis ante a commodo', + \ ' facilisis. Nam suscipit vulputate odio, vel', + \ ' dapibus nisl dignissim facilisis. Vestibulum', + \ ' ante ipsum primis in faucibus orci luctus et', + \ ' ultrices posuere cubilia curae;', '', ''] + call assert_equal(expected, getline(1, '$')) + + bwipe! + delmark ab + delfunction GetTeXIndent +endfu + +func Test_formatting_keeps_first_line_indent() + let lines =<< trim END + foo() + { + int x; // manually positioned + // more text that will be formatted + // but not reindented + END + new + call setline(1, lines) + setlocal sw=4 cindent tw=45 et + normal! 4Ggqj + let expected =<< trim END + foo() + { + int x; // manually positioned + // more text that will be + // formatted but not + // reindented + END + call assert_equal(expected, getline(1, '$')) + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_input.vim b/test/old/testdir/test_input.vim new file mode 100644 index 0000000000..3b1e2eb2df --- /dev/null +++ b/test/old/testdir/test_input.vim @@ -0,0 +1,61 @@ +" Tests for character input and feedkeys() function. + +func Test_feedkeys_x_with_empty_string() + new + call feedkeys("ifoo\<Esc>") + call assert_equal('', getline('.')) + call feedkeys('', 'x') + call assert_equal('foo', getline('.')) + + " check it goes back to normal mode immediately. + call feedkeys('i', 'x') + call assert_equal('foo', getline('.')) + quit! +endfunc + +func Test_feedkeys_with_abbreviation() + new + inoreabbrev trigger value + call feedkeys("atrigger ", 'x') + call feedkeys("atrigger ", 'x') + call assert_equal('value value ', getline(1)) + bwipe! + iunabbrev trigger +endfunc + +func Test_feedkeys_escape_special() + nnoremap … <Cmd>let g:got_ellipsis += 1<CR> + call feedkeys('…', 't') + call assert_equal('…', getcharstr()) + let g:got_ellipsis = 0 + call feedkeys('…', 'xt') + call assert_equal(1, g:got_ellipsis) + unlet g:got_ellipsis + nunmap … +endfunc + +func Test_input_simplify_ctrl_at() + new + " feeding unsimplified CTRL-@ should still trigger i_CTRL-@ + call feedkeys("ifoo\<Esc>A\<*C-@>x", 'xt') + call assert_equal('foofo', getline(1)) + bw! +endfunc + +func Test_input_simplify_noremap() + call feedkeys("i\<*C-M>", 'nx') + call assert_equal('', getline(1)) + call assert_equal([0, 2, 1, 0, 1], getcurpos()) + bw! +endfunc + +func Test_input_simplify_timedout() + inoremap <C-M>a b + call feedkeys("i\<*C-M>", 'xt') + call assert_equal('', getline(1)) + call assert_equal([0, 2, 1, 0, 1], getcurpos()) + iunmap <C-M>a + bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_ins_complete.vim b/test/old/testdir/test_ins_complete.vim new file mode 100644 index 0000000000..e1c8b82908 --- /dev/null +++ b/test/old/testdir/test_ins_complete.vim @@ -0,0 +1,2410 @@ +" Test for insert completion + +source screendump.vim +source check.vim +source vim9.vim + +" Test for insert expansion +func Test_ins_complete() + edit test_ins_complete.vim + " The files in the current directory interferes with the files + " used by this test. So use a separate directory for the test. + call mkdir('Xdir') + cd Xdir + + set ff=unix + call writefile(["test11\t36Gepeto\t/Tag/", + \ "asd\ttest11file\t36G", + \ "Makefile\tto\trun"], 'Xtestfile') + call writefile(['', 'start of testfile', + \ 'ru', + \ 'run1', + \ 'run2', + \ 'STARTTEST', + \ 'ENDTEST', + \ 'end of testfile'], 'Xtestdata') + set ff& + + enew! + edit Xtestdata + new + call append(0, ['#include "Xtestfile"', '']) + call cursor(2, 1) + + set cot= + set cpt=.,w + " add-expands (word from next line) from other window + exe "normal iru\<C-N>\<C-N>\<C-X>\<C-N>\<Esc>\<C-A>" + call assert_equal('run1 run3', getline('.')) + " add-expands (current buffer first) + exe "normal o\<C-P>\<C-X>\<C-N>" + call assert_equal('run3 run3', getline('.')) + " Local expansion, ends in an empty line (unless it becomes a global + " expansion) + exe "normal o\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>" + call assert_equal('', getline('.')) + " starts Local and switches to global add-expansion + exe "normal o\<C-X>\<C-P>\<C-P>\<C-X>\<C-X>\<C-N>\<C-X>\<C-N>\<C-N>" + call assert_equal('run1 run2', getline('.')) + + set cpt=.,\ ,w,i + " i-add-expands and switches to local + exe "normal OM\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-X>\<C-X>\<C-P>" + call assert_equal("Makefile\tto\trun3", getline('.')) + " add-expands lines (it would end in an empty line if it didn't ignore + " itself) + exe "normal o\<C-X>\<C-L>\<C-X>\<C-L>\<C-P>\<C-P>" + call assert_equal("Makefile\tto\trun3", getline('.')) + call assert_equal("Makefile\tto\trun3", getline(line('.') - 1)) + + set cpt=kXtestfile + " checks k-expansion, and file expansion (use Xtest11 instead of test11, + " because TEST11.OUT may match first on DOS) + write Xtest11.one + write Xtest11.two + exe "normal o\<C-N>\<Esc>IX\<Esc>A\<C-X>\<C-F>\<C-N>" + call assert_equal('Xtest11.two', getline('.')) + + " use CTRL-X CTRL-F to complete Xtest11.one, remove it and then use CTRL-X + " CTRL-F again to verify this doesn't cause trouble. + exe "normal oXt\<C-X>\<C-F>\<BS>\<BS>\<BS>\<BS>\<BS>\<BS>\<BS>\<BS>\<C-X>\<C-F>" + call assert_equal('Xtest11.one', getline('.')) + normal ddk + + " Test for expanding a non-existing filename + exe "normal oa1b2X3Y4\<C-X>\<C-F>" + call assert_equal('a1b2X3Y4', getline('.')) + normal ddk + + set cpt=w + " checks make_cyclic in other window + exe "normal oST\<C-N>\<C-P>\<C-P>\<C-P>\<C-P>" + call assert_equal('STARTTEST', getline('.')) + + set cpt=u nohid + " checks unloaded buffer expansion + only + exe "normal oEN\<C-N>" + call assert_equal('ENDTEST', getline('.')) + " checks adding mode abortion + exe "normal ounl\<C-N>\<C-X>\<C-X>\<C-P>" + call assert_equal('unless', getline('.')) + + set cpt=t,d def=^\\k* tags=Xtestfile notagbsearch + " tag expansion, define add-expansion interrupted + exe "normal o\<C-X>\<C-]>\<C-X>\<C-D>\<C-X>\<C-D>\<C-X>\<C-X>\<C-D>\<C-X>\<C-D>\<C-X>\<C-D>\<C-X>\<C-D>" + call assert_equal('test11file 36Gepeto /Tag/ asd', getline('.')) + " t-expansion + exe "normal oa\<C-N>\<Esc>" + call assert_equal('asd', getline('.')) + + %bw! + call delete('Xtestfile') + call delete('Xtest11.one') + call delete('Xtest11.two') + call delete('Xtestdata') + set cpt& cot& def& tags& tagbsearch& hidden& + cd .. + call delete('Xdir', 'rf') +endfunc + +func Test_omni_dash() + func Omni(findstart, base) + if a:findstart + return 5 + else + echom a:base + return ['-help', '-v'] + endif + endfunc + set omnifunc=Omni + new + exe "normal Gofind -\<C-x>\<C-o>" + call assert_equal("find -help", getline('$')) + + bwipe! + delfunc Omni + set omnifunc= +endfunc + +func Test_omni_throw() + let g:CallCount = 0 + func Omni(findstart, base) + let g:CallCount += 1 + if a:findstart + throw "he he he" + endif + endfunc + set omnifunc=Omni + new + try + exe "normal ifoo\<C-x>\<C-o>" + call assert_false(v:true, 'command should have failed') + catch + call assert_exception('he he he') + call assert_equal(1, g:CallCount) + endtry + + bwipe! + delfunc Omni + unlet g:CallCount + set omnifunc= +endfunc + +func Test_completefunc_args() + let s:args = [] + func! CompleteFunc(findstart, base) + let s:args += [[a:findstart, empty(a:base)]] + endfunc + new + + set completefunc=CompleteFunc + call feedkeys("i\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([1, 1], s:args[0]) + call assert_equal(0, s:args[1][0]) + set completefunc= + + let s:args = [] + set omnifunc=CompleteFunc + call feedkeys("i\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([1, 1], s:args[0]) + call assert_equal(0, s:args[1][0]) + set omnifunc= + + bwipe! + unlet s:args + delfunc CompleteFunc +endfunc + +func s:CompleteDone_CompleteFuncNone( findstart, base ) + throw 'skipped: Nvim does not support v:none' + if a:findstart + return 0 + endif + + return v:none +endfunc + +func s:CompleteDone_CompleteFuncDict( findstart, base ) + if a:findstart + return 0 + endif + + return { + \ 'words': [ + \ { + \ 'word': 'aword', + \ 'abbr': 'wrd', + \ 'menu': 'extra text', + \ 'info': 'words are cool', + \ 'kind': 'W', + \ 'user_data': ['one', 'two'] + \ } + \ ] + \ } +endfunc + +func s:CompleteDone_CheckCompletedItemNone() + let s:called_completedone = 1 +endfunc + +func s:CompleteDone_CheckCompletedItemDict(pre) + call assert_equal( 'aword', v:completed_item[ 'word' ] ) + call assert_equal( 'wrd', v:completed_item[ 'abbr' ] ) + call assert_equal( 'extra text', v:completed_item[ 'menu' ] ) + call assert_equal( 'words are cool', v:completed_item[ 'info' ] ) + call assert_equal( 'W', v:completed_item[ 'kind' ] ) + call assert_equal( ['one', 'two'], v:completed_item[ 'user_data' ] ) + + if a:pre + call assert_equal('function', complete_info().mode) + endif + + let s:called_completedone = 1 +endfunc + +func Test_CompleteDoneNone() + throw 'skipped: Nvim does not support v:none' + au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemNone() + let oldline = join(map(range(&columns), 'nr2char(screenchar(&lines-1, v:val+1))'), '') + + set completefunc=<SID>CompleteDone_CompleteFuncNone + execute "normal a\<C-X>\<C-U>\<C-Y>" + set completefunc& + let newline = join(map(range(&columns), 'nr2char(screenchar(&lines-1, v:val+1))'), '') + + call assert_true(s:called_completedone) + call assert_equal(oldline, newline) + + let s:called_completedone = 0 + au! CompleteDone +endfunc + +func Test_CompleteDoneDict() + au CompleteDonePre * :call <SID>CompleteDone_CheckCompletedItemDict(1) + au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemDict(0) + + set completefunc=<SID>CompleteDone_CompleteFuncDict + execute "normal a\<C-X>\<C-U>\<C-Y>" + set completefunc& + + call assert_equal(['one', 'two'], v:completed_item[ 'user_data' ]) + call assert_true(s:called_completedone) + + let s:called_completedone = 0 + au! CompleteDone +endfunc + +func s:CompleteDone_CompleteFuncDictNoUserData(findstart, base) + if a:findstart + return 0 + endif + + return { + \ 'words': [ + \ { + \ 'word': 'aword', + \ 'abbr': 'wrd', + \ 'menu': 'extra text', + \ 'info': 'words are cool', + \ 'kind': 'W', + \ } + \ ] + \ } +endfunc + +func s:CompleteDone_CheckCompletedItemDictNoUserData() + call assert_equal( 'aword', v:completed_item[ 'word' ] ) + call assert_equal( 'wrd', v:completed_item[ 'abbr' ] ) + call assert_equal( 'extra text', v:completed_item[ 'menu' ] ) + call assert_equal( 'words are cool', v:completed_item[ 'info' ] ) + call assert_equal( 'W', v:completed_item[ 'kind' ] ) + call assert_equal( '', v:completed_item[ 'user_data' ] ) + + let s:called_completedone = 1 +endfunc + +func Test_CompleteDoneDictNoUserData() + au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemDictNoUserData() + + set completefunc=<SID>CompleteDone_CompleteFuncDictNoUserData + execute "normal a\<C-X>\<C-U>\<C-Y>" + set completefunc& + + call assert_equal('', v:completed_item[ 'user_data' ]) + call assert_true(s:called_completedone) + + let s:called_completedone = 0 + au! CompleteDone +endfunc + +func s:CompleteDone_CompleteFuncList(findstart, base) + if a:findstart + return 0 + endif + + return [ 'aword' ] +endfunc + +func s:CompleteDone_CheckCompletedItemList() + call assert_equal( 'aword', v:completed_item[ 'word' ] ) + call assert_equal( '', v:completed_item[ 'abbr' ] ) + call assert_equal( '', v:completed_item[ 'menu' ] ) + call assert_equal( '', v:completed_item[ 'info' ] ) + call assert_equal( '', v:completed_item[ 'kind' ] ) + call assert_equal( '', v:completed_item[ 'user_data' ] ) + + let s:called_completedone = 1 +endfunc + +func Test_CompleteDoneList() + au CompleteDone * :call <SID>CompleteDone_CheckCompletedItemList() + + set completefunc=<SID>CompleteDone_CompleteFuncList + execute "normal a\<C-X>\<C-U>\<C-Y>" + set completefunc& + + call assert_equal('', v:completed_item[ 'user_data' ]) + call assert_true(s:called_completedone) + + let s:called_completedone = 0 + au! CompleteDone +endfunc + +func Test_CompleteDone_undo() + au CompleteDone * call append(0, "prepend1") + new + call setline(1, ["line1", "line2"]) + call feedkeys("Go\<C-X>\<C-N>\<CR>\<ESC>", "tx") + call assert_equal(["prepend1", "line1", "line2", "line1", ""], + \ getline(1, '$')) + undo + call assert_equal(["line1", "line2"], getline(1, '$')) + bwipe! + au! CompleteDone +endfunc + +func Test_CompleteDone_modify() + let value = { + \ 'word': '', + \ 'abbr': '', + \ 'menu': '', + \ 'info': '', + \ 'kind': '', + \ 'user_data': '', + \ } + let v:completed_item = value + call assert_equal(value, v:completed_item) +endfunc + +func CompleteTest(findstart, query) + if a:findstart + return col('.') + endif + return ['matched'] +endfunc + +func Test_completefunc_info() + new + set completeopt=menuone + set completefunc=CompleteTest + call feedkeys("i\<C-X>\<C-U>\<C-R>\<C-R>=string(complete_info())\<CR>\<ESC>", "tx") + call assert_equal("matched{'pum_visible': 1, 'mode': 'function', 'selected': 0, 'items': [{'word': 'matched', 'menu': '', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}]}", getline(1)) + bwipe! + set completeopt& + set completefunc& +endfunc + +" Test that mouse scrolling/movement should not interrupt completion. +func Test_mouse_scroll_move_during_completion() + new + com! -buffer TestCommand1 echo 'TestCommand1' + com! -buffer TestCommand2 echo 'TestCommand2' + call setline(1, ['', '', '', '', '']) + call cursor(5, 1) + + " Without completion menu scrolling can move text. + set completeopt-=menu wrap + call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelDown>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + call assert_notequal(1, winsaveview().topline) + call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelUp>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + call assert_equal(1, winsaveview().topline) + set nowrap + call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelRight>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + call assert_notequal(0, winsaveview().leftcol) + call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelLeft>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + call assert_equal(0, winsaveview().leftcol) + call feedkeys("ccT\<C-X>\<C-V>\<MouseMove>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + + " With completion menu scrolling cannot move text. + set completeopt+=menu wrap + call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelDown>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + call assert_equal(1, winsaveview().topline) + call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelUp>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + call assert_equal(1, winsaveview().topline) + set nowrap + call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelRight>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + call assert_equal(0, winsaveview().leftcol) + call feedkeys("ccT\<C-X>\<C-V>\<ScrollWheelLeft>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + call assert_equal(0, winsaveview().leftcol) + call feedkeys("ccT\<C-X>\<C-V>\<MouseMove>\<C-V>", 'tx') + call assert_equal('TestCommand2', getline('.')) + + bwipe! + set completeopt& wrap& +endfunc + +" Check that when using feedkeys() typeahead does not interrupt searching for +" completions. +func Test_compl_feedkeys() + new + set completeopt=menuone,noselect + call feedkeys("ajump ju\<C-X>\<C-N>\<C-P>\<ESC>", "tx") + call assert_equal("jump jump", getline(1)) + bwipe! + set completeopt& +endfunc + +func s:ComplInCmdwin_GlobalCompletion(a, l, p) + return 'global' +endfunc + +func s:ComplInCmdwin_LocalCompletion(a, l, p) + return 'local' +endfunc + +func Test_compl_in_cmdwin() + set wildmenu wildchar=<Tab> + com! -nargs=1 -complete=command GetInput let input = <q-args> + com! -buffer TestCommand echo 'TestCommand' + let w:test_winvar = 'winvar' + let b:test_bufvar = 'bufvar' + + " User-defined commands + let input = '' + call feedkeys("q:iGetInput T\<C-x>\<C-v>\<CR>", 'tx!') + call assert_equal('TestCommand', input) + + let input = '' + call feedkeys("q::GetInput T\<Tab>\<CR>:q\<CR>", 'tx!') + call assert_equal('T', input) + + com! -nargs=1 -complete=var GetInput let input = <q-args> + " Window-local variables + let input = '' + call feedkeys("q:iGetInput w:test_\<C-x>\<C-v>\<CR>", 'tx!') + call assert_equal('w:test_winvar', input) + + let input = '' + call feedkeys("q::GetInput w:test_\<Tab>\<CR>:q\<CR>", 'tx!') + call assert_equal('w:test_', input) + + " Buffer-local variables + let input = '' + call feedkeys("q:iGetInput b:test_\<C-x>\<C-v>\<CR>", 'tx!') + call assert_equal('b:test_bufvar', input) + + let input = '' + call feedkeys("q::GetInput b:test_\<Tab>\<CR>:q\<CR>", 'tx!') + call assert_equal('b:test_', input) + + + " Argument completion of buffer-local command + func s:ComplInCmdwin_GlobalCompletionList(a, l, p) + return ['global'] + endfunc + + func s:ComplInCmdwin_LocalCompletionList(a, l, p) + return ['local'] + endfunc + + func s:ComplInCmdwin_CheckCompletion(arg) + call assert_equal('local', a:arg) + endfunc + + com! -nargs=1 -complete=custom,<SID>ComplInCmdwin_GlobalCompletion + \ TestCommand call s:ComplInCmdwin_CheckCompletion(<q-args>) + com! -buffer -nargs=1 -complete=custom,<SID>ComplInCmdwin_LocalCompletion + \ TestCommand call s:ComplInCmdwin_CheckCompletion(<q-args>) + call feedkeys("q:iTestCommand \<Tab>\<CR>", 'tx!') + + com! -nargs=1 -complete=customlist,<SID>ComplInCmdwin_GlobalCompletionList + \ TestCommand call s:ComplInCmdwin_CheckCompletion(<q-args>) + com! -buffer -nargs=1 -complete=customlist,<SID>ComplInCmdwin_LocalCompletionList + \ TestCommand call s:ComplInCmdwin_CheckCompletion(<q-args>) + + call feedkeys("q:iTestCommand \<Tab>\<CR>", 'tx!') + + func! s:ComplInCmdwin_CheckCompletion(arg) + call assert_equal('global', a:arg) + endfunc + new + call feedkeys("q:iTestCommand \<Tab>\<CR>", 'tx!') + quit + + delfunc s:ComplInCmdwin_GlobalCompletion + delfunc s:ComplInCmdwin_LocalCompletion + delfunc s:ComplInCmdwin_GlobalCompletionList + delfunc s:ComplInCmdwin_LocalCompletionList + delfunc s:ComplInCmdwin_CheckCompletion + + delcom -buffer TestCommand + delcom TestCommand + delcom GetInput + unlet w:test_winvar + unlet b:test_bufvar + set wildmenu& wildchar& +endfunc + +" Test for insert path completion with completeslash option +func Test_ins_completeslash() + CheckMSWindows + + call mkdir('Xdir') + let orig_shellslash = &shellslash + set cpt& + new + + set noshellslash + + set completeslash= + exe "normal oXd\<C-X>\<C-F>" + call assert_equal('Xdir\', getline('.')) + + set completeslash=backslash + exe "normal oXd\<C-X>\<C-F>" + call assert_equal('Xdir\', getline('.')) + + set completeslash=slash + exe "normal oXd\<C-X>\<C-F>" + call assert_equal('Xdir/', getline('.')) + + set shellslash + + set completeslash= + exe "normal oXd\<C-X>\<C-F>" + call assert_equal('Xdir/', getline('.')) + + set completeslash=backslash + exe "normal oXd\<C-X>\<C-F>" + call assert_equal('Xdir\', getline('.')) + + set completeslash=slash + exe "normal oXd\<C-X>\<C-F>" + call assert_equal('Xdir/', getline('.')) + %bw! + call delete('Xdir', 'rf') + + set noshellslash + set completeslash=slash + call assert_true(stridx(globpath(&rtp, 'syntax/*.vim', 1, 1)[0], '\') != -1) + + let &shellslash = orig_shellslash + set completeslash= +endfunc + +func Test_pum_stopped_by_timer() + CheckScreendump + + let lines =<< trim END + call setline(1, ['hello', 'hullo', 'heeee', '']) + func StartCompl() + call timer_start(100, { -> execute('stopinsert') }) + call feedkeys("Gah\<C-N>") + endfunc + END + + call writefile(lines, 'Xpumscript') + let buf = RunVimInTerminal('-S Xpumscript', #{rows: 12}) + call term_sendkeys(buf, ":call StartCompl()\<CR>") + call TermWait(buf, 200) + call term_sendkeys(buf, "k") + call VerifyScreenDump(buf, 'Test_pum_stopped_by_timer', {}) + + call StopVimInTerminal(buf) + call delete('Xpumscript') +endfunc + +func Test_complete_stopinsert_startinsert() + nnoremap <F2> <Cmd>startinsert<CR> + inoremap <F2> <Cmd>stopinsert<CR> + " This just checks if this causes an error + call feedkeys("i\<C-X>\<C-N>\<F2>\<F2>", 'x') + nunmap <F2> + iunmap <F2> +endfunc + +func Test_pum_with_folds_two_tabs() + CheckScreendump + + let lines =<< trim END + set fdm=marker + call setline(1, ['" x {{{1', '" a some text']) + call setline(3, range(&lines)->map({_, val -> '" a' .. val})) + norm! zm + tab sp + call feedkeys('2Gzv', 'xt') + call feedkeys("0fa", 'xt') + END + + call writefile(lines, 'Xpumscript') + let buf = RunVimInTerminal('-S Xpumscript', #{rows: 10}) + call TermWait(buf, 50) + call term_sendkeys(buf, "a\<C-N>") + call VerifyScreenDump(buf, 'Test_pum_with_folds_two_tabs', {}) + + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) + call delete('Xpumscript') +endfunc + +func Test_pum_with_preview_win() + CheckScreendump + + let lines =<< trim END + funct Omni_test(findstart, base) + if a:findstart + return col(".") - 1 + endif + return [#{word: "one", info: "1info"}, #{word: "two", info: "2info"}, #{word: "three", info: "3info"}] + endfunc + set omnifunc=Omni_test + set completeopt+=longest + END + + call writefile(lines, 'Xpreviewscript') + let buf = RunVimInTerminal('-S Xpreviewscript', #{rows: 12}) + call term_sendkeys(buf, "Gi\<C-X>\<C-O>") + call TermWait(buf, 200) + call term_sendkeys(buf, "\<C-N>") + call VerifyScreenDump(buf, 'Test_pum_with_preview_win', {}) + + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) + call delete('Xpreviewscript') +endfunc + +func Test_scrollbar_on_wide_char() + CheckScreendump + + let lines =<< trim END + call setline(1, ['a', ' 啊啊啊', + \ ' 哦哦哦', + \ ' 呃呃呃']) + call setline(5, range(10)->map({i, v -> 'aa' .. v .. 'bb'})) + END + call writefile(lines, 'Xwidescript') + let buf = RunVimInTerminal('-S Xwidescript', #{rows: 10}) + call term_sendkeys(buf, "A\<C-N>") + call VerifyScreenDump(buf, 'Test_scrollbar_on_wide_char', {}) + + call StopVimInTerminal(buf) + call delete('Xwidescript') +endfunc + +" Test for inserting the tag search pattern in insert mode +func Test_ins_compl_tag_sft() + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "first\tXfoo\t/^int first() {}$/", + \ "second\tXfoo\t/^int second() {}$/", + \ "third\tXfoo\t/^int third() {}$/"], + \ 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + int first() {} + int second() {} + int third() {} + [CODE] + call writefile(code, 'Xfoo') + + enew + set showfulltag + exe "normal isec\<C-X>\<C-]>\<C-N>\<CR>" + call assert_equal('int second() {}', getline(1)) + set noshowfulltag + + call delete('Xtags') + call delete('Xfoo') + set tags& + %bwipe! +endfunc + +" Test for 'completefunc' deleting text +func Test_completefunc_error() + new + " delete text when called for the first time + func CompleteFunc(findstart, base) + if a:findstart == 1 + normal dd + return col('.') - 1 + endif + return ['a', 'b'] + endfunc + set completefunc=CompleteFunc + call setline(1, ['', 'abcd', '']) + call assert_fails('exe "normal 2G$a\<C-X>\<C-U>"', 'E565:') + + " delete text when called for the second time + func CompleteFunc2(findstart, base) + if a:findstart == 1 + return col('.') - 1 + endif + normal dd + return ['a', 'b'] + endfunc + set completefunc=CompleteFunc2 + call setline(1, ['', 'abcd', '']) + call assert_fails('exe "normal 2G$a\<C-X>\<C-U>"', 'E565:') + + " Jump to a different window from the complete function + func CompleteFunc3(findstart, base) + if a:findstart == 1 + return col('.') - 1 + endif + wincmd p + return ['a', 'b'] + endfunc + set completefunc=CompleteFunc3 + new + call assert_fails('exe "normal a\<C-X>\<C-U>"', 'E565:') + close! + + set completefunc& + delfunc CompleteFunc + delfunc CompleteFunc2 + delfunc CompleteFunc3 + close! +endfunc + +" Test for returning non-string values from 'completefunc' +func Test_completefunc_invalid_data() + new + func! CompleteFunc(findstart, base) + if a:findstart == 1 + return col('.') - 1 + endif + return [{}, '', 'moon'] + endfunc + set completefunc=CompleteFunc + exe "normal i\<C-X>\<C-U>" + call assert_equal('moon', getline(1)) + set completefunc& + close! +endfunc + +" Test for errors in using complete() function +func Test_complete_func_error() + call assert_fails('call complete(1, ["a"])', 'E785:') + func ListColors() + call complete(col('.'), "blue") + endfunc + call assert_fails('exe "normal i\<C-R>=ListColors()\<CR>"', 'E474:') + func ListMonths() + call complete(col('.'), test_null_list()) + endfunc + " Nvim allows a NULL list + " call assert_fails('exe "normal i\<C-R>=ListMonths()\<CR>"', 'E474:') + delfunc ListColors + delfunc ListMonths + call assert_fails('call complete_info({})', 'E714:') + call assert_equal([], complete_info(['items']).items) +endfunc + +" Test for recursively starting completion mode using complete() +func Test_recursive_complete_func() + func ListColors() + call complete(5, ["red", "blue"]) + return '' + endfunc + new + call setline(1, ['a1', 'a2']) + set complete=. + exe "normal Goa\<C-X>\<C-L>\<C-R>=ListColors()\<CR>\<C-N>" + call assert_equal('a2blue', getline(3)) + delfunc ListColors + bw! +endfunc + +" Test for using complete() with completeopt+=longest +func Test_complete_with_longest() + new + inoremap <buffer> <f3> <cmd>call complete(1, ["iaax", "iaay", "iaaz"])<cr> + + " default: insert first match + set completeopt& + call setline(1, ['i']) + exe "normal Aa\<f3>\<esc>" + call assert_equal('iaax', getline(1)) + + " with longest: insert longest prefix + set completeopt+=longest + call setline(1, ['i']) + exe "normal Aa\<f3>\<esc>" + call assert_equal('iaa', getline(1)) + set completeopt& + bwipe! +endfunc + + +" Test for completing words following a completed word in a line +func Test_complete_wrapscan() + " complete words from another buffer + new + call setline(1, ['one two', 'three four']) + new + setlocal complete=w + call feedkeys("itw\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>", 'xt') + call assert_equal('two three four', getline(1)) + close! + " complete words from the current buffer + setlocal complete=. + %d + call setline(1, ['one two', '']) + call cursor(2, 1) + call feedkeys("ion\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>\<C-X>\<C-N>", 'xt') + call assert_equal('one two one two', getline(2)) + close! +endfunc + +" Test for completing special characters +func Test_complete_special_chars() + new + call setline(1, 'int .*[-\^$ func float') + call feedkeys("oin\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>", 'xt') + call assert_equal('int .*[-\^$ func float', getline(2)) + close! +endfunc + +" Test for completion when text is wrapped across lines. +func Test_complete_across_line() + new + call setline(1, ['red green blue', 'one two three']) + setlocal textwidth=20 + exe "normal 2G$a re\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>" + call assert_equal(['one two three red', 'green blue one'], getline(2, '$')) + close! +endfunc + +" Test for completing words with a '.' at the end of a word. +func Test_complete_joinspaces() + new + call setline(1, ['one two.', 'three. four']) + set joinspaces + exe "normal Goon\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>" + call assert_equal("one two. three. four", getline(3)) + set joinspaces& + bw! +endfunc + +" Test for using CTRL-L to add one character when completing matching +func Test_complete_add_onechar() + new + call setline(1, ['wool', 'woodwork']) + call feedkeys("Gowoo\<C-P>\<C-P>\<C-P>\<C-L>f", 'xt') + call assert_equal('woof', getline(3)) + + " use 'ignorecase' and backspace to erase characters from the prefix string + " and then add letters using CTRL-L + %d + set ignorecase backspace=2 + setlocal complete=. + call setline(1, ['workhorse', 'workload']) + normal Go + exe "normal aWOR\<C-P>\<bs>\<bs>\<bs>\<bs>\<bs>\<bs>\<C-L>\<C-L>\<C-L>" + call assert_equal('workh', getline(3)) + set ignorecase& backspace& + close! +endfunc + +" Test for using CTRL-X CTRL-L to complete whole lines lines +func Test_complete_wholeline() + new + " complete one-line + call setline(1, ['a1', 'a2']) + exe "normal ggoa\<C-X>\<C-L>" + call assert_equal(['a1', 'a1', 'a2'], getline(1, '$')) + " go to the next match (wrapping around the buffer) + exe "normal 2GCa\<C-X>\<C-L>\<C-N>" + call assert_equal(['a1', 'a', 'a2'], getline(1, '$')) + " go to the next match + exe "normal 2GCa\<C-X>\<C-L>\<C-N>\<C-N>" + call assert_equal(['a1', 'a2', 'a2'], getline(1, '$')) + exe "normal 2GCa\<C-X>\<C-L>\<C-N>\<C-N>\<C-N>" + call assert_equal(['a1', 'a1', 'a2'], getline(1, '$')) + " repeat the test using CTRL-L + " go to the next match (wrapping around the buffer) + exe "normal 2GCa\<C-X>\<C-L>\<C-L>" + call assert_equal(['a1', 'a2', 'a2'], getline(1, '$')) + " go to the next match + exe "normal 2GCa\<C-X>\<C-L>\<C-L>\<C-L>" + call assert_equal(['a1', 'a', 'a2'], getline(1, '$')) + exe "normal 2GCa\<C-X>\<C-L>\<C-L>\<C-L>\<C-L>" + call assert_equal(['a1', 'a1', 'a2'], getline(1, '$')) + %d + " use CTRL-X CTRL-L to add one more line + call setline(1, ['a1', 'b1']) + setlocal complete=. + exe "normal ggOa\<C-X>\<C-L>\<C-X>\<C-L>\<C-X>\<C-L>" + call assert_equal(['a1', 'b1', '', 'a1', 'b1'], getline(1, '$')) + bw! +endfunc + +" Test insert completion with 'cindent' (adjust the indent) +func Test_complete_with_cindent() + new + setlocal cindent + call setline(1, ['if (i == 1)', " j = 2;"]) + exe "normal Go{\<CR>i\<C-X>\<C-L>\<C-X>\<C-L>\<CR>}" + call assert_equal(['{', "\tif (i == 1)", "\t\tj = 2;", '}'], getline(3, '$')) + + %d + call setline(1, ['when while', '{', '']) + setlocal cinkeys+==while + exe "normal Giwh\<C-P> " + call assert_equal("\twhile ", getline('$')) + close! +endfunc + +" Test for <CTRL-X> <CTRL-V> completion. Complete commands and functions +func Test_complete_cmdline() + new + exe "normal icaddb\<C-X>\<C-V>" + call assert_equal('caddbuffer', getline(1)) + exe "normal ocall getqf\<C-X>\<C-V>" + call assert_equal('call getqflist(', getline(2)) + exe "normal oabcxyz(\<C-X>\<C-V>" + call assert_equal('abcxyz(', getline(3)) + com! -buffer TestCommand1 echo 'TestCommand1' + com! -buffer TestCommand2 echo 'TestCommand2' + write TestCommand1Test + write TestCommand2Test + " Test repeating <CTRL-X> <CTRL-V> and switching to another CTRL-X mode + exe "normal oT\<C-X>\<C-V>\<C-X>\<C-V>\<C-X>\<C-F>\<Esc>" + call assert_equal('TestCommand2Test', getline(4)) + call delete('TestCommand1Test') + call delete('TestCommand2Test') + delcom TestCommand1 + delcom TestCommand2 + close! +endfunc + +" Test for <CTRL-X> <CTRL-Z> stopping completion without changing the match +func Test_complete_stop() + new + func Save_mode1() + let g:mode1 = mode(1) + return '' + endfunc + func Save_mode2() + let g:mode2 = mode(1) + return '' + endfunc + inoremap <F1> <C-R>=Save_mode1()<CR> + inoremap <F2> <C-R>=Save_mode2()<CR> + call setline(1, ['aaa bbb ccc ']) + exe "normal A\<C-N>\<C-P>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('aaa bbb ccc ', getline(1)) + exe "normal A\<C-N>\<Down>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('aaa bbb ccc aaa', getline(1)) + set completeopt+=noselect + exe "normal A \<C-N>\<Down>\<Down>\<C-L>\<C-L>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('aaa bbb ccc aaa bb', getline(1)) + set completeopt& + exe "normal A d\<C-N>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('aaa bbb ccc aaa bb d', getline(1)) + com! -buffer TestCommand1 echo 'TestCommand1' + com! -buffer TestCommand2 echo 'TestCommand2' + exe "normal oT\<C-X>\<C-V>\<C-X>\<C-V>\<F1>\<C-X>\<C-Z>\<F2>\<Esc>" + call assert_equal('ic', g:mode1) + call assert_equal('i', g:mode2) + call assert_equal('TestCommand2', getline(2)) + delcom TestCommand1 + delcom TestCommand2 + unlet g:mode1 + unlet g:mode2 + iunmap <F1> + iunmap <F2> + delfunc Save_mode1 + delfunc Save_mode2 + close! +endfunc + +" Test for typing CTRL-R in insert completion mode to insert a register +" content. +func Test_complete_reginsert() + new + call setline(1, ['a1', 'a12', 'a123', 'a1234']) + + " if a valid CTRL-X mode key is returned from <C-R>=, then it should be + " processed. Otherwise, CTRL-X mode should be stopped and the key should be + " inserted. + exe "normal Goa\<C-P>\<C-R>=\"\\<C-P>\"\<CR>" + call assert_equal('a123', getline(5)) + let @r = "\<C-P>\<C-P>" + exe "normal GCa\<C-P>\<C-R>r" + call assert_equal('a12', getline(5)) + exe "normal GCa\<C-P>\<C-R>=\"x\"\<CR>" + call assert_equal('a1234x', getline(5)) + bw! +endfunc + +func Test_issue_7021() + CheckMSWindows + + let orig_shellslash = &shellslash + set noshellslash + + set completeslash=slash + call assert_false(expand('~') =~ '/') + + let &shellslash = orig_shellslash + set completeslash= +endfunc + +" Test for 'longest' setting in 'completeopt' with latin1 and utf-8 encodings +func Test_complete_longest_match() + " for e in ['latin1', 'utf-8'] + for e in ['utf-8'] + exe 'set encoding=' .. e + new + set complete=. + set completeopt=menu,longest + call setline(1, ['pfx_a1', 'pfx_a12', 'pfx_a123', 'pfx_b1']) + exe "normal Gopfx\<C-P>" + call assert_equal('pfx_', getline(5)) + bw! + endfor + + " Test for completing additional words with longest match set + new + call setline(1, ['abc1', 'abd2']) + exe "normal Goab\<C-P>\<C-X>\<C-P>" + call assert_equal('ab', getline(3)) + bw! + set complete& completeopt& +endfunc + +" Test for removing the first displayed completion match and selecting the +" match just before that. +func Test_complete_erase_firstmatch() + new + call setline(1, ['a12', 'a34', 'a56']) + set complete=. + exe "normal Goa\<C-P>\<BS>\<BS>3\<CR>" + call assert_equal('a34', getline('$')) + set complete& + bw! +endfunc + +" Test for completing words from unloaded buffers +func Test_complete_from_unloadedbuf() + call writefile(['abc'], "Xfile1") + call writefile(['def'], "Xfile2") + edit Xfile1 + edit Xfile2 + new | close + enew + bunload Xfile1 Xfile2 + set complete=u + " complete from an unloaded buffer + exe "normal! ia\<C-P>" + call assert_equal('abc', getline(1)) + exe "normal! od\<C-P>" + call assert_equal('def', getline(2)) + set complete& + %bw! + call delete("Xfile1") + call delete("Xfile2") +endfunc + +" Test for completing whole lines from unloaded buffers +func Test_complete_wholeline_unloadedbuf() + call writefile(['a line1', 'a line2', 'a line3'], "Xfile1") + edit Xfile1 + enew + set complete=u + exe "normal! ia\<C-X>\<C-L>\<C-P>" + call assert_equal('a line2', getline(1)) + %d + " completing from an unlisted buffer should fail + bdel Xfile1 + exe "normal! ia\<C-X>\<C-L>\<C-P>" + call assert_equal('a', getline(1)) + set complete& + %bw! + call delete("Xfile1") +endfunc + +" Test for completing words from unlisted buffers +func Test_complete_from_unlistedbuf() + call writefile(['abc'], "Xfile1") + call writefile(['def'], "Xfile2") + edit Xfile1 + edit Xfile2 + new | close + bdel Xfile1 Xfile2 + set complete=U + " complete from an unlisted buffer + exe "normal! ia\<C-P>" + call assert_equal('abc', getline(1)) + exe "normal! od\<C-P>" + call assert_equal('def', getline(2)) + set complete& + %bw! + call delete("Xfile1") + call delete("Xfile2") +endfunc + +" Test for completing whole lines from unlisted buffers +func Test_complete_wholeline_unlistedbuf() + call writefile(['a line1', 'a line2', 'a line3'], "Xfile1") + edit Xfile1 + enew + set complete=U + " completing from a unloaded buffer should fail + exe "normal! ia\<C-X>\<C-L>\<C-P>" + call assert_equal('a', getline(1)) + %d + bdel Xfile1 + exe "normal! ia\<C-X>\<C-L>\<C-P>" + call assert_equal('a line2', getline(1)) + set complete& + %bw! + call delete("Xfile1") +endfunc + +" Test for adding a multibyte character using CTRL-L in completion mode +func Test_complete_mbyte_char_add() + new + set complete=. + call setline(1, 'abė') + exe "normal! oa\<C-P>\<BS>\<BS>\<C-L>\<C-L>" + call assert_equal('abė', getline(2)) + " Test for a leader with multibyte character + %d + call setline(1, 'abėĕ') + exe "normal! oabė\<C-P>" + call assert_equal('abėĕ', getline(2)) + bw! +endfunc + +" Test for using <C-X><C-P> for local expansion even if 'complete' is set to +" not to complete matches from the local buffer. Also test using multiple +" <C-X> to cancel the current completion mode. +func Test_complete_local_expansion() + new + set complete=t + call setline(1, ['abc', 'def']) + exe "normal! Go\<C-X>\<C-P>" + call assert_equal("def", getline(3)) + exe "normal! Go\<C-P>" + call assert_equal("", getline(4)) + exe "normal! Go\<C-X>\<C-N>" + call assert_equal("abc", getline(5)) + exe "normal! Go\<C-N>" + call assert_equal("", getline(6)) + + " use multiple <C-X> to cancel the previous completion mode + exe "normal! Go\<C-P>\<C-X>\<C-P>" + call assert_equal("", getline(7)) + exe "normal! Go\<C-P>\<C-X>\<C-X>\<C-P>" + call assert_equal("", getline(8)) + exe "normal! Go\<C-P>\<C-X>\<C-X>\<C-X>\<C-P>" + call assert_equal("abc", getline(9)) + + " interrupt the current completion mode + set completeopt=menu,noinsert + exe "normal! Go\<C-X>\<C-F>\<C-X>\<C-X>\<C-P>\<C-Y>" + call assert_equal("abc", getline(10)) + + " when only one <C-X> is used to interrupt, do normal expansion + exe "normal! Go\<C-X>\<C-F>\<C-X>\<C-P>" + call assert_equal("", getline(11)) + set completeopt& + + " using two <C-X> in non-completion mode and restarting the same mode + exe "normal! God\<C-X>\<C-X>\<C-P>\<C-X>\<C-X>\<C-P>\<C-Y>" + call assert_equal("def", getline(12)) + + " test for adding a match from the original empty text + %d + call setline(1, 'abc def g') + exe "normal! o\<C-X>\<C-P>\<C-N>\<C-X>\<C-P>" + call assert_equal('def', getline(2)) + exe "normal! 0C\<C-X>\<C-N>\<C-P>\<C-X>\<C-N>" + call assert_equal('abc', getline(2)) + + bw! +endfunc + +" Test for undoing changes after a insert-mode completion +func Test_complete_undo() + new + set complete=. + " undo with 'ignorecase' + call setline(1, ['ABOVE', 'BELOW']) + set ignorecase + exe "normal! Goab\<C-G>u\<C-P>" + call assert_equal("ABOVE", getline(3)) + undo + call assert_equal("ab", getline(3)) + set ignorecase& + %d + " undo with longest match + set completeopt=menu,longest + call setline(1, ['above', 'about']) + exe "normal! Goa\<C-G>u\<C-P>" + call assert_equal("abo", getline(3)) + undo + call assert_equal("a", getline(3)) + set completeopt& + %d + " undo for line completion + call setline(1, ['above that change', 'below that change']) + exe "normal! Goabove\<C-G>u\<C-X>\<C-L>" + call assert_equal("above that change", getline(3)) + undo + call assert_equal("above", getline(3)) + + bw! +endfunc + +" Test for completing a very long word +func Test_complete_long_word() + set complete& + new + call setline(1, repeat('x', 950) .. ' one two three') + exe "normal! Gox\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>" + call assert_equal(repeat('x', 950) .. ' one two three', getline(2)) + %d + " should fail when more than 950 characters are in a word + call setline(1, repeat('x', 951) .. ' one two three') + exe "normal! Gox\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>\<C-X>\<C-P>" + call assert_equal(repeat('x', 951), getline(2)) + + " Test for adding a very long word to an existing completion + %d + call setline(1, ['abc', repeat('x', 1016) .. '012345']) + exe "normal! Goab\<C-P>\<C-X>\<C-P>" + call assert_equal('abc ' .. repeat('x', 1016) .. '0123', getline(3)) + bw! +endfunc + +" Test for some fields in the complete items used by complete() +func Test_complete_items() + func CompleteItems(idx) + let items = [[#{word: "one", dup: 1, user_data: 'u1'}, #{word: "one", dup: 1, user_data: 'u2'}], + \ [#{word: "one", dup: 0, user_data: 'u3'}, #{word: "one", dup: 0, user_data: 'u4'}], + \ [#{word: "one", icase: 1, user_data: 'u7'}, #{word: "oNE", icase: 1, user_data: 'u8'}], + \ [#{user_data: 'u9'}], + \ [#{word: "", user_data: 'u10'}], + \ [#{word: "", empty: 1, user_data: 'u11'}]] + call complete(col('.'), items[a:idx]) + return '' + endfunc + new + exe "normal! i\<C-R>=CompleteItems(0)\<CR>\<C-N>\<C-Y>" + call assert_equal('u2', v:completed_item.user_data) + call assert_equal('one', getline(1)) + exe "normal! o\<C-R>=CompleteItems(1)\<CR>\<C-Y>" + call assert_equal('u3', v:completed_item.user_data) + call assert_equal('one', getline(2)) + exe "normal! o\<C-R>=CompleteItems(1)\<CR>\<C-N>" + call assert_equal('', getline(3)) + set completeopt=menu,noinsert + exe "normal! o\<C-R>=CompleteItems(2)\<CR>one\<C-N>\<C-Y>" + call assert_equal('oNE', getline(4)) + call assert_equal('u8', v:completed_item.user_data) + set completeopt& + exe "normal! o\<C-R>=CompleteItems(3)\<CR>" + call assert_equal('', getline(5)) + exe "normal! o\<C-R>=CompleteItems(4)\<CR>" + call assert_equal('', getline(6)) + exe "normal! o\<C-R>=CompleteItems(5)\<CR>" + call assert_equal('', getline(7)) + call assert_equal('u11', v:completed_item.user_data) + " pass invalid argument to complete() + let cmd = "normal! o\<C-R>=complete(1, [[]])\<CR>" + call assert_fails('exe cmd', 'E730:') + bw! + delfunc CompleteItems +endfunc + +" Test for the "refresh" item in the dict returned by an insert completion +" function +func Test_complete_item_refresh_always() + let g:CallCount = 0 + func! Tcomplete(findstart, base) + if a:findstart + " locate the start of the word + let line = getline('.') + let start = col('.') - 1 + while start > 0 && line[start - 1] =~ '\a' + let start -= 1 + endwhile + return start + else + let g:CallCount += 1 + let res = ["update1", "update12", "update123"] + return #{words: res, refresh: 'always'} + endif + endfunc + new + set completeopt=menu,longest + set completefunc=Tcomplete + exe "normal! iup\<C-X>\<C-U>\<BS>\<BS>\<BS>\<BS>\<BS>" + call assert_equal('up', getline(1)) + call assert_equal(2, g:CallCount) + set completeopt& + set completefunc& + bw! + delfunc Tcomplete +endfunc + +" Test for completing from a thesaurus file without read permission +func Test_complete_unreadable_thesaurus_file() + CheckUnix + CheckNotRoot + + call writefile(['about', 'above'], 'Xfile') + call setfperm('Xfile', '---r--r--') + new + set complete=sXfile + exe "normal! ia\<C-P>" + call assert_equal('a', getline(1)) + bw! + call delete('Xfile') + set complete& +endfunc + +" Test to ensure 'Scanning...' messages are not recorded in messages history +func Test_z1_complete_no_history() + new + messages clear + let currmess = execute('messages') + setlocal dictionary=README.txt + exe "normal owh\<C-X>\<C-K>" + exe "normal owh\<C-N>" + call assert_equal(currmess, execute('messages')) + bwipe! +endfunc + +" A mapping is not used for the key after CTRL-X. +func Test_no_mapping_for_ctrl_x_key() + new + inoremap <buffer> <C-K> <Cmd>let was_mapped = 'yes'<CR> + setlocal dictionary=README.txt + call feedkeys("aexam\<C-X>\<C-K> ", 'xt') + call assert_equal('example ', getline(1)) + call assert_false(exists('was_mapped')) + bwipe! +endfunc + +" Test for different ways of setting the 'completefunc' option +func Test_completefunc_callback() + func CompleteFunc1(callnr, findstart, base) + call add(g:CompleteFunc1Args, [a:callnr, a:findstart, a:base]) + return a:findstart ? 0 : [] + endfunc + func CompleteFunc2(findstart, base) + call add(g:CompleteFunc2Args, [a:findstart, a:base]) + return a:findstart ? 0 : [] + endfunc + + let lines =<< trim END + #" Test for using a global function name + LET &completefunc = 'g:CompleteFunc2' + new + call setline(1, 'global') + LET g:CompleteFunc2Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'global']], g:CompleteFunc2Args) + bw! + + #" Test for using a function() + set completefunc=function('g:CompleteFunc1',\ [10]) + new + call setline(1, 'one') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[10, 1, ''], [10, 0, 'one']], g:CompleteFunc1Args) + bw! + + #" Using a funcref variable to set 'completefunc' + VAR Fn = function('g:CompleteFunc1', [11]) + LET &completefunc = Fn + new + call setline(1, 'two') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[11, 1, ''], [11, 0, 'two']], g:CompleteFunc1Args) + bw! + + #" Using string(funcref_variable) to set 'completefunc' + LET Fn = function('g:CompleteFunc1', [12]) + LET &completefunc = string(Fn) + new + call setline(1, 'two') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[12, 1, ''], [12, 0, 'two']], g:CompleteFunc1Args) + bw! + + #" Test for using a funcref() + set completefunc=funcref('g:CompleteFunc1',\ [13]) + new + call setline(1, 'three') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[13, 1, ''], [13, 0, 'three']], g:CompleteFunc1Args) + bw! + + #" Using a funcref variable to set 'completefunc' + LET Fn = funcref('g:CompleteFunc1', [14]) + LET &completefunc = Fn + new + call setline(1, 'four') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[14, 1, ''], [14, 0, 'four']], g:CompleteFunc1Args) + bw! + + #" Using a string(funcref_variable) to set 'completefunc' + LET Fn = funcref('g:CompleteFunc1', [15]) + LET &completefunc = string(Fn) + new + call setline(1, 'four') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[15, 1, ''], [15, 0, 'four']], g:CompleteFunc1Args) + bw! + + #" Test for using a lambda function with set + VAR optval = "LSTART a, b LMIDDLE CompleteFunc1(16, a, b) LEND" + LET optval = substitute(optval, ' ', '\\ ', 'g') + exe "set completefunc=" .. optval + new + call setline(1, 'five') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[16, 1, ''], [16, 0, 'five']], g:CompleteFunc1Args) + bw! + + #" Set 'completefunc' to a lambda expression + LET &completefunc = LSTART a, b LMIDDLE CompleteFunc1(17, a, b) LEND + new + call setline(1, 'six') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[17, 1, ''], [17, 0, 'six']], g:CompleteFunc1Args) + bw! + + #" Set 'completefunc' to string(lambda_expression) + LET &completefunc = 'LSTART a, b LMIDDLE CompleteFunc1(18, a, b) LEND' + new + call setline(1, 'six') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[18, 1, ''], [18, 0, 'six']], g:CompleteFunc1Args) + bw! + + #" Set 'completefunc' to a variable with a lambda expression + VAR Lambda = LSTART a, b LMIDDLE CompleteFunc1(19, a, b) LEND + LET &completefunc = Lambda + new + call setline(1, 'seven') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:CompleteFunc1Args) + bw! + + #" Set 'completefunc' to a string(variable with a lambda expression) + LET Lambda = LSTART a, b LMIDDLE CompleteFunc1(20, a, b) LEND + LET &completefunc = string(Lambda) + new + call setline(1, 'seven') + LET g:CompleteFunc1Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:CompleteFunc1Args) + bw! + + #" Test for using a lambda function with incorrect return value + LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND + LET &completefunc = Lambda + new + call setline(1, 'eight') + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + bw! + + #" Test for clearing the 'completefunc' option + set completefunc='' + set completefunc& + call assert_fails("set completefunc=function('abc')", "E700:") + call assert_fails("set completefunc=funcref('abc')", "E700:") + + #" set 'completefunc' to a non-existing function + set completefunc=CompleteFunc2 + call setline(1, 'five') + call assert_fails("set completefunc=function('NonExistingFunc')", 'E700:') + call assert_fails("LET &completefunc = function('NonExistingFunc')", 'E700:') + LET g:CompleteFunc2Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'five']], g:CompleteFunc2Args) + bw! + END + call CheckLegacyAndVim9Success(lines) + + " Test for using a script-local function name + func s:CompleteFunc3(findstart, base) + call add(g:CompleteFunc3Args, [a:findstart, a:base]) + return a:findstart ? 0 : [] + endfunc + set completefunc=s:CompleteFunc3 + new + call setline(1, 'script1') + let g:CompleteFunc3Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'script1']], g:CompleteFunc3Args) + bw! + + let &completefunc = 's:CompleteFunc3' + new + call setline(1, 'script2') + let g:CompleteFunc3Args = [] + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'script2']], g:CompleteFunc3Args) + bw! + delfunc s:CompleteFunc3 + + " invalid return value + let &completefunc = {a -> 'abc'} + call feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + + " Using Vim9 lambda expression in legacy context should fail + " set completefunc=(a,\ b)\ =>\ CompleteFunc1(21,\ a,\ b) + new | only + let g:CompleteFunc1Args = [] + " call assert_fails('call feedkeys("A\<C-X>\<C-U>\<Esc>", "x")', 'E117:') + call assert_equal([], g:CompleteFunc1Args) + + " set 'completefunc' to a partial with dict. This used to cause a crash. + func SetCompleteFunc() + let params = {'complete': function('g:DictCompleteFunc')} + let &completefunc = params.complete + endfunc + func g:DictCompleteFunc(_) dict + endfunc + call SetCompleteFunc() + new + call SetCompleteFunc() + bw + call test_garbagecollect_now() + new + set completefunc= + wincmd w + set completefunc= + %bw! + delfunc g:DictCompleteFunc + delfunc SetCompleteFunc + + " Vim9 tests + let lines =<< trim END + vim9script + + def Vim9CompleteFunc(callnr: number, findstart: number, base: string): any + add(g:Vim9completeFuncArgs, [callnr, findstart, base]) + return findstart ? 0 : [] + enddef + + # Test for using a def function with completefunc + set completefunc=function('Vim9CompleteFunc',\ [60]) + new | only + setline(1, 'one') + g:Vim9completeFuncArgs = [] + feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9completeFuncArgs) + bw! + + # Test for using a global function name + &completefunc = g:CompleteFunc2 + new | only + setline(1, 'two') + g:CompleteFunc2Args = [] + feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + assert_equal([[1, ''], [0, 'two']], g:CompleteFunc2Args) + bw! + + # Test for using a script-local function name + def LocalCompleteFunc(findstart: number, base: string): any + add(g:LocalCompleteFuncArgs, [findstart, base]) + return findstart ? 0 : [] + enddef + &completefunc = LocalCompleteFunc + new | only + setline(1, 'three') + g:LocalCompleteFuncArgs = [] + feedkeys("A\<C-X>\<C-U>\<Esc>", 'x') + assert_equal([[1, ''], [0, 'three']], g:LocalCompleteFuncArgs) + bw! + END + call CheckScriptSuccess(lines) + + " cleanup + set completefunc& + delfunc CompleteFunc1 + delfunc CompleteFunc2 + unlet g:CompleteFunc1Args g:CompleteFunc2Args + %bw! +endfunc + +" Test for different ways of setting the 'omnifunc' option +func Test_omnifunc_callback() + func OmniFunc1(callnr, findstart, base) + call add(g:OmniFunc1Args, [a:callnr, a:findstart, a:base]) + return a:findstart ? 0 : [] + endfunc + func OmniFunc2(findstart, base) + call add(g:OmniFunc2Args, [a:findstart, a:base]) + return a:findstart ? 0 : [] + endfunc + + let lines =<< trim END + #" Test for using a function name + LET &omnifunc = 'g:OmniFunc2' + new + call setline(1, 'zero') + LET g:OmniFunc2Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'zero']], g:OmniFunc2Args) + bw! + + #" Test for using a function() + set omnifunc=function('g:OmniFunc1',\ [10]) + new + call setline(1, 'one') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[10, 1, ''], [10, 0, 'one']], g:OmniFunc1Args) + bw! + + #" Using a funcref variable to set 'omnifunc' + VAR Fn = function('g:OmniFunc1', [11]) + LET &omnifunc = Fn + new + call setline(1, 'two') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[11, 1, ''], [11, 0, 'two']], g:OmniFunc1Args) + bw! + + #" Using a string(funcref_variable) to set 'omnifunc' + LET Fn = function('g:OmniFunc1', [12]) + LET &omnifunc = string(Fn) + new + call setline(1, 'two') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[12, 1, ''], [12, 0, 'two']], g:OmniFunc1Args) + bw! + + #" Test for using a funcref() + set omnifunc=funcref('g:OmniFunc1',\ [13]) + new + call setline(1, 'three') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[13, 1, ''], [13, 0, 'three']], g:OmniFunc1Args) + bw! + + #" Use let to set 'omnifunc' to a funcref + LET Fn = funcref('g:OmniFunc1', [14]) + LET &omnifunc = Fn + new + call setline(1, 'four') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[14, 1, ''], [14, 0, 'four']], g:OmniFunc1Args) + bw! + + #" Using a string(funcref) to set 'omnifunc' + LET Fn = funcref("g:OmniFunc1", [15]) + LET &omnifunc = string(Fn) + new + call setline(1, 'four') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[15, 1, ''], [15, 0, 'four']], g:OmniFunc1Args) + bw! + + #" Test for using a lambda function with set + VAR optval = "LSTART a, b LMIDDLE OmniFunc1(16, a, b) LEND" + LET optval = substitute(optval, ' ', '\\ ', 'g') + exe "set omnifunc=" .. optval + new + call setline(1, 'five') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[16, 1, ''], [16, 0, 'five']], g:OmniFunc1Args) + bw! + + #" Set 'omnifunc' to a lambda expression + LET &omnifunc = LSTART a, b LMIDDLE OmniFunc1(17, a, b) LEND + new + call setline(1, 'six') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[17, 1, ''], [17, 0, 'six']], g:OmniFunc1Args) + bw! + + #" Set 'omnifunc' to a string(lambda_expression) + LET &omnifunc = 'LSTART a, b LMIDDLE OmniFunc1(18, a, b) LEND' + new + call setline(1, 'six') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[18, 1, ''], [18, 0, 'six']], g:OmniFunc1Args) + bw! + + #" Set 'omnifunc' to a variable with a lambda expression + VAR Lambda = LSTART a, b LMIDDLE OmniFunc1(19, a, b) LEND + LET &omnifunc = Lambda + new + call setline(1, 'seven') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:OmniFunc1Args) + bw! + + #" Set 'omnifunc' to a string(variable with a lambda expression) + LET Lambda = LSTART a, b LMIDDLE OmniFunc1(20, a, b) LEND + LET &omnifunc = string(Lambda) + new + call setline(1, 'seven') + LET g:OmniFunc1Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:OmniFunc1Args) + bw! + + #" Test for using a lambda function with incorrect return value + LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND + LET &omnifunc = Lambda + new + call setline(1, 'eight') + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + bw! + + #" Test for clearing the 'omnifunc' option + set omnifunc='' + set omnifunc& + call assert_fails("set omnifunc=function('abc')", "E700:") + call assert_fails("set omnifunc=funcref('abc')", "E700:") + + #" set 'omnifunc' to a non-existing function + set omnifunc=OmniFunc2 + call setline(1, 'nine') + call assert_fails("set omnifunc=function('NonExistingFunc')", 'E700:') + call assert_fails("LET &omnifunc = function('NonExistingFunc')", 'E700:') + LET g:OmniFunc2Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'nine']], g:OmniFunc2Args) + bw! + END + call CheckLegacyAndVim9Success(lines) + + " Test for using a script-local function name + func s:OmniFunc3(findstart, base) + call add(g:OmniFunc3Args, [a:findstart, a:base]) + return a:findstart ? 0 : [] + endfunc + set omnifunc=s:OmniFunc3 + new + call setline(1, 'script1') + let g:OmniFunc3Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'script1']], g:OmniFunc3Args) + bw! + + let &omnifunc = 's:OmniFunc3' + new + call setline(1, 'script2') + let g:OmniFunc3Args = [] + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'script2']], g:OmniFunc3Args) + bw! + delfunc s:OmniFunc3 + + " invalid return value + let &omnifunc = {a -> 'abc'} + call feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + + " Using Vim9 lambda expression in legacy context should fail + " set omnifunc=(a,\ b)\ =>\ OmniFunc1(21,\ a,\ b) + new | only + let g:OmniFunc1Args = [] + " call assert_fails('call feedkeys("A\<C-X>\<C-O>\<Esc>", "x")', 'E117:') + call assert_equal([], g:OmniFunc1Args) + + " set 'omnifunc' to a partial with dict. This used to cause a crash. + func SetOmniFunc() + let params = {'omni': function('g:DictOmniFunc')} + let &omnifunc = params.omni + endfunc + func g:DictOmniFunc(_) dict + endfunc + call SetOmniFunc() + new + call SetOmniFunc() + bw + call test_garbagecollect_now() + new + set omnifunc= + wincmd w + set omnifunc= + %bw! + delfunc g:DictOmniFunc + delfunc SetOmniFunc + + " Vim9 tests + let lines =<< trim END + vim9script + + def Vim9omniFunc(callnr: number, findstart: number, base: string): any + add(g:Vim9omniFunc_Args, [callnr, findstart, base]) + return findstart ? 0 : [] + enddef + + # Test for using a def function with omnifunc + set omnifunc=function('Vim9omniFunc',\ [60]) + new | only + setline(1, 'one') + g:Vim9omniFunc_Args = [] + feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9omniFunc_Args) + bw! + + # Test for using a global function name + &omnifunc = g:OmniFunc2 + new | only + setline(1, 'two') + g:OmniFunc2Args = [] + feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + assert_equal([[1, ''], [0, 'two']], g:OmniFunc2Args) + bw! + + # Test for using a script-local function name + def LocalOmniFunc(findstart: number, base: string): any + add(g:LocalOmniFuncArgs, [findstart, base]) + return findstart ? 0 : [] + enddef + &omnifunc = LocalOmniFunc + new | only + setline(1, 'three') + g:LocalOmniFuncArgs = [] + feedkeys("A\<C-X>\<C-O>\<Esc>", 'x') + assert_equal([[1, ''], [0, 'three']], g:LocalOmniFuncArgs) + bw! + END + call CheckScriptSuccess(lines) + + " cleanup + set omnifunc& + delfunc OmniFunc1 + delfunc OmniFunc2 + unlet g:OmniFunc1Args g:OmniFunc2Args + %bw! +endfunc + +" Test for different ways of setting the 'thesaurusfunc' option +func Test_thesaurusfunc_callback() + func TsrFunc1(callnr, findstart, base) + call add(g:TsrFunc1Args, [a:callnr, a:findstart, a:base]) + return a:findstart ? 0 : [] + endfunc + func TsrFunc2(findstart, base) + call add(g:TsrFunc2Args, [a:findstart, a:base]) + return a:findstart ? 0 : ['sunday'] + endfunc + + let lines =<< trim END + #" Test for using a function name + LET &thesaurusfunc = 'g:TsrFunc2' + new + call setline(1, 'zero') + LET g:TsrFunc2Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'zero']], g:TsrFunc2Args) + bw! + + #" Test for using a function() + set thesaurusfunc=function('g:TsrFunc1',\ [10]) + new + call setline(1, 'one') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[10, 1, ''], [10, 0, 'one']], g:TsrFunc1Args) + bw! + + #" Using a funcref variable to set 'thesaurusfunc' + VAR Fn = function('g:TsrFunc1', [11]) + LET &thesaurusfunc = Fn + new + call setline(1, 'two') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[11, 1, ''], [11, 0, 'two']], g:TsrFunc1Args) + bw! + + #" Using a string(funcref_variable) to set 'thesaurusfunc' + LET Fn = function('g:TsrFunc1', [12]) + LET &thesaurusfunc = string(Fn) + new + call setline(1, 'two') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[12, 1, ''], [12, 0, 'two']], g:TsrFunc1Args) + bw! + + #" Test for using a funcref() + set thesaurusfunc=funcref('g:TsrFunc1',\ [13]) + new + call setline(1, 'three') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[13, 1, ''], [13, 0, 'three']], g:TsrFunc1Args) + bw! + + #" Using a funcref variable to set 'thesaurusfunc' + LET Fn = funcref('g:TsrFunc1', [14]) + LET &thesaurusfunc = Fn + new + call setline(1, 'four') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[14, 1, ''], [14, 0, 'four']], g:TsrFunc1Args) + bw! + + #" Using a string(funcref_variable) to set 'thesaurusfunc' + LET Fn = funcref('g:TsrFunc1', [15]) + LET &thesaurusfunc = string(Fn) + new + call setline(1, 'four') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[15, 1, ''], [15, 0, 'four']], g:TsrFunc1Args) + bw! + + #" Test for using a lambda function + VAR optval = "LSTART a, b LMIDDLE TsrFunc1(16, a, b) LEND" + LET optval = substitute(optval, ' ', '\\ ', 'g') + exe "set thesaurusfunc=" .. optval + new + call setline(1, 'five') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[16, 1, ''], [16, 0, 'five']], g:TsrFunc1Args) + bw! + + #" Test for using a lambda function with set + LET &thesaurusfunc = LSTART a, b LMIDDLE TsrFunc1(17, a, b) LEND + new + call setline(1, 'six') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[17, 1, ''], [17, 0, 'six']], g:TsrFunc1Args) + bw! + + #" Set 'thesaurusfunc' to a string(lambda expression) + LET &thesaurusfunc = 'LSTART a, b LMIDDLE TsrFunc1(18, a, b) LEND' + new + call setline(1, 'six') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[18, 1, ''], [18, 0, 'six']], g:TsrFunc1Args) + bw! + + #" Set 'thesaurusfunc' to a variable with a lambda expression + VAR Lambda = LSTART a, b LMIDDLE TsrFunc1(19, a, b) LEND + LET &thesaurusfunc = Lambda + new + call setline(1, 'seven') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[19, 1, ''], [19, 0, 'seven']], g:TsrFunc1Args) + bw! + + #" Set 'thesaurusfunc' to a string(variable with a lambda expression) + LET Lambda = LSTART a, b LMIDDLE TsrFunc1(20, a, b) LEND + LET &thesaurusfunc = string(Lambda) + new + call setline(1, 'seven') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[20, 1, ''], [20, 0, 'seven']], g:TsrFunc1Args) + bw! + + #" Test for using a lambda function with incorrect return value + LET Lambda = LSTART a, b LMIDDLE strlen(a) LEND + LET &thesaurusfunc = Lambda + new + call setline(1, 'eight') + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + bw! + + #" Test for clearing the 'thesaurusfunc' option + set thesaurusfunc='' + set thesaurusfunc& + call assert_fails("set thesaurusfunc=function('abc')", "E700:") + call assert_fails("set thesaurusfunc=funcref('abc')", "E700:") + + #" set 'thesaurusfunc' to a non-existing function + set thesaurusfunc=TsrFunc2 + call setline(1, 'ten') + call assert_fails("set thesaurusfunc=function('NonExistingFunc')", 'E700:') + call assert_fails("LET &thesaurusfunc = function('NonExistingFunc')", 'E700:') + LET g:TsrFunc2Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'ten']], g:TsrFunc2Args) + bw! + + #" Use a buffer-local value and a global value + set thesaurusfunc& + setlocal thesaurusfunc=function('g:TsrFunc1',\ [22]) + call setline(1, 'sun') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", "x") + call assert_equal('sun', getline(1)) + call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:TsrFunc1Args) + new + call setline(1, 'sun') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", "x") + call assert_equal('sun', getline(1)) + call assert_equal([], g:TsrFunc1Args) + set thesaurusfunc=function('g:TsrFunc1',\ [23]) + wincmd w + call setline(1, 'sun') + LET g:TsrFunc1Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", "x") + call assert_equal('sun', getline(1)) + call assert_equal([[22, 1, ''], [22, 0, 'sun']], g:TsrFunc1Args) + :%bw! + END + call CheckLegacyAndVim9Success(lines) + + " Test for using a script-local function name + func s:TsrFunc3(findstart, base) + call add(g:TsrFunc3Args, [a:findstart, a:base]) + return a:findstart ? 0 : [] + endfunc + set tsrfu=s:TsrFunc3 + new + call setline(1, 'script1') + let g:TsrFunc3Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'script1']], g:TsrFunc3Args) + bw! + + let &tsrfu = 's:TsrFunc3' + new + call setline(1, 'script2') + let g:TsrFunc3Args = [] + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + call assert_equal([[1, ''], [0, 'script2']], g:TsrFunc3Args) + bw! + delfunc s:TsrFunc3 + + " invalid return value + let &thesaurusfunc = {a -> 'abc'} + call feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + + " Using Vim9 lambda expression in legacy context should fail + " set thesaurusfunc=(a,\ b)\ =>\ TsrFunc1(21,\ a,\ b) + new | only + let g:TsrFunc1Args = [] + " call assert_fails('call feedkeys("A\<C-X>\<C-T>\<Esc>", "x")', 'E117:') + call assert_equal([], g:TsrFunc1Args) + bw! + + " set 'thesaurusfunc' to a partial with dict. This used to cause a crash. + func SetTsrFunc() + let params = {'thesaurus': function('g:DictTsrFunc')} + let &thesaurusfunc = params.thesaurus + endfunc + func g:DictTsrFunc(_) dict + endfunc + call SetTsrFunc() + new + call SetTsrFunc() + bw + call test_garbagecollect_now() + new + set thesaurusfunc= + wincmd w + %bw! + delfunc SetTsrFunc + + " set buffer-local 'thesaurusfunc' to a partial with dict. This used to + " cause a crash. + func SetLocalTsrFunc() + let params = {'thesaurus': function('g:DictTsrFunc')} + let &l:thesaurusfunc = params.thesaurus + endfunc + call SetLocalTsrFunc() + call test_garbagecollect_now() + call SetLocalTsrFunc() + set thesaurusfunc= + bw! + delfunc g:DictTsrFunc + delfunc SetLocalTsrFunc + + " Vim9 tests + let lines =<< trim END + vim9script + + def Vim9tsrFunc(callnr: number, findstart: number, base: string): any + add(g:Vim9tsrFunc_Args, [callnr, findstart, base]) + return findstart ? 0 : [] + enddef + + # Test for using a def function with thesaurusfunc + set thesaurusfunc=function('Vim9tsrFunc',\ [60]) + new | only + setline(1, 'one') + g:Vim9tsrFunc_Args = [] + feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + assert_equal([[60, 1, ''], [60, 0, 'one']], g:Vim9tsrFunc_Args) + bw! + + # Test for using a global function name + &thesaurusfunc = g:TsrFunc2 + new | only + setline(1, 'two') + g:TsrFunc2Args = [] + feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + assert_equal([[1, ''], [0, 'two']], g:TsrFunc2Args) + bw! + + # Test for using a script-local function name + def LocalTsrFunc(findstart: number, base: string): any + add(g:LocalTsrFuncArgs, [findstart, base]) + return findstart ? 0 : [] + enddef + &thesaurusfunc = LocalTsrFunc + new | only + setline(1, 'three') + g:LocalTsrFuncArgs = [] + feedkeys("A\<C-X>\<C-T>\<Esc>", 'x') + assert_equal([[1, ''], [0, 'three']], g:LocalTsrFuncArgs) + bw! + END + call CheckScriptSuccess(lines) + + " cleanup + set thesaurusfunc& + delfunc TsrFunc1 + delfunc TsrFunc2 + unlet g:TsrFunc1Args g:TsrFunc2Args + %bw! +endfunc + +func FooBarComplete(findstart, base) + if a:findstart + return col('.') - 1 + else + return ["Foo", "Bar", "}"] + endif +endfunc + +func Test_complete_smartindent() + new + setlocal smartindent completefunc=FooBarComplete + + exe "norm! o{\<cr>\<c-x>\<c-u>\<c-p>}\<cr>\<esc>" + let result = getline(1,'$') + call assert_equal(['', '{','}',''], result) + bw! + delfunction! FooBarComplete +endfunc + +func Test_complete_overrun() + " this was going past the end of the copied text + new + sil norm si0s0 + bwipe! +endfunc + +func Test_infercase_very_long_line() + " this was truncating the line when inferring case + new + let longLine = "blah "->repeat(300) + let verylongLine = "blah "->repeat(400) + call setline(1, verylongLine) + call setline(2, longLine) + set ic infercase + exe "normal 2Go\<C-X>\<C-L>\<Esc>" + call assert_equal(longLine, getline(3)) + + " check that the too long text is NUL terminated + %del + norm o + norm 1987ax + exec "norm ox\<C-X>\<C-L>" + call assert_equal(repeat('x', 1987), getline(3)) + + bwipe! + set noic noinfercase +endfunc + +func Test_ins_complete_add() + " this was reading past the end of allocated memory + new + norm o + norm 7o + sil! norm o + + bwipe! +endfunc + +func Test_ins_complete_end_of_line() + " this was reading past the end of the line + new + norm 8oý + sil! norm o + + bwipe! +endfunc + +func s:Tagfunc(t,f,o) + bwipe! + return [] +endfunc + +" This was using freed memory, since 'complete' was in a wiped out buffer. +" Also using a window that was closed. +func Test_tagfunc_wipes_out_buffer() + new + set complete=.,t,w,b,u,i + se tagfunc=s:Tagfunc + sil norm i + + bwipe! +endfunc + +func Test_ins_complete_popup_position() + CheckScreendump + + let lines =<< trim END + vim9script + set nowrap + setline(1, ['one', 'two', 'this is line ', 'four']) + prop_type_add('test', {highlight: 'Error'}) + prop_add(3, 0, { + text_align: 'above', + text: 'The quick brown fox jumps over the lazy dog', + type: 'test' + }) + END + call writefile(lines, 'XinsPopup', 'D') + let buf = RunVimInTerminal('-S XinsPopup', #{rows: 10}) + + call term_sendkeys(buf, "3GA\<C-N>") + call VerifyScreenDump(buf, 'Test_ins_complete_popup_position_1', {}) + + call StopVimInTerminal(buf) +endfunc + +func GetCompleteInfo() + let g:compl_info = complete_info() + return '' +endfunc + +func Test_completion_restart() + new + set complete=. completeopt=menuone backspace=2 + call setline(1, 'workhorse workhorse') + exe "normal $a\<C-N>\<BS>\<BS>\<C-R>=GetCompleteInfo()\<CR>" + call assert_equal(1, len(g:compl_info['items'])) + call assert_equal('workhorse', g:compl_info['items'][0]['word']) + set complete& completeopt& backspace& + bwipe! +endfunc + +func Test_complete_info_index() + new + call setline(1, ["aaa", "bbb", "ccc", "ddd", "eee", "fff"]) + inoremap <buffer><F5> <C-R>=GetCompleteInfo()<CR> + + " Ensure 'index' in complete_info() is coherent with the 'items' array. + + set completeopt=menu,preview + " Search forward + call feedkeys("Go\<C-X>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal("bbb", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal("ccc", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal("ddd", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal("eee", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + " Search forward: unselected item + call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal(6 , len(g:compl_info['items'])) + call assert_equal(-1 , g:compl_info['selected']) + + " Search backward + call feedkeys("Go\<C-X>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal("eee", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal("ddd", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal("ccc", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal("bbb", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + " search backwards: unselected item + call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal(6 , len(g:compl_info['items'])) + call assert_equal(-1 , g:compl_info['selected']) + + " switch direction: forwards, then backwards + call feedkeys("Go\<C-X>\<C-N>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + " switch direction: forwards, then backwards, then forwards again + call feedkeys("Go\<C-X>\<C-N>\<C-P>\<C-P>\<F5>\<Esc>_dd", 'tx') + call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-P>\<C-P>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + + " switch direction: backwards, then forwards + call feedkeys("Go\<C-X>\<C-P>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + " switch direction: backwards, then forwards, then backwards again + call feedkeys("Go\<C-X>\<C-P>\<C-P>\<C-N>\<C-N>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + + " Add 'noselect', check that 'selected' is -1 when nothing is selected. + set completeopt+=noselect + " Search forward. + call feedkeys("Go\<C-X>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal(-1, g:compl_info['selected']) + + " Search backward. + call feedkeys("Go\<C-X>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal(-1, g:compl_info['selected']) + + call feedkeys("Go\<C-X>\<C-N>\<C-P>\<F5>\<Esc>_dd", 'tx') + call assert_equal(0, g:compl_info['selected']) + call assert_equal(6 , len(g:compl_info['items'])) + call assert_equal("fff", g:compl_info['items'][g:compl_info['selected']]['word']) + call feedkeys("Go\<C-X>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal("aaa", g:compl_info['items'][g:compl_info['selected']]['word']) + call assert_equal(6 , len(g:compl_info['items'])) + call feedkeys("Go\<C-X>\<C-N>\<F5>\<Esc>_dd", 'tx') + call assert_equal(-1, g:compl_info['selected']) + call assert_equal(6 , len(g:compl_info['items'])) + + set completeopt& + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_ins_complete_no_halt.vim b/test/old/testdir/test_ins_complete_no_halt.vim new file mode 100644 index 0000000000..e12925daa9 --- /dev/null +++ b/test/old/testdir/test_ins_complete_no_halt.vim @@ -0,0 +1,51 @@ +" Test insert mode completion does not get stuck when looping around. +" In a separate file to avoid the settings to leak to other test cases. + +set complete+=kspell +set completeopt+=menu +set completeopt+=menuone +set completeopt+=noselect +set completeopt+=noinsert +let g:autocompletion = v:true + +func Test_ins_complete_no_halt() + function! OpenCompletion() + if pumvisible() && (g:autocompletion == v:true) + call feedkeys("\<C-e>\<C-n>", "i") + return + endif + if ((v:char >= 'a' && v:char <= 'z') || (v:char >= 'A' && v:char <= 'Z')) && (g:autocompletion == v:true) + call feedkeys("\<C-n>", "i") + redraw + endif + endfunction + + autocmd InsertCharPre * noautocmd call OpenCompletion() + + setlocal spell! spelllang=en_us + + call feedkeys("iauto-complete-halt-test test test test test test test test test test test test test test test test test test test\<C-c>", "tx!") + call assert_equal(["auto-complete-halt-test test test test test test test test test test test test test test test test test test test"], getline(1, "$")) +endfunc + +func Test_auto_complete_backwards_no_halt() + function! OpenCompletion() + if pumvisible() && (g:autocompletion == v:true) + call feedkeys("\<C-e>\<C-p>", "i") + return + endif + if ((v:char >= 'a' && v:char <= 'z') || (v:char >= 'A' && v:char <= 'Z')) && (g:autocompletion == v:true) + call feedkeys("\<C-p>", "i") + redraw + endif + endfunction + + autocmd InsertCharPre * noautocmd call OpenCompletion() + + setlocal spell! spelllang=en_us + + call feedkeys("iauto-complete-halt-test test test test test test test test test test test test test test test test test test test\<C-c>", "tx!") + call assert_equal(["auto-complete-halt-test test test test test test test test test test test test test test test test test test test"], getline(1, "$")) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_interrupt.vim b/test/old/testdir/test_interrupt.vim new file mode 100644 index 0000000000..aa7f634302 --- /dev/null +++ b/test/old/testdir/test_interrupt.vim @@ -0,0 +1,32 @@ +" Test behavior of interrupt() + +let s:bufwritepre_called = 0 +let s:bufwritepost_called = 0 + +func s:bufwritepre() + let s:bufwritepre_called = 1 + call interrupt() +endfunction + +func s:bufwritepost() + let s:bufwritepost_called = 1 +endfunction + +func Test_interrupt() + new Xinterrupt + let n = 0 + try + au BufWritePre Xinterrupt call s:bufwritepre() + au BufWritePost Xinterrupt call s:bufwritepost() + w! + catch /^Vim:Interrupt$/ + endtry + call assert_equal(1, s:bufwritepre_called) + call assert_equal(0, s:bufwritepost_called) + call assert_equal(0, filereadable('Xinterrupt')) + + au! BufWritePre + au! BufWritePost +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_join.vim b/test/old/testdir/test_join.vim new file mode 100644 index 0000000000..1f7a0825a5 --- /dev/null +++ b/test/old/testdir/test_join.vim @@ -0,0 +1,447 @@ +" Test for joining lines. + +func Test_join_with_count() + new + call setline(1, ['one', 'two', 'three', 'four']) + normal J + call assert_equal('one two', getline(1)) + %del + call setline(1, ['one', 'two', 'three', 'four']) + normal 10J + call assert_equal('one two three four', getline(1)) + + call setline(1, ['one', '', 'two']) + normal J + call assert_equal('one', getline(1)) + + call setline(1, ['one', ' ', 'two']) + normal J + call assert_equal('one', getline(1)) + + call setline(1, ['one', '', '', 'two']) + normal JJ + call assert_equal('one', getline(1)) + + call setline(1, ['one', ' ', ' ', 'two']) + normal JJ + call assert_equal('one', getline(1)) + + call setline(1, ['one', '', '', 'two']) + normal 2J + call assert_equal('one', getline(1)) + + quit! +endfunc + +" Tests for setting the '[,'] marks when joining lines. +func Test_join_marks() + enew + call append(0, [ + \ "\t\tO sodales, ludite, vos qui", + \ "attamen consulite per voster honur. Tua pulchra " . + \ "facies me fay planszer milies", + \ "", + \ "This line.", + \ "Should be joined with the next line", + \ "and with this line"]) + + normal gg0gqj + call assert_equal([0, 1, 1, 0], getpos("'[")) + call assert_equal([0, 2, 1, 0], getpos("']")) + + /^This line/;'}-join + call assert_equal([0, 4, 11, 0], getpos("'[")) + call assert_equal([0, 4, 67, 0], getpos("']")) + enew! +endfunc + +" Test for joining lines and marks in them +" in compatible and nocompatible modes +" and with 'joinspaces' set or not +" and with 'cpoptions' flag 'j' set or not +func Test_join_spaces_marks() + new + " Text used for the test + insert +asdfasdf. +asdf +asdfasdf. +asdf +asdfasdf. +asdf +asdfasdf. +asdf +asdfasdf. +asdf +asdfasdf. +asdf +asdfasdf. +asdf +asdfasdf +asdf +asdfasdf +asdf +asdfasdf +asdf +asdfasdf +asdf +asdfasdf +asdf +asdfasdf +asdf +asdfasdf +asdf +zx cvn. +as dfg? +hjkl iop! +ert +zx cvn. +as dfg? +hjkl iop! +ert +. + let text = getline(1, '$') + normal gg + + set nojoinspaces + set cpoptions-=j + normal JjJjJjJjJjJjJjJjJjJjJjJjJjJ + normal j05lmx + normal 2j06lmy + normal 2k4Jy3l$p + normal `xyl$p + normal `yy2l$p + + " set cpoptions+=j + normal j05lmx + normal 2j06lmy + normal 2k4Jy3l$p + normal `xyl$p + normal `yy2l$p + + " Expected output + let expected =<< trim [DATA] + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + zx cvn. as dfg? hjkl iop! ert ernop + zx cvn. as dfg? hjkl iop! ert ernop + [DATA] + + call assert_equal(expected, getline(1, '$')) + throw 'skipped: Nvim does not support "set compatible" or "set cpoptions+=j"' + + enew! + call append(0, text) + normal gg + + set cpoptions-=j + set joinspaces + normal JjJjJjJjJjJjJjJjJjJjJjJjJjJ + normal j05lmx + normal 2j06lmy + normal 2k4Jy3l$p + normal `xyl$p + normal `yy2l$p + + set cpoptions+=j + normal j05lmx + normal 2j06lmy + normal 2k4Jy3l$p + normal `xyl$p + normal `yy2l$p + + " Expected output + let expected =<< trim [DATA] + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + zx cvn. as dfg? hjkl iop! ert enop + zx cvn. as dfg? hjkl iop! ert ernop + + [DATA] + + call assert_equal(expected, getline(1, '$')) + + enew! + call append(0, text) + normal gg + + set cpoptions-=j + set nojoinspaces + set compatible + + normal JjJjJjJjJjJjJjJjJjJjJjJjJjJ + normal j4Jy3l$pjdG + + " Expected output + let expected =<< trim [DATA] + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf. asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + asdfasdf asdf + zx cvn. as dfg? hjkl iop! ert a + [DATA] + + call assert_equal(expected, getline(1, '$')) + + set nocompatible + set cpoptions&vim + set joinspaces&vim + close! +endfunc + +" Test for joining lines with comments +func Test_join_lines_with_comments() + new + + " Text used by the test + insert +{ + +/* +* Make sure the previous comment leader is not removed. +*/ + +/* +* Make sure the previous comment leader is not removed. +*/ + +// Should the next comment leader be left alone? +// Yes. + +// Should the next comment leader be left alone? +// Yes. + +/* Here the comment leader should be left intact. */ +// And so should this one. + +/* Here the comment leader should be left intact. */ +// And so should this one. + +if (condition) // Remove the next comment leader! +// OK, I will. +action(); + +if (condition) // Remove the next comment leader! +// OK, I will. +action(); +} +. + + call cursor(2, 1) + set comments=s1:/*,mb:*,ex:*/,:// + set nojoinspaces fo=j + set backspace=eol,start + + .,+3join + exe "normal j4J\<CR>" + .,+2join + exe "normal j3J\<CR>" + .,+2join + exe "normal j3J\<CR>" + .,+2join + exe "normal jj3J\<CR>" + + " Expected output + let expected =<< trim [CODE] + { + /* Make sure the previous comment leader is not removed. */ + /* Make sure the previous comment leader is not removed. */ + // Should the next comment leader be left alone? Yes. + // Should the next comment leader be left alone? Yes. + /* Here the comment leader should be left intact. */ // And so should this one. + /* Here the comment leader should be left intact. */ // And so should this one. + if (condition) // Remove the next comment leader! OK, I will. + action(); + if (condition) // Remove the next comment leader! OK, I will. + action(); + } + [CODE] + + call assert_equal(expected, getline(1, '$')) + + set comments&vim + set joinspaces&vim + set fo&vim + set backspace&vim + close! +endfunc + +" Test for joining lines with different comment leaders +func Test_join_comments_2() + new + + insert +{ + +/* + * Make sure the previous comment leader is not removed. + */ + +/* + * Make sure the previous comment leader is not removed. + */ + +/* List: + * - item1 + * foo bar baz + * foo bar baz + * - item2 + * foo bar baz + * foo bar baz + */ + +/* List: + * - item1 + * foo bar baz + * foo bar baz + * - item2 + * foo bar baz + * foo bar baz + */ + +// Should the next comment leader be left alone? +// Yes. + +// Should the next comment leader be left alone? +// Yes. + +/* Here the comment leader should be left intact. */ +// And so should this one. + +/* Here the comment leader should be left intact. */ +// And so should this one. + +if (condition) // Remove the next comment leader! + // OK, I will. + action(); + +if (condition) // Remove the next comment leader! + // OK, I will. + action(); + +int i = 7 /* foo *// 3 + // comment + ; + +int i = 7 /* foo *// 3 + // comment + ; + +># Note that the last character of the ending comment leader (left angle + # bracket) is a comment leader itself. Make sure that this comment leader is + # not removed from the next line #< +< On this line a new comment is opened which spans 2 lines. This comment should +< retain its comment leader. + +># Note that the last character of the ending comment leader (left angle + # bracket) is a comment leader itself. Make sure that this comment leader is + # not removed from the next line #< +< On this line a new comment is opened which spans 2 lines. This comment should +< retain its comment leader. + +} +. + + call cursor(2, 1) + set comments=sO:*\ -,mO:*\ \ ,exO:*/ + set comments+=s1:/*,mb:*,ex:*/,:// + set comments+=s1:>#,mb:#,ex:#<,:< + set cpoptions-=j joinspaces fo=j + set backspace=eol,start + + .,+3join + exe "normal j4J\<CR>" + .,+8join + exe "normal j9J\<CR>" + .,+2join + exe "normal j3J\<CR>" + .,+2join + exe "normal j3J\<CR>" + .,+2join + exe "normal jj3J\<CR>j" + .,+2join + exe "normal jj3J\<CR>j" + .,+5join + exe "normal j6J\<CR>" + exe "normal oSome code!\<CR>// Make sure backspacing does not remove this comment leader.\<Esc>0i\<C-H>\<Esc>" + + " Expected output + let expected =<< trim [CODE] + { + /* Make sure the previous comment leader is not removed. */ + /* Make sure the previous comment leader is not removed. */ + /* List: item1 foo bar baz foo bar baz item2 foo bar baz foo bar baz */ + /* List: item1 foo bar baz foo bar baz item2 foo bar baz foo bar baz */ + // Should the next comment leader be left alone? Yes. + // Should the next comment leader be left alone? Yes. + /* Here the comment leader should be left intact. */ // And so should this one. + /* Here the comment leader should be left intact. */ // And so should this one. + if (condition) // Remove the next comment leader! OK, I will. + action(); + if (condition) // Remove the next comment leader! OK, I will. + action(); + int i = 7 /* foo *// 3 // comment + ; + int i = 7 /* foo *// 3 // comment + ; + ># Note that the last character of the ending comment leader (left angle bracket) is a comment leader itself. Make sure that this comment leader is not removed from the next line #< < On this line a new comment is opened which spans 2 lines. This comment should retain its comment leader. + ># Note that the last character of the ending comment leader (left angle bracket) is a comment leader itself. Make sure that this comment leader is not removed from the next line #< < On this line a new comment is opened which spans 2 lines. This comment should retain its comment leader. + + Some code!// Make sure backspacing does not remove this comment leader. + } + [CODE] + + call assert_equal(expected, getline(1, '$')) + close! +endfunc + +func Test_join_lines() + new + call setline(1, ['a', 'b', '', 'c', 'd']) + %join + call assert_equal('a b c d', getline(1)) + call setline(1, ['a', 'b', '', 'c', 'd']) + normal 5J + call assert_equal('a b c d', getline(1)) + call setline(1, ['a', 'b', 'c']) + 2,2join + call assert_equal(['a', 'b', 'c'], getline(1, '$')) + call assert_equal(2, line('.')) + 2join + call assert_equal(['a', 'b c'], getline(1, '$')) + bwipe! +endfunc diff --git a/test/old/testdir/test_jumplist.vim b/test/old/testdir/test_jumplist.vim new file mode 100644 index 0000000000..b4dcdad9d6 --- /dev/null +++ b/test/old/testdir/test_jumplist.vim @@ -0,0 +1,173 @@ +" Tests for the jumplist functionality + +" Tests for the getjumplist() function +func Test_getjumplist() + if !has("jumplist") + return + endif + + %bwipe + clearjumps + call assert_equal([[], 0], getjumplist()) + call assert_equal([[], 0], getjumplist(1)) + call assert_equal([[], 0], getjumplist(1, 1)) + + call assert_equal([], getjumplist(100)) + call assert_equal([], getjumplist(1, 100)) + + let lines = [] + for i in range(1, 100) + call add(lines, "Line " . i) + endfor + call writefile(lines, "Xtest") + + " Jump around and create a jump list + edit Xtest + let bnr = bufnr('%') + normal 50% + normal G + normal gg + + let expected = [[ + \ {'lnum': 1, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 50, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 100, 'bufnr': bnr, 'col': 0, 'coladd': 0}], 3] + call assert_equal(expected, getjumplist()) + " jumplist doesn't change in between calls + call assert_equal(expected, getjumplist()) + + " Traverse the jump list and verify the results + 5 + exe "normal \<C-O>" + call assert_equal(2, 1->getjumplist()[1]) + exe "normal 2\<C-O>" + call assert_equal(0, getjumplist(1, 1)[1]) + exe "normal 3\<C-I>" + call assert_equal(3, getjumplist()[1]) + exe "normal \<C-O>" + normal 20% + let expected = [[ + \ {'lnum': 1, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 50, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 5, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 100, 'bufnr': bnr, 'col': 0, 'coladd': 0}], 4] + call assert_equal(expected, getjumplist()) + " jumplist doesn't change in between calls + call assert_equal(expected, getjumplist()) + + let l = getjumplist() + call test_garbagecollect_now() + call assert_equal(4, l[1]) + clearjumps + call test_garbagecollect_now() + call assert_equal(4, l[1]) + + call delete("Xtest") +endfunc + +func Test_jumplist_invalid() + new + clearjumps + " put some randome text + put ='a' + let prev = bufnr('%') + setl nomodified bufhidden=wipe + e XXJumpListBuffer + let bnr = bufnr('%') + " 1) empty jumplist + let expected = [[ + \ {'lnum': 2, 'bufnr': prev, 'col': 0, 'coladd': 0}], 1] + call assert_equal(expected, getjumplist()) + let jumps = execute(':jumps') + call assert_equal('>', jumps[-1:]) + " now jump back + exe ":norm! \<c-o>" + let expected = [[ + \ {'lnum': 2, 'bufnr': prev, 'col': 0, 'coladd': 0}, + \ {'lnum': 1, 'bufnr': bnr, 'col': 0, 'coladd': 0}], 0] + call assert_equal(expected, getjumplist()) + let jumps = execute(':jumps') + call assert_match('> 0 2 0 -invalid-', jumps) +endfunc + +" Test for '' mark in an empty buffer + +func Test_empty_buffer() + new + insert +a +b +c +d +. + call assert_equal(1, line("''")) + bwipe! +endfunc + +" Test for 'jumpoptions' +func Test_jumpoptions() + new + call setline(1, range(1, 200)) + clearjumps + set jumpoptions=stack + + " Jump around to add some locations to the jump list. + normal 10G + normal 20G + normal 30G + normal 40G + normal 50G + let bnr = bufnr() + + " discards the tail when navigating from the middle + exe "normal \<C-O>\<C-O>" + call assert_equal([ + \ [{'lnum': 1, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 10, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 20, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 30, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 40, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 50, 'bufnr': bnr, 'col': 0, 'coladd': 0} + \ ], 3], getjumplist()) + + " new jump location is added immediately after the last one + normal 90G + call assert_equal([ + \ [{'lnum': 1, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 10, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 20, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 30, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ ], 4], getjumplist()) + + " does not add the same location twice adjacently + normal 60G + normal 60G + call assert_equal([ + \ [{'lnum': 1, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 10, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 20, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 30, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 90, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + "\ Nvim: avoids useless/phantom jumps + "\ {'lnum': 60, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + "\ ], 6], getjumplist()) + \ ], 5], getjumplist()) + + " does add the same location twice non adjacently + normal 10G + normal 20G + call assert_equal([ + \ [{'lnum': 1, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 10, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 20, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 30, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 90, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 60, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ {'lnum': 10, 'bufnr': bnr, 'col': 0, 'coladd': 0}, + \ ], 7], getjumplist()) + + set jumpoptions& + %bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_lambda.vim b/test/old/testdir/test_lambda.vim new file mode 100644 index 0000000000..810b41b389 --- /dev/null +++ b/test/old/testdir/test_lambda.vim @@ -0,0 +1,335 @@ +" Test for lambda and closure + +func Test_lambda_feature() + call assert_equal(1, has('lambda')) +endfunc + +func Test_lambda_with_filter() + let s:x = 2 + call assert_equal([2, 3], filter([1, 2, 3], {i, v -> v >= s:x})) +endfunc + +func Test_lambda_with_map() + let s:x = 1 + call assert_equal([2, 3, 4], map([1, 2, 3], {i, v -> v + s:x})) +endfunc + +func Test_lambda_with_sort() + call assert_equal([1, 2, 3, 4, 7], sort([3,7,2,1,4], {a, b -> a - b})) +endfunc + +func Test_lambda_with_timer() + if !has('timers') + return + endif + + let s:n = 0 + let s:timer_id = 0 + func! s:Foo() + let s:timer_id = timer_start(10, {-> execute("let s:n += 1 | echo s:n", "")}, {"repeat": -1}) + endfunc + + call s:Foo() + " check timer works + for i in range(0, 10) + if s:n > 0 + break + endif + sleep 10m + endfor + + " do not collect lambda + call test_garbagecollect_now() + + " check timer still works + let m = s:n + for i in range(0, 10) + if s:n > m + break + endif + sleep 10m + endfor + + call timer_stop(s:timer_id) + call assert_true(s:n > m) +endfunc + +func Test_lambda_with_partial() + let l:Cb = function({... -> ['zero', a:1, a:2, a:3]}, ['one', 'two']) + call assert_equal(['zero', 'one', 'two', 'three'], l:Cb('three')) +endfunc + +function Test_lambda_fails() + call assert_equal(3, {a, b -> a + b}(1, 2)) + call assert_fails('echo {a, a -> a + a}(1, 2)', 'E853:') + call assert_fails('echo {a, b -> a + b)}(1, 2)', 'E451:') + echo assert_fails('echo 10->{a -> a + 2}', 'E107:') +endfunc + +func Test_not_lambda() + let x = {'>' : 'foo'} + call assert_equal('foo', x['>']) +endfunc + +func Test_lambda_capture_by_reference() + let v = 1 + let l:F = {x -> x + v} + let v = 2 + call assert_equal(12, l:F(10)) +endfunc + +func Test_lambda_side_effect() + func! s:update_and_return(arr) + let a:arr[1] = 5 + return a:arr + endfunc + + func! s:foo(arr) + return {-> s:update_and_return(a:arr)} + endfunc + + let arr = [3,2,1] + call assert_equal([3, 5, 1], s:foo(arr)()) +endfunc + +func Test_lambda_refer_local_variable_from_other_scope() + func! s:foo(X) + return a:X() " refer l:x in s:bar() + endfunc + + func! s:bar() + let x = 123 + return s:foo({-> x}) + endfunc + + call assert_equal(123, s:bar()) +endfunc + +func Test_lambda_do_not_share_local_variable() + func! s:define_funcs() + let l:One = {-> split(execute("let a = 'abc' | echo a"))[0]} + let l:Two = {-> exists("a") ? a : "no"} + return [l:One, l:Two] + endfunc + + let l:F = s:define_funcs() + + call assert_equal('no', l:F[1]()) + call assert_equal('abc', l:F[0]()) + call assert_equal('no', l:F[1]()) +endfunc + +func Test_lambda_closure_counter() + func! s:foo() + let x = 0 + return {-> [execute("let x += 1"), x][-1]} + endfunc + + let l:F = s:foo() + call test_garbagecollect_now() + call assert_equal(1, l:F()) + call assert_equal(2, l:F()) + call assert_equal(3, l:F()) + call assert_equal(4, l:F()) +endfunc + +func Test_lambda_with_a_var() + func! s:foo() + let x = 2 + return {... -> a:000 + [x]} + endfunc + func! s:bar() + return s:foo()(1) + endfunc + + call assert_equal([1, 2], s:bar()) +endfunc + +func Test_lambda_call_lambda_from_lambda() + func! s:foo(x) + let l:F1 = {-> {-> a:x}} + return {-> l:F1()} + endfunc + + let l:F = s:foo(1) + call assert_equal(1, l:F()()) +endfunc + +func Test_lambda_delfunc() + func! s:gen() + let pl = l: + let l:Foo = {-> get(pl, "Foo", get(pl, "Bar", {-> 0}))} + let l:Bar = l:Foo + delfunction l:Foo + return l:Bar + endfunc + + let l:F = s:gen() + call assert_fails(':call l:F()', 'E933:') +endfunc + +func Test_lambda_scope() + func! s:NewCounter() + let c = 0 + return {-> [execute('let c += 1'), c][-1]} + endfunc + + func! s:NewCounter2() + return {-> [execute('let c += 100'), c][-1]} + endfunc + + let l:C = s:NewCounter() + let l:D = s:NewCounter2() + + call assert_equal(1, l:C()) + call assert_fails(':call l:D()', 'E121:') + call assert_equal(2, l:C()) +endfunc + +func Test_lambda_share_scope() + func! s:New() + let c = 0 + let l:Inc0 = {-> [execute('let c += 1'), c][-1]} + let l:Dec0 = {-> [execute('let c -= 1'), c][-1]} + return [l:Inc0, l:Dec0] + endfunc + + let [l:Inc, l:Dec] = s:New() + + call assert_equal(1, l:Inc()) + call assert_equal(2, l:Inc()) + call assert_equal(1, l:Dec()) +endfunc + +func Test_lambda_circular_reference() + func! s:Foo() + let d = {} + let d.f = {-> d} + return d.f + endfunc + + call s:Foo() + call test_garbagecollect_now() + let i = 0 | while i < 10000 | call s:Foo() | let i+= 1 | endwhile + call test_garbagecollect_now() +endfunc + +func Test_lambda_combination() + call assert_equal(2, {x -> {x -> x}}(1)(2)) + call assert_equal(10, {y -> {x -> x(y)(10)}({y -> y})}({z -> z})) + call assert_equal(5.0, {x -> {y -> x / y}}(10)(2.0)) + call assert_equal(6, {x -> {y -> {z -> x + y + z}}}(1)(2)(3)) + + call assert_equal(6, {x -> {f -> f(x)}}(3)({x -> x * 2})) + call assert_equal(6, {f -> {x -> f(x)}}({x -> x * 2})(3)) + + " Z combinator + let Z = {f -> {x -> f({y -> x(x)(y)})}({x -> f({y -> x(x)(y)})})} + let Fact = {f -> {x -> x == 0 ? 1 : x * f(x - 1)}} + call assert_equal(120, Z(Fact)(5)) +endfunc + +func Test_closure_counter() + func! s:foo() + let x = 0 + func! s:bar() closure + let x += 1 + return x + endfunc + return function('s:bar') + endfunc + + let l:F = s:foo() + call test_garbagecollect_now() + call assert_equal(1, l:F()) + call assert_equal(2, l:F()) + call assert_equal(3, l:F()) + call assert_equal(4, l:F()) + + call assert_match("^\n function <SNR>\\d\\+_bar() closure" + \ .. "\n1 let x += 1" + \ .. "\n2 return x" + \ .. "\n endfunction$", execute('func s:bar')) +endfunc + +func Test_closure_unlet() + func! s:foo() + let x = 1 + func! s:bar() closure + unlet x + endfunc + call s:bar() + return l: + endfunc + + call assert_false(has_key(s:foo(), 'x')) + call test_garbagecollect_now() +endfunc + +func LambdaFoo() + let x = 0 + func! LambdaBar() closure + let x += 1 + return x + endfunc + return function('LambdaBar') +endfunc + +func Test_closure_refcount() + let g:Count = LambdaFoo() + call test_garbagecollect_now() + call assert_equal(1, g:Count()) + let g:Count2 = LambdaFoo() + call test_garbagecollect_now() + call assert_equal(1, g:Count2()) + call assert_equal(2, g:Count()) + call assert_equal(3, g:Count2()) + + delfunc LambdaFoo + delfunc LambdaBar +endfunc + +" This test is causing a use-after-free on shutdown. +func Test_named_function_closure() + func! Afoo() + let x = 14 + func! s:Abar() closure + return x + endfunc + call assert_equal(14, s:Abar()) + endfunc + call Afoo() + call assert_equal(14, s:Abar()) + call test_garbagecollect_now() + call assert_equal(14, s:Abar()) +endfunc + +func Test_lambda_with_index() + let List = {x -> [x]} + let Extract = {-> function(List, ['foobar'])()[0]} + call assert_equal('foobar', Extract()) +endfunc + +func Test_lambda_error() + " This was causing a crash + call assert_fails('ec{@{->{d->()()', 'E15') +endfunc + +func Test_closure_error() + let l =<< trim END + func F1() closure + return 1 + endfunc + END + call writefile(l, 'Xscript') + let caught_932 = 0 + try + source Xscript + catch /E932:/ + let caught_932 = 1 + endtry + call assert_equal(1, caught_932) + call delete('Xscript') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_langmap.vim b/test/old/testdir/test_langmap.vim new file mode 100644 index 0000000000..aaed77e109 --- /dev/null +++ b/test/old/testdir/test_langmap.vim @@ -0,0 +1,89 @@ +" tests for 'langmap' + +source check.vim +CheckFeature langmap + +func Test_langmap() + new + set langmap=}l,^x,%v + + call setline(1, ['abc']) + call feedkeys('gg0}^', 'tx') + call assert_equal('ac', getline(1)) + + " in Replace mode + " need silent! to avoid a delay when entering Insert mode + call setline(1, ['abcde']) + silent! call feedkeys("gg0lR%{z\<Esc>00", 'tx') + call assert_equal('a%{ze', getline(1)) + + " in Select mode + " need silent! to avoid a delay when entering Insert mode + call setline(1, ['abcde']) + silent! call feedkeys("gg0}%}\<C-G>}^\<Esc>00", 'tx') + call assert_equal('a}^de', getline(1)) + + " Error cases + call assert_fails('set langmap=aA,b', 'E357:') + call assert_fails('set langmap=z;y;y;z', 'E358:') + + " Map character > 256 + enew! + set langmap=āx,ăl,āx + call setline(1, ['abcde']) + call feedkeys('gg2lā', 'tx') + call assert_equal('abde', getline(1)) + + " special characters in langmap + enew! + call setline(1, ['Hello World']) + set langmap=\\;\\,,\\,\\; + call feedkeys('ggfo,', 'tx') + call assert_equal(8, col('.')) + call feedkeys(';', 'tx') + call assert_equal(5, col('.')) + set langmap& + set langmap=\\;\\,;\\,\\; + call feedkeys('ggfo,', 'tx') + call assert_equal(8, col('.')) + call feedkeys(';', 'tx') + call assert_equal(5, col('.')) + + set langmap=RL + let g:counter = 0 + nnoremap L;L <Cmd>let g:counter += 1<CR> + nnoremap <C-L> <Cmd>throw 'This mapping should not be triggered'<CR> + + " 'langmap' is applied to keys without modifiers when matching a mapping + call feedkeys('R;R', 'tx') + call assert_equal(1, g:counter) + nunmap L;L + unlet g:counter + + delete + call assert_equal('', getline(1)) + undo + call assert_equal('Hello World', getline(1)) + " 'langmap' does not change Ctrl-R to Ctrl-L for consistency + call feedkeys("\<*C-R>", 'tx') + call assert_equal('', getline(1)) + + set langmap=6L + undo + setlocal bufhidden=hide + let oldbuf = bufnr() + enew + call assert_notequal(oldbuf, bufnr()) + " 'langmap' does not change Ctrl-6 to Ctrl-L for consistency + " Ctrl-6 becomes Ctrl-^ after merging the Ctrl modifier + call feedkeys("\<*C-6>", 'tx') + call assert_equal(oldbuf, bufnr()) + setlocal bufhidden& + + nunmap <C-L> + + set langmap& + quit! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_largefile.vim b/test/old/testdir/test_largefile.vim new file mode 100644 index 0000000000..fa32b7fb5c --- /dev/null +++ b/test/old/testdir/test_largefile.vim @@ -0,0 +1,29 @@ +" Tests for large files +" This is only executed manually: "TEST_FILE=test_largefile.res make oldtest". +" This is not run as part of "make test". + +func Test_largefile() + let fname = 'Xlarge.txt' + + call delete(fname) + exe "e" fname + " Make sure that a line break is 1 byte (LF). + set ff=unix + set undolevels=-1 + " Input 99 'A's. The line becomes 100 bytes including a line break. + exe "normal 99iA\<Esc>" + yank + " Put 39,999,999 times. The file becomes 4,000,000,000 bytes. + normal 39999999p + " Moving around in the file randomly. + normal G + normal 10% + normal 90% + normal 50% + normal gg + w + " Check if the file size is 4,000,000,000 bytes. + let fsize=getfsize(fname) + call assert_true(fsize == 4000000000) + call delete(fname) +endfunc diff --git a/test/old/testdir/test_let.vim b/test/old/testdir/test_let.vim new file mode 100644 index 0000000000..a9cc8a14a4 --- /dev/null +++ b/test/old/testdir/test_let.vim @@ -0,0 +1,696 @@ +" Tests for the :let command. + +source vim9.vim + +func Test_let() + " Test to not autoload when assigning. It causes internal error. + set runtimepath+=./sautest + let Test104#numvar = function('tr') + call assert_equal("function('tr')", string(Test104#numvar)) + + let foo#tr = function('tr') + call assert_equal("function('tr')", string(foo#tr)) + unlet foo#tr + + let a = 1 + let b = 2 + + let out = execute('let a b') + let s = "\na #1\nb #2" + call assert_equal(s, out) + + let out = execute('let {0 == 1 ? "a" : "b"}') + let s = "\nb #2" + call assert_equal(s, out) + + let out = execute('let {0 == 1 ? "a" : "b"} a') + let s = "\nb #2\na #1" + call assert_equal(s, out) + + let out = execute('let a {0 == 1 ? "a" : "b"}') + let s = "\na #1\nb #2" + call assert_equal(s, out) + + " Test for displaying a string variable + let s = 'vim' + let out = execute('let s') + let s = "\ns vim" + call assert_equal(s, out) + + " Test for displaying a list variable + let l = [1, 2] + let out = execute('let l') + let s = "\nl [1, 2]" + call assert_equal(s, out) + + " Test for displaying a dict variable + let d = {'k' : 'v'} + let out = execute('let d') + let s = "\nd {'k': 'v'}" + call assert_equal(s, out) + + " Test for displaying a function reference variable + let F = function('min') + let out = execute('let F') + let s = "\nF *min()" + call assert_equal(s, out) + + let x = 0 + if 0 | let x = 1 | endif + call assert_equal(0, x) + + " Display a list item using an out of range index + let l = [10] + call assert_fails('let l[1]', 'E684:') + + " List special variable dictionaries + let g:Test_Global_Var = 5 + call assert_match("\nTest_Global_Var #5", execute('let g:')) + unlet g:Test_Global_Var + + let b:Test_Buf_Var = 8 + call assert_match("\nb:Test_Buf_Var #8", execute('let b:')) + unlet b:Test_Buf_Var + + let w:Test_Win_Var = 'foo' + call assert_equal("\nw:Test_Win_Var foo", execute('let w:')) + unlet w:Test_Win_Var + + let t:Test_Tab_Var = 'bar' + call assert_equal("\nt:Test_Tab_Var bar", execute('let t:')) + unlet t:Test_Tab_Var + + let s:Test_Script_Var = [7] + call assert_match("\ns:Test_Script_Var \\[7]", execute('let s:')) + unlet s:Test_Script_Var + + let l:Test_Local_Var = {'k' : 5} + call assert_match("\nl:Test_Local_Var {'k': 5}", execute('let l:')) + call assert_match("v:errors []", execute('let v:')) + + " Test for assigning multiple list items + let l = [1, 2, 3] + let [l[0], l[1]] = [10, 20] + call assert_equal([10, 20, 3], l) + + " Test for errors in conditional expression + call assert_fails('let val = [] ? 1 : 2', 'E745:') + call assert_fails('let val = 1 ? 5+ : 6', 'E121:') + call assert_fails('let val = 1 ? 0 : 5+', 'E15:') + call assert_false(exists('val')) + + " Test for errors in logical operators + let @a = 'if [] || 0 | let val = 2 | endif' + call assert_fails('exe @a', 'E745:') + call assert_fails('call feedkeys(":let val = 0 || []\<cr>", "xt")', 'E745:') + call assert_fails('exe "let val = [] && 5"', 'E745:') + call assert_fails('exe "let val = 6 && []"', 'E745:') +endfunc + +func s:set_arg1(a) abort + let a:a = 1 +endfunction + +func s:set_arg2(a) abort + let a:b = 1 +endfunction + +func s:set_arg3(a) abort + let b = a: + let b['a'] = 1 +endfunction + +func s:set_arg4(a) abort + let b = a: + let b['a'] = 1 +endfunction + +func s:set_arg5(a) abort + let b = a: + let b['a'][0] = 1 +endfunction + +func s:set_arg6(a) abort + let a:a[0] = 1 +endfunction + +func s:set_arg7(a) abort + call extend(a:, {'a': 1}) +endfunction + +func s:set_arg8(a) abort + call extend(a:, {'b': 1}) +endfunction + +func s:set_arg9(a) abort + let a:['b'] = 1 +endfunction + +func s:set_arg10(a) abort + let b = a: + call extend(b, {'a': 1}) +endfunction + +func s:set_arg11(a) abort + let b = a: + call extend(b, {'b': 1}) +endfunction + +func s:set_arg12(a) abort + let b = a: + let b['b'] = 1 +endfunction + +func Test_let_arg_fail() + call assert_fails('call s:set_arg1(1)', 'E46:') + call assert_fails('call s:set_arg2(1)', 'E461:') + call assert_fails('call s:set_arg3(1)', 'E46:') + call assert_fails('call s:set_arg4(1)', 'E46:') + call assert_fails('call s:set_arg5(1)', 'E46:') + call s:set_arg6([0]) + call assert_fails('call s:set_arg7(1)', 'E742:') + call assert_fails('call s:set_arg8(1)', 'E742:') + call assert_fails('call s:set_arg9(1)', 'E461:') + call assert_fails('call s:set_arg10(1)', 'E742:') + call assert_fails('call s:set_arg11(1)', 'E742:') + call assert_fails('call s:set_arg12(1)', 'E461:') +endfunction + +func s:set_varg1(...) abort + let a:000 = [] +endfunction + +func s:set_varg2(...) abort + let a:000[0] = 1 +endfunction + +func s:set_varg3(...) abort + let a:000 += [1] +endfunction + +func s:set_varg4(...) abort + call add(a:000, 1) +endfunction + +func s:set_varg5(...) abort + let a:000[0][0] = 1 +endfunction + +func s:set_varg6(...) abort + let b = a:000 + let b[0] = 1 +endfunction + +func s:set_varg7(...) abort + let b = a:000 + let b += [1] +endfunction + +func s:set_varg8(...) abort + let b = a:000 + call add(b, 1) +endfunction + +func s:set_varg9(...) abort + let b = a:000 + let b[0][0] = 1 +endfunction + +func Test_let_varg_fail() + call assert_fails('call s:set_varg1(1)', 'E46:') + call assert_fails('call s:set_varg2(1)', 'E742:') + call assert_fails('call s:set_varg3(1)', 'E46:') + call assert_fails('call s:set_varg4(1)', 'E742:') + call s:set_varg5([0]) + call assert_fails('call s:set_varg6(1)', 'E742:') + call assert_fails('call s:set_varg7(1)', 'E742:') + call assert_fails('call s:set_varg8(1)', 'E742:') + call s:set_varg9([0]) +endfunction + +func Test_let_utf8_environment() + let $a = 'ĀĒĪŌŪあいうえお' + call assert_equal('ĀĒĪŌŪあいうえお', $a) +endfunc + +func Test_let_no_type_checking() + let v = 1 + let v = [1,2,3] + let v = {'a': 1, 'b': 2} + let v = 3.4 + let v = 'hello' +endfunc + +func Test_let_termcap() + throw 'Skipped: Nvim does not support termcap options' + " Terminal code + let old_t_te = &t_te + let &t_te = "\<Esc>[yes;" + call assert_match('t_te.*^[[yes;', execute("set termcap")) + let &t_te = old_t_te + + if exists("+t_k1") + " Key code + let old_t_k1 = &t_k1 + let &t_k1 = "that" + call assert_match('t_k1.*that', execute("set termcap")) + let &t_k1 = old_t_k1 + endif + + call assert_fails('let x = &t_xx', 'E113:') + let &t_xx = "yes" + call assert_equal("yes", &t_xx) + let &t_xx = "" + call assert_fails('let x = &t_xx', 'E113:') +endfunc + +func Test_let_option_error() + let _w = &tw + let &tw = 80 + call assert_fails('let &tw .= 1', ['E734:', 'E734:']) + call assert_fails('let &tw .= []', ['E734:', 'E734:']) + call assert_fails('let &tw = []', ['E745:', 'E745:']) + call assert_fails('let &tw += []', ['E745:', 'E745:']) + call assert_equal(80, &tw) + let &tw = _w + + let _w = &autoread + let &autoread = 1 + call assert_fails('let &autoread .= 1', ['E734:', 'E734:']) + call assert_fails('let &autoread .= []', ['E734:', 'E734:']) + call assert_fails('let &autoread = []', ['E745:', 'E745:']) + call assert_fails('let &autoread += []', ['E745:', 'E745:']) + call assert_equal(1, &autoread) + let &autoread = _w + + let _w = &fillchars + let &fillchars = "vert:|" + call assert_fails('let &fillchars += "diff:-"', ['E734:', 'E734:']) + call assert_fails('let &fillchars += []', ['E734:', 'E734:']) + call assert_fails('let &fillchars = []', ['E730:', 'E730:']) + call assert_fails('let &fillchars .= []', ['E730:', 'E730:']) + call assert_equal("vert:|", &fillchars) + let &fillchars = _w + + call assert_fails('let &nosuchoption = 1', ['E355:', 'E355:']) + call assert_fails('let &nosuchoption = ""', ['E355:', 'E355:']) + call assert_fails('let &nosuchoption = []', ['E355:', 'E355:']) + call assert_fails('let &t_xx = []', ['E730:', 'E730:']) +endfunc + +" Errors with the :let statement +func Test_let_errors() + let s = 'abcd' + call assert_fails('let s[1] = 5', 'E689:') + + let l = [1, 2, 3] + call assert_fails('let l[:] = 5', 'E709:') + + call assert_fails('let x:lnum=5', ['E121:', 'E488:']) + call assert_fails('let v:=5', 'E461:') + call assert_fails('let [a]', 'E474:') + call assert_fails('let [a, b] = [', 'E697:') + call assert_fails('let [a, b] = [10, 20', 'E696:') + call assert_fails('let [a, b] = 10', 'E714:') + call assert_fails('let [a, , b] = [10, 20]', 'E475:') + call assert_fails('let [a, b&] = [10, 20]', 'E475:') + call assert_fails('let $ = 10', 'E475:') + call assert_fails('let $FOO[1] = "abc"', 'E18:') + call assert_fails('let &buftype[1] = "nofile"', 'E18:') + let s = "var" + let var = 1 + call assert_fails('let var += [1,2]', 'E734:') + call assert_fails('let {s}.1 = 2', 'E1203:') + call assert_fails('let a[1] = 5', 'E121:') + let l = [[1,2]] + call assert_fails('let l[:][0] = [5]', 'E708:') + let d = {'k' : 4} + call assert_fails('let d.# = 5', 'E488:') + call assert_fails('let d.m += 5', 'E716:') + call assert_fails('let m = d[{]', 'E15:') + let l = [1, 2] + call assert_fails('let l[2] = 0', 'E684:') + call assert_fails('let l[0:1] = [1, 2, 3]', 'E710:') + call assert_fails('let l[-2:-3] = [3, 4]', 'E684:') + call assert_fails('let l[0:4] = [5, 6]', 'E711:') + call assert_fails('let l -= 2', 'E734:') + call assert_fails('let l += 2', 'E734:') + call assert_fails('let g:["a;b"] = 10', 'E461:') + call assert_fails('let g:.min = function("max")', 'E704:') + call assert_fails('let g:cos = "" | let g:.cos = {-> 42}', 'E704:') + if has('channel') + let ch = test_null_channel() + call assert_fails('let ch += 1', 'E734:') + endif + call assert_fails('let name = "a" .. "b",', 'E488: Trailing characters: ,') + + " This test works only when the language is English + if v:lang == "C" || v:lang =~ '^[Ee]n' + call assert_fails('let [a ; b;] = [10, 20]', + \ 'Double ; in list of variables') + endif +endfunc + +func Test_let_heredoc_fails() + call assert_fails('let v =<< marker', 'E991:') + try + exe "let v =<< TEXT | abc | TEXT" + call assert_report('No exception thrown') + catch /E488:/ + catch + call assert_report('Caught exception: ' .. v:exception) + endtry + + try + let &commentstring =<< trim TEXT + change + insert + append + TEXT + call assert_report('No exception thrown') + catch /E730:/ + catch + call assert_report('Caught exception: ' .. v:exception) + endtry + + try + let $SOME_ENV_VAR =<< trim TEXT + change + insert + append + TEXT + call assert_report('No exception thrown') + catch /E730:/ + catch + call assert_report('Caught exception: ' .. v:exception) + endtry + + try + let @r =<< trim TEXT + change + insert + append + TEXT + call assert_report('No exception thrown') + catch /E730:/ + catch + call assert_report('Caught exception: ' .. v:exception) + endtry + + let text =<< trim END + func WrongSyntax() + let v =<< that there + endfunc + END + call writefile(text, 'XheredocFail') + call assert_fails('source XheredocFail', 'E1145:') + call delete('XheredocFail') + + let text =<< trim CodeEnd + func MissingEnd() + let v =<< END + endfunc + CodeEnd + call writefile(text, 'XheredocWrong') + call assert_fails('source XheredocWrong', 'E1145:') + call delete('XheredocWrong') + + let text =<< trim TEXTend + let v =<< " comment + TEXTend + call writefile(text, 'XheredocNoMarker') + call assert_fails('source XheredocNoMarker', 'E172:') + call delete('XheredocNoMarker') + + let text =<< trim TEXTend + let v =<< text + TEXTend + call writefile(text, 'XheredocBadMarker') + call assert_fails('source XheredocBadMarker', 'E221:') + call delete('XheredocBadMarker') + + call writefile(['let v =<< TEXT', 'abc'], 'XheredocMissingMarker') + call assert_fails('source XheredocMissingMarker', 'E990:') + call delete('XheredocMissingMarker') +endfunc + +func Test_let_heredoc_trim_no_indent_marker() + let text =<< trim END + Text + with + indent +END + call assert_equal(['Text', 'with', 'indent'], text) +endfunc + +func Test_let_interpolated() + call assert_equal('{text}', $'{{text}}') + call assert_equal('{{text}}', $'{{{{text}}}}') + let text = 'text' + call assert_equal('text{{', $'{text .. "{{"}') + call assert_equal('text{{', $"{text .. '{{'}") + call assert_equal('text{{', $'{text .. '{{'}') + call assert_equal('text{{', $"{text .. "{{"}") +endfunc + +" Test for the setting a variable using the heredoc syntax. +" Keep near the end, this messes up highlighting. +func Test_let_heredoc() + let var1 =<< END +Some sample text + Text with indent + !@#$%^&*()-+_={}|[]\~`:";'<>?,./ +END + + call assert_equal(["Some sample text", "\tText with indent", " !@#$%^&*()-+_={}|[]\\~`:\";'<>?,./"], var1) + + let var2 =<< XXX +Editor +XXX + call assert_equal(['Editor'], var2) + + let var3 =<<END +END + call assert_equal([], var3) + + let var3 =<<END +vim + +end + END +END +END + call assert_equal(['vim', '', 'end', ' END', 'END '], var3) + + let var1 =<< trim END + Line1 + Line2 + Line3 + END + END + call assert_equal(['Line1', ' Line2', "\tLine3", ' END'], var1) + + let var1 =<< trim !!! + Line1 + line2 + Line3 + !!! + !!! + call assert_equal(['Line1', ' line2', "\tLine3", '!!!',], var1) + + let var1 =<< trim XX + Line1 + XX + call assert_equal(['Line1'], var1) + + " ignore "endfunc" + let var1 =<< END +something +endfunc +END + call assert_equal(['something', 'endfunc'], var1) + + " ignore "endfunc" with trim + let var1 =<< trim END + something + endfunc + END + call assert_equal(['something', 'endfunc'], var1) + + " ignore "python << xx" + let var1 =<<END +something +python << xx +END + call assert_equal(['something', 'python << xx'], var1) + + " ignore "python << xx" with trim + let var1 =<< trim END + something + python << xx + END + call assert_equal(['something', 'python << xx'], var1) + + " ignore "append" + let var1 =<< E +something +app +E + call assert_equal(['something', 'app'], var1) + + " ignore "append" with trim + let var1 =<< trim END + something + app + END + call assert_equal(['something', 'app'], var1) + + let check = [] + if 0 + let check =<< trim END + from heredoc + END + endif + call assert_equal([], check) + + " unpack assignment + let [a, b, c] =<< END + x + \y + z +END + call assert_equal([' x', ' \y', ' z'], [a, b, c]) + + " unpack assignment without whitespace + let[a,b,c]=<<END +change +insert +append +END + call assert_equal(['change', 'insert', 'append'], [a, b, c]) + + " curly braces name and list slice assignment + let foo_3_bar = ['', '', ''] + let foo_{1 + 2}_bar[ : ] =<< END +change +insert +append +END + call assert_equal(['change', 'insert', 'append'], foo_3_bar) + + " dictionary key containing brackets and spaces + let d = {'abc] 123': 'baz'} + let d[d['abc] 123'] .. '{'] =<< END +change +insert +append +END + call assert_equal(['change', 'insert', 'append'], d['baz{']) +endfunc + +" Test for evaluating Vim expressions in a heredoc using {expr} +" Keep near the end, this messes up highlighting. +func Test_let_heredoc_eval() + let str = '' + let code =<< trim eval END + let a = {5 + 10} + let b = {min([10, 6])} + {max([4, 6])} + {str} + let c = "abc{str}d" + END + call assert_equal(['let a = 15', 'let b = 6 + 6', '', 'let c = "abcd"'], code) + + let $TESTVAR = "Hello" + let code =<< eval trim END + let s = "{$TESTVAR}" + END + call assert_equal(['let s = "Hello"'], code) + + let code =<< eval END + let s = "{$TESTVAR}" +END + call assert_equal([' let s = "Hello"'], code) + + let a = 10 + let data =<< eval END +{a} +END + call assert_equal(['10'], data) + + let x = 'X' + let code =<< eval trim END + let a = {{abc}} + let b = {x} + let c = {{ + END + call assert_equal(['let a = {abc}', 'let b = X', 'let c = {'], code) + + let code = 'xxx' + let code =<< eval trim END + let n = {5 + + 6} + END + call assert_equal('xxx', code) + + let code =<< eval trim END + let n = {min([1, 2]} + {max([3, 4])} + END + call assert_equal('xxx', code) + + let lines =<< trim LINES + let text =<< eval trim END + let b = { + END + LINES + call CheckScriptFailure(lines, 'E1279:') + + let lines =<< trim LINES + let text =<< eval trim END + let b = {abc + END + LINES + call CheckScriptFailure(lines, 'E1279:') + + let lines =<< trim LINES + let text =<< eval trim END + let b = {} + END + LINES + call CheckScriptFailure(lines, 'E15:') + + " skipped heredoc + if 0 + let msg =<< trim eval END + n is: {n} + END + endif + + " Test for sourcing a script containing a heredoc with invalid expression. + " Variable assignment should fail, if expression evaluation fails + new + let g:Xvar = 'test' + let g:b = 10 + let lines =<< trim END + let Xvar =<< eval CODE + let a = 1 + let b = {5+} + let c = 2 + CODE + let g:Count += 1 + END + call setline(1, lines) + let g:Count = 0 + call assert_fails('source', 'E15:') + call assert_equal(1, g:Count) + call setline(3, 'let b = {abc}') + call assert_fails('source', 'E121:') + call assert_equal(2, g:Count) + call setline(3, 'let b = {abc} + {min([9, 4])} + 2') + call assert_fails('source', 'E121:') + call assert_equal(3, g:Count) + call assert_equal('test', g:Xvar) + call assert_equal(10, g:b) + bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_lineending.vim b/test/old/testdir/test_lineending.vim new file mode 100644 index 0000000000..5be3be8db3 --- /dev/null +++ b/test/old/testdir/test_lineending.vim @@ -0,0 +1,19 @@ +" Tests for saving/loading a file with some lines ending in +" CTRL-M, some not +func Test_lineending() + let l = ["this line ends in a\<CR>", + \ "this one doesn't", + \ "this one does\<CR>", + \ "and the last one doesn't"] + set fileformat=dos + enew! + call append(0, l) + $delete + write Xfile1 + bwipe Xfile1 + edit Xfile1 + let t = getline(1, '$') + call assert_equal(l, t) + new | only + call delete('Xfile1') +endfunc diff --git a/test/old/testdir/test_lispindent.vim b/test/old/testdir/test_lispindent.vim new file mode 100644 index 0000000000..2d6060bba3 --- /dev/null +++ b/test/old/testdir/test_lispindent.vim @@ -0,0 +1,129 @@ +" Tests for 'lispwords' settings being global-local. +" And other lisp indent stuff. + +set nocompatible viminfo+=nviminfo + +func Test_global_local_lispwords() + setglobal lispwords=foo,bar,baz + setlocal lispwords-=foo | setlocal lispwords+=quux + call assert_equal('foo,bar,baz', &g:lispwords) + call assert_equal('bar,baz,quux', &l:lispwords) + call assert_equal('bar,baz,quux', &lispwords) + + setlocal lispwords< + call assert_equal('foo,bar,baz', &g:lispwords) + call assert_equal('foo,bar,baz', &l:lispwords) + call assert_equal('foo,bar,baz', &lispwords) +endfunc + +func Test_lisp_indent() + enew! + + call append(0, [ + \ '(defun html-file (base)', + \ '(format nil "~(~A~).html" base))', + \ '', + \ '(defmacro page (name title &rest body)', + \ '(let ((ti (gensym)))', + \ '`(with-open-file (*standard-output*', + \ '(html-file ,name)', + \ ':direction :output', + \ ':if-exists :supersede)', + \ '(let ((,ti ,title))', + \ '(as title ,ti)', + \ '(with center ', + \ '(as h2 (string-upcase ,ti)))', + \ '(brs 3)', + \ ',@body))))', + \ '', + \ ';;; Utilities for generating links', + \ '', + \ '(defmacro with-link (dest &rest body)', + \ '`(progn', + \ '(format t "<a href=\"~A\">" (html-file ,dest))', + \ ',@body', + \ '(princ "</a>")))' + \ ]) + call assert_equal(7, lispindent(2)) + call assert_equal(5, 6->lispindent()) + call assert_equal(-1, lispindent(-1)) + + set lisp + set lispwords& + let save_copt = &cpoptions + set cpoptions+=p + normal 1G=G + + call assert_equal([ + \ '(defun html-file (base)', + \ ' (format nil "~(~A~).html" base))', + \ '', + \ '(defmacro page (name title &rest body)', + \ ' (let ((ti (gensym)))', + \ ' `(with-open-file (*standard-output*', + \ ' (html-file ,name)', + \ ' :direction :output', + \ ' :if-exists :supersede)', + \ ' (let ((,ti ,title))', + \ ' (as title ,ti)', + \ ' (with center ', + \ ' (as h2 (string-upcase ,ti)))', + \ ' (brs 3)', + \ ' ,@body))))', + \ '', + \ ';;; Utilities for generating links', + \ '', + \ '(defmacro with-link (dest &rest body)', + \ ' `(progn', + \ ' (format t "<a href=\"~A\">" (html-file ,dest))', + \ ' ,@body', + \ ' (princ "</a>")))', + \ '' + \ ], getline(1, "$")) + + enew! + let &cpoptions=save_copt + set nolisp +endfunc + +func Test_lispindent_negative() + " in legacy script there is no error + call assert_equal(-1, lispindent(-1)) +endfunc + +func Test_lispindent_with_indentexpr() + enew + setl ai lisp nocin indentexpr=11 + exe "normal a(x\<CR>1\<CR>2)\<Esc>" + let expected = ['(x', ' 1', ' 2)'] + call assert_equal(expected, getline(1, 3)) + " with Lisp indenting the first line is not indented + normal 1G=G + call assert_equal(expected, getline(1, 3)) + + %del + setl lispoptions=expr:1 indentexpr=5 + exe "normal a(x\<CR>1\<CR>2)\<Esc>" + let expected_expr = ['(x', ' 1', ' 2)'] + call assert_equal(expected_expr, getline(1, 3)) + normal 2G2<<=G + call assert_equal(expected_expr, getline(1, 3)) + + setl lispoptions=expr:0 + " with Lisp indenting the first line is not indented + normal 1G3<<=G + call assert_equal(expected, getline(1, 3)) + + bwipe! +endfunc + +func Test_lisp_indent_works() + " This was reading beyond the end of the line + new + exe "norm a\tü(\<CR>=" + set lisp + norm == + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_listchars.vim b/test/old/testdir/test_listchars.vim new file mode 100644 index 0000000000..179bdfa4a0 --- /dev/null +++ b/test/old/testdir/test_listchars.vim @@ -0,0 +1,677 @@ +" Tests for 'listchars' display with 'list' and :list + +source check.vim +source view_util.vim +source screendump.vim + +func Check_listchars(expected, end_lnum, end_scol = -1, leftcol = 0) + if a:leftcol > 0 + let save_wrap = &wrap + set nowrap + call cursor(1, 1) + exe 'normal! ' .. a:leftcol .. 'zl' + endif + + redraw! + for i in range(1, a:end_lnum) + if a:leftcol > 0 + let col = virtcol2col(0, i, a:leftcol) + let col += getline(i)->strpart(col - 1, 1, v:true)->len() + call cursor(i, col) + redraw + call assert_equal(a:leftcol, winsaveview().leftcol) + else + call cursor(i, 1) + end + + let end_scol = a:end_scol < 0 ? '$'->virtcol() - a:leftcol : a:end_scol + call assert_equal([a:expected[i - 1]->strcharpart(a:leftcol)], + \ ScreenLines(i, end_scol)) + endfor + + if a:leftcol > 0 + let &wrap = save_wrap + endif +endfunc + +func Test_listchars() + enew! + set ff=unix + set list + + set listchars+=tab:>-,space:.,trail:< + call append(0, [ + \ ' aa ', + \ ' bb ', + \ ' cccc ', + \ 'dd ee ', + \ ' ' + \ ]) + let expected = [ + \ '>-------aa>-----$', + \ '..bb>---<<$', + \ '...cccc><$', + \ 'dd........ee<<>-$', + \ '<$' + \ ] + call Check_listchars(expected, 5) + call Check_listchars(expected, 4, -1, 5) + + set listchars-=trail:< + let expected = [ + \ '>-------aa>-----$', + \ '..bb>---..$', + \ '...cccc>.$', + \ 'dd........ee..>-$', + \ '.$' + \ ] + call Check_listchars(expected, 5) + call Check_listchars(expected, 4, -1, 5) + + " tab with 3rd character. + set listchars-=tab:>- + set listchars+=tab:<=>,trail:- + let expected = [ + \ '<======>aa<====>$', + \ '..bb<==>--$', + \ '...cccc>-$', + \ 'dd........ee--<>$', + \ '-$' + \ ] + call Check_listchars(expected, 5) + call Check_listchars(expected, 4, -1, 5) + + " tab with 3rd character and linebreak set + set listchars-=tab:<=> + set listchars+=tab:<·> + set linebreak + let expected = [ + \ '<······>aa<····>$', + \ '..bb<··>--$', + \ '...cccc>-$', + \ 'dd........ee--<>$', + \ '-$' + \ ] + call Check_listchars(expected, 5) + set nolinebreak + set listchars-=tab:<·> + set listchars+=tab:<=> + + set listchars-=trail:- + let expected = [ + \ '<======>aa<====>$', + \ '..bb<==>..$', + \ '...cccc>.$', + \ 'dd........ee..<>$', + \ '.$' + \ ] + call Check_listchars(expected, 5) + call Check_listchars(expected, 4, -1, 5) + + set listchars-=tab:<=> + set listchars+=tab:>- + set listchars+=trail:< + set nolist + normal ggdG + call append(0, [ + \ ' fff ', + \ ' gg ', + \ ' h ', + \ 'iii ', + \ ]) + let l = split(execute("%list"), "\n") + call assert_equal([ + \ '..fff>--<<$', + \ '>-------gg>-----$', + \ '.....h>-$', + \ 'iii<<<<><<$', + \ '$'], l) + + " Test lead and trail + normal ggdG + set listchars=eol:$ " Accommodate Nvim default + set listchars+=lead:>,trail:<,space:x + set list + + call append(0, [ + \ ' ffff ', + \ ' gg', + \ 'h ', + \ ' ', + \ ' 0 0 ', + \ ]) + + let expected = [ + \ '>>>>ffff<<<<$', + \ '>>>>>>>>>>gg$', + \ 'h<<<<<<<<<<<$', + \ '<<<<<<<<<<<<$', + \ '>>>>0xx0<<<<$', + \ '$' + \ ] + call Check_listchars(expected, 6) + call Check_listchars(expected, 5, -1, 6) + call assert_equal(expected, split(execute("%list"), "\n")) + + " Test multispace + normal ggdG + set listchars=eol:$ " Accommodate Nvim default + set listchars+=multispace:yYzZ + set list + + call append(0, [ + \ ' ffff ', + \ ' i i gg', + \ ' h ', + \ ' j ', + \ ' 0 0 ', + \ ]) + + let expected = [ + \ 'yYzZffffyYzZ$', + \ 'yYi iyYzZygg$', + \ ' hyYzZyYzZyY$', + \ 'yYzZyYzZyYj $', + \ 'yYzZ0yY0yYzZ$', + \ '$' + \ ] + call Check_listchars(expected, 6) + call Check_listchars(expected, 5, -1, 6) + call assert_equal(expected, split(execute("%list"), "\n")) + + " Test leadmultispace + multispace + normal ggdG + set listchars=eol:$,multispace:yYzZ,nbsp:S + set listchars+=leadmultispace:.-+* + set list + + call append(0, [ + \ ' ffff ', + \ ' i i gg', + \ ' h ', + \ ' j ', + \ ' 0 0 ', + \ ]) + + let expected = [ + \ '.-+*ffffyYzZ$', + \ '.-i iSyYzZgg$', + \ ' hyYzZyYzZyY$', + \ '.-+*.-+*.-j $', + \ '.-+*0yY0yYzZ$', + \ '$' + \ ] + call assert_equal('eol:$,multispace:yYzZ,nbsp:S,leadmultispace:.-+*', &listchars) + call Check_listchars(expected, 6) + call Check_listchars(expected, 5, -1, 1) + call Check_listchars(expected, 5, -1, 2) + call Check_listchars(expected, 5, -1, 3) + call Check_listchars(expected, 5, -1, 6) + call assert_equal(expected, split(execute("%list"), "\n")) + + " Test leadmultispace without multispace + normal ggdG + set listchars-=multispace:yYzZ + set listchars+=space:+,trail:>,eol:$ + set list + + call append(0, [ + \ ' ffff ', + \ ' i i gg', + \ ' h ', + \ ' j ', + \ ' 0 0 ', + \ ]) + + let expected = [ + \ '.-+*ffff>>>>$', + \ '.-i+i+++++gg$', + \ '+h>>>>>>>>>>$', + \ '.-+*.-+*.-j>$', + \ '.-+*0++0>>>>$', + \ '$' + \ ] + call assert_equal('eol:$,nbsp:S,leadmultispace:.-+*,space:+,trail:>,eol:$', &listchars) + call Check_listchars(expected, 6) + call Check_listchars(expected, 5, -1, 1) + call Check_listchars(expected, 5, -1, 2) + call Check_listchars(expected, 5, -1, 3) + call Check_listchars(expected, 5, -1, 6) + call assert_equal(expected, split(execute("%list"), "\n")) + + " Test leadmultispace only + normal ggdG + set listchars=eol:$ " Accommodate Nvim default + set listchars=leadmultispace:.-+* + set list + + call append(0, [ + \ ' ffff ', + \ ' i i gg', + \ ' h ', + \ ' j ', + \ ' 0 0 ', + \ ]) + + let expected = [ + \ '.-+*ffff ', + \ '.-i i gg', + \ ' h ', + \ '.-+*.-+*.-j ', + \ '.-+*0 0 ', + \ ' ' + \ ] + call assert_equal('leadmultispace:.-+*', &listchars) + call Check_listchars(expected, 5, 12) + call assert_equal(expected, split(execute("%list"), "\n")) + + " Changing the value of 'ambiwidth' twice shouldn't cause double-free when + " "leadmultispace" is specified. + set ambiwidth=double + set ambiwidth& + + " Test leadmultispace and lead and space + normal ggdG + set listchars=eol:$ " Accommodate Nvim default + set listchars+=lead:<,space:- + set listchars+=leadmultispace:.-+* + set list + + call append(0, [ + \ ' ffff ', + \ ' i i gg', + \ ' h ', + \ ' j ', + \ ' 0 0 ', + \ ]) + + let expected = [ + \ '.-+*ffff----$', + \ '.-i-i-----gg$', + \ '<h----------$', + \ '.-+*.-+*.-j-$', + \ '.-+*0--0----$', + \ '$' + \ ] + call assert_equal('eol:$,lead:<,space:-,leadmultispace:.-+*', &listchars) + call Check_listchars(expected, 6) + call Check_listchars(expected, 5, -1, 1) + call Check_listchars(expected, 5, -1, 2) + call Check_listchars(expected, 5, -1, 3) + call Check_listchars(expected, 5, -1, 6) + call assert_equal(expected, split(execute("%list"), "\n")) + + " the last occurrence of 'multispace:' is used + set listchars=eol:$ " Accommodate Nvim default + set listchars+=multispace:yYzZ + set listchars+=space:x,multispace:XyY + + let expected = [ + \ 'XyYXffffXyYX$', + \ 'XyixiXyYXygg$', + \ 'xhXyYXyYXyYX$', + \ 'XyYXyYXyYXjx$', + \ 'XyYX0Xy0XyYX$', + \ '$' + \ ] + call assert_equal('eol:$,multispace:yYzZ,space:x,multispace:XyY', &listchars) + call Check_listchars(expected, 6) + call Check_listchars(expected, 5, -1, 6) + call assert_equal(expected, split(execute("%list"), "\n")) + + set listchars+=lead:>,trail:< + + let expected = [ + \ '>>>>ffff<<<<$', + \ '>>ixiXyYXygg$', + \ '>h<<<<<<<<<<$', + \ '>>>>>>>>>>j<$', + \ '>>>>0Xy0<<<<$', + \ '$' + \ ] + call Check_listchars(expected, 6) + call Check_listchars(expected, 5, -1, 6) + call assert_equal(expected, split(execute("%list"), "\n")) + + " removing 'multispace:' + set listchars-=multispace:XyY + set listchars-=multispace:yYzZ + + let expected = [ + \ '>>>>ffff<<<<$', + \ '>>ixixxxxxgg$', + \ '>h<<<<<<<<<<$', + \ '>>>>>>>>>>j<$', + \ '>>>>0xx0<<<<$', + \ '$' + \ ] + call Check_listchars(expected, 6) + call Check_listchars(expected, 5, -1, 6) + call assert_equal(expected, split(execute("%list"), "\n")) + + " test nbsp + normal ggdG + set listchars=nbsp:X,trail:Y + set list + " Non-breaking space + let nbsp = nr2char(0xa0) + call append(0, [ ">" .. nbsp .. "<" ]) + + let expected = '>X< ' + call Check_listchars([expected], 1) + + set listchars=nbsp:X + call Check_listchars([expected], 1) + + " test extends + normal ggdG + set listchars=extends:Z + set nowrap + set nolist + call append(0, [ repeat('A', &columns + 1) ]) + + let expected = repeat('A', &columns) + call Check_listchars([expected], 1, &columns) + + set list + let expected = expected[:-2] . 'Z' + call Check_listchars([expected], 1, &columns) + + enew! + set listchars& ff& +endfunc + +" Test that unicode listchars characters get properly inserted +func Test_listchars_unicode() + enew! + let oldencoding=&encoding + set encoding=utf-8 + set ff=unix + + set listchars=eol:⇔,space:␣,multispace:≡≢≣,nbsp:≠,tab:←↔→ + set list + + let nbsp = nr2char(0xa0) + call append(0, [" a\tb c" .. nbsp .. "d "]) + let expected = ['≡≢≣≡≢≣≡≢a←↔↔↔↔↔→b␣c≠d≡≢⇔'] + call Check_listchars(expected, 1) + call Check_listchars(expected, 1, -1, 3) + call Check_listchars(expected, 1, -1, 13) + + set listchars=eol:\\u21d4,space:\\u2423,multispace:≡\\u2262\\U00002263,nbsp:\\U00002260,tab:←↔\\u2192 + call Check_listchars(expected, 1) + call Check_listchars(expected, 1, -1, 3) + call Check_listchars(expected, 1, -1, 13) + + set listchars+=lead:⇨,trail:⇦ + let expected = ['⇨⇨⇨⇨⇨⇨⇨⇨a←↔↔↔↔↔→b␣c≠d⇦⇦⇔'] + call Check_listchars(expected, 1) + call Check_listchars(expected, 1, -1, 3) + call Check_listchars(expected, 1, -1, 13) + + let &encoding=oldencoding + enew! + set listchars& ff& +endfunction + +func Test_listchars_invalid() + enew! + set ff=unix + + set listchars=eol:$ " Accommodate Nvim default + set list + set ambiwidth=double + + " No colon + call assert_fails('set listchars=x', 'E474:') + call assert_fails('set listchars=x', 'E474:') + call assert_fails('set listchars=multispace', 'E474:') + call assert_fails('set listchars=leadmultispace', 'E474:') + + " Too short + call assert_fails('set listchars=space:', 'E474:') + call assert_fails('set listchars=tab:x', 'E474:') + call assert_fails('set listchars=multispace:', 'E474:') + call assert_fails('set listchars=leadmultispace:', 'E474:') + + " One occurrence too short + call assert_fails('set listchars=space:,space:x', 'E474:') + call assert_fails('set listchars=space:x,space:', 'E474:') + call assert_fails('set listchars=tab:x,tab:xx', 'E474:') + call assert_fails('set listchars=tab:xx,tab:x', 'E474:') + call assert_fails('set listchars=multispace:,multispace:x', 'E474:') + call assert_fails('set listchars=multispace:x,multispace:', 'E474:') + call assert_fails('set listchars=leadmultispace:,leadmultispace:x', 'E474:') + call assert_fails('set listchars=leadmultispace:x,leadmultispace:', 'E474:') + + " Too long + call assert_fails('set listchars=space:xx', 'E474:') + call assert_fails('set listchars=tab:xxxx', 'E474:') + + " Has double-width character + call assert_fails('set listchars=space:·', 'E474:') + call assert_fails('set listchars=tab:·x', 'E474:') + call assert_fails('set listchars=tab:x·', 'E474:') + call assert_fails('set listchars=tab:xx·', 'E474:') + call assert_fails('set listchars=multispace:·', 'E474:') + call assert_fails('set listchars=multispace:xxx·', 'E474:') + call assert_fails('set listchars=leadmultispace:·', 'E474:') + call assert_fails('set listchars=leadmultispace:xxx·', 'E474:') + + " Has control character + call assert_fails("set listchars=space:\x01", 'E474:') + call assert_fails("set listchars=tab:\x01x", 'E474:') + call assert_fails("set listchars=tab:x\x01", 'E474:') + call assert_fails("set listchars=tab:xx\x01", 'E474:') + call assert_fails("set listchars=multispace:\x01", 'E474:') + call assert_fails("set listchars=multispace:xxx\x01", 'E474:') + call assert_fails('set listchars=space:\\x01', 'E474:') + call assert_fails('set listchars=tab:\\x01x', 'E474:') + call assert_fails('set listchars=tab:x\\x01', 'E474:') + call assert_fails('set listchars=tab:xx\\x01', 'E474:') + call assert_fails('set listchars=multispace:\\x01', 'E474:') + call assert_fails('set listchars=multispace:xxx\\x01', 'E474:') + call assert_fails("set listchars=leadmultispace:\x01", 'E474:') + call assert_fails('set listchars=leadmultispace:\\x01', 'E474:') + call assert_fails("set listchars=leadmultispace:xxx\x01", 'E474:') + call assert_fails('set listchars=leadmultispace:xxx\\x01', 'E474:') + + enew! + set ambiwidth& listchars& ff& +endfunction + +" Tests that space characters following composing character won't get replaced +" by listchars. +func Test_listchars_composing() + enew! + let oldencoding=&encoding + set encoding=utf-8 + set ff=unix + set list + + set listchars=eol:$,space:_,nbsp:= + + let nbsp1 = nr2char(0xa0) + let nbsp2 = nr2char(0x202f) + call append(0, [ + \ " \u3099\t \u309A" .. nbsp1 .. nbsp1 .. "\u0302" .. nbsp2 .. nbsp2 .. "\u0302", + \ ]) + let expected = [ + \ "_ \u3099^I \u309A=" .. nbsp1 .. "\u0302=" .. nbsp2 .. "\u0302$" + \ ] + call Check_listchars(expected, 1) + let &encoding=oldencoding + enew! + set listchars& ff& +endfunction + +" Check for the value of the 'listchars' option +func s:CheckListCharsValue(expected) + call assert_equal(a:expected, &listchars) + call assert_equal(a:expected, getwinvar(0, '&listchars')) +endfunc + +" Test for using a window local value for 'listchars' +func Test_listchars_window_local() + %bw! + set list listchars& + let nvim_default = &listchars " Accommodate Nvim default + new + " set a local value for 'listchars' + setlocal listchars=tab:+-,eol:# + call s:CheckListCharsValue('tab:+-,eol:#') + " When local value is reset, global value should be used + setlocal listchars= + call s:CheckListCharsValue(nvim_default) + " Use 'setlocal <' to copy global value + setlocal listchars=space:.,extends:> + setlocal listchars< + call s:CheckListCharsValue(nvim_default) + " Use 'set <' to copy global value + setlocal listchars=space:.,extends:> + set listchars< + call s:CheckListCharsValue(nvim_default) + " Changing global setting should not change the local setting + setlocal listchars=space:.,extends:> + setglobal listchars=tab:+-,eol:# + call s:CheckListCharsValue('space:.,extends:>') + " when split opening a new window, local value should be copied + split + call s:CheckListCharsValue('space:.,extends:>') + " clearing local value in one window should not change the other window + set listchars& + call s:CheckListCharsValue(nvim_default) + close + call s:CheckListCharsValue('space:.,extends:>') + + " use different values for 'listchars' items in two different windows + call setline(1, ["\t one two "]) + setlocal listchars=tab:<->,lead:_,space:.,trail:@,eol:# + split + setlocal listchars=tab:[.],lead:#,space:_,trail:.,eol:& + split + set listchars=tab:+-+,lead:^,space:>,trail:<,eol:% + call assert_equal(['+------+^^one>>two<<%'], ScreenLines(1, virtcol('$'))) + close + call assert_equal(['[......]##one__two..&'], ScreenLines(1, virtcol('$'))) + close + call assert_equal(['<------>__one..two@@#'], ScreenLines(1, virtcol('$'))) + " changing the global setting should not change the local value + setglobal listchars=tab:[.],lead:#,space:_,trail:.,eol:& + call assert_equal(['<------>__one..two@@#'], ScreenLines(1, virtcol('$'))) + set listchars< + call assert_equal(['[......]##one__two..&'], ScreenLines(1, virtcol('$'))) + + " Using setglobal in a window with local setting should not affect the + " window. But should impact other windows using the global setting. + enew! | only + call setline(1, ["\t one two "]) + set listchars=tab:[.],lead:#,space:_,trail:.,eol:& + split + setlocal listchars=tab:+-+,lead:^,space:>,trail:<,eol:% + split + setlocal listchars=tab:<->,lead:_,space:.,trail:@,eol:# + setglobal listchars=tab:{.},lead:-,space:=,trail:#,eol:$ + call assert_equal(['<------>__one..two@@#'], ScreenLines(1, virtcol('$'))) + close + call assert_equal(['+------+^^one>>two<<%'], ScreenLines(1, virtcol('$'))) + close + call assert_equal(['{......}--one==two##$'], ScreenLines(1, virtcol('$'))) + + " Setting the global setting to the default value should not impact a window + " using a local setting. + split + setlocal listchars=tab:<->,lead:_,space:.,trail:@,eol:# + setglobal listchars=eol:$ " Accommodate Nvim default + call assert_equal(['<------>__one..two@@#'], ScreenLines(1, virtcol('$'))) + close + call assert_equal(['^I one two $'], ScreenLines(1, virtcol('$'))) + + " Setting the local setting to the default value should not impact a window + " using a global setting. + set listchars=tab:{.},lead:-,space:=,trail:#,eol:$ + split + setlocal listchars=tab:<->,lead:_,space:.,trail:@,eol:# + call assert_equal(['<------>__one..two@@#'], ScreenLines(1, virtcol('$'))) + setlocal listchars=eol:$ " Accommodate Nvim default + call assert_equal(['^I one two $'], ScreenLines(1, virtcol('$'))) + close + call assert_equal(['{......}--one==two##$'], ScreenLines(1, virtcol('$'))) + + " Using set in a window with a local setting should change it to use the + " global setting and also impact other windows using the global setting. + split + setlocal listchars=tab:<->,lead:_,space:.,trail:@,eol:# + call assert_equal(['<------>__one..two@@#'], ScreenLines(1, virtcol('$'))) + set listchars=tab:+-+,lead:^,space:>,trail:<,eol:% + call assert_equal(['+------+^^one>>two<<%'], ScreenLines(1, virtcol('$'))) + close + call assert_equal(['+------+^^one>>two<<%'], ScreenLines(1, virtcol('$'))) + + " Setting invalid value for a local setting should not impact the local and + " global settings. + split + setlocal listchars=tab:<->,lead:_,space:.,trail:@,eol:# + let cmd = 'setlocal listchars=tab:{.},lead:-,space:=,trail:#,eol:$,x' + call assert_fails(cmd, 'E474:') + call assert_equal(['<------>__one..two@@#'], ScreenLines(1, virtcol('$'))) + close + call assert_equal(['+------+^^one>>two<<%'], ScreenLines(1, virtcol('$'))) + + " Setting invalid value for a global setting should not impact the local and + " global settings. + split + setlocal listchars=tab:<->,lead:_,space:.,trail:@,eol:# + let cmd = 'setglobal listchars=tab:{.},lead:-,space:=,trail:#,eol:$,x' + call assert_fails(cmd, 'E474:') + call assert_equal(['<------>__one..two@@#'], ScreenLines(1, virtcol('$'))) + close + call assert_equal(['+------+^^one>>two<<%'], ScreenLines(1, virtcol('$'))) + + " Closing window with local lcs-multispace should not cause a memory leak. + setlocal listchars=multispace:---+ + split + call s:CheckListCharsValue('multispace:---+') + close + + %bw! + set list& listchars& +endfunc + +func Test_listchars_foldcolumn() + CheckScreendump + + let lines =<< trim END + call setline(1, ['aaa', '', 'a', 'aaaaaa']) + vsplit + vsplit + windo set signcolumn=yes foldcolumn=1 winminwidth=0 nowrap list listchars=extends:>,precedes:< + END + call writefile(lines, 'XTest_listchars') + + let buf = RunVimInTerminal('-S XTest_listchars', {'rows': 10, 'cols': 60}) + + call term_sendkeys(buf, "13\<C-W>>") + call VerifyScreenDump(buf, 'Test_listchars_01', {}) + call term_sendkeys(buf, "\<C-W>>") + call VerifyScreenDump(buf, 'Test_listchars_02', {}) + call term_sendkeys(buf, "\<C-W>>") + call VerifyScreenDump(buf, 'Test_listchars_03', {}) + call term_sendkeys(buf, "\<C-W>>") + call VerifyScreenDump(buf, 'Test_listchars_04', {}) + call term_sendkeys(buf, "\<C-W>>") + call VerifyScreenDump(buf, 'Test_listchars_05', {}) + call term_sendkeys(buf, "\<C-W>h") + call term_sendkeys(buf, ":set nowrap foldcolumn=4\<CR>") + call term_sendkeys(buf, "15\<C-W><") + call VerifyScreenDump(buf, 'Test_listchars_06', {}) + call term_sendkeys(buf, "4\<C-W><") + call VerifyScreenDump(buf, 'Test_listchars_07', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XTest_listchars') +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_listdict.vim b/test/old/testdir/test_listdict.vim new file mode 100644 index 0000000000..fef7c6a9bc --- /dev/null +++ b/test/old/testdir/test_listdict.vim @@ -0,0 +1,1425 @@ +" Tests for the List and Dict types +scriptencoding utf-8 + +source vim9.vim + +func TearDown() + " Run garbage collection after every test + call test_garbagecollect_now() +endfunc + +" Tests for List type + +" List creation +func Test_list_create() + " Creating List directly with different types + let l = [1, 'as''d', [1, 2, function("strlen")], {'a': 1},] + call assert_equal("[1, 'as''d', [1, 2, function('strlen')], {'a': 1}]", string(l)) + call assert_equal({'a' : 1}, l[-1]) + call assert_equal(1, l[-4]) + let x = 10 + try + let x = l[-5] + catch + call assert_match('E684:', v:exception) + endtry + call assert_equal(10, x) +endfunc + +" List slices +func Test_list_slice() + let l = [1, 'as''d', [1, 2, function("strlen")], {'a': 1},] + call assert_equal([1, 'as''d', [1, 2, function('strlen')], {'a': 1}], l[:]) + call assert_equal(['as''d', [1, 2, function('strlen')], {'a': 1}], l[1:]) + call assert_equal([1, 'as''d', [1, 2, function('strlen')]], l[:-2]) + call assert_equal([1, 'as''d', [1, 2, function('strlen')], {'a': 1}], l[0:8]) + call assert_equal([], l[8:-1]) + call assert_equal([], l[0:-10]) + " perform an operation on a list slice + let l = [1, 2, 3] + let l[:1] += [1, 2] + let l[2:] -= [1] + call assert_equal([2, 4, 2], l) + + let lines =<< trim END + VAR l = [1, 2] + call assert_equal([1, 2], l[:]) + call assert_equal([2], l[-1 : -1]) + call assert_equal([1, 2], l[-2 : -1]) + END + call CheckLegacyAndVim9Success(lines) + + let l = [1, 2] + call assert_equal([], l[-3 : -1]) + + let lines =<< trim END + var l = [1, 2] + assert_equal([1, 2], l[-3 : -1]) + END + call CheckDefAndScriptSuccess(lines) +endfunc + +" List identity +func Test_list_identity() + let lines =<< trim END + VAR l = [1, 'as''d', [1, 2, function("strlen")], {'a': 1},] + VAR ll = l + VAR lx = copy(l) + call assert_true(l == ll) + call assert_false(l isnot ll) + call assert_true(l is ll) + call assert_true(l == lx) + call assert_false(l is lx) + call assert_true(l isnot lx) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +" removing items with :unlet +func Test_list_unlet() + let lines =<< trim END + VAR l = [1, 'as''d', [1, 2, function("strlen")], {'a': 1},] + unlet l[2] + call assert_equal([1, 'as''d', {'a': 1}], l) + LET l = range(8) + unlet l[: 3] + unlet l[1 :] + call assert_equal([4], l) + + #" removing items out of range: silently skip items that don't exist + LET l = [0, 1, 2, 3] + unlet l[2 : 2] + call assert_equal([0, 1, 3], l) + LET l = [0, 1, 2, 3] + unlet l[2 : 3] + call assert_equal([0, 1], l) + LET l = [0, 1, 2, 3] + unlet l[2 : 4] + call assert_equal([0, 1], l) + LET l = [0, 1, 2, 3] + unlet l[2 : 5] + call assert_equal([0, 1], l) + LET l = [0, 1, 2, 3] + unlet l[-2 : 2] + call assert_equal([0, 1, 3], l) + LET l = [0, 1, 2, 3] + unlet l[-3 : 2] + call assert_equal([0, 3], l) + LET l = [0, 1, 2, 3] + unlet l[-4 : 2] + call assert_equal([3], l) + LET l = [0, 1, 2, 3] + unlet l[-5 : 2] + call assert_equal([3], l) + LET l = [0, 1, 2, 3] + unlet l[-6 : 2] + call assert_equal([3], l) + END + call CheckLegacyAndVim9Success(lines) + + let l = [0, 1, 2, 3] + unlet l[2:2] + call assert_equal([0, 1, 3], l) + let l = [0, 1, 2, 3] + unlet l[2:3] + call assert_equal([0, 1], l) + + let lines =<< trim END + VAR l = [0, 1, 2, 3] + unlet l[2 : 1] + END + call CheckLegacyAndVim9Failure(lines, 'E684:') + + let lines =<< trim END + VAR l = [0, 1, 2, 3] + unlet l[-1 : 2] + END + call CheckLegacyAndVim9Failure(lines, 'E684:') +endfunc + +" assignment to a list +func Test_list_assign() + let lines =<< trim END + VAR l = [0, 1, 2, 3] + VAR va = 0 + VAR vb = 0 + LET [va, vb] = l[2 : 3] + call assert_equal([2, 3], [va, vb]) + END + call CheckLegacyAndVim9Success(lines) + + let lines =<< trim END + let l = [0, 1, 2, 3] + let [va, vb] = l + END + call CheckScriptFailure(lines, 'E687:') + let lines =<< trim END + var l = [0, 1, 2, 3] + var va = 0 + var vb = 0 + [va, vb] = l + END + call CheckScriptFailure(['vim9script'] + lines, 'E687:') + call CheckDefExecFailure(lines, 'E1093: Expected 2 items but got 4') + + let lines =<< trim END + let l = [0, 1, 2, 3] + let [va, vb] = l[1:1] + END + call CheckScriptFailure(lines, 'E688:') + let lines =<< trim END + var l = [0, 1, 2, 3] + var va = 0 + var vb = 0 + [va, vb] = l[1 : 1] + END + call CheckScriptFailure(['vim9script'] + lines, 'E688:') + call CheckDefExecFailure(lines, 'E1093: Expected 2 items but got 1') +endfunc + +" test for range assign +func Test_list_range_assign() + let lines =<< trim END + VAR l = [0] + LET l[:] = [1, 2] + call assert_equal([1, 2], l) + LET l[-4 : -1] = [5, 6] + call assert_equal([5, 6], l) + END + call CheckLegacyAndVim9Success(lines) + + let lines =<< trim END + var l = [7] + l[:] = ['text'] + END + call CheckDefAndScriptFailure(lines, 'E1012:', 2) +endfunc + +" Test removing items in list +func Test_list_func_remove() + let lines =<< trim END + #" Test removing 1 element + VAR l = [1, 2, 3, 4] + call assert_equal(1, remove(l, 0)) + call assert_equal([2, 3, 4], l) + + LET l = [1, 2, 3, 4] + call assert_equal(2, remove(l, 1)) + call assert_equal([1, 3, 4], l) + + LET l = [1, 2, 3, 4] + call assert_equal(4, remove(l, -1)) + call assert_equal([1, 2, 3], l) + + #" Test removing range of element(s) + LET l = [1, 2, 3, 4] + call assert_equal([3], remove(l, 2, 2)) + call assert_equal([1, 2, 4], l) + + LET l = [1, 2, 3, 4] + call assert_equal([2, 3], remove(l, 1, 2)) + call assert_equal([1, 4], l) + + LET l = [1, 2, 3, 4] + call assert_equal([2, 3], remove(l, -3, -2)) + call assert_equal([1, 4], l) + END + call CheckLegacyAndVim9Success(lines) + + " Test invalid cases + let l = [1, 2, 3, 4] + call assert_fails("call remove(l, 5)", 'E684:') + call assert_fails("call remove(l, 1, 5)", 'E684:') + call assert_fails("call remove(l, 3, 2)", 'E16:') + call assert_fails("call remove(1, 0)", 'E896:') + call assert_fails("call remove(l, l)", 'E745:') +endfunc + +" List add() function +func Test_list_add() + let lines =<< trim END + VAR l = [] + call add(l, 1) + call add(l, [2, 3]) + call add(l, []) + call add(l, v:_null_list) + call add(l, {'k': 3}) + call add(l, {}) + call add(l, v:_null_dict) + call assert_equal([1, [2, 3], [], [], {'k': 3}, {}, {}], l) + END + call CheckLegacyAndVim9Success(lines) + + " weird legacy behavior + " call assert_equal(1, add(v:_null_list, 4)) +endfunc + +" Tests for Dictionary type + +func Test_dict() + " Creating Dictionary directly with different types + let lines =<< trim END + VAR d = {'1': 'asd', 'b': [1, 2, function('strlen')], '-1': {'a': 1}, } + call assert_equal("{'1': 'asd', 'b': [1, 2, function('strlen')], '-1': {'a': 1}}", string(d)) + call assert_equal('asd', d.1) + call assert_equal(['-1', '1', 'b'], sort(keys(d))) + call assert_equal(['asd', [1, 2, function('strlen')], {'a': 1}], values(d)) + call extend(d, {3: 33, 1: 99}) + call extend(d, {'b': 'bbb', 'c': 'ccc'}, "keep") + call assert_equal({'c': 'ccc', '1': 99, 'b': [1, 2, function('strlen')], '3': 33, '-1': {'a': 1}}, d) + END + call CheckLegacyAndVim9Success(lines) + + let d = {001: 'asd', 'b': [1, 2, function('strlen')], -1: {'a': 1},} + call assert_equal("{'1': 'asd', 'b': [1, 2, function('strlen')], '-1': {'a': 1}}", string(d)) + + let v = [] + for [key, val] in items(d) + call extend(v, [key, val]) + unlet key val + endfor + call assert_equal(['1','asd','b',[1, 2, function('strlen')],'-1',{'a': 1}], v) + + call extend(d, {3: 33, 1: 99}) + call assert_fails("call extend(d, {3:333,4:444}, 'error')", 'E737:') + + " duplicate key + call assert_fails("let d = {'k' : 10, 'k' : 20}", 'E721:') + " missing comma + call assert_fails("let d = {'k' : 10 'k' : 20}", 'E722:') + " missing curly brace + call assert_fails("let d = {'k' : 10,", 'E723:') + " invalid key + call assert_fails('let d = #{++ : 10}', 'E15:') + " wrong type for key + call assert_fails('let d={[] : 10}', 'E730:') + " undefined variable as value + call assert_fails("let d={'k' : i}", 'E121:') + + " allow key starting with number at the start, not a curly expression + call assert_equal({'1foo': 77}, #{1foo: 77}) + + " #{expr} is not a curly expression + let x = 'x' + call assert_equal(#{g: x}, #{g:x}) +endfunc + +" Dictionary identity +func Test_dict_identity() + let lines =<< trim END + VAR d = {'1': 'asd', 'b': [1, 2, function('strlen')], -1: {'a': 1}, } + VAR dd = d + VAR dx = copy(d) + call assert_true(d == dd) + call assert_false(d isnot dd) + call assert_true(d is dd) + call assert_true(d == dx) + call assert_false(d is dx) + call assert_true(d isnot dx) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +" removing items with :unlet +func Test_dict_unlet() + let lines =<< trim END + VAR d = {'b': 'bbb', '1': 99, '3': 33, '-1': {'a': 1}} + unlet d.b + unlet d[-1] + call assert_equal({'1': 99, '3': 33}, d) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +" manipulating a big Dictionary (hashtable.c has a border of 1000 entries) +func Test_dict_big() + let d = {} + for i in range(1500) + let d[i] = 3000 - i + endfor + call assert_equal([3000, 2900, 2001, 1600, 1501], [d[0], d[100], d[999], d[1400], d[1499]]) + let str = '' + try + let n = d[1500] + catch + let str = substitute(v:exception, '\v(.{14}).*( "\d{4}").*', '\1\2', '') + endtry + call assert_equal('Vim(let):E716: "1500"', str) + + " lookup each item + for i in range(1500) + call assert_equal(3000 - i, d[i]) + endfor + let i += 1 + + " delete even items + while i >= 2 + let i -= 2 + unlet d[i] + endwhile + call assert_equal('NONE', get(d, 1500 - 100, 'NONE')) + call assert_equal(2999, d[1]) + + " delete odd items, checking value, one intentionally wrong + let d[33] = 999 + let i = 1 + while i < 1500 + if i != 33 + call assert_equal(3000 - i, d[i]) + else + call assert_equal(999, d[i]) + endif + unlet d[i] + let i += 2 + endwhile + call assert_equal({}, d) + unlet d +endfunc + +" Dictionary function +func Test_dict_func() + let d = {} + func d.func(a) dict + return a:a . len(self.data) + endfunc + let d.data = [1,2,3] + call assert_equal('len: 3', d.func('len: ')) + let x = d.func('again: ') + call assert_equal('again: 3', x) + let Fn = d.func + call assert_equal('xxx3', Fn('xxx')) +endfunc + +func Test_dict_assign() + let d = {} + let d.1 = 1 + let d._ = 2 + call assert_equal({'1': 1, '_': 2}, d) + + let lines =<< trim END + VAR d = {} + LET d.a = 1 + LET d._ = 2 + call assert_equal({'a': 1, '_': 2}, d) + END + call CheckLegacyAndVim9Success(lines) + + let lines =<< trim END + let n = 0 + let n.key = 3 + END + call CheckScriptFailure(lines, 'E1203: Dot can only be used on a dictionary: n.key = 3') + let lines =<< trim END + vim9script + var n = 0 + n.key = 3 + END + call CheckScriptFailure(lines, 'E1203: Dot can only be used on a dictionary: n.key = 3') + let lines =<< trim END + var n = 0 + n.key = 3 + END + call CheckDefFailure(lines, 'E1141:') +endfunc + +" Function in script-local List or Dict +func Test_script_local_dict_func() + let g:dict = {} + function g:dict.func() dict + return 'g:dict.func' . self.foo[1] . self.foo[0]('asdf') + endfunc + let g:dict.foo = ['-', 2, 3] + call insert(g:dict.foo, function('strlen')) + call assert_equal('g:dict.func-4', g:dict.func()) + unlet g:dict +endfunc + +" Test removing items in a dictionary +func Test_dict_func_remove() + let lines =<< trim END + VAR d = {1: 'a', 2: 'b', 3: 'c'} + call assert_equal('b', remove(d, 2)) + call assert_equal({1: 'a', 3: 'c'}, d) + END + call CheckLegacyAndVim9Success(lines) + + let lines =<< trim END + VAR d = {1: 'a', 3: 'c'} + call remove(d, 1, 2) + END + call CheckLegacyAndVim9Failure(lines, 'E118:') + + let lines =<< trim END + VAR d = {1: 'a', 3: 'c'} + call remove(d, 'a') + END + call CheckLegacyAndVim9Failure(lines, 'E716:') + + let lines =<< trim END + let d = {1: 'a', 3: 'c'} + call remove(d, []) + END + call CheckScriptFailure(lines, 'E730:') + let lines =<< trim END + vim9script + var d = {1: 'a', 3: 'c'} + call remove(d, []) + END + call CheckScriptFailure(lines, 'E1174: String required for argument 2') + let lines =<< trim END + var d = {1: 'a', 3: 'c'} + call remove(d, []) + END + call CheckDefExecFailure(lines, 'E1013: Argument 2: type mismatch, expected string but got list<unknown>') +endfunc + +" Nasty: remove func from Dict that's being called (works) +func Test_dict_func_remove_in_use() + let d = {1:1} + func d.func(a) + return "a:" . a:a + endfunc + let expected = 'a:' . string(get(d, 'func')) + call assert_equal(expected, d.func(string(remove(d, 'func')))) + + " similar, in a way it also works in Vim9 + let lines =<< trim END + VAR d = {1: 1, 2: 'x'} + func GetArg(a) + return "a:" .. a:a + endfunc + LET d.func = function('GetArg') + VAR expected = 'a:' .. string(get(d, 'func')) + call assert_equal(expected, d.func(string(remove(d, 'func')))) + END + call CheckTransLegacySuccess(lines) + call CheckTransVim9Success(lines) +endfunc + +func Test_dict_literal_keys() + call assert_equal({'one': 1, 'two2': 2, '3three': 3, '44': 4}, #{one: 1, two2: 2, 3three: 3, 44: 4},) + + " why *{} cannot be used for a literal dictionary + let blue = 'blue' + call assert_equal('6', trim(execute('echo 2 *{blue: 3}.blue'))) +endfunc + +" Nasty: deepcopy() dict that refers to itself (fails when noref used) +func Test_dict_deepcopy() + let lines =<< trim END + VAR d = {1: 1, 2: '2'} + VAR l = [4, d, 6] + LET d[3] = l + VAR dc = deepcopy(d) + call deepcopy(d, 1) + END + call CheckLegacyAndVim9Failure(lines, 'E698:') + + let lines =<< trim END + VAR d = {1: 1, 2: '2'} + VAR l = [4, d, 6] + LET d[3] = l + VAR l2 = [0, l, l, 3] + LET l[1] = l2 + VAR l3 = deepcopy(l2) + call assert_true(l3[1] is l3[2]) + END + call CheckLegacyAndVim9Success(lines) + + call assert_fails("call deepcopy([1, 2], 2)", 'E1212:') +endfunc + +" Locked variables +func Test_list_locked_var() + " Not tested with :def function, local vars cannot be locked. + let lines =<< trim END + VAR expected = [ + \ [['1000-000', 'ppppppF'], + \ ['0000-000', 'ppppppp'], + \ ['0000-000', 'ppppppp']], + \ [['1000-000', 'ppppppF'], + \ ['0000-000', 'ppppppp'], + \ ['0000-000', 'ppppppp']], + \ [['1100-100', 'ppFppFF'], + \ ['0000-000', 'ppppppp'], + \ ['0000-000', 'ppppppp']], + \ [['1110-110', 'pFFpFFF'], + \ ['0010-010', 'pFppFpp'], + \ ['0000-000', 'ppppppp']], + \ [['1111-111', 'FFFFFFF'], + \ ['0011-011', 'FFpFFpp'], + \ ['0000-000', 'ppppppp']] + \ ] + for depth in range(5) + for u in range(3) + VAR l = [0, [1, [2, 3]], {4: 5, 6: {7: 8}}] + exe "lockvar " .. depth .. " l" + if u == 1 + exe "unlockvar l" + elseif u == 2 + exe "unlockvar " .. depth .. " l" + endif + VAR ps = islocked("l") .. islocked("l[1]") .. islocked("l[1][1]") .. islocked("l[1][1][0]") .. '-' .. islocked("l[2]") .. islocked("l[2]['6']") .. islocked("l[2]['6'][7]") + call assert_equal(expected[depth][u][0], ps, 'depth: ' .. depth) + LET ps = '' + try + LET l[1][1][0] = 99 + LET ps ..= 'p' + catch + LET ps ..= 'F' + endtry + try + LET l[1][1] = [99] + LET ps ..= 'p' + catch + LET ps ..= 'F' + endtry + try + LET l[1] = [99] + LET ps ..= 'p' + catch + LET ps ..= 'F' + endtry + try + LET l[2]['6'][7] = 99 + LET ps ..= 'p' + catch + LET ps ..= 'F' + endtry + try + LET l[2][6] = {99: 99} + LET ps ..= 'p' + catch + LET ps ..= 'F' + endtry + try + LET l[2] = {99: 99} + LET ps ..= 'p' + catch + LET ps ..= 'F' + endtry + try + LET l = [99] + LET ps ..= 'p' + catch + LET ps ..= 'F' + endtry + call assert_equal(expected[depth][u][1], ps, 'depth: ' .. depth) + unlock! l + endfor + endfor + END + call CheckTransLegacySuccess(lines) + call CheckTransVim9Success(lines) + + call assert_fails("let x=islocked('a b')", 'E488:') + let mylist = [1, 2, 3] + call assert_fails("let x = islocked('mylist[1:2]')", 'E786:') + let mydict = {'k' : 'v'} + call assert_fails("let x = islocked('mydict.a')", 'E716:') +endfunc + +" Unletting locked variables +func Test_list_locked_var_unlet() + " Not tested with Vim9: script and local variables cannot be unlocked + let expected = [ + \ [['1000-000', 'ppppppp'], + \ ['0000-000', 'ppppppp'], + \ ['0000-000', 'ppppppp']], + \ [['1000-000', 'ppFppFp'], + \ ['0000-000', 'ppppppp'], + \ ['0000-000', 'ppppppp']], + \ [['1100-100', 'pFFpFFp'], + \ ['0000-000', 'ppppppp'], + \ ['0000-000', 'ppppppp']], + \ [['1110-110', 'FFFFFFp'], + \ ['0010-010', 'FppFppp'], + \ ['0000-000', 'ppppppp']], + \ [['1111-111', 'FFFFFFp'], + \ ['0011-011', 'FppFppp'], + \ ['0000-000', 'ppppppp']] + \ ] + + for depth in range(5) + for u in range(3) + unlet! l + let l = [0, [1, [2, 3]], {4: 5, 6: {7: 8}}] + exe "lockvar " . depth . " l" + if u == 1 + exe "unlockvar l" + elseif u == 2 + exe "unlockvar " . depth . " l" + endif + let ps = islocked("l").islocked("l[1]").islocked("l[1][1]").islocked("l[1][1][0]").'-'.islocked("l[2]").islocked("l[2]['6']").islocked("l[2]['6'][7]") + call assert_equal(expected[depth][u][0], ps, 'depth: ' .. depth) + let ps = '' + try + unlet l[2]['6'][7] + let ps .= 'p' + catch + let ps .= 'F' + endtry + try + unlet l[2][6] + let ps .= 'p' + catch + let ps .= 'F' + endtry + try + unlet l[2] + let ps .= 'p' + catch + let ps .= 'F' + endtry + try + unlet l[1][1][0] + let ps .= 'p' + catch + let ps .= 'F' + endtry + try + unlet l[1][1] + let ps .= 'p' + catch + let ps .= 'F' + endtry + try + unlet l[1] + let ps .= 'p' + catch + let ps .= 'F' + endtry + try + unlet l + let ps .= 'p' + catch + let ps .= 'F' + endtry + call assert_equal(expected[depth][u][1], ps) + endfor + endfor + + " Deleting a list range with locked items works, but changing the items + " fails. + let l = [1, 2, 3, 4] + lockvar l[1:2] + call assert_fails('let l[1:2] = [8, 9]', 'E741:') + unlet l[1:2] + call assert_equal([1, 4], l) + unlet l +endfunc + +" Locked variables and :unlet or list / dict functions + +" No :unlet after lock on dict: +func Test_dict_lock_unlet() + let d = {'a': 99, 'b': 100} + lockvar 1 d + call assert_fails('unlet d.a', 'E741:') +endfunc + +" unlet after lock on dict item +func Test_dict_item_lock_unlet() + let lines =<< trim END + VAR d = {'a': 99, 'b': 100} + lockvar d.a + unlet d.a + call assert_equal({'b': 100}, d) + END + " TODO: make this work in a :def function + "call CheckLegacyAndVim9Success(lines) + call CheckTransLegacySuccess(lines) + call CheckTransVim9Success(lines) +endfunc + +" filter() after lock on dict item +func Test_dict_lock_filter() + let lines =<< trim END + VAR d = {'a': 99, 'b': 100} + lockvar d.a + call filter(d, 'v:key != "a"') + call assert_equal({'b': 100}, d) + END + " TODO: make this work in a :def function + "call CheckLegacyAndVim9Success(lines) + call CheckTransLegacySuccess(lines) + call CheckTransVim9Success(lines) +endfunc + +" map() after lock on dict +func Test_dict_lock_map() + let lines =<< trim END + VAR d = {'a': 99, 'b': 100} + lockvar 1 d + call map(d, 'v:val + 200') + call assert_equal({'a': 299, 'b': 300}, d) + END + " This won't work in a :def function + call CheckTransLegacySuccess(lines) + call CheckTransVim9Success(lines) +endfunc + +" No extend() after lock on dict item +func Test_dict_lock_extend() + let d = {'a': 99, 'b': 100} + lockvar d.a + call assert_fails("call extend(d, {'a' : 123})", 'E741:') + call assert_equal({'a': 99, 'b': 100}, d) +endfunc + +" Cannot use += with a locked dict +func Test_dict_lock_operator() + let d = {} + lockvar d + call assert_fails("let d += {'k' : 10}", 'E741:') + unlockvar d +endfunc + +" No remove() of write-protected scope-level variable +func Tfunc1(this_is_a_long_parameter_name) + call assert_fails("call remove(a:, 'this_is_a_long_parameter_name')", 'E742:') +endfunc +func Test_dict_scope_var_remove() + call Tfunc1('testval') +endfunc + +" No extend() of write-protected scope-level variable +func Test_dict_scope_var_extend() + call assert_fails("call extend(a:, {'this_is_a_long_parameter_name': 1234})", 'E742:') +endfunc +func Tfunc2(this_is_a_long_parameter_name) + call assert_fails("call extend(a:, {'this_is_a_long_parameter_name': 1234})", 'E742:') +endfunc +func Test_dict_scope_var_extend_overwrite() + call Tfunc2('testval') +endfunc + +" No :unlet of variable in locked scope +func Test_lock_var_unlet() + let b:testvar = 123 + lockvar 1 b: + call assert_fails('unlet b:testvar', 'E741:') + unlockvar 1 b: + unlet! b:testvar +endfunc + +" No :let += of locked list variable +func Test_let_lock_list() + let l = ['a', 'b', 3] + lockvar 1 l + call assert_fails("let l += ['x']", 'E741:') + call assert_equal(['a', 'b', 3], l) + + unlet l + let l = [1, 2, 3, 4] + lockvar! l + call assert_equal([1, 2, 3, 4], l) + unlockvar l[1] + call assert_fails('unlet l[0:1]', 'E741:') + call assert_equal([1, 2, 3, 4], l) + call assert_fails('unlet l[1:2]', 'E741:') + call assert_equal([1, 2, 3, 4], l) + unlockvar l[1] + call assert_fails('let l[0:1] = [0, 1]', 'E741:') + call assert_equal([1, 2, 3, 4], l) + call assert_fails('let l[1:2] = [0, 1]', 'E741:') + call assert_equal([1, 2, 3, 4], l) + unlet l +endfunc + +" Locking part of the list +func Test_let_lock_list_items() + let l = [1, 2, 3, 4] + lockvar l[2:] + call assert_equal(0, islocked('l[0]')) + call assert_equal(1, islocked('l[2]')) + call assert_equal(1, islocked('l[3]')) + call assert_fails('let l[2] = 10', 'E741:') + call assert_fails('let l[3] = 20', 'E741:') + unlet l +endfunc + +" lockvar/islocked() triggering script autoloading +func Test_lockvar_script_autoload() + let old_rtp = &rtp + set rtp+=./sautest + lockvar g:footest#x + unlockvar g:footest#x + call assert_equal(-1, 'g:footest#x'->islocked()) + call assert_equal(0, exists('g:footest#x')) + call assert_equal(1, g:footest#x) + let &rtp = old_rtp +endfunc + +" a:000 function argument test +func s:arg_list_test(...) + call assert_fails('let a:000 = [1, 2]', 'E46:') + call assert_fails('let a:000[0] = 9', 'E742:') + call assert_fails('let a:000[2] = [9, 10]', 'E742:') + call assert_fails('let a:000[3] = {9 : 10}', 'E742:') + + " now the tests that should pass + let a:000[2][1] = 9 + call extend(a:000[2], [5, 6]) + let a:000[3][5] = 8 + let a:000[3]['a'] = 12 + call assert_equal([1, 2, [3, 9, 5, 6], {'a': 12, '5': 8}], a:000) +endfunc + +func Test_func_arg_list() + call s:arg_list_test(1, 2, [3, 4], {5: 6}) +endfunc + +" Tests for reverse(), sort(), uniq() +func Test_reverse_sort_uniq() + let lines =<< trim END + VAR l = ['-0', 'A11', 2, 2, 'xaaa', 4, 'foo', 'foo6', 'foo', [0, 1, 2], 'x8', [0, 1, 2], 1.5] + call assert_equal(['-0', 'A11', 2, 'xaaa', 4, 'foo', 'foo6', 'foo', [0, 1, 2], 'x8', [0, 1, 2], 1.5], uniq(copy(l))) + call assert_equal([1.5, [0, 1, 2], 'x8', [0, 1, 2], 'foo', 'foo6', 'foo', 4, 'xaaa', 2, 2, 'A11', '-0'], reverse(l)) + call assert_equal([1.5, [0, 1, 2], 'x8', [0, 1, 2], 'foo', 'foo6', 'foo', 4, 'xaaa', 2, 2, 'A11', '-0'], reverse(reverse(l))) + if has('float') + call assert_equal(['-0', 'A11', 'foo', 'foo', 'foo6', 'x8', 'xaaa', 1.5, 2, 2, 4, [0, 1, 2], [0, 1, 2]], sort(l)) + call assert_equal([[0, 1, 2], [0, 1, 2], 4, 2, 2, 1.5, 'xaaa', 'x8', 'foo6', 'foo', 'foo', 'A11', '-0'], reverse(sort(l))) + call assert_equal(['-0', 'A11', 'foo', 'foo', 'foo6', 'x8', 'xaaa', 1.5, 2, 2, 4, [0, 1, 2], [0, 1, 2]], sort(reverse(sort(l)))) + call assert_equal(['-0', 'A11', 'foo', 'foo6', 'x8', 'xaaa', 1.5, 2, 4, [0, 1, 2]], uniq(sort(l))) + + LET l = [7, 9, 'one', 18, 12, 22, 'two', 10.0e-16, -1, 'three', 0xff, 0.22, 'four'] + call assert_equal([-1, 'one', 'two', 'three', 'four', 1.0e-15, 0.22, 7, 9, 12, 18, 22, 255], sort(copy(l), 'n')) + + LET l = [7, 9, 18, 12, 22, 10.0e-16, -1, 0xff, 0, -0, 0.22, 'bar', 'BAR', 'Bar', 'Foo', 'FOO', 'foo', 'FOOBAR', {}, []] + call assert_equal(['bar', 'BAR', 'Bar', 'Foo', 'FOO', 'foo', 'FOOBAR', -1, 0, 0, 0.22, 1.0e-15, 12, 18, 22, 255, 7, 9, [], {}], sort(copy(l), 'i')) + call assert_equal(['bar', 'BAR', 'Bar', 'Foo', 'FOO', 'foo', 'FOOBAR', -1, 0, 0, 0.22, 1.0e-15, 12, 18, 22, 255, 7, 9, [], {}], sort(copy(l), 'i')) + call assert_equal(['BAR', 'Bar', 'FOO', 'FOOBAR', 'Foo', 'bar', 'foo', -1, 0, 0, 0.22, 1.0e-15, 12, 18, 22, 255, 7, 9, [], {}], sort(copy(l))) + endif + END + call CheckLegacyAndVim9Success(lines) + + call assert_fails('call reverse({})', 'E1252:') + call assert_fails('call uniq([1, 2], {x, y -> []})', 'E745:') + call assert_fails("call sort([1, 2], function('min'), 1)", "E1206:") + call assert_fails("call sort([1, 2], function('invalid_func'))", "E700:") + call assert_fails("call sort([1, 2], function('min'))", "E118:") + + let lines =<< trim END + call sort(['a', 'b'], 0) + END + call CheckDefAndScriptFailure(lines, 'E1256: String or function required for argument 2') + + let lines =<< trim END + call sort(['a', 'b'], 1) + END + call CheckDefAndScriptFailure(lines, 'E1256: String or function required for argument 2') +endfunc + +" reduce a list, blob or string +func Test_reduce() + let lines =<< trim END + call assert_equal(1, reduce([], LSTART acc, val LMIDDLE acc + val LEND, 1)) + call assert_equal(10, reduce([1, 3, 5], LSTART acc, val LMIDDLE acc + val LEND, 1)) + call assert_equal(2 * (2 * ((2 * 1) + 2) + 3) + 4, reduce([2, 3, 4], LSTART acc, val LMIDDLE 2 * acc + val LEND, 1)) + call assert_equal('a x y z', ['x', 'y', 'z']->reduce(LSTART acc, val LMIDDLE acc .. ' ' .. val LEND, 'a')) + call assert_equal([0, 1, 2, 3], reduce([1, 2, 3], function('add'), [0])) + + VAR l = ['x', 'y', 'z'] + call assert_equal(42, reduce(l, function('get'), {'x': {'y': {'z': 42 } } })) + call assert_equal(['x', 'y', 'z'], l) + + call assert_equal(1, reduce([1], LSTART acc, val LMIDDLE acc + val LEND)) + call assert_equal('x y z', reduce(['x', 'y', 'z'], LSTART acc, val LMIDDLE acc .. ' ' .. val LEND)) + call assert_equal(120, range(1, 5)->reduce(LSTART acc, val LMIDDLE acc * val LEND)) + + call assert_equal(1, reduce(0z, LSTART acc, val LMIDDLE acc + val LEND, 1)) + call assert_equal(1 + 0xaf + 0xbf + 0xcf, reduce(0zAFBFCF, LSTART acc, val LMIDDLE acc + val LEND, 1)) + call assert_equal(2 * (2 * 1 + 0xaf) + 0xbf, 0zAFBF->reduce(LSTART acc, val LMIDDLE 2 * acc + val LEND, 1)) + + call assert_equal(0xff, reduce(0zff, LSTART acc, val LMIDDLE acc + val LEND)) + call assert_equal(2 * (2 * 0xaf + 0xbf) + 0xcf, reduce(0zAFBFCF, LSTART acc, val LMIDDLE 2 * acc + val LEND)) + + call assert_equal('x,y,z', 'xyz'->reduce(LSTART acc, val LMIDDLE acc .. ',' .. val LEND)) + call assert_equal('', ''->reduce(LSTART acc, val LMIDDLE acc .. ',' .. val LEND, '')) + call assert_equal('あ,い,う,え,お,😊,💕', 'あいうえお😊💕'->reduce(LSTART acc, val LMIDDLE acc .. ',' .. val LEND)) + call assert_equal('😊,あ,い,う,え,お,💕', 'あいうえお💕'->reduce(LSTART acc, val LMIDDLE acc .. ',' .. val LEND, '😊')) + call assert_equal('ऊ,ॠ,ॡ', reduce('ऊॠॡ', LSTART acc, val LMIDDLE acc .. ',' .. val LEND)) + call assert_equal('c,à,t', reduce('càt', LSTART acc, val LMIDDLE acc .. ',' .. val LEND)) + call assert_equal('Å,s,t,r,ö,m', reduce('Åström', LSTART acc, val LMIDDLE acc .. ',' .. val LEND)) + call assert_equal('Å,s,t,r,ö,m', reduce('Åström', LSTART acc, val LMIDDLE acc .. ',' .. val LEND)) + call assert_equal(',a,b,c', reduce('abc', LSTART acc, val LMIDDLE acc .. ',' .. val LEND, v:_null_string)) + + call assert_equal(0x7d, reduce([0x30, 0x25, 0x08, 0x61], 'or')) + call assert_equal(0x7d, reduce(0z30250861, 'or')) + call assert_equal('β', reduce('ββββ', 'matchstr')) + END + call CheckLegacyAndVim9Success(lines) + + call assert_equal({'x': 1, 'y': 1, 'z': 1 }, ['x', 'y', 'z']->reduce({ acc, val -> extend(acc, { val: 1 }) }, {})) + " vim9 assert_equal({'x': 1, 'y': 1, 'z': 1 }, ['x', 'y', 'z']->reduce((acc, val) => extend(acc, {[val]: 1 }), {})) + + call assert_fails("call reduce([], { acc, val -> acc + val })", 'E998: Reduce of an empty List with no initial value') + call assert_fails("call reduce(0z, { acc, val -> acc + val })", 'E998: Reduce of an empty Blob with no initial value') + call assert_fails("call reduce(v:_null_blob, { acc, val -> acc + val })", 'E998: Reduce of an empty Blob with no initial value') + call assert_fails("call reduce('', { acc, val -> acc + val })", 'E998: Reduce of an empty String with no initial value') + call assert_fails("call reduce(v:_null_string, { acc, val -> acc + val })", 'E998: Reduce of an empty String with no initial value') + + call assert_fails("call reduce({}, { acc, val -> acc + val }, 1)", 'E1098:') + call assert_fails("call reduce(0, { acc, val -> acc + val }, 1)", 'E1098:') + call assert_fails("call reduce([1, 2], 'Xdoes_not_exist')", 'E117:') + call assert_fails("echo reduce(0z01, { acc, val -> 2 * acc + val }, '')", 'E1210:') + + " call assert_fails("vim9 reduce(0, (acc, val) => (acc .. val), '')", 'E1252:') + " call assert_fails("vim9 reduce({}, (acc, val) => (acc .. val), '')", 'E1252:') + " call assert_fails("vim9 reduce(0.1, (acc, val) => (acc .. val), '')", 'E1252:') + " call assert_fails("vim9 reduce(function('tr'), (acc, val) => (acc .. val), '')", 'E1252:') + call assert_fails("call reduce('', { acc, val -> acc + val }, 1)", 'E1174:') + call assert_fails("call reduce('', { acc, val -> acc + val }, {})", 'E1174:') + call assert_fails("call reduce('', { acc, val -> acc + val }, 0.1)", 'E1174:') + call assert_fails("call reduce('', { acc, val -> acc + val }, function('tr'))", 'E1174:') + call assert_fails("call reduce('abc', { a, v -> a10}, '')", 'E121:') + call assert_fails("call reduce(0z0102, { a, v -> a10}, 1)", 'E121:') + call assert_fails("call reduce([1, 2], { a, v -> a10}, '')", 'E121:') + + let g:lut = [1, 2, 3, 4] + func EvilRemove() + call remove(g:lut, 1) + return 1 + endfunc + call assert_fails("call reduce(g:lut, { acc, val -> EvilRemove() }, 1)", 'E742:') + unlet g:lut + delfunc EvilRemove + + call assert_equal(42, reduce(v:_null_list, function('add'), 42)) + call assert_equal(42, reduce(v:_null_blob, function('add'), 42)) + + " should not crash + " Nvim doesn't have null functions + " call assert_fails('echo reduce([1], test_null_function())', 'E1132:') + " Nvim doesn't have null partials + " call assert_fails('echo reduce([1], test_null_partial())', 'E1132:') +endfunc + +" splitting a string to a List using split() +func Test_str_split() + let lines =<< trim END + call assert_equal(['aa', 'bb'], split(' aa bb ')) + call assert_equal(['aa', 'bb'], split(' aa bb ', '\W\+', 0)) + call assert_equal(['', 'aa', 'bb', ''], split(' aa bb ', '\W\+', 1)) + call assert_equal(['', '', 'aa', '', 'bb', '', ''], split(' aa bb ', '\W', 1)) + call assert_equal(['aa', '', 'bb'], split(':aa::bb:', ':', 0)) + call assert_equal(['', 'aa', '', 'bb', ''], split(':aa::bb:', ':', 1)) + call assert_equal(['aa', '', 'bb', 'cc', ''], split('aa,,bb, cc,', ',\s*', 1)) + call assert_equal(['a', 'b', 'c'], split('abc', '\zs')) + call assert_equal(['', 'a', '', 'b', '', 'c', ''], split('abc', '\zs', 1)) + call assert_equal(['abc'], split('abc', '\\%(')) + END + call CheckLegacyAndVim9Success(lines) + + call assert_fails("call split('abc', [])", 'E730:') + call assert_fails("call split('abc', 'b', [])", 'E745:') +endfunc + +" compare recursively linked list and dict +func Test_listdict_compare() + let lines =<< trim END + VAR l = [1, 2, 3, '4'] + VAR d = {'1': 1, '2': l, '3': 3} + LET l[1] = d + call assert_true(l == l) + call assert_true(d == d) + call assert_false(l != deepcopy(l)) + call assert_false(d != deepcopy(d)) + END + call CheckLegacyAndVim9Success(lines) + + " comparison errors + call assert_fails('echo [1, 2] =~ {}', 'E691:') + call assert_fails('echo [1, 2] =~ [1, 2]', 'E692:') + call assert_fails('echo {} =~ 5', 'E735:') + call assert_fails('echo {} =~ {}', 'E736:') +endfunc + + " compare complex recursively linked list and dict +func Test_listdict_compare_complex() + let lines =<< trim END + VAR l = [] + call add(l, l) + VAR dict4 = {"l": l} + call add(dict4.l, dict4) + VAR lcopy = deepcopy(l) + VAR dict4copy = deepcopy(dict4) + call assert_true(l == lcopy) + call assert_true(dict4 == dict4copy) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +" Test for extending lists and dictionaries +func Test_listdict_extend() + " Test extend() with lists + + " Pass the same List to extend() + let lines =<< trim END + VAR l = [1, 2, 3] + call assert_equal([1, 2, 3, 1, 2, 3], extend(l, l)) + call assert_equal([1, 2, 3, 1, 2, 3], l) + + LET l = [1, 2, 3] + call assert_equal([1, 2, 3, 4, 5, 6], extend(l, [4, 5, 6])) + call assert_equal([1, 2, 3, 4, 5, 6], l) + + LET l = [1, 2, 3] + call extend(l, [4, 5, 6], 0) + call assert_equal([4, 5, 6, 1, 2, 3], l) + + LET l = [1, 2, 3] + call extend(l, [4, 5, 6], 1) + call assert_equal([1, 4, 5, 6, 2, 3], l) + + LET l = [1, 2, 3] + call extend(l, [4, 5, 6], 3) + call assert_equal([1, 2, 3, 4, 5, 6], l) + + LET l = [1, 2, 3] + call extend(l, [4, 5, 6], -1) + call assert_equal([1, 2, 4, 5, 6, 3], l) + + LET l = [1, 2, 3] + call extend(l, [4, 5, 6], -3) + call assert_equal([4, 5, 6, 1, 2, 3], l) + END + call CheckLegacyAndVim9Success(lines) + + let l = [1, 2, 3] + call assert_fails("call extend(l, [4, 5, 6], 4)", 'E684:') + call assert_fails("call extend(l, [4, 5, 6], -4)", 'E684:') + if has('float') + call assert_fails("call extend(l, [4, 5, 6], 1.2)", 'E805:') + endif + + " Test extend() with dictionaries. + + " Pass the same Dict to extend() + let lines =<< trim END + VAR d = {'a': {'b': 'B'}, 'x': 9} + call extend(d, d) + call assert_equal({'a': {'b': 'B'}, 'x': 9}, d) + + LET d = {'a': 'A', 'b': 9} + call assert_equal({'a': 'A', 'b': 0, 'c': 'C'}, extend(d, {'b': 0, 'c': 'C'})) + call assert_equal({'a': 'A', 'b': 0, 'c': 'C'}, d) + + LET d = {'a': 'A', 'b': 9} + call extend(d, {'a': 'A', 'b': 0, 'c': 'C'}, "force") + call assert_equal({'a': 'A', 'b': 0, 'c': 'C'}, d) + + LET d = {'a': 'A', 'b': 9} + call extend(d, {'b': 0, 'c': 'C'}, "keep") + call assert_equal({'a': 'A', 'b': 9, 'c': 'C'}, d) + END + call CheckLegacyAndVim9Success(lines) + + let d = {'a': 'A', 'b': 'B'} + call assert_fails("call extend(d, {'b': 0, 'c':'C'}, 'error')", 'E737:') + call assert_fails("call extend(d, {'b': 0}, [])", 'E730:') + call assert_fails("call extend(d, {'b': 0, 'c':'C'}, 'xxx')", 'E475:') + if has('float') + call assert_fails("call extend(d, {'b': 0, 'c':'C'}, 1.2)", 'E475:') + endif + call assert_equal({'a': 'A', 'b': 'B'}, d) + + call assert_fails("call extend([1, 2], 1)", 'E712:') + call assert_fails("call extend([1, 2], {})", 'E712:') + + " Extend g: dictionary with an invalid variable name + call assert_fails("call extend(g:, {'-!' : 10})", 'E461:') + + " Extend a list with itself. + let lines =<< trim END + VAR l = [1, 5, 7] + call extend(l, l, 0) + call assert_equal([1, 5, 7, 1, 5, 7], l) + LET l = [1, 5, 7] + call extend(l, l, 1) + call assert_equal([1, 1, 5, 7, 5, 7], l) + LET l = [1, 5, 7] + call extend(l, l, 2) + call assert_equal([1, 5, 1, 5, 7, 7], l) + LET l = [1, 5, 7] + call extend(l, l, 3) + call assert_equal([1, 5, 7, 1, 5, 7], l) + END + call CheckLegacyAndVim9Success(lines) +endfunc + +func Test_listdict_extendnew() + " Test extendnew() with lists + let l = [1, 2, 3] + call assert_equal([1, 2, 3, 4, 5], extendnew(l, [4, 5])) + call assert_equal([1, 2, 3], l) + lockvar l + call assert_equal([1, 2, 3, 4, 5], extendnew(l, [4, 5])) + + " Test extendnew() with dictionaries. + let d = {'a': {'b': 'B'}} + call assert_equal({'a': {'b': 'B'}, 'c': 'cc'}, extendnew(d, {'c': 'cc'})) + call assert_equal({'a': {'b': 'B'}}, d) + lockvar d + call assert_equal({'a': {'b': 'B'}, 'c': 'cc'}, extendnew(d, {'c': 'cc'})) +endfunc + +func s:check_scope_dict(x, fixed) + func s:gen_cmd(cmd, x) + return substitute(a:cmd, '\<x\ze:', a:x, 'g') + endfunc + + let cmd = s:gen_cmd('let x:foo = 1', a:x) + if a:fixed + call assert_fails(cmd, 'E461') + else + exe cmd + exe s:gen_cmd('call assert_equal(1, x:foo)', a:x) + endif + + let cmd = s:gen_cmd('let x:["bar"] = 2', a:x) + if a:fixed + call assert_fails(cmd, 'E461') + else + exe cmd + exe s:gen_cmd('call assert_equal(2, x:bar)', a:x) + endif + + let cmd = s:gen_cmd('call extend(x:, {"baz": 3})', a:x) + if a:fixed + call assert_fails(cmd, 'E742') + else + exe cmd + exe s:gen_cmd('call assert_equal(3, x:baz)', a:x) + endif + + if a:fixed + if a:x ==# 'a' + call assert_fails('unlet a:x', 'E795') + call assert_fails('call remove(a:, "x")', 'E742') + elseif a:x ==# 'v' + call assert_fails('unlet v:count', 'E795') + call assert_fails('call remove(v:, "count")', 'E742') + endif + else + exe s:gen_cmd('unlet x:foo', a:x) + exe s:gen_cmd('unlet x:bar', a:x) + exe s:gen_cmd('call remove(x:, "baz")', a:x) + endif + + delfunc s:gen_cmd +endfunc + +func Test_scope_dict() + " Test for g: + call s:check_scope_dict('g', v:false) + + " Test for s: + call s:check_scope_dict('s', v:false) + + " Test for l: + call s:check_scope_dict('l', v:false) + + " Test for a: + call s:check_scope_dict('a', v:true) + + " Test for b: + call s:check_scope_dict('b', v:false) + + " Test for w: + call s:check_scope_dict('w', v:false) + + " Test for t: + call s:check_scope_dict('t', v:false) + + " Test for v: + call s:check_scope_dict('v', v:true) +endfunc + +" Test for deep nesting of lists (> 100) +func Test_deep_nested_list() + let deep_list = [] + let l = deep_list + for i in range(102) + let newlist = [] + call add(l, newlist) + let l = newlist + endfor + call add(l, 102) + + call assert_fails('let m = deepcopy(deep_list)', 'E698:') + call assert_fails('lockvar 110 deep_list', 'E743:') + call assert_fails('unlockvar 110 deep_list', 'E743:') + " Nvim implements :echo very differently + " call assert_fails('let x = execute("echo deep_list")', 'E724:') + call test_garbagecollect_now() + unlet deep_list +endfunc + +" Test for deep nesting of dicts (> 100) +func Test_deep_nested_dict() + let deep_dict = {} + let d = deep_dict + for i in range(102) + let newdict = {} + let d.k = newdict + let d = newdict + endfor + let d.k = 'v' + + call assert_fails('let m = deepcopy(deep_dict)', 'E698:') + call assert_fails('lockvar 110 deep_dict', 'E743:') + call assert_fails('unlockvar 110 deep_dict', 'E743:') + " Nvim implements :echo very differently + " call assert_fails('let x = execute("echo deep_dict")', 'E724:') + call test_garbagecollect_now() + unlet deep_dict +endfunc + +" List and dict indexing tests +func Test_listdict_index() + call CheckLegacyAndVim9Failure(['echo function("min")[0]'], 'E695:') + call CheckLegacyAndVim9Failure(['echo v:true[0]'], 'E909:') + call CheckLegacyAndVim9Failure(['echo v:null[0]'], 'E909:') + call CheckLegacyAndVim9Failure(['VAR d = {"k": 10}', 'echo d.'], ['E15:', 'E1127:', 'E15:']) + call CheckLegacyAndVim9Failure(['VAR d = {"k": 10}', 'echo d[1 : 2]'], 'E719:') + + call assert_fails("let v = [4, 6][{-> 1}]", 'E729:') + call CheckDefAndScriptFailure(['var v = [4, 6][() => 1]'], ['E1012', 'E703:']) + + call CheckLegacyAndVim9Failure(['VAR v = range(5)[2 : []]'], ['E730:', 'E1012:', 'E730:']) + + call assert_fails("let v = range(5)[2:{-> 2}(]", ['E15:', 'E116:']) + call CheckDefAndScriptFailure(['var v = range(5)[2 : () => 2(]'], 'E15:') + + call CheckLegacyAndVim9Failure(['VAR v = range(5)[2 : 3'], ['E111:', 'E1097:', 'E111:']) + call CheckLegacyAndVim9Failure(['VAR l = insert([1, 2, 3], 4, 10)'], 'E684:') + call CheckLegacyAndVim9Failure(['VAR l = insert([1, 2, 3], 4, -10)'], 'E684:') + call CheckLegacyAndVim9Failure(['VAR l = insert([1, 2, 3], 4, [])'], ['E745:', 'E1013:', 'E1210:']) + + call CheckLegacyAndVim9Failure(['VAR l = [1, 2, 3]', 'LET l[i] = 3'], ['E121:', 'E1001:', 'E121:']) + call CheckLegacyAndVim9Failure(['VAR l = [1, 2, 3]', 'LET l[1.1] = 4'], ['E805:', 'E1012:', 'E805:']) + call CheckLegacyAndVim9Failure(['VAR l = [1, 2, 3]', 'LET l[: i] = [4, 5]'], ['E121:', 'E1001:', 'E121:']) + call CheckLegacyAndVim9Failure(['VAR l = [1, 2, 3]', 'LET l[: 3.2] = [4, 5]'], ['E805:', 'E1012:', 'E805:']) + " call CheckLegacyAndVim9Failure(['VAR t = test_unknown()', 'echo t[0]'], 'E685:') +endfunc + +" Test for a null list +func Test_null_list() + let l = v:_null_list + call assert_equal('', join(l)) + call assert_equal(0, len(l)) + call assert_equal(1, empty(l)) + call assert_fails('let s = join([1, 2], [])', 'E730:') + call assert_equal([], split(v:_null_string)) + call assert_equal([], l[:2]) + call assert_true([] == l) + call assert_equal('[]', string(l)) + " call assert_equal(0, sort(l)) + " call assert_equal(0, sort(l)) + " call assert_equal(0, uniq(l)) + let k = [] + l + call assert_equal([], k) + let k = l + [] + call assert_equal([], k) + call assert_equal(0, len(copy(l))) + call assert_equal(0, count(l, 5)) + call assert_equal([], deepcopy(l)) + call assert_equal(5, get(l, 2, 5)) + call assert_equal(-1, index(l, 2, 5)) + " call assert_equal(0, insert(l, 2, -1)) + call assert_equal(0, min(l)) + call assert_equal(0, max(l)) + " call assert_equal(0, remove(l, 0, 2)) + call assert_equal([], repeat(l, 2)) + " call assert_equal(0, reverse(l)) + " call assert_equal(0, sort(l)) + call assert_equal('[]', string(l)) + " call assert_equal(0, extend(l, l, 0)) + lockvar l + call assert_equal(1, islocked('l')) + unlockvar l +endfunc + +" Test for a null dict +func Test_null_dict() + call assert_equal(v:_null_dict, v:_null_dict) + let d = v:_null_dict + call assert_equal({}, d) + call assert_equal(0, len(d)) + call assert_equal(1, empty(d)) + call assert_equal([], items(d)) + call assert_equal([], keys(d)) + call assert_equal([], values(d)) + call assert_false(has_key(d, 'k')) + call assert_equal('{}', string(d)) + call assert_fails('let x = d[10]') + call assert_equal({}, {}) + call assert_equal(0, len(copy(d))) + call assert_equal(0, count(d, 'k')) + call assert_equal({}, deepcopy(d)) + call assert_equal(20, get(d, 'k', 20)) + call assert_equal(0, min(d)) + call assert_equal(0, max(d)) + call assert_equal(0, remove(d, 'k')) + call assert_equal('{}', string(d)) + " call assert_equal(0, extend(d, d, 0)) + lockvar d + call assert_equal(1, islocked('d')) + unlockvar d +endfunc + +" Test for the indexof() function +func Test_indexof() + let l = [#{color: 'red'}, #{color: 'blue'}, #{color: 'green'}] + call assert_equal(0, indexof(l, {i, v -> v.color == 'red'})) + call assert_equal(2, indexof(l, {i, v -> v.color == 'green'})) + call assert_equal(-1, indexof(l, {i, v -> v.color == 'grey'})) + call assert_equal(1, indexof(l, "v:val.color == 'blue'")) + call assert_equal(-1, indexof(l, "v:val.color == 'cyan'")) + + let l = [#{n: 10}, #{n: 10}, #{n: 20}] + call assert_equal(0, indexof(l, "v:val.n == 10", #{startidx: 0})) + call assert_equal(1, indexof(l, "v:val.n == 10", #{startidx: -2})) + call assert_equal(-1, indexof(l, "v:val.n == 10", #{startidx: 4})) + call assert_equal(-1, indexof(l, "v:val.n == 10", #{startidx: -4})) + call assert_equal(0, indexof(l, "v:val.n == 10", v:_null_dict)) + + let s = ["a", "b", "c"] + call assert_equal(2, indexof(s, {_, v -> v == 'c'})) + call assert_equal(-1, indexof(s, {_, v -> v == 'd'})) + call assert_equal(-1, indexof(s, {_, v -> "v == 'd'"})) + + call assert_equal(-1, indexof([], {i, v -> v == 'a'})) + call assert_equal(-1, indexof([1, 2, 3], {_, v -> "v == 2"})) + call assert_equal(-1, indexof(v:_null_list, {i, v -> v == 'a'})) + call assert_equal(-1, indexof(l, v:_null_string)) + " Nvim doesn't have null functions + " call assert_equal(-1, indexof(l, test_null_function())) + + " failure cases + call assert_fails('let i = indexof(l, "v:val == ''cyan''")', 'E735:') + call assert_fails('let i = indexof(l, "color == ''cyan''")', 'E121:') + call assert_fails('let i = indexof(l, {})', 'E1256:') + call assert_fails('let i = indexof({}, "v:val == 2")', 'E1226:') + call assert_fails('let i = indexof([], "v:val == 2", [])', 'E1206:') + + func TestIdx(k, v) + return a:v.n == 20 + endfunc + call assert_equal(2, indexof(l, function("TestIdx"))) + delfunc TestIdx + func TestIdx(k, v) + return {} + endfunc + call assert_fails('let i = indexof(l, function("TestIdx"))', 'E728:') + delfunc TestIdx + func TestIdx(k, v) + throw "IdxError" + endfunc + call assert_fails('let i = indexof(l, function("TestIdx"))', 'E605:') + delfunc TestIdx +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_listlbr.vim b/test/old/testdir/test_listlbr.vim new file mode 100644 index 0000000000..6dea94fbf1 --- /dev/null +++ b/test/old/testdir/test_listlbr.vim @@ -0,0 +1,391 @@ +" Test for linebreak and list option (non-utf8) + +scriptencoding latin1 + +source check.vim +CheckOption linebreak +CheckFeature conceal + +source view_util.vim +source screendump.vim + +function s:screen_lines(lnum, width) abort + return ScreenLines(a:lnum, a:width) +endfunction + +func s:compare_lines(expect, actual) + call assert_equal(a:expect, a:actual) +endfunc + +function s:test_windows(...) + call NewWindow(10, 20) + setl ts=8 sw=4 sts=4 linebreak sbr= wrap + exe get(a:000, 0, '') +endfunction + +function s:close_windows(...) + call CloseWindow() + exe get(a:000, 0, '') +endfunction + +func Test_set_linebreak() + call s:test_windows('setl ts=4 sbr=+') + call setline(1, "\tabcdef hijklmn\tpqrstuvwxyz_1060ABCDEFGHIJKLMNOP ") + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ " abcdef ", +\ "+hijklmn ", +\ "+pqrstuvwxyz_1060ABC", +\ "+DEFGHIJKLMNOP ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_linebreak_with_list() + throw 'skipped: Nvim does not support enc=latin1' + set listchars= + call s:test_windows('setl ts=4 sbr=+ list listchars=') + call setline(1, "\tabcdef hijklmn\tpqrstuvwxyz_1060ABCDEFGHIJKLMNOP ") + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ "^Iabcdef hijklmn^I ", +\ "+pqrstuvwxyz_1060ABC", +\ "+DEFGHIJKLMNOP ", +\ "~ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() + set listchars&vim +endfunc + +func Test_linebreak_with_nolist() + call s:test_windows('setl ts=4 sbr=+ nolist') + call setline(1, "\tabcdef hijklmn\tpqrstuvwxyz_1060ABCDEFGHIJKLMNOP ") + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ " abcdef ", +\ "+hijklmn ", +\ "+pqrstuvwxyz_1060ABC", +\ "+DEFGHIJKLMNOP ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_linebreak_with_list_and_number() + call s:test_windows('setl list listchars+=tab:>-') + call setline(1, ["abcdefg\thijklmnopqrstu", "v"]) + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect_nonumber = [ +\ "abcdefg>------------", +\ "hijklmnopqrstu$ ", +\ "v$ ", +\ "~ ", +\ ] + call s:compare_lines(expect_nonumber, lines) + + setl number + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect_number = [ +\ " 1 abcdefg>--------", +\ " hijklmnopqrstu$ ", +\ " 2 v$ ", +\ "~ ", +\ ] + call s:compare_lines(expect_number, lines) + call s:close_windows() +endfunc + +func Test_should_break() + call s:test_windows('setl sbr=+ nolist') + call setline(1, "1\t" . repeat('a', winwidth(0)-2)) + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ "1 ", +\ "+aaaaaaaaaaaaaaaaaa ", +\ "~ ", +\ "~ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_linebreak_with_conceal() + call s:test_windows('setl cpo&vim sbr=+ list conceallevel=2 concealcursor=nv listchars=tab:ab') + call setline(1, "_S_\t bla") + syn match ConcealVar contained /_/ conceal + syn match All /.*/ contains=ConcealVar + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ "Sabbbbbb bla ", +\ "~ ", +\ "~ ", +\ "~ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_linebreak_with_visual_operations() + call s:test_windows() + let line = '1234567890 2234567890 3234567890' + call setline(1, line) + + " yank + exec "norm! ^w\<C-V>ey" + call assert_equal('2234567890', @@) + exec "norm! w\<C-V>ey" + call assert_equal('3234567890', @@) + + " increment / decrement + exec "norm! ^w\<C-V>\<C-A>w\<C-V>\<C-X>" + call assert_equal('1234567890 3234567890 2234567890', getline(1)) + + " replace + exec "norm! ^w\<C-V>3lraw\<C-V>3lrb" + call assert_equal('1234567890 aaaa567890 bbbb567890', getline(1)) + + " tilde + exec "norm! ^w\<C-V>2l~w\<C-V>2l~" + call assert_equal('1234567890 AAAa567890 BBBb567890', getline(1)) + + " delete and insert + exec "norm! ^w\<C-V>3lc2345\<Esc>w\<C-V>3lc3456\<Esc>" + call assert_equal('1234567890 2345567890 3456567890', getline(1)) + call assert_equal('BBBb', @@) + + call s:close_windows() +endfunc + +" Test that cursor is drawn at correct position after an operator when +" 'linebreak' is enabled. +func Test_linebreak_reset_restore() + CheckScreendump + + " f_wincol() calls validate_cursor() + let lines =<< trim END + set linebreak showcmd noshowmode formatexpr=wincol()-wincol() + call setline(1, repeat('a', &columns - 10) .. ' bbbbbbbbbb c') + END + call writefile(lines, 'XlbrResetRestore', 'D') + let buf = RunVimInTerminal('-S XlbrResetRestore', {'rows': 8}) + + call term_sendkeys(buf, '$v$') + call WaitForAssert({-> assert_equal(13, term_getcursor(buf)[1])}) + call term_sendkeys(buf, 'zo') + call WaitForAssert({-> assert_equal(12, term_getcursor(buf)[1])}) + + call term_sendkeys(buf, '$v$') + call WaitForAssert({-> assert_equal(13, term_getcursor(buf)[1])}) + call term_sendkeys(buf, 'gq') + call WaitForAssert({-> assert_equal(12, term_getcursor(buf)[1])}) + + call term_sendkeys(buf, "$\<C-V>$") + call WaitForAssert({-> assert_equal(13, term_getcursor(buf)[1])}) + call term_sendkeys(buf, 'I') + call WaitForAssert({-> assert_equal(12, term_getcursor(buf)[1])}) + + call term_sendkeys(buf, "\<Esc>$v$") + call WaitForAssert({-> assert_equal(13, term_getcursor(buf)[1])}) + call term_sendkeys(buf, 's') + call WaitForAssert({-> assert_equal(12, term_getcursor(buf)[1])}) + call VerifyScreenDump(buf, 'Test_linebreak_reset_restore_1', {}) + + " clean up + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) +endfunc + +func Test_virtual_block() + call s:test_windows('setl sbr=+') + call setline(1, [ +\ "REMOVE: this not", +\ "REMOVE: aaaaaaaaaaaaa", +\ ]) + exe "norm! 1/^REMOVE:" + exe "norm! 0\<C-V>jf x" + $put + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ "this not ", +\ "aaaaaaaaaaaaa ", +\ "REMOVE: ", +\ "REMOVE: ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_virtual_block_and_vbA() + call s:test_windows() + call setline(1, "long line: " . repeat("foobar ", 40) . "TARGET at end") + exe "norm! $3B\<C-v>eAx\<Esc>" + let lines = s:screen_lines([1, 10], winwidth(0)) + let expect = [ +\ "<<<bar foobar ", +\ "foobar foobar ", +\ "foobar foobar ", +\ "foobar foobar ", +\ "foobar foobar ", +\ "foobar foobar ", +\ "foobar foobar ", +\ "foobar foobar ", +\ "foobar foobar ", +\ "foobar TARGETx at ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_virtual_char_and_block() + call s:test_windows() + call setline(1, "1111-1111-1111-11-1111-1111-1111") + exe "norm! 0f-lv3lc2222\<Esc>bgj." + let lines = s:screen_lines([1, 2], winwidth(0)) + let expect = [ +\ "1111-2222-1111-11- ", +\ "1111-2222-1111 ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_undo_after_block_visual() + call s:test_windows() + call setline(1, ["aaa", "aaa", "a"]) + exe "norm! gg\<C-V>2j~e." + let lines = s:screen_lines([1, 3], winwidth(0)) + let expect = [ +\ "AaA ", +\ "AaA ", +\ "A ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_norm_after_block_visual() + call s:test_windows() + call setline(1, ["abcd{ef", "ghijklm", "no}pgrs"]) + exe "norm! ggf{\<C-V>\<C-V>c%" + let lines = s:screen_lines([1, 3], winwidth(0)) + let expect = [ +\ "abcdpgrs ", +\ "~ ", +\ "~ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_block_replace_after_wrapping() + throw 'skipped: Nvim does not support enc=latin1' + call s:test_windows() + call setline(1, repeat("a", 150)) + exe "norm! 0yypk147|\<C-V>jr0" + call assert_equal(repeat("a", 146) . "0aaa", getline(1)) + call assert_equal(repeat("a", 146) . "0aaa", getline(2)) + let lines = s:screen_lines([1, 10], winwidth(0)) + let expect = [ +\ "aaaaaaaaaaaaaaaaaaaa", +\ "aaaaaaaaaaaaaaaaaaaa", +\ "aaaaaaaaaaaaaaaaaaaa", +\ "aaaaaaaaaaaaaaaaaaaa", +\ "aaaaaaaaaaaaaaaaaaaa", +\ "aaaaaaaaaaaaaaaaaaaa", +\ "aaaaaaaaaaaaaaaaaaaa", +\ "aaaaaa0aaa ", +\ "@ ", +\ "@ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_list_with_listchars() + call s:test_windows('setl list listchars=space:_,trail:-,tab:>-,eol:$') + call setline(1, "a aaaaaaaaaaaaaaaaaaaaaa\ta ") + let lines = s:screen_lines([1, 3], winwidth(0)) + let expect = [ +\ "a_ ", +\ "aaaaaaaaaaaaaaaaaaaa", +\ "aa>-----a-$ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_list_with_tab_and_skipping_first_chars() + call s:test_windows('setl list listchars=tab:>- ts=70 nowrap') + call setline(1, ["iiiiiiiiiiiiiiii\taaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii\taaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii\taaaaaaaaaaaaaaaaaa", "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii\taaaaaaaaaaaaaaaaaa"]) + call cursor(4,64) + norm! 2zl + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ "---------------aaaaa", +\ "---------------aaaaa", +\ "---------------aaaaa", +\ "iiiiiiiii>-----aaaaa", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_ctrl_char_on_wrap_column() + call s:test_windows("setl nolbr wrap sbr=") + call setline(1, 'aaa' .. repeat("\<C-A>", 150) .. 'bbb') + call cursor(1,1) + norm! $ + redraw! + let expect=[ +\ '<<<^A^A^A^A^A^A^A^A^', +\ 'A^A^A^A^A^A^A^A^A^A^', +\ 'A^A^A^A^A^A^A^A^A^A^', +\ 'A^A^A^A^A^A^A^A^A^A^', +\ 'A^A^A^A^A^A^A^A^A^A^', +\ 'A^A^A^A^A^A^A^A^A^A^', +\ 'A^A^A^A^A^A^A^A^A^A^', +\ 'A^A^A^A^A^A^A^A^A^A^', +\ 'A^A^A^A^A^A^A^A^A^A^', +\ 'A^Abbb '] + let lines = s:screen_lines([1, 10], winwidth(0)) + call s:compare_lines(expect, lines) + call assert_equal(len(expect), winline()) + call assert_equal(strwidth(trim(expect[-1], ' ', 2)), wincol()) + setl sbr=!! + redraw! + let expect=[ +\ '!!A^A^A^A^A^A^A^A^A^', +\ '!!A^A^A^A^A^A^A^A^A^', +\ '!!A^A^A^A^A^A^A^A^A^', +\ '!!A^A^A^A^A^A^A^A^A^', +\ '!!A^A^A^A^A^A^A^A^A^', +\ '!!A^A^A^A^A^A^A^A^A^', +\ '!!A^A^A^A^A^A^A^A^A^', +\ '!!A^A^A^A^A^A^A^A^A^', +\ '!!A^A^A^A^A^A^A^A^A^', +\ '!!A^A^A^A^A^A^Abbb '] + let lines = s:screen_lines([1, 10], winwidth(0)) + call s:compare_lines(expect, lines) + call assert_equal(len(expect), winline()) + call assert_equal(strwidth(trim(expect[-1], ' ', 2)), wincol()) + call s:close_windows() +endfunc + +func Test_linebreak_no_break_after_whitespace_only() + call s:test_windows('setl ts=4 linebreak wrap') + call setline(1, "\tabcdefghijklmnopqrstuvwxyz" .. + \ "abcdefghijklmnopqrstuvwxyz") + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ " abcdefghijklmnop", +\ "qrstuvwxyzabcdefghij", +\ "klmnopqrstuvwxyz ", +\ "~ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_listlbr_utf8.vim b/test/old/testdir/test_listlbr_utf8.vim new file mode 100644 index 0000000000..1bbbd2d2ae --- /dev/null +++ b/test/old/testdir/test_listlbr_utf8.vim @@ -0,0 +1,361 @@ +" Test for linebreak and list option in utf-8 mode + +set encoding=utf-8 +scriptencoding utf-8 + +source check.vim +CheckOption linebreak +CheckFeature conceal +CheckFeature signs + +source view_util.vim + +func s:screen_lines(lnum, width) abort + return ScreenLines(a:lnum, a:width) +endfunc + +func s:compare_lines(expect, actual) + call assert_equal(a:expect, a:actual) +endfunc + +func s:screen_attr(lnum, chars, ...) abort + let line = getline(a:lnum) + let attr = [] + let prefix = get(a:000, 0, 0) + for i in range(a:chars[0], a:chars[1]) + let scol = strdisplaywidth(strcharpart(line, 0, i-1)) + 1 + let attr += [screenattr(a:lnum, scol + prefix)] + endfor + return attr +endfunc + +func s:test_windows(...) + call NewWindow(10, 20) + setl ts=4 sw=4 sts=4 linebreak sbr=+ wrap + exe get(a:000, 0, '') +endfunc + +func s:close_windows(...) + call CloseWindow() + exe get(a:000, 0, '') +endfunc + +func Test_linebreak_with_fancy_listchars() + call s:test_windows("setl list listchars=nbsp:\u2423,tab:\u2595\u2014,trail:\u02d1,eol:\ub6") + call setline(1, "\tabcdef hijklmn\tpqrstuvwxyz\u00a01060ABCDEFGHIJKLMNOP ") + redraw! + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ "▕———abcdef ", +\ "+hijklmn▕——— ", +\ "+pqrstuvwxyz␣1060ABC", +\ "+DEFGHIJKLMNOPˑ¶ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_nolinebreak_with_list() + call s:test_windows("setl nolinebreak list listchars=nbsp:\u2423,tab:\u2595\u2014,trail:\u02d1,eol:\ub6") + call setline(1, "\tabcdef hijklmn\tpqrstuvwxyz\u00a01060ABCDEFGHIJKLMNOP ") + redraw! + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ "▕———abcdef hijklmn▕—", +\ "+pqrstuvwxyz␣1060ABC", +\ "+DEFGHIJKLMNOPˑ¶ ", +\ "~ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +" this was causing a crash +func Test_linebreak_with_list_and_tabs() + set linebreak list listchars=tab:⇤\ ⇥ tabstop=100 + new + call setline(1, "\t\t\ttext") + redraw + bwipe! + set nolinebreak nolist listchars&vim tabstop=8 +endfunc + +func Test_linebreak_with_nolist() + call s:test_windows('setl nolist') + call setline(1, "\t*mask = nil;") + redraw! + let lines = s:screen_lines([1, 4], winwidth(0)) + let expect = [ +\ " *mask = nil; ", +\ "~ ", +\ "~ ", +\ "~ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_list_and_concealing1() + call s:test_windows('setl list listchars=tab:>- cole=1') + call setline(1, [ +\ "#define ABCDE\t\t1", +\ "#define ABCDEF\t\t1", +\ "#define ABCDEFG\t\t1", +\ "#define ABCDEFGH\t1", +\ "#define MSG_MODE_FILE\t\t\t1", +\ "#define MSG_MODE_CONSOLE\t\t2", +\ "#define MSG_MODE_FILE_AND_CONSOLE\t3", +\ "#define MSG_MODE_FILE_THEN_CONSOLE\t4", +\ ]) + vert resize 40 + syn match Conceal conceal cchar=>'AB\|MSG_MODE' + redraw! + let lines = s:screen_lines([1, 7], winwidth(0)) + let expect = [ +\ "#define ABCDE>-->---1 ", +\ "#define >CDEF>-->---1 ", +\ "#define >CDEFG>->---1 ", +\ "#define >CDEFGH>----1 ", +\ "#define >_FILE>--------->--->---1 ", +\ "#define >_CONSOLE>---------->---2 ", +\ "#define >_FILE_AND_CONSOLE>---------3 ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_list_and_concealing2() + call s:test_windows('setl nowrap ts=2 list listchars=tab:>- cole=2 concealcursor=n') + call setline(1, "bbeeeeee\t\t;\tsome text") + vert resize 40 + syn clear + syn match meaning /;\s*\zs.*/ + syn match hasword /^\x\{8}/ contains=word + syn match word /\<\x\{8}\>/ contains=beginword,endword contained + syn match beginword /\<\x\x/ contained conceal + syn match endword /\x\{6}\>/ contained + hi meaning guibg=blue + hi beginword guibg=green + hi endword guibg=red + redraw! + let lines = s:screen_lines([1, 1], winwidth(0)) + let expect = [ +\ "eeeeee>--->-;>some text ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_screenattr_for_comment() + call s:test_windows("setl ft=c ts=7 list listchars=nbsp:\u2423,tab:\u2595\u2014,trail:\u02d1,eol:\ub6") + call setline(1, " /*\t\t and some more */") + norm! gg0 + syntax on + hi SpecialKey term=underline ctermfg=red guifg=red + redraw! + let line = getline(1) + let attr = s:screen_attr(1, [1, 6]) + call assert_notequal(attr[0], attr[1]) + call assert_notequal(attr[1], attr[3]) + call assert_notequal(attr[3], attr[5]) + call s:close_windows() +endfunc + +func Test_visual_block_and_selection_exclusive() + call s:test_windows('setl selection=exclusive') + call setline(1, "long line: " . repeat("foobar ", 40) . "TARGETÃ' at end") + exe "norm! $3B\<C-v>eAx\<Esc>" + let lines = s:screen_lines([1, 10], winwidth(0)) + let expect = [ +\ "+foobar foobar ", +\ "+foobar foobar ", +\ "+foobar foobar ", +\ "+foobar foobar ", +\ "+foobar foobar ", +\ "+foobar foobar ", +\ "+foobar foobar ", +\ "+foobar foobar ", +\ "+foobar foobar ", +\ "+foobar TARGETÃx' ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_multibyte_sign_and_colorcolumn() + call s:test_windows("setl nolinebreak cc=3 list listchars=nbsp:\u2423,tab:\u2595\u2014,trail:\u02d1,eol:\ub6") + call setline(1, ["", "a b c", "a b c"]) + exe "sign define foo text=\uff0b" + exe "sign place 1 name=foo line=2 buffer=" . bufnr('%') + redraw! + norm! ggj0 + let signwidth = strdisplaywidth("\uff0b") + let attr1 = s:screen_attr(2, [1, 3], signwidth) + let attr2 = s:screen_attr(3, [1, 3], signwidth) + call assert_equal(attr1[0], attr2[0]) + call assert_equal(attr1[1], attr2[1]) + call assert_equal(attr1[2], attr2[2]) + let lines = s:screen_lines([1, 3], winwidth(0)) + let expect = [ +\ " ¶ ", +\ "+a b c¶ ", +\ " a b c¶ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_colorcolumn_priority() + call s:test_windows('setl cc=4 cuc hls') + call setline(1, ["xxyy", ""]) + norm! gg + exe "normal! /xxyy\<CR>" + norm! G + redraw! + let line_attr = s:screen_attr(1, [1, &cc]) + " Search wins over CursorColumn + call assert_equal(line_attr[1], line_attr[0]) + " Search wins over Colorcolumn + call assert_equal(line_attr[2], line_attr[3]) + call s:close_windows('setl hls&vim') +endfunc + +func Test_illegal_byte_and_breakat() + call s:test_windows("setl sbr= brk+=<") + vert resize 18 + call setline(1, repeat("\x80", 6)) + redraw! + let lines = s:screen_lines([1, 2], winwidth(0)) + let expect = [ +\ "<80><80><80><80><8", +\ "0><80> ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows('setl brk&vim') +endfunc + +func Test_multibyte_wrap_and_breakat() + call s:test_windows("setl sbr= brk+=>") + call setline(1, repeat('a', 17) . repeat('あ', 2)) + redraw! + let lines = s:screen_lines([1, 2], winwidth(0)) + let expect = [ +\ "aaaaaaaaaaaaaaaaaあ>", +\ "あ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows('setl brk&vim') +endfunc + +func Test_chinese_char_on_wrap_column() + call s:test_windows("setl nolbr wrap sbr=") + call setline(1, [ +\ 'aaaaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaaaaa中'. +\ 'hello']) + call cursor(1,1) + norm! $ + redraw! + let expect=[ +\ '<<<aaaaaaaaaaaaaaaa>', +\ '中aaaaaaaaaaaaaaaaa>', +\ '中aaaaaaaaaaaaaaaaa>', +\ '中aaaaaaaaaaaaaaaaa>', +\ '中aaaaaaaaaaaaaaaaa>', +\ '中aaaaaaaaaaaaaaaaa>', +\ '中aaaaaaaaaaaaaaaaa>', +\ '中aaaaaaaaaaaaaaaaa>', +\ '中aaaaaaaaaaaaaaaaa>', +\ '中hello '] + let lines = s:screen_lines([1, 10], winwidth(0)) + call s:compare_lines(expect, lines) + call assert_equal(len(expect), winline()) + call assert_equal(strwidth(trim(expect[-1], ' ', 2)), wincol()) + call s:close_windows() +endfunc + +func Test_chinese_char_on_wrap_column_sbr() + call s:test_windows("setl nolbr wrap sbr=!!!") + call setline(1, [ +\ 'aaaaaaaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaa中'. +\ 'aaaaaaaaaaaaaa中'. +\ 'hello']) + call cursor(1,1) + norm! $ + redraw! + let expect=[ +\ '!!!中aaaaaaaaaaaaaa>', +\ '!!!中aaaaaaaaaaaaaa>', +\ '!!!中aaaaaaaaaaaaaa>', +\ '!!!中aaaaaaaaaaaaaa>', +\ '!!!中aaaaaaaaaaaaaa>', +\ '!!!中aaaaaaaaaaaaaa>', +\ '!!!中aaaaaaaaaaaaaa>', +\ '!!!中aaaaaaaaaaaaaa>', +\ '!!!中aaaaaaaaaaaaaa>', +\ '!!!中hello '] + let lines = s:screen_lines([1, 10], winwidth(0)) + call s:compare_lines(expect, lines) + call assert_equal(len(expect), winline()) + call assert_equal(strwidth(trim(expect[-1], ' ', 2)), wincol()) + call s:close_windows() +endfunc + +func Test_unprintable_char_on_wrap_column() + call s:test_windows("setl nolbr wrap sbr=") + call setline(1, 'aaa' .. repeat("\uFEFF", 50) .. 'bbb') + call cursor(1,1) + norm! $ + redraw! + let expect=[ +\ '<<<<feff><feff><feff', +\ '><feff><feff><feff><', +\ 'feff><feff><feff><fe', +\ 'ff><feff><feff><feff', +\ '><feff><feff><feff><', +\ 'feff><feff><feff><fe', +\ 'ff><feff><feff><feff', +\ '><feff><feff><feff><', +\ 'feff><feff><feff><fe', +\ 'ff>bbb '] + let lines = s:screen_lines([1, 10], winwidth(0)) + call s:compare_lines(expect, lines) + call assert_equal(len(expect), winline()) + call assert_equal(strwidth(trim(expect[-1], ' ', 2)), wincol()) + setl sbr=!! + redraw! + let expect=[ +\ '!!><feff><feff><feff', +\ '!!><feff><feff><feff', +\ '!!><feff><feff><feff', +\ '!!><feff><feff><feff', +\ '!!><feff><feff><feff', +\ '!!><feff><feff><feff', +\ '!!><feff><feff><feff', +\ '!!><feff><feff><feff', +\ '!!><feff><feff><feff', +\ '!!><feff><feff>bbb '] + let lines = s:screen_lines([1, 10], winwidth(0)) + call s:compare_lines(expect, lines) + call assert_equal(len(expect), winline()) + call assert_equal(strwidth(trim(expect[-1], ' ', 2)), wincol()) + call s:close_windows() +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_makeencoding.py b/test/old/testdir/test_makeencoding.py new file mode 100644 index 0000000000..f6dc0f8d1c --- /dev/null +++ b/test/old/testdir/test_makeencoding.py @@ -0,0 +1,69 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# Test program for :make, :grep and :cgetfile. + +from __future__ import print_function, unicode_literals +import locale +import io +import sys + + +def set_output_encoding(enc=None): + """Set the encoding of stdout and stderr + + arguments: + enc -- Encoding name. + If omitted, locale.getpreferredencoding() is used. + """ + if enc is None: + enc = locale.getpreferredencoding() + + def get_text_writer(fo, **kwargs): + kw = dict(kwargs) + kw.setdefault('errors', 'backslashreplace') # use \uXXXX style + kw.setdefault('closefd', False) + + if sys.version_info[0] < 3: + # Work around for Python 2.x + # New line conversion isn't needed here. Done in somewhere else. + writer = io.open(fo.fileno(), mode='w', newline='', **kw) + write = writer.write # save the original write() function + enc = locale.getpreferredencoding() + + def convwrite(s): + if isinstance(s, bytes): + write(s.decode(enc)) # convert to unistr + else: + write(s) + try: + writer.flush() # needed on Windows + except IOError: + pass + writer.write = convwrite + else: + writer = io.open(fo.fileno(), mode='w', **kw) + return writer + + sys.stdout = get_text_writer(sys.stdout, encoding=enc) + sys.stderr = get_text_writer(sys.stderr, encoding=enc) + + +def main(): + enc = 'utf-8' + if len(sys.argv) > 1: + enc = sys.argv[1] + set_output_encoding(enc) + + message_tbl = { + 'utf-8': 'ÀÈÌÒÙ こんにちは 你好', + 'latin1': 'ÀÈÌÒÙ', + 'cp932': 'こんにちは', + 'cp936': '你好', + } + + print('Xfoobar.c(10) : %s (%s)' % (message_tbl[enc], enc)) + + +if __name__ == "__main__": + main() diff --git a/test/old/testdir/test_makeencoding.vim b/test/old/testdir/test_makeencoding.vim new file mode 100644 index 0000000000..0a49fba755 --- /dev/null +++ b/test/old/testdir/test_makeencoding.vim @@ -0,0 +1,127 @@ +" Tests for 'makeencoding'. + +source shared.vim +source check.vim + +CheckFeature quickfix +let s:python = PythonProg() +if s:python == '' + throw 'Skipped: python program missing' +endif + +let s:script = 'test_makeencoding.py' + +if has('iconv') + let s:message_tbl = { + \ 'utf-8': 'ÀÈÌÒÙ こんにちは 你好', + \ 'latin1': 'ÀÈÌÒÙ', + \ 'cp932': 'こんにちは', + \ 'cp936': '你好', + \} +else + let s:message_tbl = { + \ 'utf-8': 'ÀÈÌÒÙ こんにちは 你好', + \ 'latin1': 'ÀÈÌÒÙ', + \} +endif + + +" Tests for :cgetfile and :lgetfile. +func Test_getfile() + set errorfile=Xerror.txt + set errorformat=%f(%l)\ :\ %m + + " :cgetfile + for enc in keys(s:message_tbl) + let &makeencoding = enc + exec "silent !" . s:python . " " . s:script . " " . enc . " > " . &errorfile + cgetfile + copen + call assert_equal("Xfoobar.c|10| " . s:message_tbl[enc] . " (" . enc . ")", + \ getline('.')) + cclose + endfor + + " :lgetfile + for enc in keys(s:message_tbl) + let &makeencoding = enc + exec "silent !" . s:python . " " . s:script . " " . enc . " > " . &errorfile + lgetfile + lopen + call assert_equal("Xfoobar.c|10| " . s:message_tbl[enc] . " (" . enc . ")", + \ getline('.')) + lclose + endfor + + call delete(&errorfile) +endfunc + + +" Tests for :grep and :lgrep. +func Test_grep() + let &grepprg = s:python + set grepformat=%f(%l)\ :\ %m + + " :grep + for enc in keys(s:message_tbl) + let &makeencoding = enc + exec "silent grep! " . s:script . " " . enc + copen + call assert_equal("Xfoobar.c|10| " . s:message_tbl[enc] . " (" . enc . ")", + \ getline('.')) + cclose + endfor + + " :lgrep + for enc in keys(s:message_tbl) + let &makeencoding = enc + exec "silent lgrep! " . s:script . " " . enc + lopen + call assert_equal("Xfoobar.c|10| " . s:message_tbl[enc] . " (" . enc . ")", + \ getline('.')) + lclose + endfor +endfunc + + +" Tests for :make and :lmake. +func Test_make() + let &makeprg = s:python + set errorformat=%f(%l)\ :\ %m + + " :make + for enc in keys(s:message_tbl) + let &makeencoding = enc + exec "silent make! " . s:script . " " . enc + copen + call assert_equal("Xfoobar.c|10| " . s:message_tbl[enc] . " (" . enc . ")", + \ getline('.')) + cclose + endfor + + " :lmake + for enc in keys(s:message_tbl) + let &makeencoding = enc + exec "silent lmake! " . s:script . " " . enc + lopen + call assert_equal("Xfoobar.c|10| " . s:message_tbl[enc] . " (" . enc . ")", + \ getline('.')) + lclose + endfor +endfunc + +" Test for an error file with a long line that needs an encoding conversion +func Test_longline_conversion() + new + call setline(1, ['Xfile:10:' .. repeat("\xe0", 2000)]) + write ++enc=latin1 Xerr.out + bw! + set errorformat& + set makeencoding=latin1 + cfile Xerr.out + call assert_equal(repeat("\u00e0", 2000), getqflist()[0].text) + call delete('Xerr.out') + set makeencoding& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_map_functions.vim b/test/old/testdir/test_map_functions.vim new file mode 100644 index 0000000000..2aeb470a0d --- /dev/null +++ b/test/old/testdir/test_map_functions.vim @@ -0,0 +1,618 @@ +" Tests for maparg(), mapcheck(), mapset(), maplist() +" Also test utf8 map with a 0x80 byte. + +source shared.vim + +func s:SID() + return str2nr(matchstr(expand('<sfile>'), '<SNR>\zs\d\+\ze_SID$')) +endfunc + +func Test_maparg() + new + set cpo-=< + set encoding=utf8 + " Test maparg() with a string result + let sid = s:SID() + let lnum = expand('<sflnum>') + map foo<C-V> is<F4>foo + vnoremap <script> <buffer> <expr> <silent> bar isbar + call assert_equal("is<F4>foo", maparg('foo<C-V>')) + call assert_equal({'silent': 0, 'noremap': 0, 'script': 0, 'lhs': 'foo<C-V>', + \ 'lhsraw': "foo\x80\xfc\x04V", 'lhsrawalt': "foo\x16", + \ 'mode': ' ', 'nowait': 0, 'expr': 0, 'sid': sid, 'scriptversion': 1, + \ 'lnum': lnum + 1, + \ 'rhs': 'is<F4>foo', 'buffer': 0, 'abbr': 0, 'mode_bits': 0x47}, + \ maparg('foo<C-V>', '', 0, 1)) + call assert_equal({'silent': 1, 'noremap': 1, 'script': 1, 'lhs': 'bar', + \ 'lhsraw': 'bar', 'mode': 'v', + \ 'nowait': 0, 'expr': 1, 'sid': sid, 'scriptversion': 1, + \ 'lnum': lnum + 2, + \ 'rhs': 'isbar', 'buffer': 1, 'abbr': 0, 'mode_bits': 0x42}, + \ 'bar'->maparg('', 0, 1)) + let lnum = expand('<sflnum>') + map <buffer> <nowait> foo bar + call assert_equal({'silent': 0, 'noremap': 0, 'script': 0, 'lhs': 'foo', + \ 'lhsraw': 'foo', 'mode': ' ', + \ 'nowait': 1, 'expr': 0, 'sid': sid, 'scriptversion': 1, + \ 'lnum': lnum + 1, 'rhs': 'bar', + \ 'buffer': 1, 'abbr': 0, 'mode_bits': 0x47}, + \ maparg('foo', '', 0, 1)) + let lnum = expand('<sflnum>') + tmap baz foo + call assert_equal({'silent': 0, 'noremap': 0, 'script': 0, 'lhs': 'baz', + \ 'lhsraw': 'baz', 'mode': 't', + \ 'nowait': 0, 'expr': 0, 'sid': sid, 'scriptversion': 1, + \ 'lnum': lnum + 1, 'rhs': 'foo', + \ 'buffer': 0, 'abbr': 0, 'mode_bits': 0x80}, + \ maparg('baz', 't', 0, 1)) + let lnum = expand('<sflnum>') + iab A B + call assert_equal({'silent': 0, 'noremap': 0, 'script': 0, 'lhs': 'A', + \ 'lhsraw': 'A', 'mode': 'i', + \ 'nowait': 0, 'expr': 0, 'sid': sid, 'scriptversion': 1, + \ 'lnum': lnum + 1, 'rhs': 'B', + \ 'buffer': 0, 'abbr': 1, 'mode_bits': 0x0010}, + \ maparg('A', 'i', 1, 1)) + iuna A + + map abc x<char-114>x + call assert_equal("xrx", maparg('abc')) + map abc y<S-char-114>y + call assert_equal("yRy", maparg('abc')) + + " character with K_SPECIAL byte + nmap abc … + call assert_equal('…', maparg('abc')) + + " modified character with K_SPECIAL byte + nmap abc <M-…> + call assert_equal('<M-…>', maparg('abc')) + + " illegal bytes + let str = ":\x7f:\x80:\x90:\xd0:" + exe 'nmap abc ' .. str + call assert_equal(str, maparg('abc')) + unlet str + + omap { w + let d = maparg('{', 'o', 0, 1) + call assert_equal(['{', 'w', 'o'], [d.lhs, d.rhs, d.mode]) + ounmap { + + lmap { w + let d = maparg('{', 'l', 0, 1) + call assert_equal(['{', 'w', 'l'], [d.lhs, d.rhs, d.mode]) + lunmap { + + nmap { w + let d = maparg('{', 'n', 0, 1) + call assert_equal(['{', 'w', 'n'], [d.lhs, d.rhs, d.mode]) + nunmap { + + xmap { w + let d = maparg('{', 'x', 0, 1) + call assert_equal(['{', 'w', 'x'], [d.lhs, d.rhs, d.mode]) + xunmap { + + smap { w + let d = maparg('{', 's', 0, 1) + call assert_equal(['{', 'w', 's'], [d.lhs, d.rhs, d.mode]) + sunmap { + + map <C-I> foo + unmap <Tab> + " This used to cause a segfault + call maparg('<C-I>', '', 0, 1) + unmap <C-I> + + map abc <Nop> + call assert_equal("<Nop>", maparg('abc')) + unmap abc + + call feedkeys(":abbr esc \<C-V>\<C-V>\<C-V>\<C-V>\<C-V>\<Esc>\<CR>", "xt") + let d = maparg('esc', 'i', 1, 1) + call assert_equal(['esc', "\<C-V>\<C-V>\<Esc>", '!'], [d.lhs, d.rhs, d.mode]) + abclear + unlet d +endfunc + +func Test_mapcheck() + call assert_equal('', mapcheck('a')) + call assert_equal('', mapcheck('abc')) + call assert_equal('', mapcheck('ax')) + call assert_equal('', mapcheck('b')) + + map a something + call assert_equal('something', mapcheck('a')) + call assert_equal('something', mapcheck('a', 'n')) + call assert_equal('', mapcheck('a', 'c')) + call assert_equal('', mapcheck('a', 'i')) + call assert_equal('something', 'abc'->mapcheck()) + call assert_equal('something', 'ax'->mapcheck()) + call assert_equal('', mapcheck('b')) + unmap a + + map ab foobar + call assert_equal('foobar', mapcheck('a')) + call assert_equal('foobar', mapcheck('abc')) + call assert_equal('', mapcheck('ax')) + call assert_equal('', mapcheck('b')) + unmap ab + + map abc barfoo + call assert_equal('barfoo', mapcheck('a')) + call assert_equal('barfoo', mapcheck('a', 'n', 0)) + call assert_equal('', mapcheck('a', 'n', 1)) + call assert_equal('barfoo', mapcheck('abc')) + call assert_equal('', mapcheck('ax')) + call assert_equal('', mapcheck('b')) + unmap abc + + abbr ab abbrev + call assert_equal('abbrev', mapcheck('a', 'i', 1)) + call assert_equal('', mapcheck('a', 'n', 1)) + call assert_equal('', mapcheck('a', 'i', 0)) + unabbr ab +endfunc + +func Test_range_map() + new + " Outside of the range, minimum + inoremap <Char-0x1040> a + execute "normal a\u1040\<Esc>" + " Inside of the range, minimum + inoremap <Char-0x103f> b + execute "normal a\u103f\<Esc>" + " Inside of the range, maximum + inoremap <Char-0xf03f> c + execute "normal a\uf03f\<Esc>" + " Outside of the range, maximum + inoremap <Char-0xf040> d + execute "normal a\uf040\<Esc>" + call assert_equal("abcd", getline(1)) +endfunc + +func One_mapset_test(keys, rhs) + exe 'nnoremap ' .. a:keys .. ' ' .. a:rhs + let orig = maparg(a:keys, 'n', 0, 1) + call assert_equal(a:keys, orig.lhs) + call assert_equal(a:rhs, orig.rhs) + call assert_equal('n', orig.mode) + + exe 'nunmap ' .. a:keys + let d = maparg(a:keys, 'n', 0, 1) + call assert_equal({}, d) + + call mapset('n', 0, orig) + let d = maparg(a:keys, 'n', 0, 1) + call assert_equal(a:keys, d.lhs) + call assert_equal(a:rhs, d.rhs) + call assert_equal('n', d.mode) + + exe 'nunmap ' .. a:keys +endfunc + +func Test_mapset() + call One_mapset_test('K', 'original<CR>') + call One_mapset_test('<F3>', 'original<CR>') + call One_mapset_test('<F3>', '<lt>Nop>') + + " Check <> key conversion + new + inoremap K one<Left>x + call feedkeys("iK\<Esc>", 'xt') + call assert_equal('onxe', getline(1)) + + let orig = maparg('K', 'i', 0, 1) + call assert_equal('K', orig.lhs) + call assert_equal('one<Left>x', orig.rhs) + call assert_equal('i', orig.mode) + + iunmap K + let d = maparg('K', 'i', 0, 1) + call assert_equal({}, d) + + call mapset('i', 0, orig) + call feedkeys("SK\<Esc>", 'xt') + call assert_equal('onxe', getline(1)) + + iunmap K + + " Test that <Nop> is restored properly + inoremap K <Nop> + call feedkeys("SK\<Esc>", 'xt') + call assert_equal('', getline(1)) + + let orig = maparg('K', 'i', 0, 1) + call assert_equal('K', orig.lhs) + call assert_equal('<Nop>', orig.rhs) + call assert_equal('i', orig.mode) + + inoremap K foo + call feedkeys("SK\<Esc>", 'xt') + call assert_equal('foo', getline(1)) + + call mapset('i', 0, orig) + call feedkeys("SK\<Esc>", 'xt') + call assert_equal('', getline(1)) + + iunmap K + + " Test literal <CR> using a backslash + let cpo_save = &cpo + set cpo-=B + inoremap K one\<CR>two + call feedkeys("SK\<Esc>", 'xt') + call assert_equal('one<CR>two', getline(1)) + + let orig = maparg('K', 'i', 0, 1) + call assert_equal('K', orig.lhs) + call assert_equal('one\<CR>two', orig.rhs) + call assert_equal('i', orig.mode) + + iunmap K + let d = maparg('K', 'i', 0, 1) + call assert_equal({}, d) + + call mapset('i', 0, orig) + call feedkeys("SK\<Esc>", 'xt') + call assert_equal('one<CR>two', getline(1)) + + iunmap K + + " Test literal <CR> using CTRL-V + inoremap K one<CR>two + call feedkeys("SK\<Esc>", 'xt') + call assert_equal('one<CR>two', getline(1)) + + let orig = maparg('K', 'i', 0, 1) + call assert_equal('K', orig.lhs) + call assert_equal("one\x16<CR>two", orig.rhs) + call assert_equal('i', orig.mode) + + iunmap K + let d = maparg('K', 'i', 0, 1) + call assert_equal({}, d) + + call mapset('i', 0, orig) + call feedkeys("SK\<Esc>", 'xt') + call assert_equal('one<CR>two', getline(1)) + + iunmap K + let &cpo = cpo_save + bwipe! + + call assert_fails('call mapset([], v:false, {})', 'E730:') + call assert_fails('call mapset("i", 0, "")', 'E1206:') + call assert_fails('call mapset("i", 0, {})', 'E460:') +endfunc + +func Test_mapset_arg1_dir() + " This test is mostly about get_map_mode_string. + " Once the code gets past that, it's common with the 3 arg mapset. + + " GetModes() return list of modes for 'XZ' lhs using maplist. + " There is one list item per mapping + func s:GetModes(abbr = v:false) + return maplist(a:abbr)->filter({_, m -> m.lhs == 'XZ'}) + \ ->mapnew({_, m -> m.mode}) + endfunc + + func s:UnmapAll(lhs) + const unmap_cmds = [ 'unmap', 'unmap!', 'tunmap', 'lunmap' ] + for cmd in unmap_cmds + try | call execute(cmd .. ' ' .. a:lhs) | catch /E31/ | endtry + endfor + endfunc + + let tmap = {} + + " some mapset(mode, abbr, dict) tests using get_map_mode_str + map XZ x + let tmap = maplist()->filter({_, m -> m.lhs == 'XZ'})[0]->copy() + " this splits the mapping into 2 mappings + call mapset('ox', v:false, tmap) + call assert_equal(2, len(s:GetModes())) + call mapset('o', v:false, tmap) + call assert_equal(3, len(s:GetModes())) + " test that '' acts like ' ', and that the 3 mappings become 1 + call mapset('', v:false, tmap) + call assert_equal([' '], s:GetModes()) + " dict's mode/abbr are ignored + call s:UnmapAll('XZ') + let tmap.mode = '!' + let tmap.abbr = v:true + call mapset('o', v:false, tmap) + call assert_equal(['o'], s:GetModes()) + + " test the 3 arg version handles bad mode string, dict not used + call assert_fails("call mapset('vi', v:false, {})", 'E1276:') + + + " get the abbreviations out of the way + abbreviate XZ ZX + let tmap = maplist(v:true)->filter({_, m -> m.lhs == 'XZ'})[0]->copy() + + abclear + " 'ic' is the default ab command, shows up as '!' + let tmap.mode = 'ic' + call mapset(tmap) + call assert_equal(['!'], s:GetModes(v:true)) + + abclear + let tmap.mode = 'i' + call mapset(tmap) + call assert_equal(['i'], s:GetModes(v:true)) + + abclear + let tmap.mode = 'c' + call mapset(tmap) + call assert_equal(['c'], s:GetModes(v:true)) + + abclear + let tmap.mode = '!' + call mapset(tmap) + call assert_equal(['!'], s:GetModes(v:true)) + + call assert_fails("call mapset(#{mode: ' !', abbr: 1})", 'E1276:') + call assert_fails("call mapset(#{mode: 'cl', abbr: 1})", 'E1276:') + call assert_fails("call mapset(#{mode: 'in', abbr: 1})", 'E1276:') + + " the map commands + map XZ x + let tmap = maplist()->filter({_, m -> m.lhs == 'XZ'})[0]->copy() + + " try the combos + call s:UnmapAll('XZ') + " 'nxso' is ' ', the unadorned :map + let tmap.mode = 'nxso' + call mapset(tmap) + call assert_equal([' '], s:GetModes()) + + cal s:UnmapAll('XZ') + " 'ic' is '!' + let tmap.mode = 'ic' + call mapset(tmap) + call assert_equal(['!'], s:GetModes()) + + call s:UnmapAll('XZ') + " 'xs' is really 'v' + let tmap.mode = 'xs' + call mapset(tmap) + call assert_equal(['v'], s:GetModes()) + + " try the individual modes + call s:UnmapAll('XZ') + let tmap.mode = 'n' + call mapset(tmap) + call assert_equal(['n'], s:GetModes()) + + call s:UnmapAll('XZ') + let tmap.mode = 'x' + call mapset(tmap) + call assert_equal(['x'], s:GetModes()) + + call s:UnmapAll('XZ') + let tmap.mode = 's' + call mapset(tmap) + call assert_equal(['s'], s:GetModes()) + + call s:UnmapAll('XZ') + let tmap.mode = 'o' + call mapset(tmap) + call assert_equal(['o'], s:GetModes()) + + call s:UnmapAll('XZ') + let tmap.mode = 'i' + call mapset(tmap) + call assert_equal(['i'], s:GetModes()) + + call s:UnmapAll('XZ') + let tmap.mode = 'c' + call mapset(tmap) + call assert_equal(['c'], s:GetModes()) + + call s:UnmapAll('XZ') + let tmap.mode = 't' + call mapset(tmap) + call assert_equal(['t'], s:GetModes()) + + call s:UnmapAll('XZ') + let tmap.mode = 'l' + call mapset(tmap) + call assert_equal(['l'], s:GetModes()) + + call s:UnmapAll('XZ') + + " get errors for modes that can't be in one mapping + call assert_fails("call mapset(#{mode: 'nxsoi', abbr: 0})", 'E1276:') + call assert_fails("call mapset(#{mode: ' !', abbr: 0})", 'E1276:') + call assert_fails("call mapset(#{mode: 'ix', abbr: 0})", 'E1276:') + call assert_fails("call mapset(#{mode: 'tl', abbr: 0})", 'E1276:') + call assert_fails("call mapset(#{mode: ' l', abbr: 0})", 'E1276:') + call assert_fails("call mapset(#{mode: ' t', abbr: 0})", 'E1276:') +endfunc + +func Check_ctrlb_map(d, check_alt) + call assert_equal('<C-B>', a:d.lhs) + if a:check_alt + call assert_equal("\x80\xfc\x04B", a:d.lhsraw) + call assert_equal("\x02", a:d.lhsrawalt) + else + call assert_equal("\x02", a:d.lhsraw) + endif +endfunc + +func Test_map_local() + nmap a global + nmap <buffer>a local + + let prev_map_list = split(execute('nmap a'), "\n") + call assert_match('n\s*a\s*@local', prev_map_list[0]) + call assert_match('n\s*a\s*global', prev_map_list[1]) + + let mapping = maparg('a', 'n', 0, 1) + call assert_equal(1, mapping.buffer) + let mapping.rhs = 'new_local' + call mapset('n', 0, mapping) + + " Check that the global mapping is left untouched. + let map_list = split(execute('nmap a'), "\n") + call assert_match('n\s*a\s*@new_local', map_list[0]) + call assert_match('n\s*a\s*global', map_list[1]) + + nunmap a +endfunc + +func Test_map_restore() + " Test restoring map with alternate keycode + nmap <C-B> back + let d = maparg('<C-B>', 'n', 0, 1) + call Check_ctrlb_map(d, 1) + let dsimp = maparg("\x02", 'n', 0, 1) + call Check_ctrlb_map(dsimp, 0) + nunmap <C-B> + call mapset('n', 0, d) + let d = maparg('<C-B>', 'n', 0, 1) + call Check_ctrlb_map(d, 1) + let dsimp = maparg("\x02", 'n', 0, 1) + call Check_ctrlb_map(dsimp, 0) + + nunmap <C-B> +endfunc + +" Test restoring an <SID> mapping +func Test_map_restore_sid() + func RestoreMap() + const d = maparg('<CR>', 'i', v:false, v:true) + iunmap <buffer> <CR> + call mapset('i', v:false, d) + endfunc + + let mapscript =<< trim [CODE] + inoremap <silent><buffer> <SID>Return <C-R>=42<CR> + inoremap <script><buffer> <CR> <CR><SID>Return + [CODE] + call writefile(mapscript, 'Xmapscript', 'D') + + new + source Xmapscript + inoremap <buffer> <C-B> <Cmd>call RestoreMap()<CR> + call feedkeys("i\<CR>\<*C-B>\<CR>", 'xt') + call assert_equal(['', '42', '42'], getline(1, '$')) + + bwipe! + delfunc RestoreMap +endfunc + +" Test restoring a mapping with a negative script ID +func Test_map_restore_negative_sid() + let after =<< trim [CODE] + call assert_equal("\tLast set from --cmd argument", + \ execute('verbose nmap ,n')->trim()->split("\n")[-1]) + let d = maparg(',n', 'n', 0, 1) + nunmap ,n + call assert_equal('No mapping found', + \ execute('verbose nmap ,n')->trim()->split("\n")[-1]) + call mapset('n', 0, d) + call assert_equal("\tLast set from --cmd argument", + \ execute('verbose nmap ,n')->trim()->split("\n")[-1]) + call writefile(v:errors, 'Xresult') + qall! + [CODE] + + if RunVim([], after, '--clean --cmd "nmap ,n <Nop>"') + call assert_equal([], readfile('Xresult')) + endif + call delete('Xresult') +endfunc + +func Test_maplist() + new + func s:ClearMappingsAbbreviations() + mapclear | nmapclear | vmapclear | xmapclear | smapclear | omapclear + mapclear! | imapclear | lmapclear | cmapclear | tmapclear + mapclear <buffer> | nmapclear <buffer> | vmapclear <buffer> + xmapclear <buffer> | smapclear <buffer> | omapclear <buffer> + mapclear! <buffer> | imapclear <buffer> | lmapclear <buffer> + cmapclear <buffer> | tmapclear <buffer> + abclear | abclear <buffer> + endfunc + + func s:AddMaps(new, accum) + if len(a:new) > 0 && a:new[0] != "No mapping found" + eval a:accum->extend(a:new) + endif + endfunc + + call s:ClearMappingsAbbreviations() + call assert_equal(0, len(maplist())) + call assert_equal(0, len(maplist(v:true))) + + " Set up some mappings. + map dup bar + map <buffer> dup bufbar + map foo<C-V> is<F4>foo + vnoremap <script> <buffer> <expr> <silent> bar isbar + tmap baz foo + omap h w + lmap i w + nmap j w + xmap k w + smap l w + map abc <Nop> + nmap <M-j> x + nmap <M-Space> y + " And abbreviations + abbreviate xy he + abbreviate xx she + abbreviate <buffer> x they + + " Get a list of the mappings with the ':map' commands. + " Check maplist() return a list of the same size. + call assert_equal(13, len(maplist())) + call assert_equal(3, len(maplist(v:true))) + call assert_equal(13, len(maplist(v:false))) + + " collect all the current maps using :map commands + let maps_command = [] + call s:AddMaps(split(execute('map'), '\n'), maps_command) + call s:AddMaps(split(execute('map!'), '\n'), maps_command) + call s:AddMaps(split(execute('tmap'), '\n'), maps_command) + call s:AddMaps(split(execute('lmap'), '\n'), maps_command) + + " Use maplist to get all the maps + let maps_maplist = maplist() + call assert_equal(len(maps_command), len(maps_maplist)) + + " make sure all the mode-lhs are unique, no duplicates + let map_set = {} + for d in maps_maplist + let map_set[d.mode .. "-" .. d.lhs .. "-" .. d.buffer] = 0 + endfor + call assert_equal(len(maps_maplist), len(map_set)) + + " For everything returned by maplist, should be the same as from maparg. + " Except for "map dup", bacause maparg returns the <buffer> version + for d in maps_maplist + if d.lhs == 'dup' && d.buffer == 0 + continue + endif + let d_maparg = maparg(d.lhs, d.mode, v:false, v:true) + call assert_equal(d_maparg, d) + endfor + + " Check abbr matches maparg + for d in maplist(v:true) + " Note, d.mode is '!', but can't use that with maparg + let d_maparg = maparg(d.lhs, 'i', v:true, v:true) + call assert_equal(d_maparg, d) + endfor + + call s:ClearMappingsAbbreviations() + call assert_equal(0, len(maplist())) + call assert_equal(0, len(maplist(v:true))) +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_mapping.vim b/test/old/testdir/test_mapping.vim new file mode 100644 index 0000000000..36a46684c1 --- /dev/null +++ b/test/old/testdir/test_mapping.vim @@ -0,0 +1,1708 @@ +" Tests for mappings and abbreviations + +source shared.vim +source check.vim +source screendump.vim +source term_util.vim + +func Test_abbreviation() + " abbreviation with 0x80 should work + inoreab чкпр vim + call feedkeys("Goчкпр \<Esc>", "xt") + call assert_equal('vim ', getline('$')) + iunab чкпр + set nomodified +endfunc + +func Test_abclear() + abbrev foo foobar + iabbrev fooi foobari + cabbrev fooc foobarc + call assert_equal("\n\nc fooc foobarc\ni fooi foobari\n! foo foobar", execute('abbrev')) + + iabclear + call assert_equal("\n\nc fooc foobarc\nc foo foobar", execute('abbrev')) + abbrev foo foobar + iabbrev fooi foobari + + cabclear + call assert_equal("\n\ni fooi foobari\ni foo foobar", execute('abbrev')) + abbrev foo foobar + cabbrev fooc foobarc + + abclear + call assert_equal("\n\nNo abbreviation found", execute('abbrev')) + call assert_fails('%abclear', 'E481:') +endfunc + +func Test_abclear_buffer() + abbrev foo foobar + new X1 + abbrev <buffer> foo1 foobar1 + new X2 + abbrev <buffer> foo2 foobar2 + + call assert_equal("\n\n! foo2 @foobar2\n! foo foobar", execute('abbrev')) + + abclear <buffer> + call assert_equal("\n\n! foo foobar", execute('abbrev')) + + b X1 + call assert_equal("\n\n! foo1 @foobar1\n! foo foobar", execute('abbrev')) + abclear <buffer> + call assert_equal("\n\n! foo foobar", execute('abbrev')) + + abclear + call assert_equal("\n\nNo abbreviation found", execute('abbrev')) + + %bwipe +endfunc + +func Test_map_ctrl_c_insert() + " mapping of ctrl-c in Insert mode + set cpo-=< cpo-=k + inoremap <c-c> <ctrl-c> + cnoremap <c-c> dummy + cunmap <c-c> + call feedkeys("GoTEST2: CTRL-C |\<*C-C>A|\<Esc>", "xt") + call assert_equal('TEST2: CTRL-C |<ctrl-c>A|', getline('$')) + unmap! <c-c> + set nomodified +endfunc + +func Test_map_ctrl_c_visual() + " mapping of ctrl-c in Visual mode + vnoremap <c-c> :<C-u>$put ='vmap works' + call feedkeys("GV\<*C-C>\<CR>", "xt") + call assert_equal('vmap works', getline('$')) + vunmap <c-c> + set nomodified +endfunc + +func Test_map_langmap() + if !has('langmap') + return + endif + + " check langmap applies in normal mode + set langmap=+- nolangremap + new + call setline(1, ['a', 'b', 'c']) + 2 + call assert_equal('b', getline('.')) + call feedkeys("+", "xt") + call assert_equal('a', getline('.')) + + " check no remapping + map x + + 2 + call feedkeys("x", "xt") + call assert_equal('c', getline('.')) + + " check with remapping + set langremap + 2 + call feedkeys("x", "xt") + call assert_equal('a', getline('.')) + + unmap x + bwipe! + + " 'langnoremap' follows 'langremap' and vise versa + set langremap + set langnoremap + call assert_equal(0, &langremap) + set langremap + call assert_equal(0, &langnoremap) + set nolangremap + call assert_equal(1, &langnoremap) + + " check default values + set langnoremap& + call assert_equal(1, &langnoremap) + call assert_equal(0, &langremap) + set langremap& + call assert_equal(1, &langnoremap) + call assert_equal(0, &langremap) + + " langmap should not apply in insert mode, 'langremap' doesn't matter + set langmap=+{ nolangremap + call feedkeys("Go+\<Esc>", "xt") + call assert_equal('+', getline('$')) + set langmap=+{ langremap + call feedkeys("Go+\<Esc>", "xt") + call assert_equal('+', getline('$')) + + " langmap used for register name in insert mode. + call setreg('a', 'aaaa') + call setreg('b', 'bbbb') + call setreg('c', 'cccc') + set langmap=ab langremap + call feedkeys("Go\<C-R>a\<Esc>", "xt") + call assert_equal('bbbb', getline('$')) + call feedkeys("Go\<C-R>\<C-R>a\<Esc>", "xt") + call assert_equal('bbbb', getline('$')) + " mapping does not apply + imap c a + call feedkeys("Go\<C-R>c\<Esc>", "xt") + call assert_equal('cccc', getline('$')) + imap a c + call feedkeys("Go\<C-R>a\<Esc>", "xt") + call assert_equal('bbbb', getline('$')) + + " langmap should not apply in Command-line mode + set langmap=+{ nolangremap + call feedkeys(":call append(line('$'), '+')\<CR>", "xt") + call assert_equal('+', getline('$')) + + iunmap a + iunmap c + set nomodified +endfunc + +func Test_map_feedkeys() + " issue #212 (feedkeys insert mapping at current position) + nnoremap . :call feedkeys(".", "in")<cr> + call setline('$', ['a b c d', 'a b c d']) + $-1 + call feedkeys("0qqdw.ifoo\<Esc>qj0@q\<Esc>", "xt") + call assert_equal(['fooc d', 'fooc d'], getline(line('$') - 1, line('$'))) + nunmap . + set nomodified +endfunc + +func Test_map_cursor() + " <c-g>U<cursor> works only within a single line + imapclear + imap ( ()<c-g>U<left> + call feedkeys("G2o\<Esc>ki\<CR>Test1: text with a (here some more text\<Esc>k.", "xt") + call assert_equal('Test1: text with a (here some more text)', getline(line('$') - 2)) + call assert_equal('Test1: text with a (here some more text)', getline(line('$') - 1)) + + " test undo + call feedkeys("G2o\<Esc>ki\<CR>Test2: text wit a (here some more text [und undo]\<C-G>u\<Esc>k.u", "xt") + call assert_equal('', getline(line('$') - 2)) + call assert_equal('Test2: text wit a (here some more text [und undo])', getline(line('$') - 1)) + set nomodified + imapclear +endfunc + +func Test_map_cursor_ctrl_gU() + " <c-g>U<cursor> works only within a single line + nnoremap c<* *Ncgn<C-r>"<C-G>U<S-Left> + call setline(1, ['foo', 'foobar', '', 'foo']) + call cursor(1,2) + call feedkeys("c<*PREFIX\<esc>.", 'xt') + call assert_equal(['PREFIXfoo', 'foobar', '', 'PREFIXfoo'], getline(1,'$')) + " break undo manually + set ul=1000 + exe ":norm! uu" + call assert_equal(['foo', 'foobar', '', 'foo'], getline(1,'$')) + + " Test that it does not work if the cursor moves to the previous line + " 2 times <S-Left> move to the previous line + nnoremap c<* *Ncgn<C-r>"<C-G>U<S-Left><C-G>U<S-Left> + call setline(1, ['', ' foo', 'foobar', '', 'foo']) + call cursor(2,3) + call feedkeys("c<*PREFIX\<esc>.", 'xt') + call assert_equal(['PREFIXPREFIX', ' foo', 'foobar', '', 'foo'], getline(1,'$')) + nmapclear +endfunc + + +" This isn't actually testing a mapping, but similar use of CTRL-G U as above. +func Test_break_undo() + set whichwrap=<,>,[,] + call feedkeys("G4o2k", "xt") + exe ":norm! iTest3: text with a (parenthesis here\<C-G>U\<Right>new line here\<esc>\<up>\<up>." + call assert_equal('new line here', getline(line('$') - 3)) + call assert_equal('Test3: text with a (parenthesis here', getline(line('$') - 2)) + call assert_equal('new line here', getline(line('$') - 1)) + set nomodified +endfunc + +func Test_map_meta_quotes() + imap <M-"> foo + call feedkeys("Go-\<*M-\">-\<Esc>", "xt") + call assert_equal("-foo-", getline('$')) + set nomodified + iunmap <M-"> +endfunc + +func Test_map_meta_multibyte() + imap <M-á> foo + call assert_match('i <M-á>\s*foo', execute('imap')) + iunmap <M-á> +endfunc + +func Test_abbr_after_line_join() + new + abbr foo bar + set backspace=indent,eol,start + exe "normal o\<BS>foo " + call assert_equal("bar ", getline(1)) + bwipe! + unabbr foo + set backspace& +endfunc + +func Test_map_timeout() + if !has('timers') + return + endif + nnoremap aaaa :let got_aaaa = 1<CR> + nnoremap bb :let got_bb = 1<CR> + nmap b aaa + new + func ExitInsert(timer) + let g:line = getline(1) + call feedkeys("\<Esc>", "t") + endfunc + set timeout timeoutlen=200 + let timer = timer_start(300, 'ExitInsert') + " After the 'b' Vim waits for another character to see if it matches 'bb'. + " When it times out it is expanded to "aaa", but there is no wait for + " "aaaa". Can't check that reliably though. + call feedkeys("b", "xt!") + call assert_equal("aa", g:line) + call assert_false(exists('got_aaa')) + call assert_false(exists('got_bb')) + + bwipe! + nunmap aaaa + nunmap bb + nunmap b + set timeoutlen& + delfunc ExitInsert + call timer_stop(timer) +endfunc + +func Test_map_timeout_with_timer_interrupt() + CheckFeature job + CheckFeature timers + let g:test_is_flaky = 1 + + " Confirm the timer invoked in exit_cb of the job doesn't disturb mapped key + " sequence. + new + let g:val = 0 + nnoremap \12 :let g:val = 1<CR> + nnoremap \123 :let g:val = 2<CR> + set timeout timeoutlen=200 + + func ExitCb(job, status) + let g:timer = timer_start(1, {-> feedkeys("3\<Esc>", 't')}) + endfunc + + call job_start([&shell, &shellcmdflag, 'echo'], {'exit_cb': 'ExitCb'}) + call feedkeys('\12', 'xt!') + call assert_equal(2, g:val) + + bwipe! + nunmap \12 + nunmap \123 + set timeoutlen& + call WaitFor({-> exists('g:timer')}) + call timer_stop(g:timer) + unlet g:timer + unlet g:val + delfunc ExitCb +endfunc + +func Test_cabbr_visual_mode() + cabbr s su + call feedkeys(":s \<c-B>\"\<CR>", 'itx') + call assert_equal('"su ', getreg(':')) + call feedkeys(":'<,'>s \<c-B>\"\<CR>", 'itx') + let expected = '"'. "'<,'>su " + call assert_equal(expected, getreg(':')) + call feedkeys(": '<,'>s \<c-B>\"\<CR>", 'itx') + let expected = '" '. "'<,'>su " + call assert_equal(expected, getreg(':')) + call feedkeys(":'a,'bs \<c-B>\"\<CR>", 'itx') + let expected = '"'. "'a,'bsu " + call assert_equal(expected, getreg(':')) + cunabbr s +endfunc + +func Test_abbreviation_CR() + new + func Eatchar(pat) + let c = nr2char(getchar(0)) + return (c =~ a:pat) ? '' : c + endfunc + iabbrev <buffer><silent> ~~7 <c-r>=repeat('~', 7)<CR><c-r>=Eatchar('\s')<cr> + call feedkeys("GA~~7 \<esc>", 'xt') + call assert_equal('~~~~~~~', getline('$')) + %d + call feedkeys("GA~~7\<cr>\<esc>", 'xt') + call assert_equal(['~~~~~~~', ''], getline(1,'$')) + delfunc Eatchar + bw! +endfunc + +func Test_motionforce_omap() + func GetCommand() + let g:m=mode(1) + let [g:lnum1, g:col1] = searchpos('-', 'Wb') + if g:lnum1 == 0 + return "\<Esc>" + endif + let [g:lnum2, g:col2] = searchpos('-', 'W') + if g:lnum2 == 0 + return "\<Esc>" + endif + return ":call Select()\<CR>" + endfunc + func Select() + call cursor([g:lnum1, g:col1]) + exe "normal! 1 ". (strlen(g:m) == 2 ? 'v' : g:m[2]) + call cursor([g:lnum2, g:col2]) + execute "normal! \<BS>" + endfunc + new + onoremap <buffer><expr> i- GetCommand() + " 1) default omap mapping + %d_ + call setline(1, ['aaa - bbb', 'x', 'ddd - eee']) + call cursor(2, 1) + norm di- + call assert_equal('no', g:m) + call assert_equal(['aaa -- eee'], getline(1, '$')) + " 2) forced characterwise operation + %d_ + call setline(1, ['aaa - bbb', 'x', 'ddd - eee']) + call cursor(2, 1) + norm dvi- + call assert_equal('nov', g:m) + call assert_equal(['aaa -- eee'], getline(1, '$')) + " 3) forced linewise operation + %d_ + call setline(1, ['aaa - bbb', 'x', 'ddd - eee']) + call cursor(2, 1) + norm dVi- + call assert_equal('noV', g:m) + call assert_equal([''], getline(1, '$')) + " 4) forced blockwise operation + %d_ + call setline(1, ['aaa - bbb', 'x', 'ddd - eee']) + call cursor(2, 1) + exe "norm d\<C-V>i-" + call assert_equal("no\<C-V>", g:m) + call assert_equal(['aaabbb', 'x', 'dddeee'], getline(1, '$')) + bwipe! + delfunc Select + delfunc GetCommand +endfunc + +func Test_error_in_map_expr() + " Unlike CheckRunVimInTerminal this does work in a win32 console + CheckFeature terminal + if has('win32') && has('gui_running') + throw 'Skipped: cannot run Vim in a terminal window' + endif + + let lines =<< trim [CODE] + func Func() + " fail to create list + let x = [ + endfunc + nmap <expr> ! Func() + set updatetime=50 + [CODE] + call writefile(lines, 'Xtest.vim') + + let buf = term_start(GetVimCommandCleanTerm() .. ' -S Xtest.vim', {'term_rows': 8}) + let job = term_getjob(buf) + call WaitForAssert({-> assert_notequal('', term_getline(buf, 8))}) + + " GC must not run during map-expr processing, which can make Vim crash. + call term_sendkeys(buf, '!') + call TermWait(buf, 50) + call term_sendkeys(buf, "\<CR>") + call TermWait(buf, 50) + call assert_equal('run', job_status(job)) + + call term_sendkeys(buf, ":qall!\<CR>") + call WaitFor({-> job_status(job) ==# 'dead'}) + if has('unix') + call assert_equal('', job_info(job).termsig) + endif + + call delete('Xtest.vim') + exe buf .. 'bwipe!' +endfunc + +func Test_list_mappings() + " Remove default mappings + imapclear + + " reset 'isident' to check it isn't used + set isident= + inoremap <C-m> CtrlM + inoremap <A-S> AltS + inoremap <S-/> ShiftSlash + set isident& + call assert_equal([ + \ 'i <S-/> * ShiftSlash', + \ 'i <M-S> * AltS', + \ 'i <C-M> * CtrlM', + \], execute('imap')->trim()->split("\n")) + iunmap <C-M> + iunmap <A-S> + call assert_equal(['i <S-/> * ShiftSlash'], execute('imap')->trim()->split("\n")) + iunmap <S-/> + call assert_equal(['No mapping found'], execute('imap')->trim()->split("\n")) + + " List global, buffer local and script local mappings + nmap ,f /^\k\+ (<CR> + nmap <buffer> ,f /^\k\+ (<CR> + nmap <script> ,fs /^\k\+ (<CR> + call assert_equal(['n ,f @/^\k\+ (<CR>', + \ 'n ,fs & /^\k\+ (<CR>', + \ 'n ,f /^\k\+ (<CR>'], + \ execute('nmap ,f')->trim()->split("\n")) + + " List <Nop> mapping + nmap ,n <Nop> + call assert_equal(['n ,n <Nop>'], + \ execute('nmap ,n')->trim()->split("\n")) + + " verbose map + call assert_match("\tLast set from .*/test_mapping.vim line \\d\\+$", + \ execute('verbose map ,n')->trim()->split("\n")[1]) + + " character with K_SPECIAL byte in rhs + nmap foo … + call assert_equal(['n foo …'], + \ execute('nmap foo')->trim()->split("\n")) + + " modified character with K_SPECIAL byte in rhs + nmap foo <M-…> + call assert_equal(['n foo <M-…>'], + \ execute('nmap foo')->trim()->split("\n")) + + " character with K_SPECIAL byte in lhs + nmap … foo + call assert_equal(['n … foo'], + \ execute('nmap …')->trim()->split("\n")) + + " modified character with K_SPECIAL byte in lhs + nmap <M-…> foo + call assert_equal(['n <M-…> foo'], + \ execute('nmap <M-…>')->trim()->split("\n")) + + " illegal bytes + let str = ":\x7f:\x80:\x90:\xd0:" + exe 'nmap foo ' .. str + call assert_equal(['n foo ' .. strtrans(str)], + \ execute('nmap foo')->trim()->split("\n")) + unlet str + + " map to CTRL-V + exe "nmap ,k \<C-V>" + call assert_equal(['n ,k <Nop>'], + \ execute('nmap ,k')->trim()->split("\n")) + + " map with space at the beginning + exe "nmap \<C-V> w <Nop>" + call assert_equal(['n <Space>w <Nop>'], + \ execute("nmap \<C-V> w")->trim()->split("\n")) + + nmapclear +endfunc + +func Test_expr_map_gets_cursor() + new + call setline(1, ['one', 'some w!rd']) + func StoreColumn() + let g:exprLine = line('.') + let g:exprCol = col('.') + return 'x' + endfunc + nnoremap <expr> x StoreColumn() + 2 + nmap ! f!<Ignore>x + call feedkeys("!", 'xt') + call assert_equal('some wrd', getline(2)) + call assert_equal(2, g:exprLine) + call assert_equal(7, g:exprCol) + + bwipe! + unlet g:exprLine + unlet g:exprCol + delfunc StoreColumn + nunmap x + nunmap ! +endfunc + +func Test_expr_map_restore_cursor() + CheckScreendump + + let lines =<< trim END + call setline(1, ['one', 'two', 'three']) + 2 + set ls=2 + hi! link StatusLine ErrorMsg + noremap <expr> <C-B> Func() + func Func() + let g:on = !get(g:, 'on', 0) + redraws + return '' + endfunc + func Status() + return get(g:, 'on', 0) ? '[on]' : '' + endfunc + set stl=%{Status()} + END + call writefile(lines, 'XtestExprMap') + let buf = RunVimInTerminal('-S XtestExprMap', #{rows: 10}) + call term_sendkeys(buf, "\<C-B>") + call VerifyScreenDump(buf, 'Test_map_expr_1', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XtestExprMap') +endfunc + +func Test_map_listing() + CheckScreendump + + let lines =<< trim END + nmap a b + END + call writefile(lines, 'XtestMapList') + let buf = RunVimInTerminal('-S XtestMapList', #{rows: 6}) + call term_sendkeys(buf, ": nmap a\<CR>") + call VerifyScreenDump(buf, 'Test_map_list_1', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XtestMapList') +endfunc + +func Test_expr_map_error() + CheckScreendump + + let lines =<< trim END + func Func() + throw 'test' + return '' + endfunc + + nnoremap <expr> <F2> Func() + cnoremap <expr> <F2> Func() + + call test_override('ui_delay', 10) + END + call writefile(lines, 'XtestExprMap') + let buf = RunVimInTerminal('-S XtestExprMap', #{rows: 10}) + call term_sendkeys(buf, "\<F2>") + call TermWait(buf) + call term_sendkeys(buf, "\<CR>") + call VerifyScreenDump(buf, 'Test_map_expr_2', {}) + + call term_sendkeys(buf, ":abc\<F2>") + call VerifyScreenDump(buf, 'Test_map_expr_3', {}) + call term_sendkeys(buf, "\<Esc>0") + call VerifyScreenDump(buf, 'Test_map_expr_4', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XtestExprMap') +endfunc + +" Test for mapping errors +func Test_map_error() + call assert_fails('unmap', 'E474:') + call assert_fails("exe 'map ' .. repeat('a', 51) .. ' :ls'", 'E474:') + call assert_fails('unmap abc', 'E31:') + call assert_fails('unabbr abc', 'E24:') + call assert_equal('', maparg('')) + call assert_fails('echo maparg("abc", [])', 'E730:') + + " unique map + map ,w /[#&!]<CR> + call assert_fails("map <unique> ,w /[#&!]<CR>", 'E227:') + " unique buffer-local map + call assert_fails("map <buffer> <unique> ,w /[.,;]<CR>", 'E225:') + unmap ,w + + " unique abbreviation + abbr SP special + call assert_fails("abbr <unique> SP special", 'E226:') + " unique buffer-local map + call assert_fails("abbr <buffer> <unique> SP special", 'E224:') + unabbr SP + + call assert_fails('mapclear abc', 'E474:') + call assert_fails('abclear abc', 'E474:') + call assert_fails('abbr $xyz abc', 'E474:') + + " space character in an abbreviation + call assert_fails('abbr ab<space> ABC', 'E474:') + + " invalid <expr> map + map <expr> ,f abc + call assert_fails('normal ,f', 'E121:') + unmap <expr> ,f + + " Recursive use of :normal in a map + set maxmapdepth=100 + map gq :normal gq<CR> + call assert_fails('normal gq', 'E192:') + unmap gq + set maxmapdepth& +endfunc + +" Test for <special> key mapping +func Test_map_special() + throw 'skipped: Nvim does not support cpoptions flag "<"' + new + let old_cpo = &cpo + set cpo+=< + imap <F12> Blue + call feedkeys("i\<F12>", "x") + call assert_equal("<F12>", getline(1)) + call feedkeys("ddi<F12>", "x") + call assert_equal("Blue", getline(1)) + iunmap <F12> + imap <special> <F12> Green + call feedkeys("ddi\<F12>", "x") + call assert_equal("Green", getline(1)) + call feedkeys("ddi<F12>", "x") + call assert_equal("<F12>", getline(1)) + iunmap <special> <F12> + let &cpo = old_cpo + %bwipe! +endfunc + +" Test for hasmapto() +func Test_hasmapto() + call assert_equal(0, hasmapto('/^\k\+ (')) + map ,f /^\k\+ (<CR> + call assert_equal(1, hasmapto('/^\k\+ (')) + unmap ,f + + " Insert mode mapping + call assert_equal(0, hasmapto('/^\k\+ (', 'i')) + imap ,f /^\k\+ (<CR> + call assert_equal(1, hasmapto('/^\k\+ (', 'i')) + iunmap ,f + + " Normal mode mapping + call assert_equal(0, hasmapto('/^\k\+ (', 'n')) + nmap ,f /^\k\+ (<CR> + call assert_equal(1, hasmapto('/^\k\+ (')) + call assert_equal(1, hasmapto('/^\k\+ (', 'n')) + nunmap ,f + + " Visual and Select mode mapping + call assert_equal(0, hasmapto('/^\k\+ (', 'v')) + call assert_equal(0, hasmapto('/^\k\+ (', 'x')) + call assert_equal(0, hasmapto('/^\k\+ (', 's')) + vmap ,f /^\k\+ (<CR> + call assert_equal(1, hasmapto('/^\k\+ (', 'v')) + call assert_equal(1, hasmapto('/^\k\+ (', 'x')) + call assert_equal(1, hasmapto('/^\k\+ (', 's')) + vunmap ,f + + " Visual mode mapping + call assert_equal(0, hasmapto('/^\k\+ (', 'x')) + xmap ,f /^\k\+ (<CR> + call assert_equal(1, hasmapto('/^\k\+ (', 'v')) + call assert_equal(1, hasmapto('/^\k\+ (', 'x')) + call assert_equal(0, hasmapto('/^\k\+ (', 's')) + xunmap ,f + + " Select mode mapping + call assert_equal(0, hasmapto('/^\k\+ (', 's')) + smap ,f /^\k\+ (<CR> + call assert_equal(1, hasmapto('/^\k\+ (', 'v')) + call assert_equal(0, hasmapto('/^\k\+ (', 'x')) + call assert_equal(1, hasmapto('/^\k\+ (', 's')) + sunmap ,f + + " Operator-pending mode mapping + call assert_equal(0, hasmapto('/^\k\+ (', 'o')) + omap ,f /^\k\+ (<CR> + call assert_equal(1, hasmapto('/^\k\+ (', 'o')) + ounmap ,f + + " Language mapping + call assert_equal(0, hasmapto('/^\k\+ (', 'l')) + lmap ,f /^\k\+ (<CR> + call assert_equal(1, hasmapto('/^\k\+ (', 'l')) + lunmap ,f + + " Cmdline mode mapping + call assert_equal(0, hasmapto('/^\k\+ (', 'c')) + cmap ,f /^\k\+ (<CR> + call assert_equal(1, hasmapto('/^\k\+ (', 'c')) + cunmap ,f + + call assert_equal(0, hasmapto('/^\k\+ (', 'n', 1)) +endfunc + +" Test for command-line completion of maps +func Test_mapcomplete() + call assert_equal(['<buffer>', '<expr>', '<nowait>', '<script>', + \ '<silent>', '<special>', '<unique>'], + \ getcompletion('', 'mapping')) + call assert_equal([], getcompletion(',d', 'mapping')) + + call feedkeys(":unmap <buf\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"unmap <buffer>', @:) + + call feedkeys(":unabbr <buf\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"unabbr <buffer>', @:) + + call feedkeys(":abbr! \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"abbr! \x01", @:) + + " When multiple matches have the same {lhs}, it should only appear once. + " The simplified form should also not be included. + nmap ,<C-F> /H<CR> + omap ,<C-F> /H<CR> + call feedkeys(":map ,\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"map ,<C-F>', @:) + mapclear +endfunc + +func GetAbbrText() + unabbr hola + return 'hello' +endfunc + +" Test for <expr> in abbreviation +func Test_expr_abbr() + new + iabbr <expr> teh "the" + call feedkeys("iteh ", "tx") + call assert_equal('the ', getline(1)) + iabclear + call setline(1, '') + + " invalid <expr> abbreviation + abbr <expr> hte GetAbbr() + call assert_fails('normal ihte ', 'E117:') + call assert_equal('', getline(1)) + unabbr <expr> hte + + " evaluating the expression deletes the abbreviation + abbr <expr> hola GetAbbrText() + call assert_equal('GetAbbrText()', maparg('hola', 'i', '1')) + call feedkeys("ahola \<Esc>", 'xt') + call assert_equal('hello ', getline('.')) + call assert_equal('', maparg('hola', 'i', '1')) + + bwipe! +endfunc + +" Test for storing mappings in different modes in a vimrc file +func Test_mkvimrc_mapmodes() + map a1 /a1 + nmap a2 /a2 + vmap a3 /a3 + smap a4 /a4 + xmap a5 /a5 + omap a6 /a6 + map! a7 /a7 + imap a8 /a8 + lmap a9 /a9 + cmap a10 /a10 + tmap a11 /a11 + " Normal + Visual map + map a12 /a12 + sunmap a12 + ounmap a12 + " Normal + Selectmode map + map a13 /a13 + xunmap a13 + ounmap a13 + " Normal + OpPending map + map a14 /a14 + vunmap a14 + " Visual + Selectmode map + map a15 /a15 + nunmap a15 + ounmap a15 + " Visual + OpPending map + map a16 /a16 + nunmap a16 + sunmap a16 + " Selectmode + OpPending map + map a17 /a17 + nunmap a17 + xunmap a17 + " Normal + Visual + Selectmode map + map a18 /a18 + ounmap a18 + " Normal + Visual + OpPending map + map a19 /a19 + sunmap a19 + " Normal + Selectmode + OpPending map + map a20 /a20 + xunmap a20 + " Visual + Selectmode + OpPending map + map a21 /a21 + nunmap a21 + " Mapping to Nop + map a22 <Nop> + " Script local mapping + map <script> a23 /a23 + + " Newline in {lhs} and {rhs} of a map + exe "map a24\<C-V>\<C-J> ia24\<C-V>\<C-J><Esc>" + + " Abbreviation + abbr a25 A25 + cabbr a26 A26 + iabbr a27 A27 + + mkvimrc! Xvimrc + let l = readfile('Xvimrc') + call assert_equal(['map a1 /a1'], filter(copy(l), 'v:val =~ " a1 "')) + call assert_equal(['nmap a2 /a2'], filter(copy(l), 'v:val =~ " a2 "')) + call assert_equal(['vmap a3 /a3'], filter(copy(l), 'v:val =~ " a3 "')) + call assert_equal(['smap a4 /a4'], filter(copy(l), 'v:val =~ " a4 "')) + call assert_equal(['xmap a5 /a5'], filter(copy(l), 'v:val =~ " a5 "')) + call assert_equal(['omap a6 /a6'], filter(copy(l), 'v:val =~ " a6 "')) + call assert_equal(['map! a7 /a7'], filter(copy(l), 'v:val =~ " a7 "')) + call assert_equal(['imap a8 /a8'], filter(copy(l), 'v:val =~ " a8 "')) + call assert_equal(['lmap a9 /a9'], filter(copy(l), 'v:val =~ " a9 "')) + call assert_equal(['cmap a10 /a10'], filter(copy(l), 'v:val =~ " a10 "')) + call assert_equal(['tmap a11 /a11'], filter(copy(l), 'v:val =~ " a11 "')) + call assert_equal(['nmap a12 /a12', 'xmap a12 /a12'], + \ filter(copy(l), 'v:val =~ " a12 "')) + call assert_equal(['nmap a13 /a13', 'smap a13 /a13'], + \ filter(copy(l), 'v:val =~ " a13 "')) + call assert_equal(['nmap a14 /a14', 'omap a14 /a14'], + \ filter(copy(l), 'v:val =~ " a14 "')) + call assert_equal(['vmap a15 /a15'], filter(copy(l), 'v:val =~ " a15 "')) + call assert_equal(['xmap a16 /a16', 'omap a16 /a16'], + \ filter(copy(l), 'v:val =~ " a16 "')) + call assert_equal(['smap a17 /a17', 'omap a17 /a17'], + \ filter(copy(l), 'v:val =~ " a17 "')) + call assert_equal(['nmap a18 /a18', 'vmap a18 /a18'], + \ filter(copy(l), 'v:val =~ " a18 "')) + call assert_equal(['nmap a19 /a19', 'xmap a19 /a19', 'omap a19 /a19'], + \ filter(copy(l), 'v:val =~ " a19 "')) + call assert_equal(['nmap a20 /a20', 'smap a20 /a20', 'omap a20 /a20'], + \ filter(copy(l), 'v:val =~ " a20 "')) + call assert_equal(['vmap a21 /a21', 'omap a21 /a21'], + \ filter(copy(l), 'v:val =~ " a21 "')) + call assert_equal(['map a22 <Nop>'], filter(copy(l), 'v:val =~ " a22 "')) + call assert_equal([], filter(copy(l), 'v:val =~ " a23 "')) + call assert_equal(["map a24<NL> ia24<NL>\x16\e"], + \ filter(copy(l), 'v:val =~ " a24"')) + + call assert_equal(['abbr a25 A25'], filter(copy(l), 'v:val =~ " a25 "')) + call assert_equal(['cabbr a26 A26'], filter(copy(l), 'v:val =~ " a26 "')) + call assert_equal(['iabbr a27 A27'], filter(copy(l), 'v:val =~ " a27 "')) + call delete('Xvimrc') + + mapclear + nmapclear + vmapclear + xmapclear + smapclear + omapclear + imapclear + lmapclear + cmapclear + tmapclear +endfunc + +" Test for recursive mapping ('maxmapdepth') +func Test_map_recursive() + map x y + map y x + call assert_fails('normal x', 'E223:') + unmap x + unmap y +endfunc + +" Test for removing an abbreviation using {rhs} and with space after {lhs} +func Test_abbr_remove() + abbr foo bar + let d = maparg('foo', 'i', 1, 1) + call assert_equal(['foo', 'bar', '!'], [d.lhs, d.rhs, d.mode]) + unabbr bar + call assert_equal({}, maparg('foo', 'i', 1, 1)) + + abbr foo bar + unabbr foo<space><tab> + call assert_equal({}, maparg('foo', 'i', 1, 1)) +endfunc + +" Trigger an abbreviation using a special key +func Test_abbr_trigger_special() + new + iabbr teh the + call feedkeys("iteh\<F2>\<Esc>", 'xt') + call assert_equal('the<F2>', getline(1)) + iunab teh + close! +endfunc + +" Test for '<' in 'cpoptions' +func Test_map_cpo_special_keycode() + set cpo-=< + imap x<Bslash>k Test + let d = maparg('x<Bslash>k', 'i', 0, 1) + call assert_equal(['x\k', 'Test', 'i'], [d.lhs, d.rhs, d.mode]) + call feedkeys(":imap x\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"imap x\k', @:) + iunmap x<Bslash>k + " Nvim: no "<" flag in 'cpoptions'. + " set cpo+=< + " imap x<Bslash>k Test + " let d = maparg('x<Bslash>k', 'i', 0, 1) + " call assert_equal(['x<Bslash>k', 'Test', 'i'], [d.lhs, d.rhs, d.mode]) + " call feedkeys(":imap x\<C-A>\<C-B>\"\<CR>", 'tx') + " call assert_equal('"imap x<Bslash>k', @:) + " iunmap x<Bslash>k + set cpo-=< + " Modifying 'cpo' above adds some default mappings, remove them + mapclear + mapclear! +endfunc + +" Test for <Cmd> key in maps to execute commands +func Test_map_cmdkey() + new + + " Error cases + let x = 0 + noremap <F3> <Cmd><Cmd>let x = 1<CR> + call assert_fails('call feedkeys("\<F3>", "xt")', 'E1136:') + call assert_equal(0, x) + + noremap <F3> <Cmd>let x = 3 + call assert_fails('call feedkeys("\<F3>", "xt!")', 'E1255:') + call assert_equal(0, x) + + " works in various modes and sees the correct mode() + noremap <F3> <Cmd>let m = mode(1)<CR> + noremap! <F3> <Cmd>let m = mode(1)<CR> + + " normal mode + call feedkeys("\<F3>", 'xt') + call assert_equal('n', m) + + " visual mode + call feedkeys("v\<F3>", 'xt!') + call assert_equal('v', m) + " shouldn't leave the visual mode + call assert_equal('v', mode(1)) + call feedkeys("\<Esc>", 'xt') + call assert_equal('n', mode(1)) + + " visual mapping in select mode + call feedkeys("gh\<F3>", 'xt!') + call assert_equal('v', m) + " shouldn't leave select mode + call assert_equal('s', mode(1)) + call feedkeys("\<Esc>", 'xt') + call assert_equal('n', mode(1)) + + " select mode mapping + snoremap <F3> <Cmd>let m = mode(1)<cr> + call feedkeys("gh\<F3>", 'xt!') + call assert_equal('s', m) + " shouldn't leave select mode + call assert_equal('s', mode(1)) + call feedkeys("\<Esc>", 'xt') + call assert_equal('n', mode(1)) + + " operator-pending mode + call feedkeys("d\<F3>", 'xt!') + call assert_equal('no', m) + " leaves the operator-pending mode + call assert_equal('n', mode(1)) + + " insert mode + call feedkeys("i\<F3>abc", 'xt') + call assert_equal('i', m) + call assert_equal('abc', getline('.')) + + " replace mode + call feedkeys("0R\<F3>two", 'xt') + call assert_equal('R', m) + call assert_equal('two', getline('.')) + + " virtual replace mode + call setline('.', "one\ttwo") + call feedkeys("4|gR\<F3>xxx", 'xt') + call assert_equal('Rv', m) + call assert_equal("onexxx\ttwo", getline('.')) + + " cmdline mode + call feedkeys(":\<F3>\"xxx\<CR>", 'xt!') + call assert_equal('c', m) + call assert_equal('"xxx', @:) + + " terminal mode + if CanRunVimInTerminal() + tnoremap <F3> <Cmd>let m = mode(1)<CR> + let buf = Run_shell_in_terminal({}) + call feedkeys("\<F3>", 'xt') + call assert_equal('t', m) + call assert_equal('t', mode(1)) + call StopShellInTerminal(buf) + close! + tunmap <F3> + endif + + " invoke cmdline mode recursively + noremap! <F2> <Cmd>norm! :foo<CR> + %d + call setline(1, ['some short lines', 'of test text']) + call feedkeys(":bar\<F2>x\<C-B>\"\r", 'xt') + call assert_equal('"barx', @:) + unmap! <F2> + + " test for calling a <SID> function + let lines =<< trim END + map <F2> <Cmd>call <SID>do_it()<CR> + func s:do_it() + let g:x = 32 + endfunc + END + call writefile(lines, 'Xscript') + source Xscript + call feedkeys("\<F2>", 'xt') + call assert_equal(32, g:x) + call delete('Xscript') + + unmap <F3> + unmap! <F3> + %bw! +endfunc + +" text object enters visual mode +func TextObj() + if mode() !=# "v" + normal! v + end + call cursor(1, 3) + normal! o + call cursor(2, 4) +endfunc + +func s:cmdmap(lhs, rhs) + exe 'noremap ' .. a:lhs .. ' <Cmd>' .. a:rhs .. '<CR>' + exe 'noremap! ' .. a:lhs .. ' <Cmd>' .. a:rhs .. '<CR>' +endfunc + +func s:cmdunmap(lhs) + exe 'unmap ' .. a:lhs + exe 'unmap! ' .. a:lhs +endfunc + +" Map various <Fx> keys used by the <Cmd> key tests +func s:setupMaps() + call s:cmdmap('<F3>', 'let m = mode(1)') + call s:cmdmap('<F4>', 'normal! ww') + call s:cmdmap('<F5>', 'normal! "ay') + call s:cmdmap('<F6>', 'throw "very error"') + call s:cmdmap('<F7>', 'call TextObj()') + call s:cmdmap('<F8>', 'startinsert') + call s:cmdmap('<F9>', 'stopinsert') +endfunc + +" Remove the mappings setup by setupMaps() +func s:cleanupMaps() + call s:cmdunmap('<F3>') + call s:cmdunmap('<F4>') + call s:cmdunmap('<F5>') + call s:cmdunmap('<F6>') + call s:cmdunmap('<F7>') + call s:cmdunmap('<F8>') + call s:cmdunmap('<F9>') +endfunc + +" Test for <Cmd> mapping in normal mode +func Test_map_cmdkey_normal_mode() + new + call s:setupMaps() + + " check v:count and v:register works + call s:cmdmap('<F2>', 'let s = [mode(1), v:count, v:register]') + call feedkeys("\<F2>", 'xt') + call assert_equal(['n', 0, '"'], s) + call feedkeys("7\<F2>", 'xt') + call assert_equal(['n', 7, '"'], s) + call feedkeys("\"e\<F2>", 'xt') + call assert_equal(['n', 0, 'e'], s) + call feedkeys("5\"k\<F2>", 'xt') + call assert_equal(['n', 5, 'k'], s) + call s:cmdunmap('<F2>') + + call setline(1, ['some short lines', 'of test text']) + call feedkeys("\<F7>y", 'xt') + call assert_equal("me short lines\nof t", @") + call assert_equal('v', getregtype('"')) + call assert_equal([0, 1, 3, 0], getpos("'<")) + call assert_equal([0, 2, 4, 0], getpos("'>")) + + " startinsert + %d + call feedkeys("\<F8>abc", 'xt') + call assert_equal('abc', getline(1)) + + " feedkeys are not executed immediately + noremap ,a <Cmd>call feedkeys("aalpha") \| let g:a = getline(2)<CR> + %d + call setline(1, ['some short lines', 'of test text']) + call cursor(2, 3) + call feedkeys(",a\<F3>", 'xt') + call assert_equal('of test text', g:a) + call assert_equal('n', m) + call assert_equal(['some short lines', 'of alphatest text'], getline(1, '$')) + nunmap ,a + + " feedkeys(..., 'x') is executed immediately, but insert mode is aborted + noremap ,b <Cmd>call feedkeys("abeta", 'x') \| let g:b = getline(2)<CR> + call feedkeys(",b\<F3>", 'xt') + call assert_equal('n', m) + call assert_equal('of alphabetatest text', g:b) + nunmap ,b + + call s:cleanupMaps() + %bw! +endfunc + +" Test for <Cmd> mapping with the :normal command +func Test_map_cmdkey_normal_cmd() + new + noremap ,x <Cmd>call append(1, "xx") \| call append(1, "aa")<CR> + noremap ,f <Cmd>nosuchcommand<CR> + noremap ,e <Cmd>throw "very error" \| call append(1, "yy")<CR> + noremap ,m <Cmd>echoerr "The message." \| call append(1, "zz")<CR> + noremap ,w <Cmd>for i in range(5) \| if i==1 \| echoerr "Err" \| endif \| call append(1, i) \| endfor<CR> + + call setline(1, ['some short lines', 'of test text']) + exe "norm ,x\r" + call assert_equal(['some short lines', 'aa', 'xx', 'of test text'], getline(1, '$')) + + call assert_fails('norm ,f', 'E492:') + call assert_fails('norm ,e', 'very error') + call assert_fails('norm ,m', 'The message.') + call assert_equal(['some short lines', 'aa', 'xx', 'of test text'], getline(1, '$')) + + %d + let caught_err = 0 + try + exe "normal ,w" + catch /Vim(echoerr):Err/ + let caught_err = 1 + endtry + call assert_equal(1, caught_err) + call assert_equal(['', '0'], getline(1, '$')) + + %d + call assert_fails('normal ,w', 'Err') + call assert_equal(['', '4', '3', '2' ,'1', '0'], getline(1, '$')) + call assert_equal(1, line('.')) + + nunmap ,x + nunmap ,f + nunmap ,e + nunmap ,m + nunmap ,w + %bw! +endfunc + +" Test for <Cmd> mapping in visual mode +func Test_map_cmdkey_visual_mode() + new + set showmode + call s:setupMaps() + + call setline(1, ['some short lines', 'of test text']) + call feedkeys("v\<F4>", 'xt!') + call assert_equal(['v', 1, 12], [mode(1), col('v'), col('.')]) + + " can invoke an operator, ending the visual mode + let @a = '' + call feedkeys("\<F5>", 'xt!') + call assert_equal('n', mode(1)) + call assert_equal('some short l', @a) + + " error doesn't interrupt visual mode + call assert_fails('call feedkeys("ggvw\<F6>", "xt!")', 'E605:') + call assert_equal(['v', 1, 6], [mode(1), col('v'), col('.')]) + call feedkeys("\<F7>", 'xt!') + call assert_equal(['v', 1, 3, 2, 4], [mode(1), line('v'), col('v'), line('.'), col('.')]) + + " startinsert gives "-- (insert) VISUAL --" mode + call feedkeys("\<F8>", 'xt!') + call assert_equal(['v', 1, 3, 2, 4], [mode(1), line('v'), col('v'), line('.'), col('.')]) + redraw! + call assert_match('^-- (insert) VISUAL --', Screenline(&lines)) + call feedkeys("\<Esc>new ", 'x') + call assert_equal(['some short lines', 'of new test text'], getline(1, '$')) + + call s:cleanupMaps() + set showmode& + %bw! +endfunc + +" Test for <Cmd> mapping in select mode +func Test_map_cmdkey_select_mode() + new + set showmode + call s:setupMaps() + + snoremap <F1> <cmd>throw "very error"<CR> + snoremap <F2> <cmd>normal! <c-g>"by<CR> + call setline(1, ['some short lines', 'of test text']) + + call feedkeys("gh\<F4>", "xt!") + call assert_equal(['s', 1, 12], [mode(1), col('v'), col('.')]) + redraw! + call assert_match('^-- SELECT --', Screenline(&lines)) + + " visual mapping in select mode restarts select mode after operator + let @a = '' + call feedkeys("\<F5>", 'xt!') + call assert_equal('s', mode(1)) + call assert_equal('some short l', @a) + + " select mode mapping works, and does not restart select mode + let @b = '' + call feedkeys("\<F2>", 'xt!') + call assert_equal('n', mode(1)) + call assert_equal('some short l', @b) + + " error doesn't interrupt temporary visual mode + call assert_fails('call feedkeys("\<Esc>ggvw\<C-G>\<F6>", "xt!")', 'E605:') + redraw! + call assert_match('^-- VISUAL --', Screenline(&lines)) + " quirk: restoration of select mode is not performed + call assert_equal(['v', 1, 6], [mode(1), col('v'), col('.')]) + + " error doesn't interrupt select mode + call assert_fails('call feedkeys("\<Esc>ggvw\<C-G>\<F1>", "xt!")', 'E605:') + redraw! + call assert_match('^-- SELECT --', Screenline(&lines)) + call assert_equal(['s', 1, 6], [mode(1), col('v'), col('.')]) + + call feedkeys("\<F7>", 'xt!') + redraw! + call assert_match('^-- SELECT --', Screenline(&lines)) + call assert_equal(['s', 1, 3, 2, 4], [mode(1), line('v'), col('v'), line('.'), col('.')]) + + " startinsert gives "-- SELECT (insert) --" mode + call feedkeys("\<F8>", 'xt!') + redraw! + call assert_match('^-- (insert) SELECT --', Screenline(&lines)) + call assert_equal(['s', 1, 3, 2, 4], [mode(1), line('v'), col('v'), line('.'), col('.')]) + call feedkeys("\<Esc>new ", 'x') + call assert_equal(['some short lines', 'of new test text'], getline(1, '$')) + + sunmap <F1> + sunmap <F2> + call s:cleanupMaps() + set showmode& + %bw! +endfunc + +" Test for <Cmd> mapping in operator-pending mode +func Test_map_cmdkey_op_pending_mode() + new + call s:setupMaps() + + call setline(1, ['some short lines', 'of test text']) + call feedkeys("d\<F4>", 'xt') + call assert_equal(['lines', 'of test text'], getline(1, '$')) + call assert_equal(['some short '], getreg('"', 1, 1)) + " create a new undo point + let &g:undolevels = &g:undolevels + + call feedkeys(".", 'xt') + call assert_equal(['test text'], getline(1, '$')) + call assert_equal(['lines', 'of '], getreg('"', 1, 1)) + " create a new undo point + let &g:undolevels = &g:undolevels + + call feedkeys("uu", 'xt') + call assert_equal(['some short lines', 'of test text'], getline(1, '$')) + + " error aborts operator-pending, operator not performed + call assert_fails('call feedkeys("d\<F6>", "xt")', 'E605:') + call assert_equal(['some short lines', 'of test text'], getline(1, '$')) + + call feedkeys("\"bd\<F7>", 'xt') + call assert_equal(['soest text'], getline(1, '$')) + call assert_equal(['me short lines', 'of t'], getreg('b', 1, 1)) + + " startinsert aborts operator + call feedkeys("d\<F8>cc", 'xt') + call assert_equal(['soccest text'], getline(1, '$')) + + call s:cleanupMaps() + %bw! +endfunc + +" Test for <Cmd> mapping in insert mode +func Test_map_cmdkey_insert_mode() + new + call s:setupMaps() + + call setline(1, ['some short lines', 'of test text']) + " works the same as <C-O>w<C-O>w + call feedkeys("iindeed \<F4>little ", 'xt') + call assert_equal(['indeed some short little lines', 'of test text'], getline(1, '$')) + call assert_fails('call feedkeys("i\<F6> 2", "xt")', 'E605:') + call assert_equal(['indeed some short little 2 lines', 'of test text'], getline(1, '$')) + + " Note when entering visual mode from InsertEnter autocmd, an async event, + " or a <Cmd> mapping, vim ends up in undocumented "INSERT VISUAL" mode. + call feedkeys("i\<F7>stuff ", 'xt') + call assert_equal(['indeed some short little 2 lines', 'of stuff test text'], getline(1, '$')) + call assert_equal(['v', 1, 3, 2, 9], [mode(1), line('v'), col('v'), line('.'), col('.')]) + + call feedkeys("\<F5>", 'xt') + call assert_equal(['deed some short little 2 lines', 'of stuff '], getreg('a', 1, 1)) + + " also works as part of abbreviation + abbr foo <Cmd>let g:y = 17<CR>bar + exe "normal i\<space>foo " + call assert_equal(17, g:y) + call assert_equal('in bar deed some short little 2 lines', getline(1)) + unabbr foo + + " :startinsert does nothing + call setline(1, 'foo bar') + call feedkeys("ggi\<F8>vim", 'xt') + call assert_equal('vimfoo bar', getline(1)) + + " :stopinsert works + call feedkeys("ggi\<F9>Abc", 'xt') + call assert_equal('vimfoo barbc', getline(1)) + + call s:cleanupMaps() + %bw! +endfunc + +" Test for <Cmd> mapping in insert-completion mode +func Test_map_cmdkey_insert_complete_mode() + new + call s:setupMaps() + + call setline(1, 'some short lines') + call feedkeys("os\<C-X>\<C-N>\<F3>\<C-N> ", 'xt') + call assert_equal('ic', m) + call assert_equal(['some short lines', 'short '], getline(1, '$')) + + call s:cleanupMaps() + %bw! +endfunc + +" Test for <Cmd> mapping in cmdline mode +func Test_map_cmdkey_cmdline_mode() + new + call s:setupMaps() + + call setline(1, ['some short lines', 'of test text']) + let x = 0 + call feedkeys(":let x\<F3>= 10\r", 'xt') + call assert_equal('c', m) + call assert_equal(10, x) + + " exception doesn't leave cmdline mode + call assert_fails('call feedkeys(":let x\<F6>= 20\r", "xt")', 'E605:') + call assert_equal(20, x) + + " move cursor in the buffer from cmdline mode + call feedkeys(":let x\<F4>= 30\r", 'xt') + call assert_equal(30, x) + call assert_equal(12, col('.')) + + " :startinsert takes effect after leaving cmdline mode + call feedkeys(":let x\<F8>= 40\rnew ", 'xt') + call assert_equal(40, x) + call assert_equal('some short new lines', getline(1)) + + call s:cleanupMaps() + %bw! +endfunc + +func Test_map_cmdkey_redo() + func SelectDash() + call search('^---\n\zs', 'bcW') + norm! V + call search('\n\ze---$', 'W') + endfunc + + let text =<< trim END + --- + aaa + --- + bbb + bbb + --- + ccc + ccc + ccc + --- + END + new Xcmdtext + call setline(1, text) + + onoremap <silent> i- <Cmd>call SelectDash()<CR> + call feedkeys('2Gdi-', 'xt') + call assert_equal(['---', '---'], getline(1, 2)) + call feedkeys('j.', 'xt') + call assert_equal(['---', '---', '---'], getline(1, 3)) + call feedkeys('j.', 'xt') + call assert_equal(['---', '---', '---', '---'], getline(1, 4)) + + bwipe! + call delete('Xcmdtext') + delfunc SelectDash + ounmap i- + + new + call setline(1, 'aaa bbb ccc ddd') + + " command can contain special keys + onoremap ix <Cmd>let g:foo ..= '…'<Bar>normal! <C-Right><CR> + let g:foo = '' + call feedkeys('0dix.', 'xt') + call assert_equal('……', g:foo) + call assert_equal('ccc ddd', getline(1)) + unlet g:foo + + " command line ending in "0" is handled without errors + onoremap ix <Cmd>eval 0<CR> + call feedkeys('dix.', 'xt') + + ounmap ix + bwipe! +endfunc + +" Test for using <script> with a map to remap characters in rhs +func Test_script_local_remap() + new + inoremap <buffer> <SID>xyz mno + inoremap <buffer> <script> abc st<SID>xyzre + normal iabc + call assert_equal('stmnore', getline(1)) + bwipe! +endfunc + +func Test_abbreviate_multi_byte() + new + iabbrev foo bar + call feedkeys("ifoo…\<Esc>", 'xt') + call assert_equal("bar…", getline(1)) + iunabbrev foo + bwipe! +endfunc + +" Test for abbreviations with 'latin1' encoding +func Test_abbreviate_latin1_encoding() + " set encoding=latin1 + call assert_fails('abbr ab#$c ABC', 'E474:') + new + iabbr <buffer> #i #include + iabbr <buffer> ## #enddef + exe "normal i#i\<C-]>" + call assert_equal('#include', getline(1)) + exe "normal 0Di##\<C-]>" + call assert_equal('#enddef', getline(1)) + %bw! + set encoding=utf-8 +endfunc ++ +" Test for <Plug> always being mapped, even when used with "noremap". +func Test_plug_remap() + let g:foo = 0 + nnoremap <Plug>(Increase_x) <Cmd>let g:foo += 1<CR> + nmap <F2> <Plug>(Increase_x) + nnoremap <F3> <Plug>(Increase_x) + call feedkeys("\<F2>", 'xt') + call assert_equal(1, g:foo) + call feedkeys("\<F3>", 'xt') + call assert_equal(2, g:foo) + nnoremap x <Nop> + nmap <F4> x<Plug>(Increase_x)x + nnoremap <F5> x<Plug>(Increase_x)x + call setline(1, 'Some text') + normal! gg$ + call feedkeys("\<F4>", 'xt') + call assert_equal(3, g:foo) + call assert_equal('Some text', getline(1)) + call feedkeys("\<F5>", 'xt') + call assert_equal(4, g:foo) + call assert_equal('Some te', getline(1)) + nunmap <Plug>(Increase_x) + nunmap <F2> + nunmap <F3> + nunmap <F4> + nunmap <F5> + unlet g:foo + %bw! +endfunc + +func Test_mouse_drag_mapped_start_select() + set mouse=a + set selectmode=key,mouse + func ClickExpr() + call Ntest_setmouse(1, 1) + return "\<LeftMouse>" + endfunc + func DragExpr() + call Ntest_setmouse(1, 2) + return "\<LeftDrag>" + endfunc + nnoremap <expr> <F2> ClickExpr() + nmap <expr> <F3> DragExpr() + + nnoremap <LeftDrag> <LeftDrag><Cmd><CR> + exe "normal \<F2>\<F3>" + call assert_equal('s', mode()) + exe "normal! \<C-\>\<C-N>" + + nunmap <LeftDrag> + nunmap <F2> + nunmap <F3> + delfunc ClickExpr + delfunc DragExpr + set selectmode& + set mouse& +endfunc + +func Test_mouse_drag_statusline() + set laststatus=2 + set mouse=a + func ClickExpr() + call Ntest_setmouse(&lines - 1, 1) + return "\<LeftMouse>" + endfunc + func DragExpr() + call Ntest_setmouse(&lines - 2, 1) + return "\<LeftDrag>" + endfunc + nnoremap <expr> <F2> ClickExpr() + nnoremap <expr> <F3> DragExpr() + + " this was causing a crash in win_drag_status_line() + call feedkeys("\<F2>:tabnew\<CR>\<F3>", 'tx') + + nunmap <F2> + nunmap <F3> + delfunc ClickExpr + delfunc DragExpr + set laststatus& mouse& +endfunc + +" Test for mapping <LeftDrag> in Insert mode +func Test_mouse_drag_insert_map() + set mouse=a + func ClickExpr() + call Ntest_setmouse(1, 1) + return "\<LeftMouse>" + endfunc + func DragExpr() + call Ntest_setmouse(1, 2) + return "\<LeftDrag>" + endfunc + inoremap <expr> <F2> ClickExpr() + imap <expr> <F3> DragExpr() + + inoremap <LeftDrag> <LeftDrag><Cmd>let g:dragged = 1<CR> + exe "normal i\<F2>\<F3>" + call assert_equal(1, g:dragged) + call assert_equal('v', mode()) + exe "normal! \<C-\>\<C-N>" + unlet g:dragged + + inoremap <LeftDrag> <LeftDrag><C-\><C-N> + exe "normal i\<F2>\<F3>" + call assert_equal('n', mode()) + + iunmap <LeftDrag> + iunmap <F2> + iunmap <F3> + delfunc ClickExpr + delfunc DragExpr + set mouse& +endfunc + +func Test_unmap_simplifiable() + map <C-I> foo + map <Tab> bar + call assert_equal('foo', maparg('<C-I>')) + call assert_equal('bar', maparg('<Tab>')) + unmap <C-I> + call assert_equal('', maparg('<C-I>')) + call assert_equal('bar', maparg('<Tab>')) + unmap <Tab> + + map <C-I> foo + unmap <Tab> + " This should not error + unmap <C-I> +endfunc + +func Test_expr_map_escape_special() + nnoremap … <Cmd>let g:got_ellipsis += 1<CR> + func Func() + return '…' + endfunc + nmap <expr> <F2> Func() + let g:got_ellipsis = 0 + call feedkeys("\<F2>", 'xt') + call assert_equal(1, g:got_ellipsis) + delfunc Func + nunmap <F2> + unlet g:got_ellipsis + nunmap … +endfunc + +" Testing for mapping after an <Nop> mapping is triggered on timeout. +" Test for what patch 8.1.0052 fixes. +func Test_map_after_timed_out_nop() + CheckRunVimInTerminal + + let lines =<< trim END + set timeout timeoutlen=400 + inoremap ab TEST + inoremap a <Nop> + END + call writefile(lines, 'Xtest_map_after_timed_out_nop') + let buf = RunVimInTerminal('-S Xtest_map_after_timed_out_nop', #{rows: 6}) + + " Enter Insert mode + call term_sendkeys(buf, 'i') + " Wait for the "a" mapping to timeout + call term_sendkeys(buf, 'a') + call term_wait(buf, 500) + " Send "a" and wait for a period shorter than 'timeoutlen' + call term_sendkeys(buf, 'a') + call term_wait(buf, 100) + " Send "b", should trigger the "ab" mapping + call term_sendkeys(buf, 'b') + call WaitForAssert({-> assert_equal("TEST", term_getline(buf, 1))}) + + " clean up + call StopVimInTerminal(buf) + call delete('Xtest_map_after_timed_out_nop') +endfunc + +func Test_using_past_typeahead() + nnoremap :00 0 + exe "norm :set \x80\xfb0=0\<CR>" + exe "sil norm :0\x0f\<C-U>\<CR>" + + exe "norm :set \x80\xfb0=\<CR>" + nunmap :00 +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_marks.vim b/test/old/testdir/test_marks.vim new file mode 100644 index 0000000000..a7ccca498c --- /dev/null +++ b/test/old/testdir/test_marks.vim @@ -0,0 +1,320 @@ + +" Test that a deleted mark is restored after delete-undo-redo-undo. +func Test_Restore_DelMark() + enew! + call append(0, [" textline A", " textline B", " textline C"]) + normal! 2gg + set nocp viminfo+=nviminfo + exe "normal! i\<C-G>u\<Esc>" + exe "normal! maddu\<C-R>u" + let pos = getpos("'a") + call assert_equal(2, pos[1]) + call assert_equal(1, pos[2]) + enew! +endfunc + +" Test that CTRL-A and CTRL-X updates last changed mark '[, ']. +func Test_Incr_Marks() + enew! + call append(0, ["123 123 123", "123 123 123", "123 123 123"]) + normal! gg + execute "normal! \<C-A>`[v`]rAjwvjw\<C-X>`[v`]rX" + call assert_equal("AAA 123 123", getline(1)) + call assert_equal("123 XXXXXXX", getline(2)) + call assert_equal("XXX 123 123", getline(3)) + enew! +endfunc + +func Test_previous_jump_mark() + new + call setline(1, ['']->repeat(6)) + normal Ggg + call assert_equal(6, getpos("''")[1]) + normal jjjjj + call assert_equal(6, getpos("''")[1]) + bwipe! +endfunc + +func Test_setpos() + new Xone + let onebuf = bufnr('%') + let onewin = win_getid() + call setline(1, ['aaa', 'bbb', 'ccc']) + new Xtwo + let twobuf = bufnr('%') + let twowin = win_getid() + call setline(1, ['aaa', 'bbb', 'ccc']) + + " for the cursor the buffer number is ignored + call setpos(".", [0, 2, 1, 0]) + call assert_equal([0, 2, 1, 0], getpos(".")) + call setpos(".", [onebuf, 3, 3, 0]) + call assert_equal([0, 3, 3, 0], getpos(".")) + + call setpos("''", [0, 1, 3, 0]) + call assert_equal([0, 1, 3, 0], getpos("''")) + call setpos("''", [onebuf, 2, 2, 0]) + call assert_equal([0, 2, 2, 0], getpos("''")) + + " buffer-local marks + for mark in ["'a", "'\"", "'[", "']", "'<", "'>"] + call win_gotoid(twowin) + call setpos(mark, [0, 2, 1, 0]) + call assert_equal([0, 2, 1, 0], getpos(mark), "for mark " . mark) + call setpos(mark, [onebuf, 1, 3, 0]) + call win_gotoid(onewin) + call assert_equal([0, 1, 3, 0], getpos(mark), "for mark " . mark) + endfor + + " global marks + call win_gotoid(twowin) + call setpos("'N", [0, 2, 1, 0]) + call assert_equal([twobuf, 2, 1, 0], getpos("'N")) + call setpos("'N", [onebuf, 1, 3, 0]) + call assert_equal([onebuf, 1, 3, 0], getpos("'N")) + + " try invalid column and check virtcol() + call win_gotoid(onewin) + call setpos("'a", [0, 1, 2, 0]) + call assert_equal([0, 1, 2, 0], getpos("'a")) + call setpos("'a", [0, 1, -5, 0]) + call assert_equal([0, 1, 2, 0], getpos("'a")) + call setpos("'a", [0, 1, 0, 0]) + call assert_equal([0, 1, 1, 0], getpos("'a")) + call setpos("'a", [0, 1, 4, 0]) + call assert_equal([0, 1, 4, 0], getpos("'a")) + call assert_equal(4, virtcol("'a")) + call setpos("'a", [0, 1, 5, 0]) + call assert_equal([0, 1, 5, 0], getpos("'a")) + call assert_equal(4, virtcol("'a")) + call setpos("'a", [0, 1, 21341234, 0]) + call assert_equal([0, 1, 21341234, 0], getpos("'a")) + call assert_equal(4, virtcol("'a")) + + " Test with invalid buffer number, line number and column number + call cursor(2, 2) + call setpos('.', [-1, 1, 1, 0]) + call assert_equal([2, 2], [line('.'), col('.')]) + call setpos('.', [0, -1, 1, 0]) + call assert_equal([2, 2], [line('.'), col('.')]) + call setpos('.', [0, 1, -1, 0]) + call assert_equal([2, 2], [line('.'), col('.')]) + + call assert_fails("call setpos('ab', [0, 1, 1, 0])", 'E474:') + + bwipe! + call win_gotoid(twowin) + bwipe! +endfunc + +func Test_marks_cmd() + new Xone + call setline(1, ['aaa', 'bbb']) + norm! maG$mB + w! + new Xtwo + call setline(1, ['ccc', 'ddd']) + norm! $mcGmD + exe "norm! GVgg\<Esc>G" + w! + + b Xone + let a = split(execute('marks'), "\n") + call assert_equal(9, len(a)) + call assert_equal(['mark line col file/text', + \ " ' 2 0 bbb", + \ ' a 1 0 aaa', + \ ' B 2 2 bbb', + \ ' D 2 0 Xtwo', + \ ' " 1 0 aaa', + \ ' [ 1 0 aaa', + \ ' ] 2 0 bbb', + \ ' . 2 0 bbb'], a) + + b Xtwo + let a = split(execute('marks'), "\n") + call assert_equal(11, len(a)) + call assert_equal(['mark line col file/text', + \ " ' 1 0 ccc", + \ ' c 1 2 ccc', + \ ' B 2 2 Xone', + \ ' D 2 0 ddd', + \ ' " 2 0 ddd', + \ ' [ 1 0 ccc', + \ ' ] 2 0 ddd', + \ ' . 2 0 ddd', + \ ' < 1 0 ccc', + \ ' > 2 0 ddd'], a) + norm! Gdd + w! + let a = split(execute('marks <>'), "\n") + call assert_equal(3, len(a)) + call assert_equal(['mark line col file/text', + \ ' < 1 0 ccc', + \ ' > 2 0 -invalid-'], a) + + b Xone + delmarks aB + let a = split(execute('marks aBcD'), "\n") + call assert_equal(2, len(a)) + call assert_equal('mark line col file/text', a[0]) + call assert_equal(' D 2 0 Xtwo', a[1]) + + b Xtwo + delmarks cD + call assert_fails('marks aBcD', 'E283:') + + call delete('Xone') + call delete('Xtwo') + %bwipe +endfunc + +func Test_marks_cmd_multibyte() + new Xone + call setline(1, [repeat('á', &columns)]) + norm! ma + + let a = split(execute('marks a'), "\n") + call assert_equal(2, len(a)) + let expected = ' a 1 0 ' . repeat('á', &columns - 16) + call assert_equal(expected, a[1]) + + bwipe! +endfunc + +func Test_delmarks() + new + norm mx + norm `x + delmarks x + call assert_fails('norm `x', 'E20:') + + " Deleting an already deleted mark should not fail. + delmarks x + + " getpos() should return all zeros after deleting a filemark. + norm mA + delmarks A + call assert_equal([0, 0, 0, 0], getpos("'A")) + + " Test deleting a range of marks. + norm ma + norm mb + norm mc + norm mz + delmarks b-z + norm `a + call assert_fails('norm `b', 'E20:') + call assert_fails('norm `c', 'E20:') + call assert_fails('norm `z', 'E20:') + call assert_fails('delmarks z-b', 'E475:') + + call assert_fails('delmarks', 'E471:') + call assert_fails('delmarks /', 'E475:') + + " Test delmarks! + norm mx + norm `x + delmarks! + call assert_fails('norm `x', 'E20:') + call assert_fails('delmarks! x', 'E474:') + + bwipe! +endfunc + +func Test_mark_error() + call assert_fails('mark', 'E471:') + call assert_fails('mark xx', 'E488:') + call assert_fails('mark _', 'E191:') + call assert_beeps('normal! m~') + + call setpos("'k", [0, 100, 1, 0]) + call assert_fails("normal 'k", 'E19:') +endfunc + +" Test for :lockmarks when pasting content +func Test_lockmarks_with_put() + new + call append(0, repeat(['sky is blue'], 4)) + normal gg + 1,2yank r + put r + normal G + lockmarks put r + call assert_equal(2, line("'[")) + call assert_equal(3, line("']")) + + bwipe! +endfunc + +" Test for :k command to set a mark +func Test_marks_k_cmd() + new + call setline(1, ['foo', 'bar', 'baz', 'qux']) + 1,3kr + call assert_equal([0, 3, 1, 0], getpos("'r")) + close! +endfunc + +" Test for file marks (A-Z) +func Test_file_mark() + new Xone + call setline(1, ['aaa', 'bbb']) + norm! G$mB + w! + new Xtwo + call setline(1, ['ccc', 'ddd']) + norm! GmD + w! + + enew + normal! `B + call assert_equal('Xone', bufname()) + call assert_equal([2, 3], [line('.'), col('.')]) + normal! 'D + call assert_equal('Xtwo', bufname()) + call assert_equal([2, 1], [line('.'), col('.')]) + + call delete('Xone') + call delete('Xtwo') +endfunc + +" Test for the getmarklist() function +func Test_getmarklist() + new + " global marks + delmarks A-Z 0-9 \" ^.[] + call assert_equal([], getmarklist()) + call setline(1, ['one', 'two', 'three']) + mark A + call cursor(3, 5) + normal mN + call assert_equal([{'file' : '', 'mark' : "'A", 'pos' : [bufnr(), 1, 1, 0]}, + \ {'file' : '', 'mark' : "'N", 'pos' : [bufnr(), 3, 5, 0]}], + \ getmarklist()) + " buffer local marks + delmarks! + call assert_equal([{'mark' : "''", 'pos' : [bufnr(), 1, 1, 0]}, + \ {'mark' : "'\"", 'pos' : [bufnr(), 1, 1, 0]}], getmarklist(bufnr())) + call cursor(2, 2) + normal mr + call assert_equal({'mark' : "'r", 'pos' : [bufnr(), 2, 2, 0]}, + \ bufnr()->getmarklist()[0]) + call assert_equal([], {}->getmarklist()) + close! +endfunc + +" This was using freed memory +func Test_jump_mark_autocmd() + next 00 + edit 0 + sargument + au BufEnter 0 all + sil norm + + au! BufEnter + bwipe! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_match.vim b/test/old/testdir/test_match.vim new file mode 100644 index 0000000000..1cb52b8b2a --- /dev/null +++ b/test/old/testdir/test_match.vim @@ -0,0 +1,439 @@ +" Test for :match, :2match, :3match, clearmatches(), getmatches(), matchadd(), +" matchaddpos(), matcharg(), matchdelete(), and setmatches(). + +source screendump.vim +source check.vim + +function Test_match() + highlight MyGroup1 term=bold ctermbg=red guibg=red + highlight MyGroup2 term=italic ctermbg=green guibg=green + highlight MyGroup3 term=underline ctermbg=blue guibg=blue + + " --- Check that "matcharg()" returns the correct group and pattern if a match + " --- is defined. + match MyGroup1 /TODO/ + 2match MyGroup2 /FIXME/ + 3match MyGroup3 /XXX/ + call assert_equal(['MyGroup1', 'TODO'], matcharg(1)) + call assert_equal(['MyGroup2', 'FIXME'], 2->matcharg()) + call assert_equal(['MyGroup3', 'XXX'], matcharg(3)) + + " --- Check that "matcharg()" returns an empty list if the argument is not 1, + " --- 2 or 3 (only 0 and 4 are tested). + call assert_equal([], matcharg(0)) + call assert_equal([], matcharg(4)) + + " --- Check that "matcharg()" returns ['', ''] if a match is not defined. + match + 2match + 3match + call assert_equal(['', ''], matcharg(1)) + call assert_equal(['', ''], matcharg(2)) + call assert_equal(['', ''], matcharg(3)) + + " --- Check that "matchadd()" and "getmatches()" agree on added matches and + " --- that default values apply. + let m1 = matchadd("MyGroup1", "TODO") + let m2 = matchadd("MyGroup2", "FIXME", 42) + let m3 = matchadd("MyGroup3", "XXX", 60, 17) + let ans = [{'group': 'MyGroup1', 'pattern': 'TODO', 'priority': 10, 'id': 1000}, + \ {'group': 'MyGroup2', 'pattern': 'FIXME', 'priority': 42, 'id': 1001}, + \ {'group': 'MyGroup3', 'pattern': 'XXX', 'priority': 60, 'id': 17}] + call assert_equal(ans, getmatches()) + + " --- Check that "matchdelete()" deletes the matches defined in the previous + " --- test correctly. + call matchdelete(m1) + eval m2->matchdelete() + call matchdelete(m3) + call assert_equal([], getmatches()) + + " --- Check that "matchdelete()" returns 0 if successful and otherwise -1. + let m = matchadd("MyGroup1", "TODO") + call assert_equal(0, matchdelete(m)) + call assert_fails('call matchdelete(42)', 'E803:') + + " --- Check that "clearmatches()" clears all matches defined by ":match" and + " --- "matchadd()". + let m1 = matchadd("MyGroup1", "TODO") + let m2 = "MyGroup2"->matchadd("FIXME", 42) + let m3 = matchadd("MyGroup3", "XXX", 60, 17) + match MyGroup1 /COFFEE/ + 2match MyGroup2 /HUMPPA/ + 3match MyGroup3 /VIM/ + call clearmatches() + call assert_equal([], getmatches()) + + " --- Check that "setmatches()" restores a list of matches saved by + " --- "getmatches()" without changes. (Matches with equal priority must also + " --- remain in the same order.) + let m1 = matchadd("MyGroup1", "TODO") + let m2 = matchadd("MyGroup2", "FIXME", 42) + let m3 = matchadd("MyGroup3", "XXX", 60, 17) + match MyGroup1 /COFFEE/ + 2match MyGroup2 /HUMPPA/ + 3match MyGroup3 /VIM/ + let ml = getmatches() + call clearmatches() + call setmatches(ml) + call assert_equal(ml, getmatches()) + call clearmatches() + + " --- Check that "setmatches()" will not add two matches with the same ID. The + " --- expected behaviour (for now) is to add the first match but not the + " --- second and to return 0 (even though it is a matter of debate whether + " --- this can be considered successful behaviour). + let data = [{'group': 'MyGroup1', 'pattern': 'TODO', 'priority': 10, 'id': 1}, + \ {'group': 'MyGroup2', 'pattern': 'FIXME', 'priority': 10, 'id': 1}] + call assert_fails('call setmatches(data)', 'E801:') + call assert_equal([data[0]], getmatches()) + call clearmatches() + + " --- Check that "setmatches()" returns 0 if successful and otherwise -1. + " --- (A range of valid and invalid input values are tried out to generate the + " --- return values.) + call assert_equal(0, setmatches([])) + call assert_equal(0, setmatches([{'group': 'MyGroup1', 'pattern': 'TODO', 'priority': 10, 'id': 1}])) + call clearmatches() + call assert_fails('call setmatches(0)', 'E714:') + call assert_fails('call setmatches([0])', 'E474:') + call assert_fails("call setmatches([{'wrong key': 'wrong value'}])", 'E474:') + + call setline(1, 'abcdefghijklmnopq') + call matchaddpos("MyGroup1", [[1, 5], [1, 8, 3]], 10, 3) + 1 + redraw! + let v1 = screenattr(1, 1) + let v5 = screenattr(1, 5) + let v6 = screenattr(1, 6) + let v8 = screenattr(1, 8) + let v10 = screenattr(1, 10) + let v11 = screenattr(1, 11) + call assert_notequal(v1, v5) + call assert_equal(v6, v1) + call assert_equal(v8, v5) + call assert_equal(v10, v5) + call assert_equal(v11, v1) + call assert_equal([{'group': 'MyGroup1', 'id': 3, 'priority': 10, 'pos1': [1, 5, 1], 'pos2': [1, 8, 3]}], getmatches()) + call clearmatches() + + call setline(1, 'abcdΣabcdef') + eval "MyGroup1"->matchaddpos([[1, 4, 2], [1, 9, 2]], 10, 42) + 1 + redraw! + let v1 = screenattr(1, 1) + let v4 = screenattr(1, 4) + let v5 = screenattr(1, 5) + let v6 = screenattr(1, 6) + let v7 = screenattr(1, 7) + let v8 = screenattr(1, 8) + let v9 = screenattr(1, 9) + let v10 = screenattr(1, 10) + call assert_equal([{'group': 'MyGroup1', 'id': 42, 'priority': 10, 'pos1': [1, 4, 2], 'pos2': [1, 9, 2]}], getmatches()) + call assert_notequal(v1, v4) + call assert_equal(v5, v4) + call assert_equal(v6, v1) + call assert_equal(v7, v1) + call assert_equal(v8, v4) + call assert_equal(v9, v4) + call assert_equal(v10, v1) + + " Check, that setmatches() can correctly restore the matches from matchaddpos() + call matchadd('MyGroup1', '\%2lmatchadd') + let m=getmatches() + call clearmatches() + call setmatches(m) + call assert_equal([{'group': 'MyGroup1', 'id': 42, 'priority': 10, 'pos1': [1, 4, 2], 'pos2': [1,9, 2]}, {'group': 'MyGroup1', 'pattern': '\%2lmatchadd', 'priority': 10, 'id': 1106}], getmatches()) + + highlight MyGroup1 NONE + highlight MyGroup2 NONE + highlight MyGroup3 NONE +endfunc + +func Test_match_error() + call assert_fails('match Error', 'E475:') + call assert_fails('match Error /', 'E475:') + call assert_fails('4match Error /x/', 'E476:') + call assert_fails('match Error /x/ x', 'E488:') +endfunc + +func Test_matchadd_error() + call clearmatches() + " Nvim: not an error anymore: + " call assert_fails("call matchadd('GroupDoesNotExist', 'X')", 'E28:') + call matchadd('GroupDoesNotExist', 'X') + call assert_equal([{'group': 'GroupDoesNotExist', 'pattern': 'X', 'priority': 10, 'id': 1206}], getmatches()) + call assert_fails("call matchadd('Search', '\\(')", 'E54:') + call assert_fails("call matchadd('Search', 'XXX', 1, 123, 1)", 'E715:') + call assert_fails("call matchadd('Error', 'XXX', 1, 3)", 'E798:') + call assert_fails("call matchadd('Error', 'XXX', 1, 0)", 'E799:') + call assert_fails("call matchadd('Error', 'XXX', [], 0)", 'E745:') +endfunc + +func Test_matchaddpos() + syntax on + set hlsearch + + call setline(1, ['12345', 'NP']) + call matchaddpos('Error', [[1,2], [1,6], [2,2]]) + redraw! + call assert_notequal(screenattr(2,2), 0) + call assert_equal(screenattr(2,2), screenattr(1,2)) + call assert_notequal(screenattr(2,2), screenattr(1,6)) + 1 + call matchadd('Search', 'N\|\n') + redraw! + call assert_notequal(screenattr(2,1), 0) + call assert_equal(screenattr(2,1), screenattr(1,6)) + exec "norm! i0\<Esc>" + redraw! + call assert_equal(screenattr(2,2), screenattr(1,6)) + + " Check overlapping pos + call clearmatches() + call setline(1, ['1234567890', 'NH']) + call matchaddpos('Error', [[1,1,5], [1,3,5], [2,2]]) + redraw! + call assert_notequal(screenattr(2,2), 0) + call assert_equal(screenattr(2,2), screenattr(1,5)) + call assert_equal(screenattr(2,2), screenattr(1,7)) + call assert_notequal(screenattr(2,2), screenattr(1,8)) + + call clearmatches() + call matchaddpos('Error', [[1], [2,2]]) + redraw! + call assert_equal(screenattr(2,2), screenattr(1,1)) + call assert_equal(screenattr(2,2), screenattr(1,10)) + call assert_notequal(screenattr(2,2), screenattr(1,11)) + + " Check overlapping pos + call clearmatches() + call setline(1, ['1234567890', 'NH']) + call matchaddpos('Error', [[1,1,5], [1,3,5], [2,2]]) + redraw! + call assert_notequal(screenattr(2,2), 0) + call assert_equal(screenattr(2,2), screenattr(1,5)) + call assert_equal(screenattr(2,2), screenattr(1,7)) + call assert_notequal(screenattr(2,2), screenattr(1,8)) + + nohl + call clearmatches() + syntax off + set hlsearch& +endfunc + +" Add 12 match positions (previously the limit was 8 positions). +func Test_matchaddpos_dump() + CheckScreendump + + let lines =<< trim END + call setline(1, ['1234567890123']->repeat(14)) + call matchaddpos('Search', range(1, 12)->map({i, v -> [v, v]})) + END + call writefile(lines, 'Xmatchaddpos', 'D') + let buf = RunVimInTerminal('-S Xmatchaddpos', #{rows: 14}) + call VerifyScreenDump(buf, 'Test_matchaddpos_1', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_matchaddpos_otherwin() + syntax on + new + call setline(1, ['12345', 'NP']) + let winid = win_getid() + + wincmd w + call matchadd('Search', '4', 10, -1, {'window': winid}) + call matchaddpos('Error', [[1,2], [2,2]], 10, -1, {'window': winid}) + redraw! + call assert_notequal(screenattr(1,2), 0) + call assert_notequal(screenattr(1,4), 0) + call assert_notequal(screenattr(2,2), 0) + call assert_equal(screenattr(1,2), screenattr(2,2)) + call assert_notequal(screenattr(1,2), screenattr(1,4)) + + let savematches = getmatches(winid) + let expect = [ + \ {'group': 'Search', 'pattern': '4', 'priority': 10, 'id': 1000}, + \ {'group': 'Error', 'id': 1001, 'priority': 10, 'pos1': [1, 2, 1], 'pos2': [2, 2, 1]}, + \] + call assert_equal(expect, savematches) + + eval winid->clearmatches() + call assert_equal([], getmatches(winid)) + + call setmatches(savematches, winid) + call assert_equal(expect, savematches) + + wincmd w + bwipe! + call clearmatches() + syntax off +endfunc + +func Test_matchaddpos_using_negative_priority() + set hlsearch + + call clearmatches() + + call setline(1, 'x') + let @/='x' + redraw! + let search_attr = screenattr(1,1) + + let @/='' + call matchaddpos('Error', [1], 10) + redraw! + let error_attr = screenattr(1,1) + + call setline(2, '-1 match priority') + call matchaddpos('Error', [2], -1) + redraw! + let negative_match_priority_attr = screenattr(2,1) + + call assert_notequal(negative_match_priority_attr, search_attr, "Match with negative priority is incorrectly highlighted with Search highlight.") + call assert_equal(negative_match_priority_attr, error_attr) + + nohl + set hlsearch& +endfunc + +func Test_matchaddpos_error() + call assert_fails("call matchaddpos('Error', 1)", 'E686:') + call assert_fails("call matchaddpos('Error', [1], 1, 1)", 'E798:') + call assert_fails("call matchaddpos('Error', [1], 1, 2)", 'E798:') + call assert_fails("call matchaddpos('Error', [1], 1, 0)", 'E799:') + call assert_fails("call matchaddpos('Error', [1], 1, 123, 1)", 'E715:') + call assert_fails("call matchaddpos('Error', [1], 1, 5, {'window':12345})", 'E957:') + " Why doesn't the following error have an error code E...? + " call assert_fails("call matchaddpos('Error', [{}])", 'E290:') + call assert_fails("call matchaddpos('Error', [{}])", 'E5031:') + call assert_equal(-1, matchaddpos('Error', v:_null_list)) + call assert_fails("call matchaddpos('Error', [1], [], 1)", 'E745:') +endfunc + +func OtherWindowCommon() + let lines =<< trim END + call setline(1, 'Hello Vim world') + let mid = matchadd('Error', 'world', 1) + let winid = win_getid() + new + END + call writefile(lines, 'XscriptMatchCommon') + let buf = RunVimInTerminal('-S XscriptMatchCommon', #{rows: 12}) + call TermWait(buf) + return buf +endfunc + +func Test_matchdelete_other_window() + CheckScreendump + + let buf = OtherWindowCommon() + call term_sendkeys(buf, ":call matchdelete(mid, winid)\<CR>") + call VerifyScreenDump(buf, 'Test_matchdelete_1', {}) + + call StopVimInTerminal(buf) + call delete('XscriptMatchCommon') +endfunc + +func Test_matchdelete_error() + call assert_fails("call matchdelete(0)", 'E802:') + call assert_fails("call matchdelete(1, -1)", 'E957:') +endfunc + +func Test_matchclear_other_window() + CheckRunVimInTerminal + let buf = OtherWindowCommon() + call term_sendkeys(buf, ":call clearmatches(winid)\<CR>") + call VerifyScreenDump(buf, 'Test_matchclear_1', {}) + + call StopVimInTerminal(buf) + call delete('XscriptMatchCommon') +endfunc + +func Test_matchadd_other_window() + CheckRunVimInTerminal + let buf = OtherWindowCommon() + call term_sendkeys(buf, ":call matchadd('Search', 'Hello', 1, -1, #{window: winid})\<CR>") + call term_sendkeys(buf, ":\<CR>") + call VerifyScreenDump(buf, 'Test_matchadd_1', {}) + + call StopVimInTerminal(buf) + call delete('XscriptMatchCommon') +endfunc + +func Test_match_in_linebreak() + CheckRunVimInTerminal + + let lines =<< trim END + set breakindent linebreak breakat+=] + call printf('%s]%s', repeat('x', 50), repeat('x', 70))->setline(1) + call matchaddpos('ErrorMsg', [[1, 51]]) + END + call writefile(lines, 'XscriptMatchLinebreak') + let buf = RunVimInTerminal('-S XscriptMatchLinebreak', #{rows: 10}) + call VerifyScreenDump(buf, 'Test_match_linebreak', {}) + + call StopVimInTerminal(buf) + call delete('XscriptMatchLinebreak') +endfunc + +func Test_match_with_incsearch() + CheckRunVimInTerminal + + let lines =<< trim END + set incsearch + call setline(1, range(20)) + call matchaddpos('ErrorMsg', [3]) + END + call writefile(lines, 'XmatchWithIncsearch') + let buf = RunVimInTerminal('-S XmatchWithIncsearch', #{rows: 6}) + call VerifyScreenDump(buf, 'Test_match_with_incsearch_1', {}) + + call term_sendkeys(buf, ":s/0") + call VerifyScreenDump(buf, 'Test_match_with_incsearch_2', {}) + + call term_sendkeys(buf, "\<CR>") + call StopVimInTerminal(buf) + call delete('XmatchWithIncsearch') +endfunc + +" Test for deleting matches outside of the screen redraw top/bottom lines +" This should cause a redraw of those lines. +func Test_matchdelete_redraw() + new + call setline(1, range(1, 500)) + call cursor(250, 1) + let m1 = matchaddpos('Search', [[250]]) + let m2 = matchaddpos('Search', [[10], [450]]) + redraw! + let m3 = matchaddpos('Search', [[240], [260]]) + call matchdelete(m2) + let m = getmatches() + call assert_equal(2, len(m)) + call assert_equal([250], m[0].pos1) + redraw! + call matchdelete(m1) + call assert_equal(1, len(getmatches())) + bw! +endfunc + +func Test_match_tab_with_linebreak() + CheckRunVimInTerminal + + let lines =<< trim END + set linebreak + call setline(1, "\tix") + call matchadd('ErrorMsg', '\t') + END + call writefile(lines, 'XscriptMatchTabLinebreak') + let buf = RunVimInTerminal('-S XscriptMatchTabLinebreak', #{rows: 10}) + call VerifyScreenDump(buf, 'Test_match_tab_linebreak', {}) + + call StopVimInTerminal(buf) + call delete('XscriptMatchTabLinebreak') +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_matchadd_conceal.vim b/test/old/testdir/test_matchadd_conceal.vim new file mode 100644 index 0000000000..6c9b8786f5 --- /dev/null +++ b/test/old/testdir/test_matchadd_conceal.vim @@ -0,0 +1,422 @@ +" Test for matchadd() and conceal feature + +source check.vim +CheckFeature conceal + +source shared.vim +source term_util.vim +source view_util.vim + +func Test_simple_matchadd() + new + + 1put='# This is a Test' + " 1234567890123456 + let expect = '# This is a Test' + + call cursor(1, 1) + call matchadd('Conceal', '\%2l ') + redraw! + let lnum = 2 + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + quit! +endfunc + +func Test_simple_matchadd_and_conceal() + new + setlocal concealcursor=n conceallevel=1 + + 1put='# This is a Test' + " 1234567890123456 + let expect = '#XThisXisXaXTest' + + call cursor(1, 1) + call matchadd('Conceal', '\%2l ', 10, -1, {'conceal': 'X'}) + redraw! + let lnum = 2 + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + quit! +endfunc + +func Test_matchadd_and_conceallevel_3() + new + + setlocal conceallevel=3 + " set filetype and :syntax on to change screenattr() + setlocal filetype=conf + syntax on + + 1put='# This is a Test $' + " 1234567890123 + let expect = '#ThisisaTest$' + + call cursor(1, 1) + call matchadd('Conceal', '\%2l ', 10, -1, {'conceal': 'X'}) + redraw! + let lnum = 2 + call assert_equal(expect, Screenline(lnum)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 13)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 14)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 16)) + + " more matchadd() + " 12345678901234 + let expect = '#Thisisa Test$' + + call matchadd('ErrorMsg', '\%2l Test', 20, -1, {'conceal': 'X'}) + redraw! + call assert_equal(expect, Screenline(lnum)) + call assert_equal(screenattr(lnum, 1) , screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 1) , screenattr(lnum, 7)) + call assert_notequal(screenattr(lnum, 1) , screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 10), screenattr(lnum, 13)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 14)) + call assert_notequal(screenattr(lnum, 1) , screenattr(lnum, 16)) + call assert_notequal(screenattr(lnum, 10), screenattr(lnum, 16)) + + syntax off + quit! +endfunc + +func Test_default_conceal_char() + new + setlocal concealcursor=n conceallevel=1 + + 1put='# This is a Test' + " 1234567890123456 + let expect = '# This is a Test' + + call cursor(1, 1) + call matchadd('Conceal', '\%2l ', 10, -1, {}) + redraw! + let lnum = 2 + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + " 1234567890123456 + let expect = '#+This+is+a+Test' + let listchars_save = &listchars + set listchars=conceal:+ + redraw! + + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + let &listchars = listchars_save + quit! +endfunc + +func Test_syn_and_match_conceal() + new + setlocal concealcursor=n conceallevel=1 + + 1put='# This is a Test ' + + let lnum = 2 + call cursor(1, 1) + + " 123456789012345678 + let expect = '#ZThisZisZaZTestZZ' + call matchadd('Conceal', '\%2l ', 10, -1, {'conceal': 'Z'}) + syntax match MyConceal /\%2l / conceal containedin=ALL + hi MyConceal ctermbg=4 ctermfg=2 + redraw! + + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + syntax clear MyConceal + syntax match MyConceal /\%2l / conceal containedin=ALL cchar=* + redraw! + + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + " 123456789012345678 + let expect = '#*This*is*a*Test**' + call clearmatches() + redraw! + + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + " 123456789012345678 + let expect = '#*ThisXis*a*Test**' + call matchadd('Conceal', '\%2l\%7c ', 10, -1, {'conceal': 'X'}) + redraw! + + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + " 123456789012345678 + let expect = '#*ThisXis*a*Test**' + call matchadd('ErrorMsg', '\%2l Test', 20, -1) + redraw! + + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_notequal(screenattr(lnum, 12), screenattr(lnum, 13)) + call assert_equal(screenattr(lnum, 13), screenattr(lnum, 16)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 17)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 18)) + call assert_notequal(screenattr(lnum, 18), screenattr(lnum, 19)) + + " 123456789012345678 + let expect = '# ThisXis a Test' + syntax clear MyConceal + syntax match MyConceal /\%2l / conceal containedin=ALL + redraw! + + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 12)) + call assert_notequal(screenattr(lnum, 12), screenattr(lnum, 13)) + call assert_equal(screenattr(lnum, 13), screenattr(lnum, 16)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 17)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 18)) + call assert_notequal(screenattr(lnum, 18), screenattr(lnum, 19)) + + syntax off + quit! +endfunc + +func Test_clearmatches() + new + setlocal concealcursor=n conceallevel=1 + + 1put='# This is a Test' + " 1234567890123456 + let expect = '# This is a Test' + + call cursor(1, 1) + call matchadd('Conceal', '\%2l ', 10, -1, {'conceal': 'Z'}) + let a = getmatches() + call clearmatches() + redraw! + + let lnum = 2 + call assert_equal(expect, Screenline(lnum)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + " reset match using setmatches() + " 1234567890123456 + let expect = '#ZThisZisZaZTest' + call setmatches(a) + redraw! + + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + call assert_equal({'group': 'Conceal', 'pattern': '\%2l ', 'priority': 10, 'id': a[0].id, 'conceal': 'Z'}, a[0]) + + quit! +endfunc + +func Test_using_matchaddpos() + new + setlocal concealcursor=n conceallevel=1 + " set filetype and :syntax on to change screenattr() + setlocal filetype=conf + syntax on + + 1put='# This is a Test' + " 1234567890123456 + let expect = '#Pis a Test' + + call cursor(1, 1) + call matchaddpos('Conceal', [[2,2,6]], 10, -1, {'conceal': 'P'}) + let a = getmatches() + redraw! + + let lnum = 2 + call assert_equal(expect, Screenline(lnum)) + call assert_notequal(screenattr(lnum, 1) , screenattr(lnum, 2)) + call assert_notequal(screenattr(lnum, 2) , screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 1) , screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 1) , screenattr(lnum, 10)) + call assert_notequal(screenattr(lnum, 1) , screenattr(lnum, 12)) + call assert_notequal(screenattr(lnum, 1) , screenattr(lnum, 16)) + call assert_equal(screenattr(lnum, 12), screenattr(lnum, 16)) + call assert_equal({'group': 'Conceal', 'id': a[0].id, 'priority': 10, 'pos1': [2, 2, 6], 'conceal': 'P'}, a[0]) + + syntax off + quit! +endfunc + +func Test_matchadd_repeat_conceal_with_syntax_off() + new + + " To test targets in the same line string is replaced with conceal char + " correctly, repeat 'TARGET' + 1put ='TARGET_TARGETTARGET' + call cursor(1, 1) + redraw + call assert_equal('TARGET_TARGETTARGET', Screenline(2)) + + setlocal conceallevel=2 + call matchadd('Conceal', 'TARGET', 10, -1, {'conceal': 't'}) + + redraw + call assert_equal('t_tt', Screenline(2)) + + quit! +endfunc + +func Test_matchadd_and_syn_conceal() + new + let cnt='Inductive bool : Type := | true : bool | false : bool.' + let expect = 'Inductive - : Type := | true : - | false : -.' + 0put =cnt + " set filetype and :syntax on to change screenattr() + set cole=1 cocu=nv + hi link CheckedByCoq WarningMsg + syntax on + syntax keyword coqKwd bool conceal cchar=- + redraw! + call assert_equal(expect, Screenline(1)) + call assert_notequal(screenattr(1, 10) , screenattr(1, 11)) + call assert_notequal(screenattr(1, 11) , screenattr(1, 12)) + call assert_equal(screenattr(1, 11) , screenattr(1, 32)) + call matchadd('CheckedByCoq', '\%<2l\%>9c\%<16c') + redraw! + call assert_equal(expect, Screenline(1)) + call assert_notequal(screenattr(1, 10) , screenattr(1, 11)) + call assert_notequal(screenattr(1, 11) , screenattr(1, 12)) + call assert_equal(screenattr(1, 11) , screenattr(1, 32)) +endfunc + +func Test_interaction_matchadd_syntax() + new + " Test for issue #7268 fix. + " When redrawing the second column, win_line() was comparing the sequence + " number of the syntax-concealed region with a bogus zero value that was + " returned for the matchadd-concealed region. Before 8.0.0672 the sequence + " number was never reset, thus masking the problem. + call setline(1, 'aaa|bbb|ccc') + call matchadd('Conceal', '^..', 10, -1, #{conceal: 'X'}) + syn match foobar '^.' + setl concealcursor=n conceallevel=1 + redraw! + + call assert_equal('Xa|bbb|ccc', Screenline(1)) + call assert_notequal(screenattr(1, 1), screenattr(1, 2)) + + bwipe! +endfunc + +func Test_cursor_column_in_concealed_line_after_window_scroll() + CheckRunVimInTerminal + + " Test for issue #5012 fix. + " For a concealed line with cursor, there should be no window's cursor + " position invalidation during win_update() after scrolling attempt that is + " not successful and no real topline change happens. The invalidation would + " cause a window's cursor position recalc outside of win_line() where it's + " not possible to take conceal into account. + let lines =<< trim END + 3split + let m = matchadd('Conceal', '=') + setl conceallevel=2 concealcursor=nc + normal gg + "==expr== + END + call writefile(lines, 'Xcolesearch') + let buf = RunVimInTerminal('Xcolesearch', {}) + call TermWait(buf, 50) + + " Jump to something that is beyond the bottom of the window, + " so there's a scroll down. + call term_sendkeys(buf, ":so %\<CR>") + call TermWait(buf, 50) + call term_sendkeys(buf, "/expr\<CR>") + call TermWait(buf, 50) + + " Are the concealed parts of the current line really hidden? + let cursor_row = term_scrape(buf, '.')->map({_, e -> e.chars})->join('') + call assert_equal('"expr', cursor_row) + + " BugFix check: Is the window's cursor column properly updated for hidden + " parts of the current line? + call assert_equal(2, term_getcursor(buf)[1]) + + call StopVimInTerminal(buf) + call delete('Xcolesearch') +endfunc + +func Test_cursor_column_in_concealed_line_after_leftcol_change() + CheckRunVimInTerminal + + " Test for issue #5214 fix. + let lines =<< trim END + 0put = 'ab' .. repeat('-', &columns) .. 'c' + call matchadd('Conceal', '-') + set nowrap ss=0 cole=3 cocu=n + END + call writefile(lines, 'Xcurs-columns') + let buf = RunVimInTerminal('-S Xcurs-columns', {}) + + " Go to the end of the line (3 columns beyond the end of the screen). + " Horizontal scroll would center the cursor in the screen line, but conceal + " makes it go to screen column 1. + call term_sendkeys(buf, "$") + call TermWait(buf) + + " Are the concealed parts of the current line really hidden? + call WaitForAssert({-> assert_equal('c', term_getline(buf, '.'))}) + + " BugFix check: Is the window's cursor column properly updated for conceal? + call assert_equal(1, term_getcursor(buf)[1]) + + call StopVimInTerminal(buf) + call delete('Xcurs-columns') +endfunc diff --git a/test/old/testdir/test_matchadd_conceal_utf8.vim b/test/old/testdir/test_matchadd_conceal_utf8.vim new file mode 100644 index 0000000000..f33c7f694c --- /dev/null +++ b/test/old/testdir/test_matchadd_conceal_utf8.vim @@ -0,0 +1,39 @@ +" Test for matchadd() and conceal feature using utf-8. + +source check.vim +CheckFeature conceal + +func s:screenline(lnum) abort + let line = [] + for c in range(1, winwidth(0)) + call add(line, nr2char(a:lnum->screenchar(c))) + endfor + return s:trim(join(line, '')) +endfunc + +func s:trim(str) abort + return matchstr(a:str,'^\s*\zs.\{-}\ze\s*$') +endfunc + +func Test_match_using_multibyte_conceal_char() + new + setlocal concealcursor=n conceallevel=1 + + 1put='# This is a Test' + " 1234567890123456 + let expect = '#ˑThisˑisˑaˑTest' + + call cursor(1, 1) + call matchadd('Conceal', '\%2l ', 20, -1, {'conceal': "\u02d1"}) + redraw! + + let lnum = 2 + call assert_equal(expect, s:screenline(lnum)) + call assert_notequal(screenattr(lnum, 1), screenattr(lnum, 2)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 7)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 10)) + call assert_equal(screenattr(lnum, 2), screenattr(lnum, 12)) + call assert_equal(screenattr(lnum, 1), screenattr(lnum, 16)) + + quit! +endfunc diff --git a/test/old/testdir/test_matchfuzzy.vim b/test/old/testdir/test_matchfuzzy.vim new file mode 100644 index 0000000000..90f3366b23 --- /dev/null +++ b/test/old/testdir/test_matchfuzzy.vim @@ -0,0 +1,290 @@ +" Tests for fuzzy matching + +source shared.vim +source check.vim +source term_util.vim + +" Test for matchfuzzy() +func Test_matchfuzzy() + call assert_fails('call matchfuzzy(10, "abc")', 'E686:') + call assert_fails('call matchfuzzy(["abc"], [])', 'E730:') + call assert_fails("let x = matchfuzzy(v:_null_list, 'foo')", 'E686:') + call assert_fails('call matchfuzzy(["abc"], v:_null_string)', 'E475:') + call assert_equal([], matchfuzzy([], 'abc')) + call assert_equal([], matchfuzzy(['abc'], '')) + call assert_equal(['abc'], matchfuzzy(['abc', 10], 'ac')) + call assert_equal([], matchfuzzy([10, 20], 'ac')) + call assert_equal(['abc'], matchfuzzy(['abc'], 'abc')) + call assert_equal(['crayon', 'camera'], matchfuzzy(['camera', 'crayon'], 'cra')) + call assert_equal(['aabbaa', 'aaabbbaaa', 'aaaabbbbaaaa', 'aba'], matchfuzzy(['aba', 'aabbaa', 'aaabbbaaa', 'aaaabbbbaaaa'], 'aa')) + call assert_equal(['one'], matchfuzzy(['one', 'two'], 'one')) + call assert_equal(['oneTwo', 'onetwo'], matchfuzzy(['onetwo', 'oneTwo'], 'oneTwo')) + call assert_equal(['onetwo', 'one_two'], matchfuzzy(['onetwo', 'one_two'], 'oneTwo')) + call assert_equal(['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'], matchfuzzy(['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'], 'aa')) + call assert_equal(256, matchfuzzy([repeat('a', 256)], repeat('a', 256))[0]->len()) + call assert_equal([], matchfuzzy([repeat('a', 300)], repeat('a', 257))) + " matches with same score should not be reordered + let l = ['abc1', 'abc2', 'abc3'] + call assert_equal(l, l->matchfuzzy('abc')) + + " Tests for match preferences + " preference for camel case match + call assert_equal(['oneTwo', 'onetwo'], ['onetwo', 'oneTwo']->matchfuzzy('onetwo')) + " preference for match after a separator (_ or space) + call assert_equal(['onetwo', 'one_two', 'one two'], ['onetwo', 'one_two', 'one two']->matchfuzzy('onetwo')) + " preference for leading letter match + call assert_equal(['onetwo', 'xonetwo'], ['xonetwo', 'onetwo']->matchfuzzy('onetwo')) + " preference for sequential match + call assert_equal(['onetwo', 'oanbectdweo'], ['oanbectdweo', 'onetwo']->matchfuzzy('onetwo')) + " non-matching leading letter(s) penalty + call assert_equal(['xonetwo', 'xxonetwo'], ['xxonetwo', 'xonetwo']->matchfuzzy('onetwo')) + " total non-matching letter(s) penalty + call assert_equal(['one', 'onex', 'onexx'], ['onexx', 'one', 'onex']->matchfuzzy('one')) + " prefer complete matches over separator matches + call assert_equal(['.vim/vimrc', '.vim/vimrc_colors', '.vim/v_i_m_r_c'], ['.vim/vimrc', '.vim/vimrc_colors', '.vim/v_i_m_r_c']->matchfuzzy('vimrc')) + " gap penalty + call assert_equal(['xxayybxxxx', 'xxayyybxxx', 'xxayyyybxx'], ['xxayyyybxx', 'xxayyybxxx', 'xxayybxxxx']->matchfuzzy('ab')) + " path separator vs word separator + call assert_equal(['color/setup.vim', 'color\\setup.vim', 'color setup.vim', 'color_setup.vim', 'colorsetup.vim'], matchfuzzy(['colorsetup.vim', 'color setup.vim', 'color/setup.vim', 'color_setup.vim', 'color\\setup.vim'], 'setup.vim')) + + " match multiple words (separated by space) + call assert_equal(['foo bar baz'], ['foo bar baz', 'foo', 'foo bar', 'baz bar']->matchfuzzy('baz foo')) + call assert_equal([], ['foo bar baz', 'foo', 'foo bar', 'baz bar']->matchfuzzy('one two')) + call assert_equal([], ['foo bar']->matchfuzzy(" \t ")) + + " test for matching a sequence of words + call assert_equal(['bar foo'], ['foo bar', 'bar foo', 'foobar', 'barfoo']->matchfuzzy('bar foo', {'matchseq' : 1})) + call assert_equal([#{text: 'two one'}], [#{text: 'one two'}, #{text: 'two one'}]->matchfuzzy('two one', #{key: 'text', matchseq: v:true})) + + %bw! + eval ['somebuf', 'anotherone', 'needle', 'yetanotherone']->map({_, v -> bufadd(v) + bufload(v)}) + let l = getbufinfo()->map({_, v -> fnamemodify(v.name, ':t')})->matchfuzzy('ndl') + call assert_equal(1, len(l)) + call assert_match('needle', l[0]) + + " Test for fuzzy matching dicts + let l = [{'id' : 5, 'val' : 'crayon'}, {'id' : 6, 'val' : 'camera'}] + call assert_equal([{'id' : 6, 'val' : 'camera'}], matchfuzzy(l, 'cam', {'text_cb' : {v -> v.val}})) + call assert_equal([{'id' : 6, 'val' : 'camera'}], matchfuzzy(l, 'cam', {'key' : 'val'})) + call assert_equal([], matchfuzzy(l, 'day', {'text_cb' : {v -> v.val}})) + call assert_equal([], matchfuzzy(l, 'day', {'key' : 'val'})) + call assert_fails("let x = matchfuzzy(l, 'cam', 'random')", 'E1206:') + call assert_equal([], matchfuzzy(l, 'day', {'text_cb' : {v -> []}})) + call assert_equal([], matchfuzzy(l, 'day', {'text_cb' : {v -> 1}})) + call assert_fails("let x = matchfuzzy(l, 'day', {'text_cb' : {a, b -> 1}})", 'E119:') + call assert_equal([], matchfuzzy(l, 'cam')) + " Nvim's callback implementation is different, so E6000 is expected instead, + " call assert_fails("let x = matchfuzzy(l, 'cam', {'text_cb' : []})", 'E921:') + call assert_fails("let x = matchfuzzy(l, 'cam', {'text_cb' : []})", 'E6000:') + call assert_fails("let x = matchfuzzy(l, 'foo', {'key' : []})", 'E730:') + call assert_fails("let x = matchfuzzy(l, 'cam', v:_null_dict)", 'E1297:') + call assert_fails("let x = matchfuzzy(l, 'foo', {'key' : v:_null_string})", 'E475:') + " Nvim doesn't have null functions + " call assert_fails("let x = matchfuzzy(l, 'foo', {'text_cb' : test_null_function()})", 'E475:') + " matches with same score should not be reordered + let l = [#{text: 'abc', id: 1}, #{text: 'abc', id: 2}, #{text: 'abc', id: 3}] + call assert_equal(l, l->matchfuzzy('abc', #{key: 'text'})) + + let l = [{'id' : 5, 'name' : 'foo'}, {'id' : 6, 'name' : []}, {'id' : 7}] + call assert_fails("let x = matchfuzzy(l, 'foo', {'key' : 'name'})", 'E730:') + + " Test in latin1 encoding + let save_enc = &encoding + " Nvim supports utf-8 encoding only + " set encoding=latin1 + call assert_equal(['abc'], matchfuzzy(['abc'], 'abc')) + let &encoding = save_enc +endfunc + +" Test for the matchfuzzypos() function +func Test_matchfuzzypos() + call assert_equal([['curl', 'world'], [[2,3], [2,3]], [128, 127]], matchfuzzypos(['world', 'curl'], 'rl')) + call assert_equal([['curl', 'world'], [[2,3], [2,3]], [128, 127]], matchfuzzypos(['world', 'one', 'curl'], 'rl')) + call assert_equal([['hello', 'hello world hello world'], + \ [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]], [275, 257]], + \ matchfuzzypos(['hello world hello world', 'hello', 'world'], 'hello')) + call assert_equal([['aaaaaaa'], [[0, 1, 2]], [191]], matchfuzzypos(['aaaaaaa'], 'aaa')) + call assert_equal([['a b'], [[0, 3]], [219]], matchfuzzypos(['a b'], 'a b')) + call assert_equal([['a b'], [[0, 3]], [219]], matchfuzzypos(['a b'], 'a b')) + call assert_equal([['a b'], [[0]], [112]], matchfuzzypos(['a b'], ' a ')) + call assert_equal([[], [], []], matchfuzzypos(['a b'], ' ')) + call assert_equal([[], [], []], matchfuzzypos(['world', 'curl'], 'ab')) + let x = matchfuzzypos([repeat('a', 256)], repeat('a', 256)) + call assert_equal(range(256), x[1][0]) + call assert_equal([[], [], []], matchfuzzypos([repeat('a', 300)], repeat('a', 257))) + call assert_equal([[], [], []], matchfuzzypos([], 'abc')) + + " match in a long string + call assert_equal([[repeat('x', 300) .. 'abc'], [[300, 301, 302]], [-135]], + \ matchfuzzypos([repeat('x', 300) .. 'abc'], 'abc')) + + " preference for camel case match + call assert_equal([['xabcxxaBc'], [[6, 7, 8]], [189]], matchfuzzypos(['xabcxxaBc'], 'abc')) + " preference for match after a separator (_ or space) + call assert_equal([['xabx_ab'], [[5, 6]], [145]], matchfuzzypos(['xabx_ab'], 'ab')) + " preference for leading letter match + call assert_equal([['abcxabc'], [[0, 1]], [150]], matchfuzzypos(['abcxabc'], 'ab')) + " preference for sequential match + call assert_equal([['aobncedone'], [[7, 8, 9]], [158]], matchfuzzypos(['aobncedone'], 'one')) + " best recursive match + call assert_equal([['xoone'], [[2, 3, 4]], [168]], matchfuzzypos(['xoone'], 'one')) + + " match multiple words (separated by space) + call assert_equal([['foo bar baz'], [[8, 9, 10, 0, 1, 2]], [369]], ['foo bar baz', 'foo', 'foo bar', 'baz bar']->matchfuzzypos('baz foo')) + call assert_equal([[], [], []], ['foo bar baz', 'foo', 'foo bar', 'baz bar']->matchfuzzypos('baz foo', {'matchseq': 1})) + call assert_equal([['foo bar baz'], [[0, 1, 2, 8, 9, 10]], [369]], ['foo bar baz', 'foo', 'foo bar', 'baz bar']->matchfuzzypos('foo baz')) + call assert_equal([['foo bar baz'], [[0, 1, 2, 3, 4, 5, 10]], [326]], ['foo bar baz', 'foo', 'foo bar', 'baz bar']->matchfuzzypos('foo baz', {'matchseq': 1})) + call assert_equal([[], [], []], ['foo bar baz', 'foo', 'foo bar', 'baz bar']->matchfuzzypos('one two')) + call assert_equal([[], [], []], ['foo bar']->matchfuzzypos(" \t ")) + call assert_equal([['grace'], [[1, 2, 3, 4, 2, 3, 4, 0, 1, 2, 3, 4]], [657]], ['grace']->matchfuzzypos('race ace grace')) + + let l = [{'id' : 5, 'val' : 'crayon'}, {'id' : 6, 'val' : 'camera'}] + call assert_equal([[{'id' : 6, 'val' : 'camera'}], [[0, 1, 2]], [192]], + \ matchfuzzypos(l, 'cam', {'text_cb' : {v -> v.val}})) + call assert_equal([[{'id' : 6, 'val' : 'camera'}], [[0, 1, 2]], [192]], + \ matchfuzzypos(l, 'cam', {'key' : 'val'})) + call assert_equal([[], [], []], matchfuzzypos(l, 'day', {'text_cb' : {v -> v.val}})) + call assert_equal([[], [], []], matchfuzzypos(l, 'day', {'key' : 'val'})) + call assert_fails("let x = matchfuzzypos(l, 'cam', 'random')", 'E1206:') + call assert_equal([[], [], []], matchfuzzypos(l, 'day', {'text_cb' : {v -> []}})) + call assert_equal([[], [], []], matchfuzzypos(l, 'day', {'text_cb' : {v -> 1}})) + call assert_fails("let x = matchfuzzypos(l, 'day', {'text_cb' : {a, b -> 1}})", 'E119:') + call assert_equal([[], [], []], matchfuzzypos(l, 'cam')) + " Nvim's callback implementation is different, so E6000 is expected instead, + " call assert_fails("let x = matchfuzzypos(l, 'cam', {'text_cb' : []})", 'E921:') + call assert_fails("let x = matchfuzzypos(l, 'cam', {'text_cb' : []})", 'E6000:') + call assert_fails("let x = matchfuzzypos(l, 'foo', {'key' : []})", 'E730:') + call assert_fails("let x = matchfuzzypos(l, 'cam', v:_null_dict)", 'E1297:') + call assert_fails("let x = matchfuzzypos(l, 'foo', {'key' : v:_null_string})", 'E475:') + " Nvim doesn't have null functions + " call assert_fails("let x = matchfuzzypos(l, 'foo', {'text_cb' : test_null_function()})", 'E475:') + + let l = [{'id' : 5, 'name' : 'foo'}, {'id' : 6, 'name' : []}, {'id' : 7}] + call assert_fails("let x = matchfuzzypos(l, 'foo', {'key' : 'name'})", 'E730:') +endfunc + +" Test for matchfuzzy() with multibyte characters +func Test_matchfuzzy_mbyte() + CheckFeature multi_lang + call assert_equal(['ンヹㄇヺヴ'], matchfuzzy(['ンヹㄇヺヴ'], 'ヹヺ')) + " reverse the order of characters + call assert_equal([], matchfuzzy(['ンヹㄇヺヴ'], 'ヺヹ')) + call assert_equal(['αβΩxxx', 'xαxβxΩx'], + \ matchfuzzy(['αβΩxxx', 'xαxβxΩx'], 'αβΩ')) + call assert_equal(['ππbbππ', 'πππbbbπππ', 'ππππbbbbππππ', 'πbπ'], + \ matchfuzzy(['πbπ', 'ππbbππ', 'πππbbbπππ', 'ππππbbbbππππ'], 'ππ')) + + " match multiple words (separated by space) + call assert_equal(['세 마리의 작은 돼지'], ['세 마리의 작은 돼지', '마리의', '마리의 작은', '작은 돼지']->matchfuzzy('돼지 마리의')) + call assert_equal([], ['세 마리의 작은 돼지', '마리의', '마리의 작은', '작은 돼지']->matchfuzzy('파란 하늘')) + + " preference for camel case match + call assert_equal(['oneĄwo', 'oneąwo'], + \ ['oneąwo', 'oneĄwo']->matchfuzzy('oneąwo')) + " preference for complete match then match after separator (_ or space) + call assert_equal(['ⅠⅡabㄟㄠ'] + sort(['ⅠⅡa_bㄟㄠ', 'ⅠⅡa bㄟㄠ']), + \ ['ⅠⅡabㄟㄠ', 'ⅠⅡa bㄟㄠ', 'ⅠⅡa_bㄟㄠ']->matchfuzzy('ⅠⅡabㄟㄠ')) + " preference for match after a separator (_ or space) + call assert_equal(['ㄓㄔabㄟㄠ', 'ㄓㄔa_bㄟㄠ', 'ㄓㄔa bㄟㄠ'], + \ ['ㄓㄔa_bㄟㄠ', 'ㄓㄔa bㄟㄠ', 'ㄓㄔabㄟㄠ']->matchfuzzy('ㄓㄔabㄟㄠ')) + " preference for leading letter match + call assert_equal(['ŗŝţũŵż', 'xŗŝţũŵż'], + \ ['xŗŝţũŵż', 'ŗŝţũŵż']->matchfuzzy('ŗŝţũŵż')) + " preference for sequential match + call assert_equal(['ㄞㄡㄤfffifl', 'ㄞaㄡbㄤcffdfiefl'], + \ ['ㄞaㄡbㄤcffdfiefl', 'ㄞㄡㄤfffifl']->matchfuzzy('ㄞㄡㄤfffifl')) + " non-matching leading letter(s) penalty + call assert_equal(['xㄞㄡㄤfffifl', 'xxㄞㄡㄤfffifl'], + \ ['xxㄞㄡㄤfffifl', 'xㄞㄡㄤfffifl']->matchfuzzy('ㄞㄡㄤfffifl')) + " total non-matching letter(s) penalty + call assert_equal(['ŗŝţ', 'ŗŝţx', 'ŗŝţxx'], + \ ['ŗŝţxx', 'ŗŝţ', 'ŗŝţx']->matchfuzzy('ŗŝţ')) +endfunc + +" Test for matchfuzzypos() with multibyte characters +func Test_matchfuzzypos_mbyte() + CheckFeature multi_lang + call assert_equal([['こんにちは世界'], [[0, 1, 2, 3, 4]], [273]], + \ matchfuzzypos(['こんにちは世界'], 'こんにちは')) + call assert_equal([['ンヹㄇヺヴ'], [[1, 3]], [88]], matchfuzzypos(['ンヹㄇヺヴ'], 'ヹヺ')) + " reverse the order of characters + call assert_equal([[], [], []], matchfuzzypos(['ンヹㄇヺヴ'], 'ヺヹ')) + call assert_equal([['αβΩxxx', 'xαxβxΩx'], [[0, 1, 2], [1, 3, 5]], [222, 113]], + \ matchfuzzypos(['αβΩxxx', 'xαxβxΩx'], 'αβΩ')) + call assert_equal([['ππbbππ', 'πππbbbπππ', 'ππππbbbbππππ', 'πbπ'], + \ [[0, 1], [0, 1], [0, 1], [0, 2]], [151, 148, 145, 110]], + \ matchfuzzypos(['πbπ', 'ππbbππ', 'πππbbbπππ', 'ππππbbbbππππ'], 'ππ')) + call assert_equal([['ααααααα'], [[0, 1, 2]], [191]], + \ matchfuzzypos(['ααααααα'], 'ααα')) + + call assert_equal([[], [], []], matchfuzzypos(['ンヹㄇ', 'ŗŝţ'], 'fffifl')) + let x = matchfuzzypos([repeat('Ψ', 256)], repeat('Ψ', 256)) + call assert_equal(range(256), x[1][0]) + call assert_equal([[], [], []], matchfuzzypos([repeat('✓', 300)], repeat('✓', 257))) + + " match multiple words (separated by space) + call assert_equal([['세 마리의 작은 돼지'], [[9, 10, 2, 3, 4]], [328]], ['세 마리의 작은 돼지', '마리의', '마리의 작은', '작은 돼지']->matchfuzzypos('돼지 마리의')) + call assert_equal([[], [], []], ['세 마리의 작은 돼지', '마리의', '마리의 작은', '작은 돼지']->matchfuzzypos('파란 하늘')) + + " match in a long string + call assert_equal([[repeat('ぶ', 300) .. 'ẼẼẼ'], [[300, 301, 302]], [-135]], + \ matchfuzzypos([repeat('ぶ', 300) .. 'ẼẼẼ'], 'ẼẼẼ')) + " preference for camel case match + call assert_equal([['xѳѵҁxxѳѴҁ'], [[6, 7, 8]], [189]], matchfuzzypos(['xѳѵҁxxѳѴҁ'], 'ѳѵҁ')) + " preference for match after a separator (_ or space) + call assert_equal([['xちだx_ちだ'], [[5, 6]], [145]], matchfuzzypos(['xちだx_ちだ'], 'ちだ')) + " preference for leading letter match + call assert_equal([['ѳѵҁxѳѵҁ'], [[0, 1]], [150]], matchfuzzypos(['ѳѵҁxѳѵҁ'], 'ѳѵ')) + " preference for sequential match + call assert_equal([['aンbヹcㄇdンヹㄇ'], [[7, 8, 9]], [158]], matchfuzzypos(['aンbヹcㄇdンヹㄇ'], 'ンヹㄇ')) + " best recursive match + call assert_equal([['xффйд'], [[2, 3, 4]], [168]], matchfuzzypos(['xффйд'], 'фйд')) +endfunc + +" Test for matchfuzzy() with limit +func Test_matchfuzzy_limit() + let x = ['1', '2', '3', '2'] + call assert_equal(['2', '2'], x->matchfuzzy('2')) + call assert_equal(['2', '2'], x->matchfuzzy('2', #{})) + call assert_equal(['2', '2'], x->matchfuzzy('2', #{limit: 0})) + call assert_equal(['2'], x->matchfuzzy('2', #{limit: 1})) + call assert_equal(['2', '2'], x->matchfuzzy('2', #{limit: 2})) + call assert_equal(['2', '2'], x->matchfuzzy('2', #{limit: 3})) + call assert_fails("call matchfuzzy(x, '2', #{limit: '2'})", 'E475:') + + let l = [{'id': 5, 'val': 'crayon'}, {'id': 6, 'val': 'camera'}] + call assert_equal([{'id': 5, 'val': 'crayon'}, {'id': 6, 'val': 'camera'}], l->matchfuzzy('c', #{text_cb: {v -> v.val}})) + call assert_equal([{'id': 5, 'val': 'crayon'}, {'id': 6, 'val': 'camera'}], l->matchfuzzy('c', #{key: 'val'})) + call assert_equal([{'id': 5, 'val': 'crayon'}, {'id': 6, 'val': 'camera'}], l->matchfuzzy('c', #{text_cb: {v -> v.val}, limit: 0})) + call assert_equal([{'id': 5, 'val': 'crayon'}, {'id': 6, 'val': 'camera'}], l->matchfuzzy('c', #{key: 'val', limit: 0})) + call assert_equal([{'id': 5, 'val': 'crayon'}], l->matchfuzzy('c', #{text_cb: {v -> v.val}, limit: 1})) + call assert_equal([{'id': 5, 'val': 'crayon'}], l->matchfuzzy('c', #{key: 'val', limit: 1})) +endfunc + +" This was using uninitialized memory +func Test_matchfuzzy_initialized() + CheckRunVimInTerminal + + " This can take a very long time (esp. when using valgrind). Run in a + " separate Vim instance and kill it after two seconds. We only check for + " memory errors. + let lines =<< trim END + lvimgrep [ss [fg* + END + call writefile(lines, 'XTest_matchfuzzy', 'D') + + let buf = RunVimInTerminal('-u NONE -X -Z', {}) + call term_sendkeys(buf, ":source XTest_matchfuzzy\n") + call TermWait(buf, 2000) + + let job = term_getjob(buf) + if job_status(job) == "run" + call job_stop(job, "int") + call TermWait(buf, 50) + endif + + " clean up + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_matchparen.vim b/test/old/testdir/test_matchparen.vim new file mode 100644 index 0000000000..3138180c66 --- /dev/null +++ b/test/old/testdir/test_matchparen.vim @@ -0,0 +1,87 @@ +" Test for the matchparen plugin + +if !has('gui_running') && has('unix') + " set term=ansi +endif + +source view_util.vim +source check.vim +source screendump.vim + +" 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 + +" Test for scrolling that modifies buffer during visual block +func Test_matchparen_pum_clear() + CheckScreendump + + let lines =<< trim END + source $VIMRUNTIME/plugin/matchparen.vim + set completeopt=menuone + call setline(1, ['aa', 'aaa', 'aaaa', '(a)']) + call cursor(4, 3) + END + + let filename = 'Xmatchparen' + call writefile(lines, filename, 'D') + + let buf = RunVimInTerminal('-S '.filename, #{rows: 10}) + call term_sendkeys(buf, "i\<C-N>\<C-N>") + + call VerifyScreenDump(buf, 'Test_matchparen_pum_clear_1', {}) + + call StopVimInTerminal(buf) +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_menu.vim b/test/old/testdir/test_menu.vim new file mode 100644 index 0000000000..d1c1180ce1 --- /dev/null +++ b/test/old/testdir/test_menu.vim @@ -0,0 +1,574 @@ +" Test that the system menu can be loaded. + +source check.vim +CheckFeature menu + +func Test_load_menu() + try + source $VIMRUNTIME/menu.vim + catch + call assert_report('error while loading menus: ' . v:exception) + endtry + call assert_match('browse confirm w', execute(':menu File.Save')) + + let v:errmsg = '' + doautocmd LoadBufferMenu VimEnter + call assert_equal('', v:errmsg) + + source $VIMRUNTIME/delmenu.vim + call assert_equal('', v:errmsg) +endfunc + +func Test_buffer_menu_special_buffers() + " Load in runtime menus + try + source $VIMRUNTIME/menu.vim + catch + call assert_report('error while loading menus: ' . v:exception) + endtry + + let v:errmsg = '' + doautocmd LoadBufferMenu VimEnter + call assert_equal('', v:errmsg) + + let orig_buffer_menus = execute("nmenu Buffers") + + " Test that regular new buffer results in a new buffer menu item. + new + let new_buffer_menus = execute('nmenu Buffers') + call assert_equal(len(split(orig_buffer_menus, "\n")) + 2, len(split(new_buffer_menus, "\n"))) + bwipe! + call assert_equal(orig_buffer_menus, execute("nmenu Buffers")) + + " Make a new command-line window, test that it does not create a new buffer + " menu. + call feedkeys("q::let cmdline_buffer_menus=execute('nmenu Buffers')\<CR>:q\<CR>", 'ntx') + call assert_equal(len(split(orig_buffer_menus, "\n")) + 2, len(split(cmdline_buffer_menus, "\n"))) + call assert_equal(orig_buffer_menus, execute("nmenu Buffers")) + + if has('terminal') + " Open a terminal window and test that it does not create a buffer menu + " item. + terminal + let term_buffer_menus = execute('nmenu Buffers') + call assert_equal(len(split(orig_buffer_menus, "\n")) + 2, len(split(term_buffer_menus, "\n"))) + bwipe! + call assert_equal(orig_buffer_menus, execute("nmenu Buffers")) + endif + + " Remove menus to clean up + source $VIMRUNTIME/delmenu.vim + call assert_equal('', v:errmsg) +endfunc + +func Test_translate_menu() + if !has('multi_lang') + return + endif + if !filereadable($VIMRUNTIME . '/lang/menu_de_de.latin1.vim') + throw 'Skipped: translated menu not found' + endif + + " First delete any English menus. + source $VIMRUNTIME/delmenu.vim + set langmenu=de_de + source $VIMRUNTIME/menu.vim + call assert_match('browse confirm w', execute(':menu Datei.Speichern')) + + source $VIMRUNTIME/delmenu.vim +endfunc + +func Test_menu_commands() + nmenu 2 Test.FooBar :let g:did_menu = 'normal'<CR> + vmenu 2 Test.FooBar :let g:did_menu = 'visual'<CR> + smenu 2 Test.FooBar :let g:did_menu = 'select'<CR> + omenu 2 Test.FooBar :let g:did_menu = 'op-pending'<CR> + tlmenu 2 Test.FooBar :let g:did_menu = 'terminal'<CR> + imenu 2 Test.FooBar :let g:did_menu = 'insert'<CR> + cmenu 2 Test.FooBar :let g:did_menu = 'cmdline'<CR> + emenu n Test.FooBar + + call feedkeys(":menu Test.FooB\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"menu Test.FooBar', @:) + + call assert_equal('normal', g:did_menu) + emenu v Test.FooBar + call assert_equal('visual', g:did_menu) + emenu s Test.FooBar + call assert_equal('select', g:did_menu) + emenu o Test.FooBar + call assert_equal('op-pending', g:did_menu) + emenu t Test.FooBar + call assert_equal('terminal', g:did_menu) + emenu i Test.FooBar + call assert_equal('insert', g:did_menu) + emenu c Test.FooBar + call assert_equal('cmdline', g:did_menu) + + nunmenu Test.FooBar + call assert_fails('emenu n Test.FooBar', 'E335: Menu not defined for Normal mode') + vunmenu Test.FooBar + call assert_fails('emenu v Test.FooBar', 'E335: Menu not defined for Visual mode') + vmenu 2 Test.FooBar :let g:did_menu = 'visual'<CR> + sunmenu Test.FooBar + call assert_fails('emenu s Test.FooBar', 'E335: Menu not defined for Select mode') + ounmenu Test.FooBar + call assert_fails('emenu o Test.FooBar', 'E335: Menu not defined for Op-pending mode') + iunmenu Test.FooBar + call assert_fails('emenu i Test.FooBar', 'E335: Menu not defined for Insert mode') + cunmenu Test.FooBar + call assert_fails('emenu c Test.FooBar', 'E335: Menu not defined for Cmdline mode') + tlunmenu Test.FooBar + call assert_fails('emenu t Test.FooBar', 'E335: Menu not defined for Terminal mode') + + aunmenu Test.FooBar + call assert_fails('emenu n Test.FooBar', 'E334:') + + nmenu 2 Test.FooBar.Child :let g:did_menu = 'foobar'<CR> + call assert_fails('emenu n Test.FooBar', 'E333:') + nunmenu Test.FooBar.Child + + unlet g:did_menu +endfun + +" Test various menu related errors +func Test_menu_errors() + menu Test.Foo :version<CR> + + " Error cases + call assert_fails('menu .Test.Foo :ls<CR>', 'E475:') + call assert_fails('menu Test. :ls<CR>', 'E330:') + call assert_fails('menu Foo. :ls<CR>', 'E331:') + call assert_fails('unmenu Test.Foo abc', 'E488:') + call assert_fails('menu <Tab>:ls :ls<CR>', 'E792:') + call assert_fails('menu Test.<Tab>:ls :ls<CR>', 'E792:') + call assert_fails('menu Test.Foo.Bar :ls<CR>', 'E327:') + call assert_fails('menu Test.-Sep-.Baz :ls<CR>', 'E332:') + call assert_fails('menu Foo.Bar.--.Baz :ls<CR>', 'E332:') + call assert_fails('menu disable Test.Foo.Bar', 'E327:') + call assert_fails('menu disable T.Foo', 'E329:') + call assert_fails('unmenu Test.Foo.Bar', 'E327:') + call assert_fails('cunmenu Test.Foo', 'E328:') + call assert_fails('unmenu Test.Bar', 'E329:') + call assert_fails('menu Test.Foo.Bar', 'E327:') + call assert_fails('cmenu Test.Foo', 'E328:') + call assert_fails('emenu x Test.Foo', 'E475:') + call assert_fails('emenu Test.Foo.Bar', 'E327:') + call assert_fails('menutranslate Test', 'E474:') + + silent! unmenu Foo + unmenu Test +endfunc + +" Test for menu item completion in command line +func Test_menu_expand() + " Create the menu items for test + menu Dummy.Nothing lll + for i in range(1, 4) + let m = 'menu Xmenu.A' .. i .. '.A' .. i + for j in range(1, 4) + exe m .. 'B' .. j .. ' :echo "A' .. i .. 'B' .. j .. '"' .. "<CR>" + endfor + endfor + set wildmenu + + " Test for <CR> selecting a submenu + call feedkeys(":emenu Xmenu.A\<Tab>\<CR>\<Right>x\<BS>\<C-B>\"\<CR>", 'xt') + call assert_equal('"emenu Xmenu.A1.A1B2', @:) + + " Test for <Down> selecting a submenu + call feedkeys(":emenu Xmenu.A\<Tab>\<Right>\<Right>\<Down>" .. + \ "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"emenu Xmenu.A3.A3B1 A3B2 A3B3 A3B4', @:) + + " Test for <Up> to go up a submenu + call feedkeys(":emenu Xmenu.A\<Tab>\<Down>\<Up>\<Right>\<Right>" .. + \ "\<Left>\<Down>\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"emenu Xmenu.A2.A2B1 A2B2 A2B3 A2B4', @:) + + " Test for <Up> to go up a menu + call feedkeys(":emenu Xmenu.A\<Tab>\<Down>\<Up>\<Up>\<Up>" .. + \ "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"emenu Dummy. Xmenu.', @:) + + " Test for expanding only submenus + call feedkeys(":popup Xmenu.\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"popup Xmenu.A1 A2 A3 A4', @:) + + " Test for expanding menus after enable/disable + call feedkeys(":menu enable Xmenu.\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"menu enable Xmenu.A1. A2. A3. A4.', @:) + call feedkeys(":menu disable Xmenu.\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"menu disable Xmenu.A1. A2. A3. A4.', @:) + + " Test for expanding non-existing menu path + call feedkeys(":menu xyz.\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"menu xyz.', @:) + call feedkeys(":menu Xmenu.A1.A1B1.xyz.\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"menu Xmenu.A1.A1B1.xyz.', @:) + + set wildmenu& + unmenu Xmenu + unmenu Dummy + + " Test for expanding popup menus with some hidden items + menu Xmenu.foo.A1 a1 + menu Xmenu.]bar bar + menu Xmenu.]baz.B1 b1 + menu Xmenu.-sep- : + call feedkeys(":popup Xmenu.\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"popup Xmenu.foo', @:) + unmenu Xmenu +endfunc + +" Test for the menu_info() function +func Test_menu_info() + " Define menus with various attributes + 10nnoremenu 10.10 T&est.F&oo :echo 'foo'<CR> + 10nmenu <silent> 10.20 T&est.B&ar<Tab>:bar :echo 'bar'<CR> + 10nmenu <script> 10.30.5 T&est.Ba&z.Qu&x :echo 'qux'<CR> + + let d = #{name: "B&ar\t:bar", display: 'Bar', modes: 'n', shortcut: 'a', + \ accel: ':bar', priority: 20, enabled: v:true, silent: v:true, + \ noremenu: v:false, script: v:false, rhs: ":echo 'bar'<CR>"} + call assert_equal(d, menu_info('Test.Bar')) + + let d = #{name: 'Ba&z', display: 'Baz', modes: 'n', shortcut: 'z', + \ priority: 30, submenus: ['Qux']} + call assert_equal(d, menu_info('Test.Baz')) + + let d = #{name: 'T&est', display: 'Test', modes: 'n', shortcut: 'e', + \ priority: 10, submenus: ['Foo', 'Bar', 'Baz']} + call assert_equal(d, menu_info('Test')) + call assert_equal({}, menu_info('Test.Dummy')) + call assert_equal({}, menu_info('Dummy')) + + nmenu disable Test.Foo + call assert_equal(v:false, menu_info('Test.Foo').enabled) + nmenu enable Test.Foo + call assert_equal(v:true, menu_info('Test.Foo').enabled) + + call assert_equal(menu_info('Test.Foo'), menu_info('Test.Foo', '')) + nmenu Test.abc <Nop> + call assert_equal('<Nop>', menu_info('Test.abc').rhs) + call assert_fails('call menu_info([])', 'E730:') + call assert_fails('call menu_info("", [])', 'E730:') + nunmenu Test + + " Test for defining menus in different modes + menu Test.menu :menu<CR> + menu! Test.menu! :menu!<CR> + amenu Test.amenu :amenu<CR> + nmenu Test.nmenu :nmenu<CR> + omenu Test.omenu :omenu<CR> + vmenu Test.vmenu :vmenu<CR> + xmenu Test.xmenu :xmenu<CR> + smenu Test.smenu :smenu<CR> + imenu <silent> <script> Test.imenu :imenu<CR> + cmenu Test.cmenu :cmenu<CR> + tlmenu Test.tlmenu :tlmenu<CR> + tmenu Test.nmenu Normal mode menu + tmenu Test.omenu Op-pending mode menu + noremenu Test.noremenu :noremenu<CR> + noremenu! Test.noremenu! :noremenu!<CR> + anoremenu Test.anoremenu :anoremenu<CR> + nnoremenu Test.nnoremenu :nnoremenu<CR> + onoremenu Test.onoremenu :onoremenu<CR> + vnoremenu Test.vnoremenu :vnoremenu<CR> + xnoremenu Test.xnoremenu :xnoremenu<CR> + snoremenu Test.snoremenu :snoremenu<CR> + inoremenu <silent> Test.inoremenu :inoremenu<CR> + cnoremenu Test.cnoremenu :cnoremenu<CR> + tlnoremenu Test.tlnoremenu :tlnoremenu<CR> + call assert_equal(#{name: 'menu', priority: 500, shortcut: '', + \ display: 'menu', modes: ' ', enabled: v:true, silent: v:false, + \ rhs: ":menu<CR>", noremenu: v:false, script: v:false}, + \ menu_info('Test.menu')) + call assert_equal(#{name: 'menu!', priority: 500, shortcut: '', + \ display: 'menu!', modes: '!', enabled: v:true, silent: v:false, + \ rhs: ":menu!<CR>", noremenu: v:false, script: v:false}, + \ menu_info('Test.menu!', '!')) + call assert_equal(#{name: 'amenu', priority: 500, shortcut: '', + \ display: 'amenu', modes: 'a', enabled: v:true, silent: v:false, + \ rhs: ":amenu<CR>", noremenu: v:false, script: v:false}, + \ menu_info('Test.amenu', 'a')) + call assert_equal(#{name: 'nmenu', priority: 500, shortcut: '', + \ display: 'nmenu', modes: 'n', enabled: v:true, silent: v:false, + \ rhs: ':nmenu<CR>', noremenu: v:false, script: v:false}, + \ menu_info('Test.nmenu', 'n')) + call assert_equal(#{name: 'omenu', priority: 500, shortcut: '', + \ display: 'omenu', modes: 'o', enabled: v:true, silent: v:false, + \ rhs: ':omenu<CR>', noremenu: v:false, script: v:false}, + \ menu_info('Test.omenu', 'o')) + call assert_equal(#{name: 'vmenu', priority: 500, shortcut: '', + \ display: 'vmenu', modes: 'v', enabled: v:true, silent: v:false, + \ rhs: ':vmenu<CR>', noremenu: v:false, script: v:false}, + \ menu_info('Test.vmenu', 'v')) + call assert_equal(#{name: 'xmenu', priority: 500, shortcut: '', + \ display: 'xmenu', modes: 'x', enabled: v:true, silent: v:false, + \ rhs: ':xmenu<CR>', noremenu: v:false, script: v:false}, + \ menu_info('Test.xmenu', 'x')) + call assert_equal(#{name: 'smenu', priority: 500, shortcut: '', + \ display: 'smenu', modes: 's', enabled: v:true, silent: v:false, + \ rhs: ':smenu<CR>', noremenu: v:false, script: v:false}, + \ menu_info('Test.smenu', 's')) + call assert_equal(#{name: 'imenu', priority: 500, shortcut: '', + \ display: 'imenu', modes: 'i', enabled: v:true, silent: v:true, + \ rhs: ':imenu<CR>', noremenu: v:false, script: v:true}, + \ menu_info('Test.imenu', 'i')) + call assert_equal(#{ name: 'cmenu', priority: 500, shortcut: '', + \ display: 'cmenu', modes: 'c', enabled: v:true, silent: v:false, + \ rhs: ':cmenu<CR>', noremenu: v:false, script: v:false}, + \ menu_info('Test.cmenu', 'c')) + call assert_equal(#{name: 'tlmenu', priority: 500, shortcut: '', + \ display: 'tlmenu', modes: 'tl', enabled: v:true, silent: v:false, + \ rhs: ':tlmenu<CR>', noremenu: v:false, script: v:false}, + \ menu_info('Test.tlmenu', 'tl')) + call assert_equal(#{name: 'noremenu', priority: 500, shortcut: '', + \ display: 'noremenu', modes: ' ', enabled: v:true, silent: v:false, + \ rhs: ":noremenu<CR>", noremenu: v:true, script: v:false}, + \ menu_info('Test.noremenu')) + call assert_equal(#{name: 'noremenu!', priority: 500, shortcut: '', + \ display: 'noremenu!', modes: '!', enabled: v:true, silent: v:false, + \ rhs: ":noremenu!<CR>", noremenu: v:true, script: v:false}, + \ menu_info('Test.noremenu!', '!')) + call assert_equal(#{name: 'anoremenu', priority: 500, shortcut: '', + \ display: 'anoremenu', modes: 'a', enabled: v:true, silent: v:false, + \ rhs: ":anoremenu<CR>", noremenu: v:true, script: v:false}, + \ menu_info('Test.anoremenu', 'a')) + call assert_equal(#{name: 'nnoremenu', priority: 500, shortcut: '', + \ display: 'nnoremenu', modes: 'n', enabled: v:true, silent: v:false, + \ rhs: ':nnoremenu<CR>', noremenu: v:true, script: v:false}, + \ menu_info('Test.nnoremenu', 'n')) + call assert_equal(#{name: 'onoremenu', priority: 500, shortcut: '', + \ display: 'onoremenu', modes: 'o', enabled: v:true, silent: v:false, + \ rhs: ':onoremenu<CR>', noremenu: v:true, script: v:false}, + \ menu_info('Test.onoremenu', 'o')) + call assert_equal(#{name: 'vnoremenu', priority: 500, shortcut: '', + \ display: 'vnoremenu', modes: 'v', enabled: v:true, silent: v:false, + \ rhs: ':vnoremenu<CR>', noremenu: v:true, script: v:false}, + \ menu_info('Test.vnoremenu', 'v')) + call assert_equal(#{name: 'xnoremenu', priority: 500, shortcut: '', + \ display: 'xnoremenu', modes: 'x', enabled: v:true, silent: v:false, + \ rhs: ':xnoremenu<CR>', noremenu: v:true, script: v:false}, + \ menu_info('Test.xnoremenu', 'x')) + call assert_equal(#{name: 'snoremenu', priority: 500, shortcut: '', + \ display: 'snoremenu', modes: 's', enabled: v:true, silent: v:false, + \ rhs: ':snoremenu<CR>', noremenu: v:true, script: v:false}, + \ menu_info('Test.snoremenu', 's')) + call assert_equal(#{name: 'inoremenu', priority: 500, shortcut: '', + \ display: 'inoremenu', modes: 'i', enabled: v:true, silent: v:true, + \ rhs: ':inoremenu<CR>', noremenu: v:true, script: v:false}, + \ menu_info('Test.inoremenu', 'i')) + call assert_equal(#{ name: 'cnoremenu', priority: 500, shortcut: '', + \ display: 'cnoremenu', modes: 'c', enabled: v:true, silent: v:false, + \ rhs: ':cnoremenu<CR>', noremenu: v:true, script: v:false}, + \ menu_info('Test.cnoremenu', 'c')) + call assert_equal(#{name: 'tlnoremenu', priority: 500, shortcut: '', + \ display: 'tlnoremenu', modes: 'tl', enabled: v:true, silent: v:false, + \ rhs: ':tlnoremenu<CR>', noremenu: v:true, script: v:false}, + \ menu_info('Test.tlnoremenu', 'tl')) + + " Test for getting all the top-level menu names + call assert_notequal(menu_info('').submenus, []) + + aunmenu Test + tlunmenu Test + call assert_equal({}, menu_info('Test')) + call assert_equal({}, menu_info('Test', '!')) + call assert_equal({}, menu_info('Test', 'a')) + call assert_equal({}, menu_info('Test', 'n')) + call assert_equal({}, menu_info('Test', 'o')) + call assert_equal({}, menu_info('Test', 'v')) + call assert_equal({}, menu_info('Test', 'x')) + call assert_equal({}, menu_info('Test', 's')) + call assert_equal({}, menu_info('Test', 'i')) + call assert_equal({}, menu_info('Test', 'c')) + call assert_equal({}, menu_info('Test', 't')) + call assert_equal({}, menu_info('Test', 'tl')) + + amenu Test.amenu :amenu<CR> + call assert_equal(':amenu<CR>', menu_info('Test.amenu', '').rhs) + call assert_equal('<C-\><C-O>:amenu<CR>', menu_info('Test.amenu', '!').rhs) + call assert_equal(':amenu<CR>', menu_info('Test.amenu', 'n').rhs) + call assert_equal('<C-C>:amenu<CR><C-\><C-G>', + \ menu_info('Test.amenu', 'o').rhs) + call assert_equal('<C-C>:amenu<CR><C-\><C-G>', + \ menu_info('Test.amenu', 'v').rhs) + call assert_equal('<C-C>:amenu<CR><C-\><C-G>', + \ menu_info('Test.amenu', 'x').rhs) + call assert_equal('<C-C>:amenu<CR><C-\><C-G>', + \ menu_info('Test.amenu', 's').rhs) + call assert_equal('<C-\><C-O>:amenu<CR>', menu_info('Test.amenu', 'i').rhs) + call assert_equal('<C-C>:amenu<CR><C-\><C-G>', + \ menu_info('Test.amenu', 'c').rhs) + aunmenu Test.amenu + + " Test for hidden menus + menu ]Test.menu :menu<CR> + call assert_equal(#{name: ']Test', display: ']Test', priority: 500, + \ shortcut: '', modes: ' ', submenus: ['menu']}, + \ menu_info(']Test')) + unmenu ]Test +endfunc + +" Test for <special> keyword in a menu with 'cpo' containing '<' +func Test_menu_special() + throw 'Skipped: Nvim does not support cpoptions flag "<"' + new + set cpo+=< + nmenu Test.Sign am<Tab>n<Esc> + call feedkeys(":emenu n Test.Sign\<CR>", 'x') + call assert_equal("m<Tab>n<Esc>", getline(1)) + nunmenu Test.Sign + nmenu <special> Test.Sign am<Tab>n<Esc> + call setline(1, '') + call feedkeys(":emenu n Test.Sign\<CR>", 'x') + call assert_equal("m\tn", getline(1)) + set cpo-=< + close! + nunmenu Test.Sign +endfunc + +" Test for "icon=filename" in a toolbar +func Test_menu_icon() + CheckFeature toolbar + nmenu icon=myicon.xpm Toolbar.Foo :echo "Foo"<CR> + call assert_equal('myicon.xpm', "Toolbar.Foo"->menu_info().icon) + nunmenu Toolbar.Foo + + " Test for using the builtin icon + amenu ToolBar.BuiltIn22 :echo "BuiltIn22"<CR> + call assert_equal(#{name: 'BuiltIn22', display: 'BuiltIn22', + \ enabled: v:true, shortcut: '', modes: 'a', script: v:false, + \ iconidx: 22, priority: 500, silent: v:false, + \ rhs: ':echo "BuiltIn22"<CR>', noremenu: v:false}, + \ menu_info("ToolBar.BuiltIn22")) + aunmenu ToolBar.BuiltIn22 +endfunc + +" Test for ":emenu" command in different modes +func Test_emenu_cmd() + new + xmenu Test.foo rx + call setline(1, ['aaaa', 'bbbb']) + normal ggVj + %emenu Test.foo + call assert_equal(['xxxx', 'xxxx'], getline(1, 2)) + call setline(1, ['aaaa', 'bbbb']) + exe "normal ggVj\<Esc>" + %emenu Test.foo + call assert_equal(['xxxx', 'xxxx'], getline(1, 2)) + call setline(1, ['aaaa', 'bbbb']) + exe "normal ggV\<Esc>" + 2emenu Test.foo + call assert_equal(['aaaa', 'xxxx'], getline(1, 2)) + xunmenu Test.foo + close! +endfunc + +" Test for PopUp menus +func Test_popup_menu() + 20menu PopUp.foo :echo 'foo'<CR> + 20menu PopUp.bar :echo 'bar'<CR> + call assert_equal(#{name: 'PopUp', display: 'PopUp', priority: 20, + \ shortcut: '', modes: ' ', submenus: ['foo', 'bar']}, + \ menu_info('PopUp')) + menu disable PopUp.bar + call assert_equal(v:true, "PopUp.foo"->menu_info().enabled) + call assert_equal(v:false, "PopUp.bar"->menu_info().enabled) + menu enable PopUp.bar + call assert_equal(v:true, "PopUp.bar"->menu_info().enabled) + unmenu PopUp +endfunc + +" Test for MenuPopup autocommand +func Test_autocmd_MenuPopup() + CheckNotGui + + set mouse=a + set mousemodel=popup + aunmenu * + autocmd MenuPopup * exe printf( + \ 'anoremenu PopUp.Foo <Cmd>let g:res = ["%s", "%s"]<CR>', + \ expand('<afile>'), expand('<amatch>')) + + call feedkeys("\<RightMouse>\<Down>\<CR>", 'tnix') + call assert_equal(['n', 'n'], g:res) + + call feedkeys("v\<RightMouse>\<Down>\<CR>\<Esc>", 'tnix') + call assert_equal(['v', 'v'], g:res) + + call feedkeys("gh\<RightMouse>\<Down>\<CR>\<Esc>", 'tnix') + call assert_equal(['s', 's'], g:res) + + call feedkeys("i\<RightMouse>\<Down>\<CR>\<Esc>", 'tnix') + call assert_equal(['i', 'i'], g:res) + + autocmd! MenuPopup + aunmenu PopUp.Foo + unlet g:res + set mouse& mousemodel& +endfunc + +" Test for listing the menus using the :menu command +func Test_show_menus() + " In the GUI, tear-off menu items are present in the output below + " So skip this test + CheckNotGui + aunmenu * + call assert_equal(['--- Menus ---'], split(execute('menu'), "\n")) + nmenu <script> 200.10 Test.nmenu1 :nmenu1<CR> + nmenu 200.20 Test.nmenu2 :nmenu2<CR> + nnoremenu 200.30 Test.nmenu3 :nmenu3<CR> + nmenu 200.40 Test.nmenu4 :nmenu4<CR> + nmenu 200.50 disable Test.nmenu4 + let exp =<< trim [TEXT] + --- Menus --- + 200 Test + 10 nmenu1 + n& :nmenu1<CR> + 20 nmenu2 + n :nmenu2<CR> + 30 nmenu3 + n* :nmenu3<CR> + 40 nmenu4 + n - :nmenu4<CR> + [TEXT] + call assert_equal(exp, split(execute('nmenu'), "\n")) + nunmenu Test +endfunc + +" Test for menu tips +func Test_tmenu() + tunmenu * + call assert_equal(['--- Menus ---'], split(execute('tmenu'), "\n")) + tmenu Test.nmenu1 nmenu1 + tmenu Test.nmenu2.sub1 nmenu2.sub1 + let exp =<< trim [TEXT] + --- Menus --- + 500 Test + 500 nmenu1 + t - nmenu1 + 500 nmenu2 + 500 sub1 + t - nmenu2.sub1 + [TEXT] + call assert_equal(exp, split(execute('tmenu'), "\n")) + tunmenu Test +endfunc + +func Test_only_modifier() + exe "tmenu a.b \x80\xfc0" + let exp =<< trim [TEXT] + --- Menus --- + 500 a + 500 b + t - <T-2-^@> + [TEXT] + call assert_equal(exp, split(execute('tmenu'), "\n")) + + tunmenu a.b +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_messages.vim b/test/old/testdir/test_messages.vim new file mode 100644 index 0000000000..5ebcb375b6 --- /dev/null +++ b/test/old/testdir/test_messages.vim @@ -0,0 +1,604 @@ +" Tests for :messages, :echomsg, :echoerr + +source check.vim +source shared.vim +source term_util.vim +source view_util.vim +source screendump.vim + +func Test_messages() + let oldmore = &more + try + set nomore + + let arr = map(range(10), '"hello" . v:val') + for s in arr + echomsg s | redraw + endfor + + " get last two messages + redir => result + 2messages | redraw + redir END + let msg_list = split(result, "\n") + call assert_equal(["hello8", "hello9"], msg_list) + + " clear messages without last one + 1messages clear + let msg_list = GetMessages() + call assert_equal(['hello9'], msg_list) + + " clear all messages + messages clear + let msg_list = GetMessages() + call assert_equal([], msg_list) + finally + let &more = oldmore + endtry + + call assert_fails('message 1', 'E474:') +endfunc + + " Patch 7.4.1696 defined the "clearmode()" command for clearing the mode +" indicator (e.g., "-- INSERT --") when ":stopinsert" is invoked. Message +" output could then be disturbed when 'cmdheight' was greater than one. +" This test ensures that the bugfix for this issue remains in place. +func Test_stopinsert_does_not_break_message_output() + set cmdheight=2 + redraw! + + stopinsert | echo 'test echo' + call assert_equal(116, screenchar(&lines - 1, 1)) + call assert_equal(32, screenchar(&lines, 1)) + redraw! + + stopinsert | echomsg 'test echomsg' + call assert_equal(116, screenchar(&lines - 1, 1)) + call assert_equal(32, screenchar(&lines, 1)) + redraw! + + set cmdheight& +endfunc + +func Test_message_completion() + call feedkeys(":message \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"message clear', @:) +endfunc + +func Test_echomsg() + call assert_equal("\nhello", execute(':echomsg "hello"')) + call assert_equal("\n", execute(':echomsg ""')) + call assert_equal("\n12345", execute(':echomsg 12345')) + call assert_equal("\n[]", execute(':echomsg []')) + call assert_equal("\n[1, 2, 3]", execute(':echomsg [1, 2, 3]')) + call assert_equal("\n[1, 2, []]", execute(':echomsg [1, 2, v:_null_list]')) + call assert_equal("\n{}", execute(':echomsg {}')) + call assert_equal("\n{'a': 1, 'b': 2}", execute(':echomsg {"a": 1, "b": 2}')) + if has('float') + call assert_equal("\n1.23", execute(':echomsg 1.23')) + endif + call assert_match("function('<lambda>\\d*')", execute(':echomsg {-> 1234}')) +endfunc + +func Test_echoerr() + CheckFunction test_ignore_error + call test_ignore_error('IgNoRe') + call assert_equal("\nIgNoRe hello", execute(':echoerr "IgNoRe hello"')) + call assert_equal("\n12345 IgNoRe", execute(':echoerr 12345 "IgNoRe"')) + call assert_equal("\n[1, 2, 'IgNoRe']", execute(':echoerr [1, 2, "IgNoRe"]')) + call assert_equal("\n{'IgNoRe': 2, 'a': 1}", execute(':echoerr {"a": 1, "IgNoRe": 2}')) + if has('float') + call assert_equal("\n1.23 IgNoRe", execute(':echoerr 1.23 "IgNoRe"')) + endif + eval '<lambda>'->test_ignore_error() + call assert_match("function('<lambda>\\d*')", execute(':echoerr {-> 1234}')) + call test_ignore_error('RESET') +endfunc + +func Test_mode_message_at_leaving_insert_by_ctrl_c() + if !has('terminal') || has('gui_running') + return + endif + + " Set custom statusline built by user-defined function. + let testfile = 'Xtest.vim' + call writefile([ + \ 'func StatusLine() abort', + \ ' return ""', + \ 'endfunc', + \ 'set statusline=%!StatusLine()', + \ 'set laststatus=2', + \ ], testfile) + + let rows = 10 + let buf = term_start([GetVimProg(), '--clean', '-S', testfile], {'term_rows': rows}) + call TermWait(buf, 100) + call assert_equal('run', job_status(term_getjob(buf))) + + call term_sendkeys(buf, "i") + call WaitForAssert({-> assert_match('^-- INSERT --\s*$', term_getline(buf, rows))}) + call term_sendkeys(buf, "\<C-C>") + call WaitForAssert({-> assert_match('^\s*$', term_getline(buf, rows))}) + + call term_sendkeys(buf, ":qall!\<CR>") + call WaitForAssert({-> assert_equal('dead', job_status(term_getjob(buf)))}) + exe buf . 'bwipe!' + call delete(testfile) +endfunc + +func Test_mode_message_at_leaving_insert_with_esc_mapped() + if !has('terminal') || has('gui_running') + return + endif + + " Set custom statusline built by user-defined function. + let testfile = 'Xtest.vim' + call writefile([ + \ 'set laststatus=2', + \ 'inoremap <Esc> <Esc>00', + \ ], testfile) + + let rows = 10 + let buf = term_start([GetVimProg(), '--clean', '-S', testfile], {'term_rows': rows}) + call WaitForAssert({-> assert_match('0,0-1\s*All$', term_getline(buf, rows - 1))}) + call assert_equal('run', job_status(term_getjob(buf))) + + call term_sendkeys(buf, "i") + call WaitForAssert({-> assert_match('^-- INSERT --\s*$', term_getline(buf, rows))}) + call term_sendkeys(buf, "\<Esc>") + call WaitForAssert({-> assert_match('^\s*$', term_getline(buf, rows))}) + + call term_sendkeys(buf, ":qall!\<CR>") + call WaitForAssert({-> assert_equal('dead', job_status(term_getjob(buf)))}) + exe buf . 'bwipe!' + call delete(testfile) +endfunc + +func Test_echospace() + set noruler noshowcmd laststatus=1 + call assert_equal(&columns - 1, v:echospace) + split + call assert_equal(&columns - 1, v:echospace) + set ruler + call assert_equal(&columns - 1, v:echospace) + close + call assert_equal(&columns - 19, v:echospace) + set showcmd noruler + call assert_equal(&columns - 12, v:echospace) + set showcmd ruler + call assert_equal(&columns - 29, v:echospace) + + set ruler& showcmd& +endfunc + +func Test_warning_scroll() + CheckRunVimInTerminal + let lines =<< trim END + call test_override('ui_delay', 50) + set noruler + set readonly + undo + END + call writefile(lines, 'XTestWarningScroll', 'D') + let buf = RunVimInTerminal('', #{rows: 8}) + + " When the warning comes from a script, messages are scrolled so that the + " stacktrace is visible. + call term_sendkeys(buf, ":source XTestWarningScroll\n") + " only match the final colon in the line that shows the source + call WaitForAssert({-> assert_match(':$', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('line 4:W10: Warning: Changing a readonly file', term_getline(buf, 6))}) + call WaitForAssert({-> assert_equal('Already at oldest change', term_getline(buf, 7))}) + call WaitForAssert({-> assert_equal('Press ENTER or type command to continue', term_getline(buf, 8))}) + call term_sendkeys(buf, "\n") + + " When the warning does not come from a script, messages are not scrolled. + call term_sendkeys(buf, ":enew\n") + call term_sendkeys(buf, ":set readonly\n") + call term_sendkeys(buf, 'u') + call WaitForAssert({-> assert_equal('W10: Warning: Changing a readonly file', term_getline(buf, 8))}) + call WaitForAssert({-> assert_equal('Already at oldest change', term_getline(buf, 8))}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +" Test more-prompt (see :help more-prompt). +func Test_message_more() + CheckRunVimInTerminal + let buf = RunVimInTerminal('', {'rows': 6}) + call term_sendkeys(buf, ":call setline(1, range(1, 100))\n") + + call term_sendkeys(buf, ":%pfoo\<C-H>\<C-H>\<C-H>#") + call WaitForAssert({-> assert_equal(':%p#', term_getline(buf, 6))}) + call term_sendkeys(buf, "\n") + call WaitForAssert({-> assert_equal(' 5 5', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('-- More --', term_getline(buf, 6))}) + + call term_sendkeys(buf, '?') + call WaitForAssert({-> assert_equal(' 5 5', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('-- More -- SPACE/d/j: screen/page/line down, b/u/k: up, q: quit ', term_getline(buf, 6))}) + + " Down a line with j, <CR>, <NL> or <Down>. + call term_sendkeys(buf, "j") + call WaitForAssert({-> assert_equal(' 6 6', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('-- More --', term_getline(buf, 6))}) + call term_sendkeys(buf, "\<NL>") + call WaitForAssert({-> assert_equal(' 7 7', term_getline(buf, 5))}) + call term_sendkeys(buf, "\<CR>") + call WaitForAssert({-> assert_equal(' 8 8', term_getline(buf, 5))}) + call term_sendkeys(buf, "\<Down>") + call WaitForAssert({-> assert_equal(' 9 9', term_getline(buf, 5))}) + + " Down a screen with <Space>, f, or <PageDown>. + call term_sendkeys(buf, 'f') + call WaitForAssert({-> assert_equal(' 14 14', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('-- More --', term_getline(buf, 6))}) + call term_sendkeys(buf, ' ') + call WaitForAssert({-> assert_equal(' 19 19', term_getline(buf, 5))}) + call term_sendkeys(buf, "\<PageDown>") + call WaitForAssert({-> assert_equal(' 24 24', term_getline(buf, 5))}) + + " Down a page (half a screen) with d. + call term_sendkeys(buf, 'd') + call WaitForAssert({-> assert_equal(' 27 27', term_getline(buf, 5))}) + + " Down all the way with 'G'. + call term_sendkeys(buf, 'G') + call WaitForAssert({-> assert_equal('100 100', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('Press ENTER or type command to continue', term_getline(buf, 6))}) + + " Up a line k, <BS> or <Up>. + call term_sendkeys(buf, 'k') + call WaitForAssert({-> assert_equal(' 99 99', term_getline(buf, 5))}) + call term_sendkeys(buf, "\<BS>") + call WaitForAssert({-> assert_equal(' 98 98', term_getline(buf, 5))}) + call term_sendkeys(buf, "\<Up>") + call WaitForAssert({-> assert_equal(' 97 97', term_getline(buf, 5))}) + + " Up a screen with b or <PageUp>. + call term_sendkeys(buf, 'b') + call WaitForAssert({-> assert_equal(' 92 92', term_getline(buf, 5))}) + call term_sendkeys(buf, "\<PageUp>") + call WaitForAssert({-> assert_equal(' 87 87', term_getline(buf, 5))}) + + " Up a page (half a screen) with u. + call term_sendkeys(buf, 'u') + call WaitForAssert({-> assert_equal(' 84 84', term_getline(buf, 5))}) + + " Up all the way with 'g'. + call term_sendkeys(buf, 'g') + call WaitForAssert({-> assert_equal(' 4 4', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal(':%p#', term_getline(buf, 1))}) + call WaitForAssert({-> assert_equal('-- More --', term_getline(buf, 6))}) + + " All the way down. Pressing f should do nothing but pressing + " space should end the more prompt. + call term_sendkeys(buf, 'G') + call WaitForAssert({-> assert_equal('100 100', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('Press ENTER or type command to continue', term_getline(buf, 6))}) + call term_sendkeys(buf, 'f') + call WaitForAssert({-> assert_equal('100 100', term_getline(buf, 5))}) + call term_sendkeys(buf, ' ') + call WaitForAssert({-> assert_equal('100', term_getline(buf, 5))}) + + " Pressing g< shows the previous command output. + call term_sendkeys(buf, 'g<') + call WaitForAssert({-> assert_equal('100 100', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('Press ENTER or type command to continue', term_getline(buf, 6))}) + + " A command line that doesn't print text is appended to scrollback, + " even if it invokes a nested command line. + call term_sendkeys(buf, ":\<C-R>=':'\<CR>:\<CR>g<") + call WaitForAssert({-> assert_equal('100 100', term_getline(buf, 4))}) + call WaitForAssert({-> assert_equal(':::', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('Press ENTER or type command to continue', term_getline(buf, 6))}) + + call term_sendkeys(buf, ":%p#\n") + call WaitForAssert({-> assert_equal(' 5 5', term_getline(buf, 5))}) + call WaitForAssert({-> assert_equal('-- More --', term_getline(buf, 6))}) + + " Stop command output with q, <Esc> or CTRL-C. + call term_sendkeys(buf, 'q') + call WaitForAssert({-> assert_equal('100', term_getline(buf, 5))}) + + " Execute a : command from the more prompt + call term_sendkeys(buf, ":%p#\n") + call term_wait(buf) + call WaitForAssert({-> assert_equal('-- More --', term_getline(buf, 6))}) + call term_sendkeys(buf, ":") + call term_wait(buf) + call WaitForAssert({-> assert_equal(':', term_getline(buf, 6))}) + call term_sendkeys(buf, "echo 'Hello'\n") + call term_wait(buf) + call WaitForAssert({-> assert_equal('Hello ', term_getline(buf, 5))}) + + call StopVimInTerminal(buf) +endfunc + +" Test more-prompt scrollback +func Test_message_more_scrollback() + CheckRunVimInTerminal + + let lines =<< trim END + set t_ut= + hi Normal ctermfg=15 ctermbg=0 + for i in range(100) + echo i + endfor + END + call writefile(lines, 'XmoreScrollback', 'D') + let buf = RunVimInTerminal('-S XmoreScrollback', {'rows': 10}) + call VerifyScreenDump(buf, 'Test_more_scrollback_1', {}) + + call term_sendkeys(buf, 'f') + call TermWait(buf) + call term_sendkeys(buf, 'b') + call VerifyScreenDump(buf, 'Test_more_scrollback_2', {}) + + call term_sendkeys(buf, 'q') + call TermWait(buf) + call StopVimInTerminal(buf) +endfunc + +func Test_message_not_cleared_after_mode() + CheckRunVimInTerminal + + let lines =<< trim END + nmap <silent> gx :call DebugSilent('normal')<CR> + vmap <silent> gx :call DebugSilent('visual')<CR> + function DebugSilent(arg) + echomsg "from DebugSilent" a:arg + endfunction + set showmode + set cmdheight=1 + call test_settime(1) + call setline(1, ['one', 'NoSuchFile', 'three']) + END + call writefile(lines, 'XmessageMode', 'D') + let buf = RunVimInTerminal('-S XmessageMode', {'rows': 10}) + + call term_sendkeys(buf, 'gx') + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_message_not_cleared_after_mode_1', {}) + + " removing the mode message used to also clear the intended message + call term_sendkeys(buf, 'vEgx') + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_message_not_cleared_after_mode_2', {}) + + " removing the mode message used to also clear the error message + call term_sendkeys(buf, ":set cmdheight=2\<CR>") + call term_sendkeys(buf, '2GvEgf') + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_message_not_cleared_after_mode_3', {}) + + call StopVimInTerminal(buf) +endfunc + +" Test verbose message before echo command +func Test_echo_verbose_system() + CheckRunVimInTerminal + CheckUnix " needs the "seq" command + CheckNotMac " doesn't use /tmp + + let buf = RunVimInTerminal('', {'rows': 10}) + call term_sendkeys(buf, ":4 verbose echo system('seq 20')\<CR>") + " Note that the screendump is filtered to remove the name of the temp file + call VerifyScreenDump(buf, 'Test_verbose_system_1', {}) + + " display a page and go back, results in exactly the same view + call term_sendkeys(buf, ' ') + call TermWait(buf, 50) + call term_sendkeys(buf, 'b') + call VerifyScreenDump(buf, 'Test_verbose_system_1', {}) + + " do the same with 'cmdheight' set to 2 + call term_sendkeys(buf, 'q') + call TermWait(buf) + call term_sendkeys(buf, ":set ch=2\<CR>") + call TermWait(buf) + call term_sendkeys(buf, ":4 verbose echo system('seq 20')\<CR>") + call VerifyScreenDump(buf, 'Test_verbose_system_2', {}) + + call term_sendkeys(buf, ' ') + call TermWait(buf, 50) + call term_sendkeys(buf, 'b') + call VerifyScreenDump(buf, 'Test_verbose_system_2', {}) + + call term_sendkeys(buf, 'q') + call TermWait(buf) + call StopVimInTerminal(buf) +endfunc + + +func Test_ask_yesno() + CheckRunVimInTerminal + let buf = RunVimInTerminal('', {'rows': 6}) + call term_sendkeys(buf, ":call setline(1, range(1, 2))\n") + + call term_sendkeys(buf, ":2,1s/^/n/\n") + call WaitForAssert({-> assert_equal('Backwards range given, OK to swap (y/n)?', term_getline(buf, 6))}) + call term_sendkeys(buf, "n") + call WaitForAssert({-> assert_match('^Backwards range given, OK to swap (y/n)?n *1,1 *All$', term_getline(buf, 6))}) + call WaitForAssert({-> assert_equal('1', term_getline(buf, 1))}) + + call term_sendkeys(buf, ":2,1s/^/Esc/\n") + call WaitForAssert({-> assert_equal('Backwards range given, OK to swap (y/n)?', term_getline(buf, 6))}) + call term_sendkeys(buf, "\<Esc>") + call WaitForAssert({-> assert_match('^Backwards range given, OK to swap (y/n)?n *1,1 *All$', term_getline(buf, 6))}) + call WaitForAssert({-> assert_equal('1', term_getline(buf, 1))}) + + call term_sendkeys(buf, ":2,1s/^/y/\n") + call WaitForAssert({-> assert_equal('Backwards range given, OK to swap (y/n)?', term_getline(buf, 6))}) + call term_sendkeys(buf, "y") + call WaitForAssert({-> assert_match('^Backwards range given, OK to swap (y/n)?y *2,1 *All$', term_getline(buf, 6))}) + call WaitForAssert({-> assert_equal('y1', term_getline(buf, 1))}) + call WaitForAssert({-> assert_equal('y2', term_getline(buf, 2))}) + + call StopVimInTerminal(buf) +endfunc + +func Test_null() + echom v:_null_list + echom v:_null_dict + echom v:_null_blob + echom v:_null_string + " Nvim doesn't have NULL functions + " echom test_null_function() + " Nvim doesn't have NULL partials + " echom test_null_partial() + if has('job') + echom test_null_job() + echom test_null_channel() + endif +endfunc + +func Test_mapping_at_hit_return_prompt() + nnoremap <C-B> :echo "hit ctrl-b"<CR> + call feedkeys(":ls\<CR>", "xt") + call feedkeys("\<*C-B>", "xt") + call assert_match('hit ctrl-b', Screenline(&lines - 1)) + nunmap <C-B> +endfunc + +func Test_quit_long_message() + CheckScreendump + + let content =<< trim END + echom range(9999)->join("\x01") + END + call writefile(content, 'Xtest_quit_message', 'D') + let buf = RunVimInTerminal('-S Xtest_quit_message', #{rows: 10, wait_for_ruler: 0}) + call WaitForAssert({-> assert_match('^-- More --', term_getline(buf, 10))}) + call term_sendkeys(buf, "q") + call VerifyScreenDump(buf, 'Test_quit_long_message', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +" this was missing a terminating NUL +func Test_echo_string_partial() + function CountSpaces() + endfunction + call assert_equal("function('CountSpaces', [{'ccccccccccc': ['ab', 'cd'], 'aaaaaaaaaaa': v:false, 'bbbbbbbbbbbb': ''}])", string(function('CountSpaces', [#{aaaaaaaaaaa: v:false, bbbbbbbbbbbb: '', ccccccccccc: ['ab', 'cd']}]))) +endfunc + +" Test that fileinfo is shown properly when 'cmdheight' has just decreased +" due to switching tabpage and 'shortmess' doesn't contain 'o' or 'O'. +func Test_fileinfo_tabpage_cmdheight() + CheckRunVimInTerminal + + let content =<< trim END + set shortmess-=o + set shortmess-=O + set shortmess-=F + tabnew + set cmdheight=2 + tabprev + edit Xfileinfo.txt + END + + call writefile(content, 'Xtest_fileinfo_tabpage_cmdheight', 'D') + let buf = RunVimInTerminal('-S Xtest_fileinfo_tabpage_cmdheight', #{rows: 6}) + call WaitForAssert({-> assert_match('^"Xfileinfo.txt" \[New\]', term_getline(buf, 6))}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +" Message output was previously overwritten by the fileinfo display, shown +" when switching buffers. If a buffer is switched to, then a message if +" echoed, we should show the message, rather than overwriting it with +" fileinfo. +func Test_fileinfo_after_echo() + CheckScreendump + + let content =<< trim END + file a.txt + + hide edit b.txt + call setline(1, "hi") + setlocal modified + + hide buffer a.txt + + autocmd CursorHold * buf b.txt | w | echo "'b' written" + END + + call writefile(content, 'Xtest_fileinfo_after_echo') + let buf = RunVimInTerminal('-S Xtest_fileinfo_after_echo', #{rows: 6}) + call term_sendkeys(buf, ":set updatetime=50\<CR>") + call term_sendkeys(buf, "0$") + call VerifyScreenDump(buf, 'Test_fileinfo_after_echo', {}) + + call term_sendkeys(buf, ":q\<CR>") + + " clean up + call StopVimInTerminal(buf) + call delete('Xtest_fileinfo_after_echo') + call delete('b.txt') +endfunc + +func Test_cmdheight_zero() + enew + set cmdheight=0 + set showcmd + redraw! + + echo 'test echo' + call assert_equal(116, screenchar(&lines, 1)) + redraw! + + echomsg 'test echomsg' + call assert_equal(116, screenchar(&lines, 1)) + redraw! + + call feedkeys(":ls\<CR>", "xt") + call assert_equal(':ls', Screenline(&lines - 1)) + redraw! + + let char = getchar(0) + call assert_match(char, 0) + + " Check change/restore cmdheight when macro + call feedkeys("qa", "xt") + call assert_equal(0, &cmdheight) + call feedkeys("q", "xt") + call assert_equal(0, &cmdheight) + + call setline(1, 'somestring') + call feedkeys("y", "n") + %s/somestring/otherstring/gc + call assert_equal('otherstring', getline(1)) + + call feedkeys("g\<C-g>", "xt") + call assert_match( + \ 'Col 1 of 11; Line 1 of 1; Word 1 of 1', + \ Screenline(&lines)) + + " Check split behavior + for i in range(1, 10) + split + endfor + only + call assert_equal(0, &cmdheight) + + " Check that pressing ":" should not scroll a window + " Check for what patch 9.0.0115 fixes + botright 10new + call setline(1, range(12)) + 7 + call feedkeys(":\"\<C-R>=line('w0')\<CR>\<CR>", "xt") + call assert_equal('"1', @:) + + bwipe! + bwipe! + set cmdheight& + set showcmd& + tabnew + tabonly +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_method.vim b/test/old/testdir/test_method.vim new file mode 100644 index 0000000000..88dbbd7bf4 --- /dev/null +++ b/test/old/testdir/test_method.vim @@ -0,0 +1,174 @@ +" Tests for ->method() + +source check.vim + +func Test_list_method() + let l = [1, 2, 3] + call assert_equal([1, 2, 3, 4], [1, 2, 3]->add(4)) + eval l->assert_equal(l) + eval l->assert_equal(l, 'wrong') + eval l->assert_notequal([3, 2, 1]) + eval l->assert_notequal([3, 2, 1], 'wrong') + call assert_equal(l, l->copy()) + call assert_equal(l, l->deepcopy()) + call assert_equal(1, l->count(2)) + call assert_false(l->empty()) + call assert_true([]->empty()) + call assert_equal(579, ['123', '+', '456']->join()->eval()) + call assert_equal([1, 2, 3, 4, 5], [1, 2, 3]->extend([4, 5])) + call assert_equal([1, 3], [1, 2, 3]->filter('v:val != 2')) + call assert_equal(2, l->get(1)) + call assert_equal(1, l->index(2)) + call assert_equal([0, 1, 2, 3], [1, 2, 3]->insert(0)) + call assert_fails('eval l->items()', 'E715:') + call assert_equal('1 2 3', l->join()) + call assert_fails('eval l->keys()', 'E715:') + call assert_equal(3, l->len()) + call assert_equal([2, 3, 4], [1, 2, 3]->map('v:val + 1')) + call assert_equal(3, l->max()) + call assert_equal(1, l->min()) + call assert_equal(2, [1, 2, 3]->remove(1)) + call assert_equal([1, 2, 3, 1, 2, 3], l->repeat(2)) + call assert_equal([3, 2, 1], [1, 2, 3]->reverse()) + call assert_equal([1, 2, 3, 4], [4, 2, 3, 1]->sort()) + call assert_equal('[1, 2, 3]', l->string()) + call assert_equal(v:t_list, l->type()) + call assert_equal([1, 2, 3], [1, 1, 2, 3, 3]->uniq()) + call assert_fails('eval l->values()', 'E715:') + call assert_fails('echo []->len', 'E107:') +endfunc + +func Test_dict_method() + let d = #{one: 1, two: 2, three: 3} + + call assert_equal(d, d->copy()) + call assert_equal(d, d->deepcopy()) + call assert_equal(1, d->count(2)) + call assert_false(d->empty()) + call assert_true({}->empty()) + call assert_equal(#{one: 1, two: 2, three: 3, four: 4}, d->extend(#{four: 4})) + call assert_equal(#{one: 1, two: 2, three: 3}, d->filter('v:val != 4')) + call assert_equal(2, d->get('two')) + call assert_fails("let x = d->index(2)", 'E897:') + call assert_fails("let x = d->insert(0)", 'E899:') + call assert_true(d->has_key('two')) + call assert_equal([['one', 1], ['two', 2], ['three', 3]], d->items()) + call assert_fails("let x = d->join()", 'E714:') + call assert_equal(['one', 'two', 'three'], d->keys()) + call assert_equal(3, d->len()) + call assert_equal(#{one: 2, two: 3, three: 4}, d->map('v:val + 1')) + call assert_equal(#{one: 1, two: 2, three: 3}, d->map('v:val - 1')) + call assert_equal(3, d->max()) + call assert_equal(1, d->min()) + call assert_equal(2, d->remove("two")) + let d.two = 2 + call assert_fails('let x = d->repeat(2)', 'E731:') + call assert_fails('let x = d->reverse()', 'E1252:') + call assert_fails('let x = d->sort()', 'E686:') + call assert_equal("{'one': 1, 'two': 2, 'three': 3}", d->string()) + call assert_equal(v:t_dict, d->type()) + call assert_fails('let x = d->uniq()', 'E686:') + call assert_equal([1, 2, 3], d->values()) +endfunc + +func Test_string_method() + eval '1 2 3'->split()->assert_equal(['1', '2', '3']) + eval '1 2 3'->split()->map({i, v -> str2nr(v)})->assert_equal([1, 2, 3]) + eval 'ABC'->str2list()->assert_equal([65, 66, 67]) + eval 'ABC'->strlen()->assert_equal(3) + eval "a\rb\ec"->strtrans()->assert_equal('a^Mb^[c') + eval "aあb"->strwidth()->assert_equal(4) + eval 'abc'->substitute('b', 'x', '')->assert_equal('axc') + + eval 'abc'->printf('the %s arg')->assert_equal('the abc arg') +endfunc + +func Test_method_append() + new + eval ['one', 'two', 'three']->append(1) + call assert_equal(['', 'one', 'two', 'three'], getline(1, '$')) + + %del + let bnr = bufnr('') + wincmd w + eval ['one', 'two', 'three']->appendbufline(bnr, 1) + call assert_equal(['', 'one', 'two', 'three'], getbufline(bnr, 1, '$')) + + exe 'bwipe! ' .. bnr +endfunc + +func Test_method_funcref() + func Concat(one, two, three) + return a:one .. a:two .. a:three + endfunc + let FuncRef = function('Concat') + eval 'foo'->FuncRef('bar', 'tail')->assert_equal('foobartail') + + " not enough arguments + call assert_fails("eval 'foo'->FuncRef('bar')", 'E119:') + " too many arguments + call assert_fails("eval 'foo'->FuncRef('bar', 'tail', 'four')", 'E118:') + + let Partial = function('Concat', ['two']) + eval 'one'->Partial('three')->assert_equal('onetwothree') + + " not enough arguments + call assert_fails("eval 'one'->Partial()", 'E119:') + " too many arguments + call assert_fails("eval 'one'->Partial('three', 'four')", 'E118:') + + delfunc Concat +endfunc + +func Test_method_float() + CheckFeature float + eval 1.234->string()->assert_equal('1.234') + eval -1.234->string()->assert_equal('-1.234') +endfunc + +func Test_method_syntax() + eval [1, 2, 3] ->sort( ) + eval [1, 2, 3] + \ ->sort( + \ ) + call assert_fails('eval [1, 2, 3]-> sort()', 'E15:') + call assert_fails('eval [1, 2, 3]->sort ()', 'E274:') + call assert_fails('eval [1, 2, 3]-> sort ()', 'E15:') +endfunc + +func Test_method_lambda() + eval "text"->{x -> x .. " extended"}()->assert_equal('text extended') + eval "text"->{x, y -> x .. " extended " .. y}('more')->assert_equal('text extended more') + + call assert_fails('eval "text"->{x -> x .. " extended"} ()', 'E274:') + + " todo: lambda accepts more arguments than it consumes + " call assert_fails('eval "text"->{x -> x .. " extended"}("more")', 'E99:') + + " Nvim doesn't include test_refcount(). + " let l = [1, 2, 3] + " eval l->{x -> x}() + " call assert_equal(1, test_refcount(l)) +endfunc + +func Test_method_not_supported() + call assert_fails('eval 123->changenr()', 'E276:') + call assert_fails('echo "abc"->invalidfunc()', 'E117:') + " Test for too many or too few arguments to a method + call assert_fails('let n="abc"->len(2)', 'E118:') + call assert_fails('let n=10->setwinvar()', 'E119:') +endfunc + +" Test for passing optional arguments to methods +func Test_method_args() + let v:errors = [] + let n = 10->assert_inrange(1, 5, "Test_assert_inrange") + if v:errors[0] !~ 'Test_assert_inrange' + call assert_report(v:errors[0]) + else + " Test passed + let v:errors = [] + endif +endfunc + +" vim: ts=8 sw=2 sts=2 expandtab tw=80 fdm=marker diff --git a/test/old/testdir/test_mksession.vim b/test/old/testdir/test_mksession.vim new file mode 100644 index 0000000000..d63d10b44c --- /dev/null +++ b/test/old/testdir/test_mksession.vim @@ -0,0 +1,1202 @@ +" Test for :mksession, :mkview and :loadview in latin1 encoding + +scriptencoding latin1 + +source check.vim +CheckFeature mksession + +source shared.vim +source term_util.vim + +" Test for storing global and local argument list in a session file +" This one must be done first. +func Test__mksession_arglocal() + enew | only + n a b c + new + arglocal + mksession! Xtest_mks.out + + %bwipe! + %argdelete + argglobal + source Xtest_mks.out + call assert_equal(2, winnr('$')) + call assert_equal(2, arglistid(1)) + call assert_equal(0, arglistid(2)) + + %bwipe! + %argdelete + argglobal + call delete('Xtest_mks.out') +endfunc + +func Test_mksession() + tabnew + let wrap_save = &wrap + set sessionoptions=buffers splitbelow fileencoding=latin1 + call setline(1, [ + \ 'start:', + \ 'no multibyte chAracter', + \ ' one leaDing tab', + \ ' four leadinG spaces', + \ 'two consecutive tabs', + \ 'two tabs in one line', + \ 'one multibyteCharacter', + \ 'a two multiByte characters', + \ 'A three mulTibyte characters', + \ 'short line', + \ ]) + let tmpfile = 'Xtemp' + exec 'w! ' . tmpfile + /^start: + set wrap + vsplit + norm! j16| + split + norm! j16| + split + norm! j16| + split + norm! j8| + split + norm! j8| + split + norm! j16| + split + norm! j16| + split + norm! j16| + split + norm! j$ + wincmd l + + set nowrap + /^start: + norm! j16|3zl + split + norm! j016|3zl + split + norm! j016|3zl + split + norm! j08|3zl + split + norm! j08|3zl + split + norm! j016|3zl + split + norm! j016|3zl + split + norm! j016|3zl + split + call wincol() + mksession! Xtest_mks.out + let li = filter(readfile('Xtest_mks.out'), 'v:val =~# "\\(^ *normal! [0$]\\|^ *exe ''normal!\\)"') + let expected = [ + \ 'normal! 016|', + \ 'normal! 016|', + \ 'normal! 016|', + \ 'normal! 08|', + \ 'normal! 08|', + \ 'normal! 016|', + \ 'normal! 016|', + \ 'normal! 016|', + \ 'normal! $', + \ " exe 'normal! ' . s:c . '|zs' . 16 . '|'", + \ " normal! 016|", + \ " exe 'normal! ' . s:c . '|zs' . 16 . '|'", + \ " normal! 016|", + \ " exe 'normal! ' . s:c . '|zs' . 16 . '|'", + \ " normal! 016|", + \ " exe 'normal! ' . s:c . '|zs' . 8 . '|'", + \ " normal! 08|", + \ " exe 'normal! ' . s:c . '|zs' . 8 . '|'", + \ " normal! 08|", + \ " exe 'normal! ' . s:c . '|zs' . 16 . '|'", + \ " normal! 016|", + \ " exe 'normal! ' . s:c . '|zs' . 16 . '|'", + \ " normal! 016|", + \ " exe 'normal! ' . s:c . '|zs' . 16 . '|'", + \ " normal! 016|", + \ " exe 'normal! ' . s:c . '|zs' . 16 . '|'", + \ " normal! 016|" + \ ] + call assert_equal(expected, li) + tabclose! + + call delete('Xtest_mks.out') + call delete(tmpfile) + let &wrap = wrap_save + set sessionoptions& +endfunc + +func Test_mksession_winheight() + new + set winheight=10 + set winminheight=2 + mksession! Xtest_mks.out + source Xtest_mks.out + + call delete('Xtest_mks.out') +endfunc + +func Test_mksession_large_winheight() + set winheight=999 + mksession! Xtest_mks_winheight.out + set winheight& + source Xtest_mks_winheight.out + call delete('Xtest_mks_winheight.out') +endfunc + +func Test_mksession_zero_winheight() + set winminheight=0 + edit SomeFile + split + wincmd _ + mksession! Xtest_mks_zero + set winminheight& + let text = readfile('Xtest_mks_zero')->join() + call delete('Xtest_mks_zero') + close + " check there is no divide by zero + call assert_notmatch('/ 0[^0-9]', text) +endfunc + +func Test_mksession_rtp() + if has('win32') + " TODO: fix problem with backslashes + return + endif + new + let _rtp=&rtp + " Make a real long (invalid) runtimepath value, + " that should exceed PATH_MAX (hopefully) + let newrtp=&rtp.',~'.repeat('/foobar', 1000) + let newrtp.=",".expand("$HOME")."/.vim" + let &rtp=newrtp + + " determine expected value + let expected=split(&rtp, ',') + let expected = map(expected, '"set runtimepath+=".v:val') + let expected = ['set runtimepath='] + expected + let expected = map(expected, {v,w -> substitute(w, $HOME, "~", "g")}) + + mksession! Xtest_mks.out + let &rtp=_rtp + let li = filter(readfile('Xtest_mks.out'), 'v:val =~# "runtimepath"') + call assert_equal(expected, li) + + call delete('Xtest_mks.out') +endfunc + +func Test_mksession_arglist() + %argdel + next file1 file2 file3 file4 + new + next | next + mksession! Xtest_mks.out + source Xtest_mks.out + call assert_equal(['file1', 'file2', 'file3', 'file4'], argv()) + call assert_equal(2, argidx()) + wincmd w + call assert_equal(0, argidx()) + + call delete('Xtest_mks.out') + enew | only + argdel * +endfunc + +func Test_mksession_one_buffer_two_windows() + edit Xtest1 + new Xtest2 + split + mksession! Xtest_mks.out + let lines = readfile('Xtest_mks.out') + let count1 = 0 + let count2 = 0 + let count2buf = 0 + let bufexists = 0 + for line in lines + if line =~ 'edit \f*Xtest1$' + let count1 += 1 + endif + if line =~ 'edit \f\{-}Xtest2' + let count2 += 1 + endif + if line =~ 'buffer \f\{-}Xtest2' + let count2buf += 1 + endif + if line =~ 'bufexists(fnamemodify(.*, ":p")' + let bufexists += 1 + endif + endfor + call assert_equal(1, count1, 'Xtest1 count') + call assert_equal(2, count2, 'Xtest2 count') + call assert_equal(2, count2buf, 'Xtest2 buffer count') + call assert_equal(2, bufexists) + + close + bwipe! + call delete('Xtest_mks.out') +endfunc + +func Test_mksession_lcd_multiple_tabs() + tabnew + tabnew + lcd . + tabfirst + lcd . + mksession! Xtest_mks.out + tabonly + source Xtest_mks.out + call assert_true(haslocaldir(), 'Tab 1 localdir') + tabnext 2 + call assert_true(!haslocaldir(), 'Tab 2 localdir') + tabnext 3 + call assert_true(haslocaldir(), 'Tab 3 localdir') + call delete('Xtest_mks.out') +endfunc + +" Test for tabpage-local directory +func Test_mksession_tcd_multiple_tabs() + let save_cwd = getcwd() + call mkdir('Xtopdir') + cd Xtopdir + call mkdir('Xtabdir1') + call mkdir('Xtabdir2') + call mkdir('Xtabdir3') + call mkdir('Xwindir1') + call mkdir('Xwindir2') + call mkdir('Xwindir3') + tcd Xtabdir1 + botright new + wincmd t + lcd ../Xwindir1 + tabnew + tcd ../Xtabdir2 + botright new + lcd ../Xwindir2 + tabnew + tcd ../Xtabdir3 + botright new + lcd ../Xwindir3 + tabfirst + 1wincmd w + mksession! Xtest_mks.out + only | tabonly + source Xtest_mks.out + call assert_equal('Xtabdir1', fnamemodify(getcwd(-1, 1), ':t')) + call assert_equal('Xwindir1', fnamemodify(getcwd(1, 1), ':t')) + call assert_equal('Xtabdir1', fnamemodify(getcwd(2, 1), ':t')) + call assert_equal('Xtabdir2', fnamemodify(getcwd(-1, 2), ':t')) + call assert_equal('Xtabdir2', fnamemodify(getcwd(1, 2), ':t')) + call assert_equal('Xwindir2', fnamemodify(getcwd(2, 2), ':t')) + call assert_equal('Xtabdir3', fnamemodify(getcwd(-1, 3), ':t')) + call assert_equal('Xtabdir3', fnamemodify(getcwd(1, 3), ':t')) + call assert_equal('Xwindir3', fnamemodify(getcwd(2, 3), ':t')) + %bwipe + call chdir(save_cwd) + call delete("Xtopdir", "rf") +endfunc + +func Test_mksession_blank_tabs() + tabnew + tabnew + tabnew + tabnext 3 + mksession! Xtest_mks.out + tabnew + tabnew + tabnext 2 + source Xtest_mks.out + call assert_equal(4, tabpagenr('$'), 'session restore should restore number of tabs') + call assert_equal(3, tabpagenr(), 'session restore should restore the active tab') + call delete('Xtest_mks.out') +endfunc + +func Test_mksession_buffer_count() + set hidden + + " Edit exactly three files in the current session. + %bwipe! + e Xfoo | tabe Xbar | tabe Xbaz + tabdo write + mksession! Xtest_mks.out + + " Verify that loading the session does not create additional buffers. + %bwipe! + source Xtest_mks.out + call assert_equal(3, len(getbufinfo())) + + " Clean up. + call delete('Xfoo') + call delete('Xbar') + call delete('Xbaz') + call delete('Xtest_mks.out') + %bwipe! + set hidden& +endfunc + +func Test_mksession_buffer_order() + %bwipe! + e Xfoo | e Xbar | e Xbaz | e Xqux + bufdo write + mksession! Xtest_mks.out + + " Verify that loading the session preserves order of buffers + %bwipe! + source Xtest_mks.out + + let s:buf_info = getbufinfo() + call assert_true(s:buf_info[0]['name'] =~# 'Xfoo$') + call assert_true(s:buf_info[1]['name'] =~# 'Xbar$') + call assert_true(s:buf_info[2]['name'] =~# 'Xbaz$') + call assert_true(s:buf_info[3]['name'] =~# 'Xqux$') + + " Clean up. + call delete('Xfoo') + call delete('Xbar') + call delete('Xbaz') + call delete('Xqux') + call delete('Xtest_mks.out') + %bwipe! +endfunc + +if has('extra_search') + +func Test_mksession_hlsearch() + set hlsearch + mksession! Xtest_mks.out + nohlsearch + source Xtest_mks.out + call assert_equal(1, v:hlsearch, 'session should restore search highlighting state') + nohlsearch + mksession! Xtest_mks.out + source Xtest_mks.out + call assert_equal(0, v:hlsearch, 'session should restore search highlighting state') + call delete('Xtest_mks.out') +endfunc + +endif + + +func Test_mksession_blank_windows() + split + split + split + 3 wincmd w + mksession! Xtest_mks.out + split + split + 2 wincmd w + source Xtest_mks.out + call assert_equal(4, winnr('$'), 'session restore should restore number of windows') + call assert_equal(3, winnr(), 'session restore should restore the active window') + call delete('Xtest_mks.out') +endfunc + +if has('terminal') + +func Test_mksession_terminal_shell() + CheckFeature quickfix + + terminal + mksession! Xtest_mks.out + let lines = readfile('Xtest_mks.out') + let term_cmd = '' + for line in lines + if line =~ '^terminal' + let term_cmd = line + elseif line =~ 'badd.*' . &shell + call assert_report('unexpected shell line: ' . line) + endif + endfor + call assert_match('terminal ++curwin ++cols=\d\+ ++rows=\d\+\s*.*$', term_cmd) + + call StopShellInTerminal(bufnr('%')) + call delete('Xtest_mks.out') +endfunc + +func Test_mksession_terminal_no_restore_cmdarg() + terminal ++norestore + mksession! Xtest_mks.out + let lines = readfile('Xtest_mks.out') + let term_cmd = '' + for line in lines + if line =~ '^terminal' + call assert_report('session must not restore terminal') + endif + endfor + + call StopShellInTerminal(bufnr('%')) + call delete('Xtest_mks.out') +endfunc + +func Test_mksession_terminal_no_restore_funcarg() + call term_start(&shell, {'norestore': 1}) + mksession! Xtest_mks.out + let lines = readfile('Xtest_mks.out') + let term_cmd = '' + for line in lines + if line =~ '^terminal' + call assert_report('session must not restore terminal') + endif + endfor + + call StopShellInTerminal(bufnr('%')) + call delete('Xtest_mks.out') +endfunc + +func Test_mksession_terminal_no_restore_func() + terminal + call term_setrestore(bufnr('%'), 'NONE') + mksession! Xtest_mks.out + let lines = readfile('Xtest_mks.out') + let term_cmd = '' + for line in lines + if line =~ '^terminal' + call assert_report('session must not restore terminal') + endif + endfor + + call StopShellInTerminal(bufnr('%')) + call delete('Xtest_mks.out') +endfunc + +func Test_mksession_terminal_no_ssop() + terminal + set sessionoptions-=terminal + mksession! Xtest_mks.out + let lines = readfile('Xtest_mks.out') + let term_cmd = '' + for line in lines + if line =~ '^terminal' + call assert_report('session must not restore terminal') + endif + endfor + + call StopShellInTerminal(bufnr('%')) + call delete('Xtest_mks.out') + set sessionoptions& +endfunc + +func Test_mksession_terminal_restore_other() + CheckFeature quickfix + + terminal + eval bufnr('%')->term_setrestore('other') + mksession! Xtest_mks.out + let lines = readfile('Xtest_mks.out') + let term_cmd = '' + for line in lines + if line =~ '^terminal' + let term_cmd = line + endif + endfor + call assert_match('terminal ++curwin ++cols=\d\+ ++rows=\d\+.*other', term_cmd) + + call StopShellInTerminal(bufnr('%')) + call delete('Xtest_mks.out') +endfunc + +endif " has('terminal') + +func Test_mkview_open_folds() + enew! + + call append(0, ['a', 'b', 'c']) + 1,3fold + write! Xtestfile + + call assert_notequal(-1, foldclosed(1)) + call assert_notequal(-1, foldclosed(2)) + call assert_notequal(-1, foldclosed(3)) + + " Save the view with folds closed + mkview! Xtestview + + " zR affects 'foldlevel', make sure the option is applied after the folds + " have been recreated. + " Open folds to ensure they get closed when restoring the view + normal zR + + call assert_equal(-1, foldclosed(1)) + call assert_equal(-1, foldclosed(2)) + call assert_equal(-1, foldclosed(3)) + + source Xtestview + + call assert_notequal(-1, foldclosed(1)) + call assert_notequal(-1, foldclosed(2)) + call assert_notequal(-1, foldclosed(3)) + + call delete('Xtestview') + call delete('Xtestfile') + %bwipe +endfunc + +func Test_mkview_no_balt() + edit Xtestfile1 + edit Xtestfile2 + + mkview! Xtestview + bdelete Xtestfile1 + + source Xtestview + call assert_equal(0, buflisted('Xtestfile1')) + + call delete('Xtestview') + %bwipe +endfunc + +func Test_mksession_no_balt() + edit Xtestfile1 + edit Xtestfile2 + + bdelete Xtestfile1 + mksession! Xtestview + + source Xtestview + call assert_equal(0, buflisted('Xtestfile1')) + + call delete('Xtestview') + %bwipe +endfunc + +" Test :mkview with a file argument. +func Test_mkview_file() + " Create a view with line number and a fold. + help :mkview + set number + norm! V}zf0 + let pos = getpos('.') + let linefoldclosed1 = foldclosed('.') + mkview! Xview + set nonumber + norm! zrj + " We can close the help window, as mkview with a file name should + " generate a command to edit the file. + helpclose + + source Xview + call assert_equal(1, &number) + call assert_match('\*:mkview\*$', getline('.')) + call assert_equal(pos, getpos('.')) + call assert_equal(linefoldclosed1, foldclosed('.')) + + " Creating a view again with the same file name should fail (file + " already exists). But with a !, the previous view should be + " overwritten without error. + help :loadview + call assert_fails('mkview Xview', 'E189:') + call assert_match('\*:loadview\*$', getline('.')) + mkview! Xview + call assert_match('\*:loadview\*$', getline('.')) + + call delete('Xview') + bwipe +endfunc + +" Test :mkview and :loadview with a custom 'viewdir'. +func Test_mkview_loadview_with_viewdir() + set viewdir=Xviewdir + + help :mkview + set number + norm! V}zf + let pos = getpos('.') + let linefoldclosed1 = foldclosed('.') + mkview 1 + set nonumber + norm! zrj + + loadview 1 + + " The directory Xviewdir/ should have been created and the view + " should be stored in that directory. + call assert_equal('Xviewdir/' . + \ substitute( + \ substitute( + \ expand('%:p'), '/', '=+', 'g'), ':', '=-', 'g') . '=1.vim', + \ glob('Xviewdir/*')) + call assert_equal(1, &number) + call assert_match('\*:mkview\*$', getline('.')) + call assert_equal(pos, getpos('.')) + call assert_equal(linefoldclosed1, foldclosed('.')) + + call delete('Xviewdir', 'rf') + set viewdir& + helpclose +endfunc + +func Test_mkview_no_file_name() + new + " :mkview or :mkview {nr} should fail in a unnamed buffer. + call assert_fails('mkview', 'E32:') + call assert_fails('mkview 1', 'E32:') + + " :mkview {file} should succeed in a unnamed buffer. + mkview Xview + help + source Xview + call assert_equal('', bufname('%')) + + call delete('Xview') + %bwipe +endfunc + +func Test_mkview_loadview_jumplist() + set viewdir=Xviewdir + au BufWinLeave * silent mkview + " au BufWinEnter * silent loadview + + edit Xfile1 + call setline(1, ['a', 'bbbbbbb', 'c']) + normal j3l + call assert_equal([2, 4], getcurpos()[1:2]) + write + + edit Xfile2 + call setline(1, ['d', 'eeeeeee', 'f']) + normal j5l + call assert_equal([2, 6], getcurpos()[1:2]) + write + + edit Xfile3 + call setline(1, ['g', 'h', 'iiiii']) + normal jj3l + call assert_equal([3, 4], getcurpos()[1:2]) + write + + " The commented :au above was moved here so that :mkview (on BufWinLeave) can + " run before :loadview. This is needed because Nvim's :loadview raises E484 if + " the view can't be opened, while Vim's silently fails instead. + au BufWinEnter * silent loadview + + edit Xfile1 + call assert_equal([2, 4], getcurpos()[1:2]) + edit Xfile2 + call assert_equal([2, 6], getcurpos()[1:2]) + edit Xfile3 + call assert_equal([3, 4], getcurpos()[1:2]) + + exe "normal \<C-O>" + call assert_equal('Xfile2', expand('%')) + call assert_equal([2, 6], getcurpos()[1:2]) + exe "normal \<C-O>" + call assert_equal('Xfile1', expand('%')) + call assert_equal([2, 4], getcurpos()[1:2]) + + au! BufWinLeave + au! BufWinEnter + bwipe! + call delete('Xviewdir', 'rf') + call delete('Xfile1') + call delete('Xfile2') + call delete('Xfile3') + set viewdir& +endfunc + +" A clean session (one empty buffer, one window, and one tab) should not +" set any error messages when sourced because no commands should fail. +func Test_mksession_no_errmsg() + let v:errmsg = '' + %bwipe! + mksession! Xtest_mks.out + source Xtest_mks.out + call assert_equal('', v:errmsg) + call delete('Xtest_mks.out') +endfunc + +func Test_mksession_quote_in_filename() + if !has('unix') + " only Unix can handle this weird filename + return + endif + let v:errmsg = '' + let filename = has('win32') ? 'x''y' : 'x''y"z' + %bwipe! + split another + execute 'split' escape(filename, '"') + mksession! Xtest_mks_quoted.out + %bwipe! + source Xtest_mks_quoted.out + call assert_true(bufexists(filename)) + + %bwipe! + call delete('Xtest_mks_quoted.out') +endfunc + +" Test for storing global variables in a session file +func Test_mksession_globals() + set sessionoptions+=globals + + " create different global variables + let g:Global_string = "Sun is shining\r\n" + let g:Global_count = 100 + let g:Global_pi = 3.14 + let g:Global_neg_float = -2.68 + + mksession! Xtest_mks.out + + unlet g:Global_string + unlet g:Global_count + unlet g:Global_pi + unlet g:Global_neg_float + + source Xtest_mks.out + call assert_equal("Sun is shining\r\n", g:Global_string) + call assert_equal(100, g:Global_count) + call assert_equal(3.14, g:Global_pi) + call assert_equal(-2.68, g:Global_neg_float) + + unlet g:Global_string + unlet g:Global_count + unlet g:Global_pi + unlet g:Global_neg_float + call delete('Xtest_mks.out') + set sessionoptions& +endfunc + +" Test for changing backslash to forward slash in filenames +func Test_mksession_slash() + if exists('+shellslash') + throw 'Skipped: cannot use backslash in file name' + endif + enew + %bwipe! + e a\\b\\c + mksession! Xtest_mks1.out + set sessionoptions+=slash + mksession! Xtest_mks2.out + + %bwipe! + source Xtest_mks1.out + call assert_equal('a/b/c', bufname('')) + %bwipe! + source Xtest_mks2.out + call assert_equal('a/b/c', bufname('')) + + %bwipe! + call delete('Xtest_mks1.out') + call delete('Xtest_mks2.out') + set sessionoptions& +endfunc + +" Test for changing directory to the session file directory +func Test_mksession_sesdir() + let save_cwd = getcwd() + call mkdir('Xproj') + mksession! Xproj/Xtest_mks1.out + set sessionoptions-=curdir + set sessionoptions+=sesdir + mksession! Xproj/Xtest_mks2.out + + source Xproj/Xtest_mks1.out + call assert_equal('testdir', fnamemodify(getcwd(), ':t')) + source Xproj/Xtest_mks2.out + call assert_equal('Xproj', fnamemodify(getcwd(), ':t')) + call chdir(save_cwd) + %bwipe + + set sessionoptions& + call delete('Xproj', 'rf') +endfunc + +" Test for saving and restoring the tab-local working directory when there is +" only a single tab and 'tabpages' is not in 'sessionoptions'. +func Test_mksession_tcd_single_tabs() + only | tabonly + + let save_cwd = getcwd() + set sessionoptions-=tabpages + set sessionoptions+=curdir + call mkdir('Xtopdir1') + call mkdir('Xtopdir2') + + " There are two tab pages, the current one has local cwd set to 'Xtopdir2'. + exec 'tcd ' .. save_cwd .. '/Xtopdir1' + tabnew + exec 'tcd ' .. save_cwd .. '/Xtopdir2' + mksession! Xtest_tcd_single + + source Xtest_tcd_single + " call assert_equal(2, haslocaldir()) + call assert_equal(1, haslocaldir(-1)) + call assert_equal('Xtopdir2', fnamemodify(getcwd(-1, 0), ':t')) + %bwipe + + set sessionoptions& + call chdir(save_cwd) + call delete('Xtopdir1', 'rf') + call delete('Xtopdir2', 'rf') +endfunc + +" Test for storing the 'lines' and 'columns' settings +func Test_mksession_resize() + mksession! Xtest_mks1.out + set sessionoptions+=resize + mksession! Xtest_mks2.out + + let lines = readfile('Xtest_mks1.out') + let found_resize = v:false + for line in lines + if line =~ '^set lines=' + let found_resize = v:true + break + endif + endfor + call assert_false(found_resize) + let lines = readfile('Xtest_mks2.out') + let found_resize = v:false + for line in lines + if line =~ '^set lines=' + let found_resize = v:true + break + endif + endfor + call assert_true(found_resize) + + call delete('Xtest_mks1.out') + call delete('Xtest_mks2.out') + set sessionoptions& +endfunc + +" Test for mksession with a named scratch buffer +func Test_mksession_scratch() + enew | only + file Xscratch + set buftype=nofile + mksession! Xtest_mks.out + %bwipe + source Xtest_mks.out + call assert_equal('Xscratch', bufname('')) + call assert_equal('nofile', &buftype) + %bwipe + call delete('Xtest_mks.out') +endfunc + +" Test for mksession with fold options +func Test_mksession_foldopt() + set sessionoptions-=options + set sessionoptions+=folds + new + setlocal foldenable + setlocal foldmethod=expr + setlocal foldmarker=<<<,>>> + setlocal foldignore=% + setlocal foldlevel=2 + setlocal foldminlines=10 + setlocal foldnestmax=15 + mksession! Xtest_mks.out + close + %bwipe + + source Xtest_mks.out + call assert_true(&foldenable) + call assert_equal('expr', &foldmethod) + call assert_equal('<<<,>>>', &foldmarker) + call assert_equal('%', &foldignore) + call assert_equal(2, &foldlevel) + call assert_equal(10, &foldminlines) + call assert_equal(15, &foldnestmax) + + close + %bwipe + set sessionoptions& + call delete('Xtest_mks.out') +endfunc + +" Test for mksession with "help" but not "options" in 'sessionoptions' +func Test_mksession_help_noopt() + set sessionoptions-=options + set sessionoptions+=help + help + let fname = expand('%') + mksession! Xtest_mks.out + bwipe + + source Xtest_mks.out + call assert_equal('help', &buftype) + call assert_equal('help', &filetype) + call assert_equal(fname, expand('%')) + call assert_false(&modifiable) + call assert_true(&readonly) + + helpclose + help index + let fname = expand('%') + mksession! Xtest_mks.out + bwipe + + source Xtest_mks.out + call assert_equal('help', &buftype) + call assert_equal(fname, expand('%')) + + call delete('Xtest_mks.out') + set sessionoptions& +endfunc + +" Test for mksession with window position +func Test_mksession_winpos() + if !has('gui_running') + " Only applicable in GUI Vim + return + endif + set sessionoptions+=winpos + mksession! Xtest_mks.out + let found_winpos = v:false + let lines = readfile('Xtest_mks.out') + for line in lines + if line =~ '^winpos ' + let found_winpos = v:true + break + endif + endfor + call assert_true(found_winpos) + call delete('Xtest_mks.out') + set sessionoptions& +endfunc + +" Test for mksession without options restores winminheight +func Test_mksession_winminheight() + set sessionoptions-=options + split + mksession! Xtest_mks.out + let found_restore = 0 + let lines = readfile('Xtest_mks.out') + for line in lines + if line =~ '= s:save_winmin\(width\|height\)' + let found_restore += 1 + endif + endfor + call assert_equal(2, found_restore) + call delete('Xtest_mks.out') + close + set sessionoptions& +endfunc + +" Test for mksession with and without options restores shortmess +func Test_mksession_shortmess() + " Without options + set sessionoptions-=options + split + mksession! Xtest_mks.out + let found_save = 0 + let found_restore = 0 + let lines = readfile('Xtest_mks.out') + for line in lines + let line = trim(line) + + if line ==# 'let s:shortmess_save = &shortmess' + let found_save += 1 + endif + + if found_save !=# 0 && line ==# 'let &shortmess = s:shortmess_save' + let found_restore += 1 + endif + endfor + call assert_equal(1, found_save) + call assert_equal(1, found_restore) + call delete('Xtest_mks.out') + close + set sessionoptions& + + " With options + set sessionoptions+=options + split + mksession! Xtest_mks.out + let found_restore = 0 + let lines = readfile('Xtest_mks.out') + for line in lines + if line =~# 's:shortmess_save' + let found_restore += 1 + endif + endfor + call assert_equal(0, found_restore) + call delete('Xtest_mks.out') + close + set sessionoptions& +endfunc + +" Test that when Vim loading session has 'A' in 'shortmess' it does not +" complain about an existing swapfile. +func Test_mksession_shortmess_with_A() + edit Xtestfile + write + let fname = swapname('%') + let cont = readblob(fname) + set sessionoptions-=options + mksession Xtestsession + bwipe! + + " Recreate the swap file to pretend the file is being edited + call writefile(cont, fname, 'D') + set shortmess+=A + source Xtestsession + + set shortmess& + set sessionoptions& + call delete('Xtestsession') + call delete('Xtestfile') +endfunc + +" Test for mksession with 'compatible' option +func Test_mksession_compatible() + throw 'skipped: Nvim does not support "compatible" option' + mksession! Xtest_mks1.out + set compatible + mksession! Xtest_mks2.out + set nocp + + let test_success = v:false + let lines = readfile('Xtest_mks1.out') + for line in lines + if line =~ '^if &cp | set nocp | endif' + let test_success = v:true + break + endif + endfor + call assert_true(test_success) + + let test_success = v:false + let lines = readfile('Xtest_mks2.out') + for line in lines + if line =~ '^if !&cp | set cp | endif' + let test_success = v:true + break + endif + endfor + call assert_true(test_success) + + call delete('Xtest_mks1.out') + call delete('Xtest_mks2.out') + set compatible& + set sessionoptions& +endfunc + +func s:ClearMappings() + mapclear + omapclear + mapclear! + lmapclear + tmapclear +endfunc + +func Test_mkvimrc() + let entries = [ + \ ['', 'nothing', '<Nop>'], + \ ['n', 'normal', 'NORMAL'], + \ ['v', 'visual', 'VISUAL'], + \ ['s', 'select', 'SELECT'], + \ ['x', 'visualonly', 'VISUALONLY'], + \ ['o', 'operator', 'OPERATOR'], + \ ['i', 'insert', 'INSERT'], + \ ['l', 'lang', 'LANG'], + \ ['c', 'command', 'COMMAND'], + \ ['t', 'terminal', 'TERMINAL'], + \ ] + for entry in entries + exe entry[0] .. 'map ' .. entry[1] .. ' ' .. entry[2] + endfor + + mkvimrc Xtestvimrc + + call s:ClearMappings() + for entry in entries + call assert_equal('', maparg(entry[1], entry[0])) + endfor + + source Xtestvimrc + + for entry in entries + call assert_equal(entry[2], maparg(entry[1], entry[0])) + endfor + + call s:ClearMappings() + + " the 'pastetoggle', 'wildchar' and 'wildcharm' option values should be + " stored as key names in the vimrc file + " set pastetoggle=<F5> + set wildchar=<F6> + set wildcharm=<F7> + call assert_fails('mkvimrc Xtestvimrc') + mkvimrc! Xtestvimrc + " call assert_notequal(-1, index(readfile('Xtestvimrc'), 'set pastetoggle=<F5>')) + call assert_notequal(-1, index(readfile('Xtestvimrc'), 'set wildchar=<F6>')) + call assert_notequal(-1, index(readfile('Xtestvimrc'), 'set wildcharm=<F7>')) + " set pastetoggle& wildchar& wildcharm& + set wildchar& wildcharm& + + call delete('Xtestvimrc') +endfunc + +func Test_scrolloff() + set sessionoptions+=localoptions + setlocal so=1 siso=1 + mksession! Xtest_mks.out + setlocal so=-1 siso=-1 + source Xtest_mks.out + call assert_equal(1, &l:so) + call assert_equal(1, &l:siso) + call delete('Xtest_mks.out') + setlocal so& siso& + set sessionoptions& +endfunc + +func Test_altfile() + edit Xone + split Xtwo + edit Xtwoalt + edit # + wincmd w + edit Xonealt + edit # + mksession! Xtest_altfile + only + bwipe Xonealt + bwipe Xtwoalt + bwipe! + source Xtest_altfile + call assert_equal('Xone', bufname()) + call assert_equal('Xonealt', bufname('#')) + wincmd w + call assert_equal('Xtwo', bufname()) + call assert_equal('Xtwoalt', bufname('#')) + only + bwipe! + call delete('Xtest_altfile') +endfunc + +" Test for creating views with manual folds +func Test_mkview_manual_fold() + call writefile(range(1,10), 'Xfile') + new Xfile + " create recursive folds + 5,6fold + 4,7fold + mkview Xview + normal zE + source Xview + call assert_equal([-1, 4, 4, 4, 4, -1], [foldclosed(3), foldclosed(4), + \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) + " open one level of fold + 4foldopen + mkview! Xview + normal zE + source Xview + call assert_equal([-1, -1, 5, 5, -1, -1], [foldclosed(3), foldclosed(4), + \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) + " open all the folds + %foldopen! + mkview! Xview + normal zE + source Xview + call assert_equal([-1, -1, -1, -1, -1, -1], [foldclosed(3), foldclosed(4), + \ foldclosed(5), foldclosed(6), foldclosed(7), foldclosed(8)]) + call delete('Xfile') + call delete('Xview') + bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_mksession_utf8.vim b/test/old/testdir/test_mksession_utf8.vim new file mode 100644 index 0000000000..4e593cc21a --- /dev/null +++ b/test/old/testdir/test_mksession_utf8.vim @@ -0,0 +1,105 @@ +" Test for :mksession, :mkview and :loadview in utf-8 encoding + +set encoding=utf-8 +scriptencoding utf-8 + +source check.vim +CheckFeature mksession + +func Test_mksession_utf8() + tabnew + let wrap_save = &wrap + set sessionoptions=buffers splitbelow fileencoding=utf-8 + call setline(1, [ + \ 'start:', + \ 'no multibyte chAracter', + \ ' one leaDing tab', + \ ' four leadinG spaces', + \ 'two consecutive tabs', + \ 'two tabs in one line', + \ 'one … multibyteCharacter', + \ 'a “b” two multiByte characters', + \ '“c”1€ three mulTibyte characters' + \ ]) + let tmpfile = tempname() + exec 'w! ' . tmpfile + /^start: + set wrap + vsplit + norm! j16| + split + norm! j16| + split + norm! j16| + split + norm! j8| + split + norm! j8| + split + norm! j16| + split + norm! j16| + split + norm! j16| + wincmd l + + set nowrap + /^start: + norm! j16|3zl + split + norm! j016|3zl + split + norm! j016|3zl + split + norm! j08|3zl + split + norm! j08|3zl + split + norm! j016|3zl + split + norm! j016|3zl + split + norm! j016|3zl + split + call wincol() + mksession! test_mks.out + let li = filter(readfile('test_mks.out'), 'v:val =~# "\\(^ *normal! 0\\|^ *exe ''normal!\\)"') + let expected =<< trim [DATA] + normal! 016| + normal! 016| + normal! 016| + normal! 08| + normal! 08| + normal! 016| + normal! 016| + normal! 016| + exe 'normal! ' . s:c . '|zs' . 16 . '|' + normal! 016| + exe 'normal! ' . s:c . '|zs' . 16 . '|' + normal! 016| + exe 'normal! ' . s:c . '|zs' . 16 . '|' + normal! 016| + exe 'normal! ' . s:c . '|zs' . 8 . '|' + normal! 08| + exe 'normal! ' . s:c . '|zs' . 8 . '|' + normal! 08| + exe 'normal! ' . s:c . '|zs' . 16 . '|' + normal! 016| + exe 'normal! ' . s:c . '|zs' . 16 . '|' + normal! 016| + exe 'normal! ' . s:c . '|zs' . 16 . '|' + normal! 016| + exe 'normal! ' . s:c . '|zs' . 16 . '|' + normal! 016| + [DATA] + + call assert_equal(expected, li) + tabclose! + + call delete('test_mks.out') + call delete(tmpfile) + let &wrap = wrap_save + set sessionoptions& splitbelow& fileencoding& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_modeline.vim b/test/old/testdir/test_modeline.vim new file mode 100644 index 0000000000..487a89e038 --- /dev/null +++ b/test/old/testdir/test_modeline.vim @@ -0,0 +1,378 @@ +" Tests for parsing the modeline. + +source check.vim + +func Test_modeline_invalid() + " This was reading allocated memory in the past. + call writefile(['vi:0', 'nothing'], 'Xmodeline') + let modeline = &modeline + set modeline + call assert_fails('split Xmodeline', 'E518:') + + " Missing end colon (ignored). + call writefile(['// vim: set ts=2'], 'Xmodeline') + edit Xmodeline_version + call assert_equal(8, &ts) + bwipe! + + " Missing colon at beginning (ignored). + call writefile(['// vim set ts=2:'], 'Xmodeline') + edit Xmodeline_version + call assert_equal(8, &ts) + bwipe! + + " Missing space after vim (ignored). + call writefile(['// vim:ts=2:'], 'Xmodeline') + edit Xmodeline_version + call assert_equal(8, &ts) + bwipe! + + let &modeline = modeline + bwipe! + call delete('Xmodeline') +endfunc + +func Test_modeline_filetype() + call writefile(['vim: set ft=c :', 'nothing'], 'Xmodeline_filetype') + let modeline = &modeline + set modeline + filetype plugin on + split Xmodeline_filetype + call assert_equal("c", &filetype) + call assert_equal(1, b:did_ftplugin) + call assert_equal("ccomplete#Complete", &ofu) + + bwipe! + call delete('Xmodeline_filetype') + let &modeline = modeline + filetype plugin off +endfunc + +func Test_modeline_syntax() + call writefile(['vim: set syn=c :', 'nothing'], 'Xmodeline_syntax') + let modeline = &modeline + set modeline + syntax enable + split Xmodeline_syntax + call assert_equal("c", &syntax) + call assert_equal("c", b:current_syntax) + + bwipe! + call delete('Xmodeline_syntax') + let &modeline = modeline + syntax off +endfunc + +func Test_modeline_keymap() + if !has('keymap') + return + endif + call writefile(['vim: set keymap=greek :', 'nothing'], 'Xmodeline_keymap') + let modeline = &modeline + set modeline + split Xmodeline_keymap + call assert_equal("greek", &keymap) + call assert_match('greek\|grk', b:keymap_name) + + bwipe! + call delete('Xmodeline_keymap') + let &modeline = modeline + set keymap= iminsert=0 imsearch=-1 +endfunc + +func Test_modeline_version() + let modeline = &modeline + set modeline + + " Test with vim:{vers}: (version {vers} or later). + call writefile(['// vim' .. v:version .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(2, &ts) + bwipe! + + call writefile(['// vim' .. (v:version - 100) .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(2, &ts) + bwipe! + + call writefile(['// vim' .. (v:version + 100) .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(8, &ts) + bw! + + " Test with vim>{vers}: (version after {vers}). + call writefile(['// vim>' .. v:version .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(8, &ts) + bwipe! + + call writefile(['// vim>' .. (v:version - 100) .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(2, &ts) + bwipe! + + call writefile(['// vim>' .. (v:version + 100) .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(8, &ts) + bwipe! + + " Test with vim<{vers}: (version before {vers}). + call writefile(['// vim<' .. v:version .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(8, &ts) + bwipe! + + call writefile(['// vim<' .. (v:version - 100) .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(8, &ts) + bwipe! + + call writefile(['// vim<' .. (v:version + 100) .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(2, &ts) + bwipe! + + " Test with vim={vers}: (version {vers} only). + call writefile(['// vim=' .. v:version .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(2, &ts) + bwipe! + + call writefile(['// vim=' .. (v:version - 100) .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(8, &ts) + bwipe! + + call writefile(['// vim=' .. (v:version + 100) .. ': ts=2:'], 'Xmodeline_version') + edit Xmodeline_version + call assert_equal(8, &ts) + bwipe! + + let &modeline = modeline + call delete('Xmodeline_version') +endfunc + +func Test_modeline_colon() + let modeline = &modeline + set modeline + + call writefile(['// vim: set showbreak=\: ts=2: sw=2'], 'Xmodeline_colon') + edit Xmodeline_colon + + " backlash colon should become colon. + call assert_equal(':', &showbreak) + + " 'ts' should be set. + " 'sw' should be ignored because it is after the end colon. + call assert_equal(2, &ts) + call assert_equal(8, &sw) + + let &modeline = modeline + call delete('Xmodeline_colon') +endfunc + +func s:modeline_fails(what, text, error) + " Don't use CheckOption(), it would skip the whole test + " just for a single un-supported option + if !exists('+' .. a:what) + return + endif + let fname = "Xmodeline_fails_" . a:what + call writefile(['vim: set ' . a:text . ' :', 'nothing'], fname) + let modeline = &modeline + set modeline + filetype plugin on + syntax enable + call assert_fails('split ' . fname, a:error) + call assert_equal("", &filetype) + call assert_equal("", &syntax) + + bwipe! + call delete(fname) + let &modeline = modeline + filetype plugin off + syntax off +endfunc + +func Test_modeline_filetype_fails() + call s:modeline_fails('filetype', 'ft=evil$CMD', 'E474:') +endfunc + +func Test_modeline_syntax_fails() + call s:modeline_fails('syntax', 'syn=evil$CMD', 'E474:') +endfunc + +func Test_modeline_keymap_fails() + call s:modeline_fails('keymap', 'keymap=evil$CMD', 'E474:') +endfunc + +func Test_modeline_fails_always() + call s:modeline_fails('backupdir', 'backupdir=Something()', 'E520:') + call s:modeline_fails('cdpath', 'cdpath=Something()', 'E520:') + call s:modeline_fails('charconvert', 'charconvert=Something()', 'E520:') + call s:modeline_fails('completefunc', 'completefunc=Something()', 'E520:') + call s:modeline_fails('cscopeprg', 'cscopeprg=Something()', 'E520:') + call s:modeline_fails('diffexpr', 'diffexpr=Something()', 'E520:') + call s:modeline_fails('directory', 'directory=Something()', 'E520:') + call s:modeline_fails('equalprg', 'equalprg=Something()', 'E520:') + call s:modeline_fails('errorfile', 'errorfile=Something()', 'E520:') + call s:modeline_fails('exrc', 'exrc=Something()', 'E520:') + call s:modeline_fails('formatprg', 'formatprg=Something()', 'E520:') + call s:modeline_fails('fsync', 'fsync=Something()', 'E520:') + call s:modeline_fails('grepprg', 'grepprg=Something()', 'E520:') + call s:modeline_fails('helpfile', 'helpfile=Something()', 'E520:') + call s:modeline_fails('imactivatefunc', 'imactivatefunc=Something()', 'E520:') + call s:modeline_fails('imstatusfunc', 'imstatusfunc=Something()', 'E520:') + call s:modeline_fails('imstyle', 'imstyle=Something()', 'E520:') + call s:modeline_fails('keywordprg', 'keywordprg=Something()', 'E520:') + call s:modeline_fails('langmap', 'langmap=Something()', 'E520:') + call s:modeline_fails('luadll', 'luadll=Something()', 'E520:') + call s:modeline_fails('makeef', 'makeef=Something()', 'E520:') + call s:modeline_fails('makeprg', 'makeprg=Something()', 'E520:') + call s:modeline_fails('mkspellmem', 'mkspellmem=Something()', 'E520:') + call s:modeline_fails('mzschemedll', 'mzschemedll=Something()', 'E520:') + call s:modeline_fails('mzschemegcdll', 'mzschemegcdll=Something()', 'E520:') + call s:modeline_fails('modelineexpr', 'modelineexpr', 'E520:') + call s:modeline_fails('omnifunc', 'omnifunc=Something()', 'E520:') + call s:modeline_fails('operatorfunc', 'operatorfunc=Something()', 'E520:') + call s:modeline_fails('perldll', 'perldll=Something()', 'E520:') + call s:modeline_fails('printdevice', 'printdevice=Something()', 'E520:') + call s:modeline_fails('patchexpr', 'patchexpr=Something()', 'E520:') + call s:modeline_fails('printexpr', 'printexpr=Something()', 'E520:') + call s:modeline_fails('pythondll', 'pythondll=Something()', 'E520:') + call s:modeline_fails('pythonhome', 'pythonhome=Something()', 'E520:') + call s:modeline_fails('pythonthreedll', 'pythonthreedll=Something()', 'E520:') + call s:modeline_fails('pythonthreehome', 'pythonthreehome=Something()', 'E520:') + call s:modeline_fails('pyxversion', 'pyxversion=Something()', 'E520:') + call s:modeline_fails('rubydll', 'rubydll=Something()', 'E520:') + call s:modeline_fails('runtimepath', 'runtimepath=Something()', 'E520:') + call s:modeline_fails('secure', 'secure=Something()', 'E520:') + call s:modeline_fails('shell', 'shell=Something()', 'E520:') + call s:modeline_fails('shellcmdflag', 'shellcmdflag=Something()', 'E520:') + call s:modeline_fails('shellpipe', 'shellpipe=Something()', 'E520:') + call s:modeline_fails('shellquote', 'shellquote=Something()', 'E520:') + call s:modeline_fails('shellredir', 'shellredir=Something()', 'E520:') + call s:modeline_fails('shellxquote', 'shellxquote=Something()', 'E520:') + call s:modeline_fails('spellfile', 'spellfile=Something()', 'E520:') + call s:modeline_fails('spellsuggest', 'spellsuggest=Something()', 'E520:') + call s:modeline_fails('tcldll', 'tcldll=Something()', 'E520:') + call s:modeline_fails('titleold', 'titleold=Something()', 'E520:') + call s:modeline_fails('viewdir', 'viewdir=Something()', 'E520:') + call s:modeline_fails('viminfo', 'viminfo=Something()', 'E520:') + call s:modeline_fails('viminfofile', 'viminfofile=Something()', 'E520:') + call s:modeline_fails('winptydll', 'winptydll=Something()', 'E520:') + call s:modeline_fails('undodir', 'undodir=Something()', 'E520:') + " only check a few terminal options + " Skip these since nvim doesn't support termcodes as options + "call s:modeline_fails('t_AB', 't_AB=Something()', 'E520:') + "call s:modeline_fails('t_ce', 't_ce=Something()', 'E520:') + "call s:modeline_fails('t_sr', 't_sr=Something()', 'E520:') + "call s:modeline_fails('t_8b', 't_8b=Something()', 'E520:') +endfunc + +func Test_modeline_fails_modelineexpr() + call s:modeline_fails('balloonexpr', 'balloonexpr=Something()', 'E992:') + call s:modeline_fails('foldexpr', 'foldexpr=Something()', 'E992:') + call s:modeline_fails('foldtext', 'foldtext=Something()', 'E992:') + call s:modeline_fails('formatexpr', 'formatexpr=Something()', 'E992:') + call s:modeline_fails('guitablabel', 'guitablabel=Something()', 'E992:') + call s:modeline_fails('iconstring', 'iconstring=Something()', 'E992:') + call s:modeline_fails('includeexpr', 'includeexpr=Something()', 'E992:') + call s:modeline_fails('indentexpr', 'indentexpr=Something()', 'E992:') + call s:modeline_fails('rulerformat', 'rulerformat=Something()', 'E992:') + call s:modeline_fails('statusline', 'statusline=Something()', 'E992:') + call s:modeline_fails('tabline', 'tabline=Something()', 'E992:') + call s:modeline_fails('titlestring', 'titlestring=Something()', 'E992:') +endfunc + +func Test_modeline_setoption_verbose() + let modeline = &modeline + set modeline + + let lines =<< trim END + 1 vim:ts=2 + 2 two + 3 three + 4 four + 5 five + 6 six + 7 seven + 8 eight + END + call writefile(lines, 'Xmodeline') + edit Xmodeline + let info = split(execute('verbose set tabstop?'), "\n") + call assert_match('^\s*Last set from modeline line 1$', info[-1]) + bwipe! + + let lines =<< trim END + 1 one + 2 two + 3 three + 4 vim:ts=4 + 5 five + 6 six + 7 seven + 8 eight + END + call writefile(lines, 'Xmodeline') + edit Xmodeline + let info = split(execute('verbose set tabstop?'), "\n") + call assert_match('^\s*Last set from modeline line 4$', info[-1]) + bwipe! + + let lines =<< trim END + 1 one + 2 two + 3 three + 4 four + 5 five + 6 six + 7 seven + 8 vim:ts=8 + END + call writefile(lines, 'Xmodeline') + edit Xmodeline + let info = split(execute('verbose set tabstop?'), "\n") + call assert_match('^\s*Last set from modeline line 8$', info[-1]) + bwipe! + + let &modeline = modeline + call delete('Xmodeline') +endfunc + +" Test for the 'modeline' default value in compatible and non-compatible modes +" for root and non-root accounts +func Test_modeline_default() + " set compatible + " call assert_false(&modeline) + set nocompatible + call assert_equal(IsRoot() ? 0 : 1, &modeline) + " set compatible&vi + " call assert_false(&modeline) + set compatible&vim + call assert_equal(IsRoot() ? 0 : 1, &modeline) + set compatible& modeline& +endfunc + +" Some options cannot be set from the modeline when 'diff' option is set +func Test_modeline_diff_buffer() + call writefile(['vim: diff foldmethod=marker wrap'], 'Xfile') + set foldmethod& nowrap + new Xfile + call assert_equal('manual', &foldmethod) + call assert_false(&wrap) + set wrap& + call delete('Xfile') + bw +endfunc + +func Test_modeline_disable() + set modeline + call writefile(['vim: sw=2', 'vim: nomodeline', 'vim: sw=3'], 'Xmodeline_disable') + edit Xmodeline_disable + call assert_equal(2, &sw) + call delete('Xmodeline_disable') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_move.vim b/test/old/testdir/test_move.vim new file mode 100644 index 0000000000..40d75d887e --- /dev/null +++ b/test/old/testdir/test_move.vim @@ -0,0 +1,70 @@ +" Test the ":move" command. + +source check.vim +source screendump.vim + +func Test_move() + enew! + call append(0, ['line 1', 'line 2', 'line 3']) + g /^$/ delete _ + set nomodified + + move . + call assert_equal(['line 1', 'line 2', 'line 3'], getline(1, 3)) + call assert_false(&modified) + + 1,2move 0 + call assert_equal(['line 1', 'line 2', 'line 3'], getline(1, 3)) + call assert_false(&modified) + + 1,3move 3 + call assert_equal(['line 1', 'line 2', 'line 3'], getline(1, 3)) + call assert_false(&modified) + + 1move 2 + call assert_equal(['line 2', 'line 1', 'line 3'], getline(1, 3)) + call assert_true(&modified) + set nomodified + + 3move 0 + call assert_equal(['line 3', 'line 2', 'line 1'], getline(1, 3)) + call assert_true(&modified) + set nomodified + + 2,3move 0 + call assert_equal(['line 2', 'line 1', 'line 3'], getline(1, 3)) + call assert_true(&modified) + set nomodified + + call assert_fails('1,2move 1', 'E134') + call assert_fails('2,3move 2', 'E134') + call assert_fails("move -100", 'E16:') + call assert_fails("move +100", 'E16:') + call assert_fails('move', 'E16:') + call assert_fails("move 'r", 'E20:') + + %bwipeout! +endfunc + +func Test_move_undo() + CheckRunVimInTerminal + + let lines =<< trim END + call setline(1, ['First', 'Second', 'Third', 'Fourth']) + END + call writefile(lines, 'Xtest_move_undo.vim', 'D') + let buf = RunVimInTerminal('-S Xtest_move_undo.vim', #{rows: 10, cols: 60, statusoff: 2}) + + call term_sendkeys(buf, "gg:move +1\<CR>") + call VerifyScreenDump(buf, 'Test_move_undo_1', {}) + + " here the display would show the last few lines scrolled down + call term_sendkeys(buf, "u") + call term_sendkeys(buf, ":\<Esc>") + call VerifyScreenDump(buf, 'Test_move_undo_2', {}) + + call StopVimInTerminal(buf) +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_nested_function.vim b/test/old/testdir/test_nested_function.vim new file mode 100644 index 0000000000..5599655461 --- /dev/null +++ b/test/old/testdir/test_nested_function.vim @@ -0,0 +1,70 @@ +" Tests for nested functions + +source check.vim + +func NestedFunc() + func! Func1() + let g:text .= 'Func1 ' + endfunc + call Func1() + func! s:func2() + let g:text .= 's:func2 ' + endfunc + call s:func2() + func! s:_func3() + let g:text .= 's:_func3 ' + endfunc + call s:_func3() + let fn = 'Func4' + func! {fn}() + let g:text .= 'Func4 ' + endfunc + call {fn}() + let fn = 'func5' + func! s:{fn}() + let g:text .= 's:func5' + endfunc + call s:{fn}() +endfunc + +func Test_nested_functions() + let g:text = '' + call NestedFunc() + call assert_equal('Func1 s:func2 s:_func3 Func4 s:func5', g:text) +endfunction + +func Test_nested_argument() + func g:X() + let g:Y = function('sort') + endfunc + let g:Y = function('sort') + echo g:Y([], g:X()) + delfunc g:X + unlet g:Y +endfunc + +func Recurse(count) + if a:count > 0 + call Recurse(a:count - 1) + endif +endfunc + +func Test_max_nesting() + " TODO: why does this fail on Windows? Runs out of stack perhaps? + CheckNotMSWindows + + let call_depth_here = 2 + let ex_depth_here = 5 + set mfd& + + call Recurse(99 - call_depth_here) + call assert_fails('call Recurse(' . (100 - call_depth_here) . ')', 'E132:') + + set mfd=210 + call Recurse(209 - ex_depth_here) + call assert_fails('call Recurse(' . (210 - ex_depth_here) . ')', 'E169:') + + set mfd& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_normal.vim b/test/old/testdir/test_normal.vim new file mode 100644 index 0000000000..6a8c15bd48 --- /dev/null +++ b/test/old/testdir/test_normal.vim @@ -0,0 +1,4172 @@ +" Test for various Normal mode commands + +source shared.vim +source check.vim +source view_util.vim +source vim9.vim +source screendump.vim + +func Setup_NewWindow() + 10new + call setline(1, range(1,100)) +endfunc + +func MyFormatExpr() + " Adds '->$' at lines having numbers followed by trailing whitespace + for ln in range(v:lnum, v:lnum+v:count-1) + let line = getline(ln) + if getline(ln) =~# '\d\s\+$' + call setline(ln, substitute(line, '\s\+$', '', '') . '->$') + endif + endfor +endfunc + +func CountSpaces(type, ...) + " for testing operatorfunc + " will count the number of spaces + " and return the result in g:a + let sel_save = &selection + let &selection = "inclusive" + let reg_save = @@ + + if a:0 " Invoked from Visual mode, use gv command. + silent exe "normal! gvy" + elseif a:type == 'line' + silent exe "normal! '[V']y" + else + silent exe "normal! `[v`]y" + endif + let g:a = strlen(substitute(@@, '[^ ]', '', 'g')) + let &selection = sel_save + let @@ = reg_save +endfunc + +func OpfuncDummy(type, ...) + " for testing operatorfunc + let g:opt = &linebreak + + if a:0 " Invoked from Visual mode, use gv command. + silent exe "normal! gvy" + elseif a:type == 'line' + silent exe "normal! '[V']y" + else + silent exe "normal! `[v`]y" + endif + " Create a new dummy window + new + let g:bufnr = bufnr('%') +endfunc + +func Test_normal00_optrans() + new + call append(0, ['1 This is a simple test: abcd', '2 This is the second line', '3 this is the third line']) + 1 + exe "norm! Sfoobar\<esc>" + call assert_equal(['foobar', '2 This is the second line', '3 this is the third line', ''], getline(1,'$')) + 2 + exe "norm! $vbsone" + call assert_equal(['foobar', '2 This is the second one', '3 this is the third line', ''], getline(1,'$')) + norm! VS Second line here + call assert_equal(['foobar', ' Second line here', '3 this is the third line', ''], getline(1, '$')) + %d + call append(0, ['4 This is a simple test: abcd', '5 This is the second line', '6 this is the third line']) + call append(0, ['1 This is a simple test: abcd', '2 This is the second line', '3 this is the third line']) + + 1 + norm! 2D + call assert_equal(['3 this is the third line', '4 This is a simple test: abcd', '5 This is the second line', '6 this is the third line', ''], getline(1,'$')) + " Nvim: no "#" flag in 'cpoptions'. + " set cpo+=# + " norm! 4D + " call assert_equal(['', '4 This is a simple test: abcd', '5 This is the second line', '6 this is the third line', ''], getline(1,'$')) + + " clean up + set cpo-=# + bw! +endfunc + +func Test_normal01_keymodel() + call Setup_NewWindow() + " Test 1: depending on 'keymodel' <s-down> does something different + 50 + call feedkeys("V\<S-Up>y", 'tx') + call assert_equal(['47', '48', '49', '50'], getline("'<", "'>")) + set keymodel=startsel + 50 + call feedkeys("V\<S-Up>y", 'tx') + call assert_equal(['49', '50'], getline("'<", "'>")) + " Start visual mode when keymodel = startsel + 50 + call feedkeys("\<S-Up>y", 'tx') + call assert_equal(['49', '5'], getreg(0, 0, 1)) + " Use the different Shift special keys + 50 + call feedkeys("\<S-Right>\<S-Left>\<S-Up>\<S-Down>\<S-Home>\<S-End>y", 'tx') + call assert_equal(['50'], getline("'<", "'>")) + call assert_equal(['50', ''], getreg(0, 0, 1)) + + " Do not start visual mode when keymodel= + set keymodel= + 50 + call feedkeys("\<S-Up>y$", 'tx') + call assert_equal(['42'], getreg(0, 0, 1)) + " Stop visual mode when keymodel=stopsel + set keymodel=stopsel + 50 + call feedkeys("Vkk\<Up>yy", 'tx') + call assert_equal(['47'], getreg(0, 0, 1)) + + set keymodel= + 50 + call feedkeys("Vkk\<Up>yy", 'tx') + call assert_equal(['47', '48', '49', '50'], getreg(0, 0, 1)) + + " Test for using special keys to start visual selection + %d + call setline(1, ['red fox tail', 'red fox tail', 'red fox tail']) + set keymodel=startsel + " Test for <S-PageUp> and <S-PageDown> + call cursor(1, 1) + call feedkeys("\<S-PageDown>y", 'xt') + call assert_equal([0, 1, 1, 0], getpos("'<")) + call assert_equal([0, 3, 1, 0], getpos("'>")) + call feedkeys("Gz\<CR>8|\<S-PageUp>y", 'xt') + call assert_equal([0, 2, 1, 0], getpos("'<")) + call assert_equal([0, 3, 8, 0], getpos("'>")) + " Test for <S-C-Home> and <S-C-End> + call cursor(2, 12) + call feedkeys("\<S-C-Home>y", 'xt') + call assert_equal([0, 1, 1, 0], getpos("'<")) + call assert_equal([0, 2, 12, 0], getpos("'>")) + call cursor(1, 4) + call feedkeys("\<S-C-End>y", 'xt') + call assert_equal([0, 1, 4, 0], getpos("'<")) + call assert_equal([0, 3, 13, 0], getpos("'>")) + " Test for <S-C-Left> and <S-C-Right> + call cursor(2, 5) + call feedkeys("\<S-C-Right>y", 'xt') + call assert_equal([0, 2, 5, 0], getpos("'<")) + call assert_equal([0, 2, 9, 0], getpos("'>")) + call cursor(2, 9) + call feedkeys("\<S-C-Left>y", 'xt') + call assert_equal([0, 2, 5, 0], getpos("'<")) + call assert_equal([0, 2, 9, 0], getpos("'>")) + + set keymodel& + + " clean up + bw! +endfunc + +func Test_normal03_join() + " basic join test + call Setup_NewWindow() + 50 + norm! VJ + call assert_equal('50 51', getline('.')) + $ + norm! J + call assert_equal('100', getline('.')) + $ + norm! V9-gJ + call assert_equal('919293949596979899100', getline('.')) + call setline(1, range(1,100)) + $ + :j 10 + call assert_equal('100', getline('.')) + call assert_beeps('normal GVJ') + " clean up + bw! +endfunc + +" basic filter test +func Test_normal04_filter() + " only test on non windows platform + CheckNotMSWindows + call Setup_NewWindow() + 1 + call feedkeys("!!sed -e 's/^/| /'\n", 'tx') + call assert_equal('| 1', getline('.')) + 90 + :sil :!echo one + call feedkeys('.', 'tx') + call assert_equal('| 90', getline('.')) + 95 + set cpo+=! + " 2 <CR>, 1: for executing the command, + " 2: clear hit-enter-prompt + call feedkeys("!!\n", 'tx') + call feedkeys(":!echo one\n\n", 'tx') + call feedkeys(".", 'tx') + call assert_equal('one', getline('.')) + set cpo-=! + bw! +endfunc + +func Test_normal05_formatexpr() + " basic formatexpr test + call Setup_NewWindow() + %d_ + call setline(1, ['here: 1 ', '2', 'here: 3 ', '4', 'not here: ']) + 1 + set formatexpr=MyFormatExpr() + norm! gqG + call assert_equal(['here: 1->$', '2', 'here: 3->$', '4', 'not here: '], getline(1,'$')) + set formatexpr= + bw! +endfunc + +func Test_normal05_formatexpr_newbuf() + " Edit another buffer in the 'formatexpr' function + new + func! Format() + edit another + endfunc + set formatexpr=Format() + norm gqG + bw! + set formatexpr= +endfunc + +func Test_normal05_formatexpr_setopt() + " Change the 'formatexpr' value in the function + new + func! Format() + set formatexpr= + endfunc + set formatexpr=Format() + norm gqG + bw! + set formatexpr= +endfunc + +" When 'formatexpr' returns non-zero, internal formatting is used. +func Test_normal_formatexpr_returns_nonzero() + new + call setline(1, ['one', 'two']) + func! Format() + return 1 + endfunc + setlocal formatexpr=Format() + normal VGgq + call assert_equal(['one two'], getline(1, '$')) + + setlocal formatexpr= + delfunc Format + bwipe! +endfunc + +" Test for using a script-local function for 'formatexpr' +func Test_formatexpr_scriptlocal_func() + func! s:Format() + let g:FormatArgs = [v:lnum, v:count] + endfunc + set formatexpr=s:Format() + call assert_equal(expand('<SID>') .. 'Format()', &formatexpr) + call assert_equal(expand('<SID>') .. 'Format()', &g:formatexpr) + new | only + call setline(1, range(1, 40)) + let g:FormatArgs = [] + normal! 2GVjgq + call assert_equal([2, 2], g:FormatArgs) + bw! + set formatexpr=<SID>Format() + call assert_equal(expand('<SID>') .. 'Format()', &formatexpr) + call assert_equal(expand('<SID>') .. 'Format()', &g:formatexpr) + new | only + call setline(1, range(1, 40)) + let g:FormatArgs = [] + normal! 4GVjgq + call assert_equal([4, 2], g:FormatArgs) + bw! + let &formatexpr = 's:Format()' + call assert_equal(expand('<SID>') .. 'Format()', &g:formatexpr) + new | only + call setline(1, range(1, 40)) + let g:FormatArgs = [] + normal! 6GVjgq + call assert_equal([6, 2], g:FormatArgs) + bw! + let &formatexpr = '<SID>Format()' + call assert_equal(expand('<SID>') .. 'Format()', &g:formatexpr) + new | only + call setline(1, range(1, 40)) + let g:FormatArgs = [] + normal! 8GVjgq + call assert_equal([8, 2], g:FormatArgs) + bw! + setlocal formatexpr= + setglobal formatexpr=s:Format() + call assert_equal(expand('<SID>') .. 'Format()', &g:formatexpr) + call assert_equal('', &formatexpr) + new + call assert_equal(expand('<SID>') .. 'Format()', &formatexpr) + call setline(1, range(1, 40)) + let g:FormatArgs = [] + normal! 10GVjgq + call assert_equal([10, 2], g:FormatArgs) + bw! + setglobal formatexpr=<SID>Format() + call assert_equal(expand('<SID>') .. 'Format()', &g:formatexpr) + call assert_equal('', &formatexpr) + new + call assert_equal(expand('<SID>') .. 'Format()', &formatexpr) + call setline(1, range(1, 40)) + let g:FormatArgs = [] + normal! 12GVjgq + call assert_equal([12, 2], g:FormatArgs) + bw! + let &g:formatexpr = 's:Format()' + call assert_equal(expand('<SID>') .. 'Format()', &g:formatexpr) + call assert_equal('', &formatexpr) + new + call assert_equal(expand('<SID>') .. 'Format()', &formatexpr) + call setline(1, range(1, 40)) + let g:FormatArgs = [] + normal! 14GVjgq + call assert_equal([14, 2], g:FormatArgs) + bw! + let &g:formatexpr = '<SID>Format()' + call assert_equal(expand('<SID>') .. 'Format()', &g:formatexpr) + call assert_equal('', &formatexpr) + new + call assert_equal(expand('<SID>') .. 'Format()', &formatexpr) + call setline(1, range(1, 40)) + let g:FormatArgs = [] + normal! 16GVjgq + call assert_equal([16, 2], g:FormatArgs) + bw! + set formatexpr= + delfunc s:Format + bw! +endfunc + +" basic test for formatprg +func Test_normal06_formatprg() + " only test on non windows platform + CheckNotMSWindows + + " uses sed to number non-empty lines + call writefile(['#!/bin/sh', 'sed ''/./=''|sed ''/./{', 'N', 's/\n/ /', '}'''], 'Xsed_format.sh', 'D') + call system('chmod +x ./Xsed_format.sh') + let text = ['a', '', 'c', '', ' ', 'd', 'e'] + let expected = ['1 a', '', '3 c', '', '5 ', '6 d', '7 e'] + + 10new + call setline(1, text) + set formatprg=./Xsed_format.sh + norm! gggqG + call assert_equal(expected, getline(1, '$')) + %d + + call setline(1, text) + set formatprg=donothing + setlocal formatprg=./Xsed_format.sh + norm! gggqG + call assert_equal(expected, getline(1, '$')) + %d + + " Check for the command-line ranges added to 'formatprg' + set formatprg=cat + call setline(1, ['one', 'two', 'three', 'four', 'five']) + call feedkeys('gggqG', 'xt') + call assert_equal('.,$!cat', @:) + call feedkeys('2Ggq2j', 'xt') + call assert_equal('.,.+2!cat', @:) + + bw! + " clean up + set formatprg= + setlocal formatprg= +endfunc + +func Test_normal07_internalfmt() + " basic test for internal formatter to textwidth of 12 + let list=range(1,11) + call map(list, 'v:val." "') + 10new + call setline(1, list) + set tw=12 + norm! ggVGgq + call assert_equal(['1 2 3', '4 5 6', '7 8 9', '10 11 '], getline(1, '$')) + " clean up + set tw=0 + bw! +endfunc + +" basic tests for foldopen/folddelete +func Test_normal08_fold() + CheckFeature folding + call Setup_NewWindow() + 50 + setl foldenable fdm=marker + " First fold + norm! V4jzf + " check that folds have been created + call assert_equal(['50/*{{{*/', '51', '52', '53', '54/*}}}*/'], getline(50,54)) + " Second fold + 46 + norm! V10jzf + " check that folds have been created + call assert_equal('46/*{{{*/', getline(46)) + call assert_equal('60/*}}}*/', getline(60)) + norm! k + call assert_equal('45', getline('.')) + norm! j + call assert_equal('46/*{{{*/', getline('.')) + norm! j + call assert_equal('61', getline('.')) + norm! k + " open a fold + norm! Vzo + norm! k + call assert_equal('45', getline('.')) + norm! j + call assert_equal('46/*{{{*/', getline('.')) + norm! j + call assert_equal('47', getline('.')) + norm! k + norm! zcVzO + call assert_equal('46/*{{{*/', getline('.')) + norm! j + call assert_equal('47', getline('.')) + norm! j + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('51', getline('.')) + " delete folds + :46 + " collapse fold + norm! V14jzC + " delete all folds recursively + norm! VzD + call assert_equal(['46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60'], getline(46,60)) + + " clean up + setl nofoldenable fdm=marker + bw! +endfunc + +func Test_normal09a_operatorfunc() + " Test operatorfunc + call Setup_NewWindow() + " Add some spaces for counting + 50,60s/$/ / + unlet! g:a + let g:a=0 + nmap <buffer><silent> ,, :set opfunc=CountSpaces<CR>g@ + vmap <buffer><silent> ,, :<C-U>call CountSpaces(visualmode(), 1)<CR> + 50 + norm V2j,, + call assert_equal(6, g:a) + norm V,, + call assert_equal(2, g:a) + norm ,,l + call assert_equal(0, g:a) + 50 + exe "norm 0\<c-v>10j2l,," + call assert_equal(11, g:a) + 50 + norm V10j,, + call assert_equal(22, g:a) + + " clean up + unmap <buffer> ,, + set opfunc= + unlet! g:a + bw! +endfunc + +func Test_normal09b_operatorfunc() + " Test operatorfunc + call Setup_NewWindow() + " Add some spaces for counting + 50,60s/$/ / + unlet! g:opt + set linebreak + nmap <buffer><silent> ,, :set opfunc=OpfuncDummy<CR>g@ + 50 + norm ,,j + exe "bd!" g:bufnr + call assert_true(&linebreak) + call assert_equal(g:opt, &linebreak) + set nolinebreak + norm ,,j + exe "bd!" g:bufnr + call assert_false(&linebreak) + call assert_equal(g:opt, &linebreak) + + " clean up + unmap <buffer> ,, + set opfunc= + call assert_fails('normal Vg@', 'E774:') + bw! + unlet! g:opt +endfunc + +func OperatorfuncRedo(_) + let g:opfunc_count = v:count +endfunc + +func Underscorize(_) + normal! '[V']r_ +endfunc + +func Test_normal09c_operatorfunc() + " Test redoing operatorfunc + new + call setline(1, 'some text') + set operatorfunc=OperatorfuncRedo + normal v3g@ + call assert_equal(3, g:opfunc_count) + let g:opfunc_count = 0 + normal . + call assert_equal(3, g:opfunc_count) + + bw! + unlet g:opfunc_count + + " Test redoing Visual mode + set operatorfunc=Underscorize + new + call setline(1, ['first', 'first', 'third', 'third', 'second']) + normal! 1GVjg@ + normal! 5G. + normal! 3G. + call assert_equal(['_____', '_____', '_____', '_____', '______'], getline(1, '$')) + bwipe! + set operatorfunc= +endfunc + +" Test for different ways of setting the 'operatorfunc' option +func Test_opfunc_callback() + new + func OpFunc1(callnr, type) + let g:OpFunc1Args = [a:callnr, a:type] + endfunc + func OpFunc2(type) + let g:OpFunc2Args = [a:type] + endfunc + + let lines =<< trim END + #" Test for using a function name + LET &opfunc = 'g:OpFunc2' + LET g:OpFunc2Args = [] + normal! g@l + call assert_equal(['char'], g:OpFunc2Args) + + #" Test for using a function() + set opfunc=function('g:OpFunc1',\ [10]) + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([10, 'char'], g:OpFunc1Args) + + #" Using a funcref variable to set 'operatorfunc' + VAR Fn = function('g:OpFunc1', [11]) + LET &opfunc = Fn + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([11, 'char'], g:OpFunc1Args) + + #" Using a string(funcref_variable) to set 'operatorfunc' + LET Fn = function('g:OpFunc1', [12]) + LET &operatorfunc = string(Fn) + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([12, 'char'], g:OpFunc1Args) + + #" Test for using a funcref() + set operatorfunc=funcref('g:OpFunc1',\ [13]) + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([13, 'char'], g:OpFunc1Args) + + #" Using a funcref variable to set 'operatorfunc' + LET Fn = funcref('g:OpFunc1', [14]) + LET &opfunc = Fn + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([14, 'char'], g:OpFunc1Args) + + #" Using a string(funcref_variable) to set 'operatorfunc' + LET Fn = funcref('g:OpFunc1', [15]) + LET &opfunc = string(Fn) + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([15, 'char'], g:OpFunc1Args) + + #" Test for using a lambda function using set + VAR optval = "LSTART a LMIDDLE OpFunc1(16, a) LEND" + LET optval = substitute(optval, ' ', '\\ ', 'g') + exe "set opfunc=" .. optval + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([16, 'char'], g:OpFunc1Args) + + #" Test for using a lambda function using LET + LET &opfunc = LSTART a LMIDDLE OpFunc1(17, a) LEND + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([17, 'char'], g:OpFunc1Args) + + #" Set 'operatorfunc' to a string(lambda expression) + LET &opfunc = 'LSTART a LMIDDLE OpFunc1(18, a) LEND' + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([18, 'char'], g:OpFunc1Args) + + #" Set 'operatorfunc' to a variable with a lambda expression + VAR Lambda = LSTART a LMIDDLE OpFunc1(19, a) LEND + LET &opfunc = Lambda + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([19, 'char'], g:OpFunc1Args) + + #" Set 'operatorfunc' to a string(variable with a lambda expression) + LET Lambda = LSTART a LMIDDLE OpFunc1(20, a) LEND + LET &opfunc = string(Lambda) + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([20, 'char'], g:OpFunc1Args) + + #" Try to use 'operatorfunc' after the function is deleted + func g:TmpOpFunc1(type) + let g:TmpOpFunc1Args = [21, a:type] + endfunc + LET &opfunc = function('g:TmpOpFunc1') + delfunc g:TmpOpFunc1 + call test_garbagecollect_now() + LET g:TmpOpFunc1Args = [] + call assert_fails('normal! g@l', 'E117:') + call assert_equal([], g:TmpOpFunc1Args) + + #" Try to use a function with two arguments for 'operatorfunc' + func g:TmpOpFunc2(x, y) + let g:TmpOpFunc2Args = [a:x, a:y] + endfunc + set opfunc=TmpOpFunc2 + LET g:TmpOpFunc2Args = [] + call assert_fails('normal! g@l', 'E119:') + call assert_equal([], g:TmpOpFunc2Args) + delfunc TmpOpFunc2 + + #" Try to use a lambda function with two arguments for 'operatorfunc' + LET &opfunc = LSTART a, b LMIDDLE OpFunc1(22, b) LEND + LET g:OpFunc1Args = [] + call assert_fails('normal! g@l', 'E119:') + call assert_equal([], g:OpFunc1Args) + + #" Test for clearing the 'operatorfunc' option + set opfunc='' + set opfunc& + call assert_fails("set opfunc=function('abc')", "E700:") + call assert_fails("set opfunc=funcref('abc')", "E700:") + + #" set 'operatorfunc' to a non-existing function + LET &opfunc = function('g:OpFunc1', [23]) + call assert_fails("set opfunc=function('NonExistingFunc')", 'E700:') + call assert_fails("LET &opfunc = function('NonExistingFunc')", 'E700:') + LET g:OpFunc1Args = [] + normal! g@l + call assert_equal([23, 'char'], g:OpFunc1Args) + END + call CheckTransLegacySuccess(lines) + + " Test for using a script-local function name + func s:OpFunc3(type) + let g:OpFunc3Args = [a:type] + endfunc + set opfunc=s:OpFunc3 + let g:OpFunc3Args = [] + normal! g@l + call assert_equal(['char'], g:OpFunc3Args) + + let &opfunc = 's:OpFunc3' + let g:OpFunc3Args = [] + normal! g@l + call assert_equal(['char'], g:OpFunc3Args) + delfunc s:OpFunc3 + + " Using Vim9 lambda expression in legacy context should fail + " set opfunc=(a)\ =>\ OpFunc1(24,\ a) + let g:OpFunc1Args = [] + " call assert_fails('normal! g@l', 'E117:') + call assert_equal([], g:OpFunc1Args) + + " set 'operatorfunc' to a partial with dict. This used to cause a crash. + func SetOpFunc() + let operator = {'execute': function('OperatorExecute')} + let &opfunc = operator.execute + endfunc + func OperatorExecute(_) dict + endfunc + call SetOpFunc() + call test_garbagecollect_now() + set operatorfunc= + delfunc SetOpFunc + delfunc OperatorExecute + + " Vim9 tests + let lines =<< trim END + vim9script + + def g:Vim9opFunc(val: number, type: string): void + g:OpFunc1Args = [val, type] + enddef + + # Test for using a def function with opfunc + set opfunc=function('g:Vim9opFunc',\ [60]) + g:OpFunc1Args = [] + normal! g@l + assert_equal([60, 'char'], g:OpFunc1Args) + + # Test for using a global function name + &opfunc = g:OpFunc2 + g:OpFunc2Args = [] + normal! g@l + assert_equal(['char'], g:OpFunc2Args) + bw! + + # Test for using a script-local function name + def LocalOpFunc(type: string): void + g:LocalOpFuncArgs = [type] + enddef + &opfunc = LocalOpFunc + g:LocalOpFuncArgs = [] + normal! g@l + assert_equal(['char'], g:LocalOpFuncArgs) + bw! + END + call CheckScriptSuccess(lines) + + " setting 'opfunc' to a script local function outside of a script context + " should fail + let cleanup =<< trim END + call writefile([execute('messages')], 'Xtest.out') + qall + END + call writefile(cleanup, 'Xverify.vim') + call RunVim([], [], "-c \"set opfunc=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') + + " cleanup + set opfunc& + delfunc OpFunc1 + delfunc OpFunc2 + unlet g:OpFunc1Args g:OpFunc2Args + %bw! +endfunc + +func Test_normal10_expand() + " Test for expand() + 10new + call setline(1, ['1', 'ifooar,,cbar']) + 2 + norm! $ + call assert_equal('cbar', expand('<cword>')) + call assert_equal('ifooar,,cbar', expand('<cWORD>')) + + call setline(1, ['prx = list[idx];']) + 1 + let expected = ['', 'prx', 'prx', 'prx', + \ 'list', 'list', 'list', 'list', 'list', 'list', 'list', + \ 'idx', 'idx', 'idx', 'idx', + \ 'list[idx]', + \ '];', + \ ] + for i in range(1, 16) + exe 'norm ' . i . '|' + call assert_equal(expected[i], expand('<cexpr>'), 'i == ' . i) + endfor + + " Test for <cexpr> in state.val and ptr->val + call setline(1, 'x = state.val;') + call cursor(1, 10) + call assert_equal('state.val', expand('<cexpr>')) + call setline(1, 'x = ptr->val;') + call cursor(1, 9) + call assert_equal('ptr->val', expand('<cexpr>')) + + if executable('echo') + " Test expand(`...`) i.e. backticks command expansion. + " MS-Windows has a trailing space. + call assert_match('^abcde *$', expand('`echo abcde`')) + endif + + " Test expand(`=...`) i.e. backticks expression expansion + call assert_equal('5', expand('`=2+3`')) + call assert_equal('3.14', expand('`=3.14`')) + + " clean up + bw! +endfunc + +" Test for expand() in latin1 encoding +func Test_normal_expand_latin1() + new + let save_enc = &encoding + " set encoding=latin1 + call setline(1, 'val = item->color;') + call cursor(1, 11) + call assert_equal('color', expand("<cword>")) + call assert_equal('item->color', expand("<cexpr>")) + let &encoding = save_enc + bw! +endfunc + +func Test_normal11_showcmd() + " test for 'showcmd' + 10new + exe "norm! ofoobar\<esc>" + call assert_equal(2, line('$')) + set showcmd + exe "norm! ofoobar2\<esc>" + call assert_equal(3, line('$')) + exe "norm! VAfoobar3\<esc>" + call assert_equal(3, line('$')) + exe "norm! 0d3\<del>2l" + call assert_equal('obar2foobar3', getline('.')) + " test for the visual block size displayed in the status line + call setline(1, ['aaaaa', 'bbbbb', 'ccccc']) + call feedkeys("ggl\<C-V>lljj", 'xt') + redraw! + call assert_match('3x3$', Screenline(&lines)) + call feedkeys("\<C-V>", 'xt') + " test for visually selecting a multi-byte character + call setline(1, ["\U2206"]) + call feedkeys("ggv", 'xt') + redraw! + call assert_match('1-3$', Screenline(&lines)) + call feedkeys("v", 'xt') + " test for visually selecting the end of line + call setline(1, ["foobar"]) + call feedkeys("$vl", 'xt') + redraw! + call assert_match('2$', Screenline(&lines)) + call feedkeys("y", 'xt') + call assert_equal("r\n", @") + bw! +endfunc + +" Test for nv_error and normal command errors +func Test_normal12_nv_error() + 10new + call setline(1, range(1,5)) + " should not do anything, just beep + call assert_beeps('exe "norm! <c-k>"') + call assert_equal(map(range(1,5), 'string(v:val)'), getline(1,'$')) + call assert_beeps('normal! G2dd') + call assert_beeps("normal! g\<C-A>") + call assert_beeps("normal! g\<C-X>") + call assert_beeps("normal! g\<C-B>") + " call assert_beeps("normal! vQ\<Esc>") + call assert_beeps("normal! 2[[") + call assert_beeps("normal! 2]]") + call assert_beeps("normal! 2[]") + call assert_beeps("normal! 2][") + call assert_beeps("normal! 4[z") + call assert_beeps("normal! 4]z") + call assert_beeps("normal! 4[c") + call assert_beeps("normal! 4]c") + call assert_beeps("normal! 200%") + call assert_beeps("normal! %") + call assert_beeps("normal! 2{") + call assert_beeps("normal! 2}") + call assert_beeps("normal! r\<Right>") + call assert_beeps("normal! 8ry") + call assert_beeps('normal! "@') + bw! +endfunc + +func Test_normal13_help() + " Test for F1 + call assert_equal(1, winnr()) + call feedkeys("\<f1>", 'txi') + call assert_match('help\.txt', bufname('%')) + call assert_equal(2, winnr('$')) + bw! +endfunc + +func Test_normal14_page() + " basic test for Ctrl-F and Ctrl-B + call Setup_NewWindow() + exe "norm! \<c-f>" + call assert_equal('9', getline('.')) + exe "norm! 2\<c-f>" + call assert_equal('25', getline('.')) + exe "norm! 2\<c-b>" + call assert_equal('18', getline('.')) + 1 + set scrolloff=5 + exe "norm! 2\<c-f>" + call assert_equal('21', getline('.')) + exe "norm! \<c-b>" + call assert_equal('13', getline('.')) + 1 + set scrolloff=99 + exe "norm! \<c-f>" + call assert_equal('13', getline('.')) + set scrolloff=0 + 100 + exe "norm! $\<c-b>" + call assert_equal('92', getline('.')) + call assert_equal([0, 92, 1, 0, 1], getcurpos()) + 100 + set nostartofline + exe "norm! $\<c-b>" + call assert_equal('92', getline('.')) + call assert_equal([0, 92, 2, 0, v:maxcol], getcurpos()) + " cleanup + set startofline + bw! +endfunc + +func Test_normal14_page_eol() + 10new + norm oxxxxxxx + exe "norm 2\<c-f>" + " check with valgrind that cursor is put back in column 1 + exe "norm 2\<c-b>" + bw! +endfunc + +" Test for errors with z command +func Test_normal_z_error() + call assert_beeps('normal! z2p') + call assert_beeps('normal! zq') + call assert_beeps('normal! cz1') +endfunc + +func Test_normal15_z_scroll_vert() + " basic test for z commands that scroll the window + call Setup_NewWindow() + 100 + norm! >> + " Test for z<cr> + exe "norm! z\<cr>" + call assert_equal(' 100', getline('.')) + call assert_equal(100, winsaveview()['topline']) + call assert_equal([0, 100, 2, 0, 9], getcurpos()) + + " Test for zt + 21 + norm! >>0zt + call assert_equal(' 21', getline('.')) + call assert_equal(21, winsaveview()['topline']) + call assert_equal([0, 21, 1, 0, 8], getcurpos()) + + " Test for zb + 30 + norm! >>$ztzb + call assert_equal(' 30', getline('.')) + call assert_equal(30, winsaveview()['topline']+winheight(0)-1) + call assert_equal([0, 30, 3, 0, v:maxcol], getcurpos()) + + " Test for z- + 1 + 30 + norm! 0z- + call assert_equal(' 30', getline('.')) + call assert_equal(30, winsaveview()['topline']+winheight(0)-1) + call assert_equal([0, 30, 2, 0, 9], getcurpos()) + + " Test for z{height}<cr> + call assert_equal(10, winheight(0)) + exe "norm! z12\<cr>" + call assert_equal(12, winheight(0)) + exe "norm! z15\<Del>0\<cr>" + call assert_equal(10, winheight(0)) + + " Test for z. + 1 + 21 + norm! 0z. + call assert_equal(' 21', getline('.')) + call assert_equal(17, winsaveview()['topline']) + call assert_equal([0, 21, 2, 0, 9], getcurpos()) + + " Test for zz + 1 + 21 + norm! 0zz + call assert_equal(' 21', getline('.')) + call assert_equal(17, winsaveview()['topline']) + call assert_equal([0, 21, 1, 0, 8], getcurpos()) + + " Test for z+ + 11 + norm! zt + norm! z+ + call assert_equal(' 21', getline('.')) + call assert_equal(21, winsaveview()['topline']) + call assert_equal([0, 21, 2, 0, 9], getcurpos()) + + " Test for [count]z+ + 1 + norm! 21z+ + call assert_equal(' 21', getline('.')) + call assert_equal(21, winsaveview()['topline']) + call assert_equal([0, 21, 2, 0, 9], getcurpos()) + + " Test for z+ with [count] greater than buffer size + 1 + norm! 1000z+ + call assert_equal(' 100', getline('.')) + call assert_equal(100, winsaveview()['topline']) + call assert_equal([0, 100, 2, 0, 9], getcurpos()) + + " Test for z+ from the last buffer line + norm! Gz.z+ + call assert_equal(' 100', getline('.')) + call assert_equal(100, winsaveview()['topline']) + call assert_equal([0, 100, 2, 0, 9], getcurpos()) + + " Test for z^ + norm! 22z+0 + norm! z^ + call assert_equal(' 21', getline('.')) + call assert_equal(12, winsaveview()['topline']) + call assert_equal([0, 21, 2, 0, 9], getcurpos()) + + " Test for z^ from first buffer line + norm! ggz^ + call assert_equal('1', getline('.')) + call assert_equal(1, winsaveview()['topline']) + call assert_equal([0, 1, 1, 0, 1], getcurpos()) + + " Test for [count]z^ + 1 + norm! 30z^ + call assert_equal(' 21', getline('.')) + call assert_equal(12, winsaveview()['topline']) + call assert_equal([0, 21, 2, 0, 9], getcurpos()) + + " cleanup + bw! +endfunc + +func Test_normal16_z_scroll_hor() + " basic test for z commands that scroll the window + 10new + 15vsp + set nowrap listchars= + let lineA='abcdefghijklmnopqrstuvwxyz' + let lineB='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + $put =lineA + $put =lineB + 1d + + " Test for zl and zh with a count + norm! 0z10l + call assert_equal([11, 1], [col('.'), wincol()]) + norm! z4h + call assert_equal([11, 5], [col('.'), wincol()]) + normal! 2gg + + " Test for zl + 1 + norm! 5zl + call assert_equal(lineA, getline('.')) + call assert_equal(6, col('.')) + call assert_equal(5, winsaveview()['leftcol']) + norm! yl + call assert_equal('f', @0) + + " Test for zh + norm! 2zh + call assert_equal(lineA, getline('.')) + call assert_equal(6, col('.')) + norm! yl + call assert_equal('f', @0) + call assert_equal(3, winsaveview()['leftcol']) + + " Test for zL + norm! zL + call assert_equal(11, col('.')) + norm! yl + call assert_equal('k', @0) + call assert_equal(10, winsaveview()['leftcol']) + norm! 2zL + call assert_equal(25, col('.')) + norm! yl + call assert_equal('y', @0) + call assert_equal(24, winsaveview()['leftcol']) + + " Test for zH + norm! 2zH + call assert_equal(25, col('.')) + call assert_equal(10, winsaveview()['leftcol']) + norm! yl + call assert_equal('y', @0) + + " Test for zs + norm! $zs + call assert_equal(26, col('.')) + call assert_equal(25, winsaveview()['leftcol']) + norm! yl + call assert_equal('z', @0) + + " Test for ze + norm! ze + call assert_equal(26, col('.')) + call assert_equal(11, winsaveview()['leftcol']) + norm! yl + call assert_equal('z', @0) + + " Test for zs and ze with folds + %fold + norm! $zs + call assert_equal(26, col('.')) + call assert_equal(0, winsaveview()['leftcol']) + norm! yl + call assert_equal('z', @0) + norm! ze + call assert_equal(26, col('.')) + call assert_equal(0, winsaveview()['leftcol']) + norm! yl + call assert_equal('z', @0) + + " cleanup + set wrap listchars=eol:$ + bw! +endfunc + +func Test_normal17_z_scroll_hor2() + " basic test for z commands that scroll the window + " using 'sidescrolloff' setting + 10new + 20vsp + set nowrap listchars= sidescrolloff=5 + let lineA='abcdefghijklmnopqrstuvwxyz' + let lineB='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + $put =lineA + $put =lineB + 1d + + " Test for zl + 1 + norm! 5zl + call assert_equal(lineA, getline('.')) + call assert_equal(11, col('.')) + call assert_equal(5, winsaveview()['leftcol']) + norm! yl + call assert_equal('k', @0) + + " Test for zh + norm! 2zh + call assert_equal(lineA, getline('.')) + call assert_equal(11, col('.')) + norm! yl + call assert_equal('k', @0) + call assert_equal(3, winsaveview()['leftcol']) + + " Test for zL + norm! 0zL + call assert_equal(16, col('.')) + norm! yl + call assert_equal('p', @0) + call assert_equal(10, winsaveview()['leftcol']) + norm! 2zL + call assert_equal(26, col('.')) + norm! yl + call assert_equal('z', @0) + call assert_equal(15, winsaveview()['leftcol']) + + " Test for zH + norm! 2zH + call assert_equal(15, col('.')) + call assert_equal(0, winsaveview()['leftcol']) + norm! yl + call assert_equal('o', @0) + + " Test for zs + norm! $zs + call assert_equal(26, col('.')) + call assert_equal(20, winsaveview()['leftcol']) + norm! yl + call assert_equal('z', @0) + + " Test for ze + norm! ze + call assert_equal(26, col('.')) + call assert_equal(11, winsaveview()['leftcol']) + norm! yl + call assert_equal('z', @0) + + " cleanup + set wrap listchars=eol:$ sidescrolloff=0 + bw! +endfunc + +" Test for commands that scroll the window horizontally. Test with folds. +" H, M, L, CTRL-E, CTRL-Y, CTRL-U, CTRL-D, PageUp, PageDown commands +func Test_vert_scroll_cmds() + 15new + call setline(1, range(1, 100)) + exe "normal! 30ggz\<CR>" + set foldenable + 33,36fold + 40,43fold + 46,49fold + let h = winheight(0) + + " Test for H, M and L commands + " Top of the screen = 30 + " Folded lines = 9 + " Bottom of the screen = 30 + h + 9 - 1 + normal! 4L + call assert_equal(35 + h, line('.')) + normal! 4H + call assert_equal(33, line('.')) + + " Test for using a large count value + %d + call setline(1, range(1, 4)) + norm! 6H + call assert_equal(4, line('.')) + + " Test for 'M' with folded lines + %d + call setline(1, range(1, 20)) + 1,5fold + norm! LM + call assert_equal(12, line('.')) + + " Test for the CTRL-E and CTRL-Y commands with folds + %d + call setline(1, range(1, 10)) + 3,5fold + exe "normal 6G3\<C-E>" + call assert_equal(6, line('w0')) + exe "normal 2\<C-Y>" + call assert_equal(2, line('w0')) + + " Test for CTRL-Y on a folded line + %d + call setline(1, range(1, 100)) + exe (h + 2) .. "," .. (h + 4) .. "fold" + exe h + 5 + normal z- + exe "normal \<C-Y>\<C-Y>" + call assert_equal(h + 1, line('w$')) + + " Test for CTRL-Y from the first line and CTRL-E from the last line + %d + set scrolloff=2 + call setline(1, range(1, 4)) + exe "normal gg\<C-Y>" + call assert_equal(1, line('w0')) + call assert_equal(1, line('.')) + exe "normal G4\<C-E>\<C-E>" + call assert_equal(4, line('w$')) + call assert_equal(4, line('.')) + set scrolloff& + + " Using <PageUp> and <PageDown> in an empty buffer should beep + %d + call assert_beeps('exe "normal \<PageUp>"') + call assert_beeps('exe "normal \<C-B>"') + call assert_beeps('exe "normal \<PageDown>"') + call assert_beeps('exe "normal \<C-F>"') + + " Test for <C-U> and <C-D> with fold + %d + call setline(1, range(1, 100)) + 10,35fold + set scroll=10 + exe "normal \<C-D>" + call assert_equal(36, line('.')) + exe "normal \<C-D>" + call assert_equal(46, line('.')) + exe "normal \<C-U>" + call assert_equal(36, line('.')) + exe "normal \<C-U>" + call assert_equal(10, line('.')) + exe "normal \<C-U>" + call assert_equal(1, line('.')) + set scroll& + + " Test for scrolling to the top of the file with <C-U> and a fold + 10 + normal ztL + exe "normal \<C-U>\<C-U>" + call assert_equal(1, line('w0')) + + " Test for CTRL-D on a folded line + %d + call setline(1, range(1, 100)) + 50,100fold + 75 + normal z- + exe "normal \<C-D>" + call assert_equal(50, line('.')) + call assert_equal(100, line('w$')) + normal z. + let lnum = winline() + exe "normal \<C-D>" + call assert_equal(lnum, winline()) + call assert_equal(50, line('.')) + normal zt + exe "normal \<C-D>" + call assert_equal(50, line('w0')) + + " Test for <S-CR>. Page down. + %d + call setline(1, range(1, 100)) + call feedkeys("\<S-CR>", 'xt') + call assert_equal(14, line('w0')) + call assert_equal(28, line('w$')) + + " Test for <S-->. Page up. + call feedkeys("\<S-->", 'xt') + call assert_equal(1, line('w0')) + call assert_equal(15, line('w$')) + + set foldenable& + bwipe! +endfunc + +func Test_scroll_in_ex_mode() + " This was using invalid memory because w_botline was invalid. + let lines =<< trim END + diffsplit + norm os00( + call writefile(['done'], 'Xdone') + qa! + END + call writefile(lines, 'Xscript') + call assert_equal(1, RunVim([], [], '--clean -X -Z -e -s -S Xscript')) + call assert_equal(['done'], readfile('Xdone')) + + call delete('Xscript') + call delete('Xdone') +endfunc + +" Test for the 'sidescroll' option +func Test_sidescroll_opt() + new + 20vnew + + " scroll by 2 characters horizontally + set sidescroll=2 nowrap + call setline(1, repeat('a', 40)) + normal g$l + call assert_equal(19, screenpos(0, 1, 21).col) + normal l + call assert_equal(20, screenpos(0, 1, 22).col) + normal g0h + call assert_equal(2, screenpos(0, 1, 2).col) + call assert_equal(20, screenpos(0, 1, 20).col) + + " when 'sidescroll' is 0, cursor positioned at the center + set sidescroll=0 + normal g$l + call assert_equal(11, screenpos(0, 1, 21).col) + normal g0h + call assert_equal(10, screenpos(0, 1, 10).col) + + %bw! + set wrap& sidescroll& +endfunc + +" basic tests for foldopen/folddelete +func Test_normal18_z_fold() + CheckFeature folding + call Setup_NewWindow() + 50 + setl foldenable fdm=marker foldlevel=5 + + call assert_beeps('normal! zj') + call assert_beeps('normal! zk') + + " Test for zF + " First fold + norm! 4zF + " check that folds have been created + call assert_equal(['50/*{{{*/', '51', '52', '53/*}}}*/'], getline(50,53)) + + " Test for zd + 51 + norm! 2zF + call assert_equal(2, foldlevel('.')) + norm! kzd + call assert_equal(['50', '51/*{{{*/', '52/*}}}*/', '53'], getline(50,53)) + norm! j + call assert_equal(1, foldlevel('.')) + + " Test for zD + " also deletes partially selected folds recursively + 51 + norm! zF + call assert_equal(2, foldlevel('.')) + norm! kV2jzD + call assert_equal(['50', '51', '52', '53'], getline(50,53)) + + " Test for zE + 85 + norm! 4zF + 86 + norm! 2zF + 90 + norm! 4zF + call assert_equal(['85/*{{{*/', '86/*{{{*/', '87/*}}}*/', '88/*}}}*/', '89', '90/*{{{*/', '91', '92', '93/*}}}*/'], getline(85,93)) + norm! zE + call assert_equal(['85', '86', '87', '88', '89', '90', '91', '92', '93'], getline(85,93)) + + " Test for zn + 50 + set foldlevel=0 + norm! 2zF + norm! zn + norm! k + call assert_equal('49', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('51/*}}}*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + call assert_equal(0, &foldenable) + + " Test for zN + 49 + norm! zN + call assert_equal('49', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + call assert_equal(1, &foldenable) + + " Test for zi + norm! zi + call assert_equal(0, &foldenable) + norm! zi + call assert_equal(1, &foldenable) + norm! zi + call assert_equal(0, &foldenable) + norm! zi + call assert_equal(1, &foldenable) + + " Test for za + 50 + norm! za + norm! k + call assert_equal('49', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('51/*}}}*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + 50 + norm! za + norm! k + call assert_equal('49', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + + 49 + norm! 5zF + norm! k + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + 49 + norm! za + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + set nofoldenable + " close fold and set foldenable + norm! za + call assert_equal(1, &foldenable) + + 50 + " have to use {count}za to open all folds and make the cursor visible + norm! 2za + norm! 2k + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('51/*}}}*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + + " Test for zA + 49 + set foldlevel=0 + 50 + norm! zA + norm! 2k + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('51/*}}}*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + + " zA on a opened fold when foldenable is not set + 50 + set nofoldenable + norm! zA + call assert_equal(1, &foldenable) + norm! k + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + + " Test for zc + norm! zE + 50 + norm! 2zF + 49 + norm! 5zF + set nofoldenable + 50 + " There most likely is a bug somewhere: + " https://groups.google.com/d/msg/vim_dev/v2EkfJ_KQjI/u-Cvv94uCAAJ + " TODO: Should this only close the inner most fold or both folds? + norm! zc + call assert_equal(1, &foldenable) + norm! k + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + set nofoldenable + 50 + norm! Vjzc + norm! k + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + + " Test for zC + set nofoldenable + 50 + norm! zCk + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + + " Test for zx + " 1) close folds at line 49-54 + set nofoldenable + 48 + norm! zx + call assert_equal(1, &foldenable) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + + " 2) do not close fold under cursor + 51 + set nofoldenable + norm! zx + call assert_equal(1, &foldenable) + norm! 3k + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('51/*}}}*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + norm! j + call assert_equal('53', getline('.')) + norm! j + call assert_equal('54/*}}}*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + + " 3) close one level of folds + 48 + set nofoldenable + set foldlevel=1 + norm! zx + call assert_equal(1, &foldenable) + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + norm! j + call assert_equal('53', getline('.')) + norm! j + call assert_equal('54/*}}}*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + + " Test for zX + " Close all folds + set foldlevel=0 nofoldenable + 50 + norm! zX + call assert_equal(1, &foldenable) + norm! k + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + + " Test for zm + 50 + set nofoldenable foldlevel=2 + norm! zm + call assert_equal(1, &foldenable) + call assert_equal(1, &foldlevel) + norm! zm + call assert_equal(0, &foldlevel) + norm! zm + call assert_equal(0, &foldlevel) + norm! k + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + + " Test for zm with a count + 50 + set foldlevel=2 + norm! 3zm + call assert_equal(0, &foldlevel) + call assert_equal(49, foldclosed(line('.'))) + + " Test for zM + 48 + set nofoldenable foldlevel=99 + norm! zM + call assert_equal(1, &foldenable) + call assert_equal(0, &foldlevel) + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('55', getline('.')) + + " Test for zr + 48 + set nofoldenable foldlevel=0 + norm! zr + call assert_equal(0, &foldenable) + call assert_equal(1, &foldlevel) + set foldlevel=0 foldenable + norm! zr + call assert_equal(1, &foldenable) + call assert_equal(1, &foldlevel) + norm! zr + call assert_equal(2, &foldlevel) + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('51/*}}}*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + + " Test for zR + 48 + set nofoldenable foldlevel=0 + norm! zR + call assert_equal(0, &foldenable) + call assert_equal(2, &foldlevel) + set foldenable foldlevel=0 + norm! zR + call assert_equal(1, &foldenable) + call assert_equal(2, &foldlevel) + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('51/*}}}*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + call append(50, ['a /*{{{*/', 'b /*}}}*/']) + 48 + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('a /*{{{*/', getline('.')) + norm! j + call assert_equal('51/*}}}*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + 48 + norm! zR + call assert_equal(1, &foldenable) + call assert_equal(3, &foldlevel) + call assert_equal('48', getline('.')) + norm! j + call assert_equal('49/*{{{*/', getline('.')) + norm! j + call assert_equal('50/*{{{*/', getline('.')) + norm! j + call assert_equal('a /*{{{*/', getline('.')) + norm! j + call assert_equal('b /*}}}*/', getline('.')) + norm! j + call assert_equal('51/*}}}*/', getline('.')) + norm! j + call assert_equal('52', getline('.')) + + " clean up + setl nofoldenable fdm=marker foldlevel=0 + bw! +endfunc + +func Test_normal20_exmode() + " Reading from redirected file doesn't work on MS-Windows + CheckNotMSWindows + call writefile(['1a', 'foo', 'bar', '.', 'w! Xfile2', 'q!'], 'Xscript') + call writefile(['1', '2'], 'Xfile') + call system(GetVimCommand() .. ' -e -s < Xscript Xfile') + let a=readfile('Xfile2') + call assert_equal(['1', 'foo', 'bar', '2'], a) + + " clean up + for file in ['Xfile', 'Xfile2', 'Xscript'] + call delete(file) + endfor + bw! +endfunc + +func Test_normal21_nv_hat() + + " Edit a fresh file and wipe the buffer list so that there is no alternate + " file present. Next, check for the expected command failures. + edit Xfoo | %bw + call assert_fails(':buffer #', 'E86') + call assert_fails(':execute "normal! \<C-^>"', 'E23') + call assert_fails("normal i\<C-R>#", 'E23:') + + " Test for the expected behavior when switching between two named buffers. + edit Xfoo | edit Xbar + call feedkeys("\<C-^>", 'tx') + call assert_equal('Xfoo', fnamemodify(bufname('%'), ':t')) + call feedkeys("\<C-^>", 'tx') + call assert_equal('Xbar', fnamemodify(bufname('%'), ':t')) + + " Test for the expected behavior when only one buffer is named. + enew | let l:nr = bufnr('%') + call feedkeys("\<C-^>", 'tx') + call assert_equal('Xbar', fnamemodify(bufname('%'), ':t')) + call feedkeys("\<C-^>", 'tx') + call assert_equal('', bufname('%')) + call assert_equal(l:nr, bufnr('%')) + + " Test that no action is taken by "<C-^>" when an operator is pending. + edit Xfoo + call feedkeys("ci\<C-^>", 'tx') + call assert_equal('Xfoo', fnamemodify(bufname('%'), ':t')) + + %bw! +endfunc + +func Test_normal22_zet() + " Test for ZZ + " let shell = &shell + " let &shell = 'sh' + call writefile(['1', '2'], 'Xn22file', 'D') + let args = ' -N -i NONE --noplugins -X --headless' + call system(GetVimCommand() .. args .. ' -c "%d" -c ":norm! ZZ" Xn22file') + let a = readfile('Xn22file') + call assert_equal([], a) + " Test for ZQ + call writefile(['1', '2'], 'Xn22file') + call system(GetVimCommand() . args . ' -c "%d" -c ":norm! ZQ" Xn22file') + let a = readfile('Xn22file') + call assert_equal(['1', '2'], a) + + " Unsupported Z command + call assert_beeps('normal! ZW') + + " clean up + " let &shell = shell +endfunc + +func Test_normal23_K() + " Test for K command + new + call append(0, ['helphelp.txt', 'man', 'aa%bb', 'cc|dd']) + let k = &keywordprg + set keywordprg=:help + 1 + norm! VK + call assert_equal('helphelp.txt', fnamemodify(bufname('%'), ':t')) + call assert_equal('help', &ft) + call assert_match('\*helphelp.txt\*', getline('.')) + helpclose + norm! 0K + call assert_equal('helphelp.txt', fnamemodify(bufname('%'), ':t')) + call assert_equal('help', &ft) + call assert_match('Help on help files', getline('.')) + helpclose + + set keywordprg=:new + set iskeyword+=% + set iskeyword+=\| + 2 + norm! K + call assert_equal('man', fnamemodify(bufname('%'), ':t')) + bwipe! + 3 + norm! K + call assert_equal('aa%bb', fnamemodify(bufname('%'), ':t')) + bwipe! + if !has('win32') + 4 + norm! K + call assert_equal('cc|dd', fnamemodify(bufname('%'), ':t')) + bwipe! + endif + set iskeyword-=% + set iskeyword-=\| + + " Currently doesn't work in Nvim, see #19436 + " Test for specifying a count to K + " 1 + " com! -nargs=* Kprog let g:Kprog_Args = <q-args> + " set keywordprg=:Kprog + " norm! 3K + " call assert_equal('3 version8', g:Kprog_Args) + " delcom Kprog + + " Only expect "man" to work on Unix + if !has("unix") || has('nvim') " Nvim K uses :terminal. #15398 + let &keywordprg = k + bw! + return + endif + + let not_gnu_man = has('mac') || has('bsd') + if not_gnu_man + " In MacOS and BSD, the option for specifying a pager is different + set keywordprg=man\ -P\ cat + else + set keywordprg=man\ --pager=cat + endif + " Test for using man + 2 + let a = execute('unsilent norm! K') + if not_gnu_man + call assert_match("man -P cat 'man'", a) + else + call assert_match("man --pager=cat 'man'", a) + endif + + " Error cases + call setline(1, '#$#') + call assert_fails('normal! ggK', 'E349:') + call setline(1, '---') + call assert_fails('normal! ggv2lK', 'E349:') + call setline(1, ['abc', 'xyz']) + call assert_fails("normal! gg2lv2h\<C-]>", 'E433:') + call assert_beeps("normal! ggVjK") + + " clean up + let &keywordprg = k + bw! +endfunc + +func Test_normal24_rot13() + " Testing for g?? g?g? + new + call append(0, 'abcdefghijklmnopqrstuvwxyzäüö') + 1 + norm! g?? + call assert_equal('nopqrstuvwxyzabcdefghijklmäüö', getline('.')) + norm! g?g? + call assert_equal('abcdefghijklmnopqrstuvwxyzäüö', getline('.')) + + " clean up + bw! +endfunc + +func Test_normal25_tag() + CheckFeature quickfix + + " Testing for CTRL-] g CTRL-] g] + " CTRL-W g] CTRL-W CTRL-] CTRL-W g CTRL-] + h + " Test for CTRL-] + call search('\<x\>$') + exe "norm! \<c-]>" + call assert_equal("change.txt", fnamemodify(bufname('%'), ':t')) + norm! yiW + call assert_equal("*x*", @0) + exe ":norm \<c-o>" + + " Test for g_CTRL-] + call search('\<v_u\>$') + exe "norm! g\<c-]>" + call assert_equal("change.txt", fnamemodify(bufname('%'), ':t')) + norm! yiW + call assert_equal("*v_u*", @0) + exe ":norm \<c-o>" + + " Test for g] + call search('\<i_<Esc>$') + let a = execute(":norm! g]") + call assert_match('i_<Esc>.*insert.txt', a) + + if !empty(exepath('cscope')) && has('cscope') + " setting cscopetag changes how g] works + set cst + exe "norm! g]" + call assert_equal("insert.txt", fnamemodify(bufname('%'), ':t')) + norm! yiW + call assert_equal("*i_<Esc>*", @0) + exe ":norm \<c-o>" + " Test for CTRL-W g] + exe "norm! \<C-W>g]" + call assert_equal("insert.txt", fnamemodify(bufname('%'), ':t')) + norm! yiW + call assert_equal("*i_<Esc>*", @0) + call assert_equal(3, winnr('$')) + helpclose + set nocst + endif + + " Test for CTRL-W g] + let a = execute("norm! \<C-W>g]") + call assert_match('i_<Esc>.*insert.txt', a) + + " Test for CTRL-W CTRL-] + exe "norm! \<C-W>\<C-]>" + call assert_equal("insert.txt", fnamemodify(bufname('%'), ':t')) + norm! yiW + call assert_equal("*i_<Esc>*", @0) + call assert_equal(3, winnr('$')) + helpclose + + " Test for CTRL-W g CTRL-] + exe "norm! \<C-W>g\<C-]>" + call assert_equal("insert.txt", fnamemodify(bufname('%'), ':t')) + norm! yiW + call assert_equal("*i_<Esc>*", @0) + call assert_equal(3, winnr('$')) + helpclose + + " clean up + helpclose +endfunc + +func Test_normal26_put() + " Test for ]p ]P [p and [P + new + call append(0, ['while read LINE', 'do', ' ((count++))', ' if [ $? -ne 0 ]; then', " echo 'Error writing file'", ' fi', 'done']) + 1 + /Error/y a + 2 + norm! "a]pj"a[p + call assert_equal(['do', "echo 'Error writing file'", " echo 'Error writing file'", ' ((count++))'], getline(2,5)) + 1 + /^\s\{4}/ + exe "norm! \"a]P3Eldt'" + exe "norm! j\"a[P2Eldt'" + call assert_equal([' if [ $? -ne 0 ]; then', " echo 'Error writing'", " echo 'Error'", " echo 'Error writing file'", ' fi'], getline(6,10)) + + " clean up + bw! +endfunc + +func Test_normal27_bracket() + " Test for [' [` ]' ]` + call Setup_NewWindow() + 1,21s/.\+/ & b/ + 1 + norm! $ma + 5 + norm! $mb + 10 + norm! $mc + 15 + norm! $md + 20 + norm! $me + + " Test for [' + 9 + norm! 2[' + call assert_equal(' 1 b', getline('.')) + call assert_equal(1, line('.')) + call assert_equal(3, col('.')) + + " Test for ]' + norm! ]' + call assert_equal(' 5 b', getline('.')) + call assert_equal(5, line('.')) + call assert_equal(3, col('.')) + + " No mark before line 1, cursor moves to first non-blank on current line + 1 + norm! 5|[' + call assert_equal(' 1 b', getline('.')) + call assert_equal(1, line('.')) + call assert_equal(3, col('.')) + + " No mark after line 21, cursor moves to first non-blank on current line + 21 + norm! 5|]' + call assert_equal(' 21 b', getline('.')) + call assert_equal(21, line('.')) + call assert_equal(3, col('.')) + + " Test for [` + norm! 2[` + call assert_equal(' 15 b', getline('.')) + call assert_equal(15, line('.')) + call assert_equal(8, col('.')) + + " Test for ]` + norm! ]` + call assert_equal(' 20 b', getline('.')) + call assert_equal(20, line('.')) + call assert_equal(8, col('.')) + + " No mark before line 1, cursor does not move + 1 + norm! 5|[` + call assert_equal(' 1 b', getline('.')) + call assert_equal(1, line('.')) + call assert_equal(5, col('.')) + + " No mark after line 21, cursor does not move + 21 + norm! 5|]` + call assert_equal(' 21 b', getline('.')) + call assert_equal(21, line('.')) + call assert_equal(5, col('.')) + + " Count too large for [` + " cursor moves to first lowercase mark + norm! 99[` + call assert_equal(' 1 b', getline('.')) + call assert_equal(1, line('.')) + call assert_equal(7, col('.')) + + " Count too large for ]` + " cursor moves to last lowercase mark + norm! 99]` + call assert_equal(' 20 b', getline('.')) + call assert_equal(20, line('.')) + call assert_equal(8, col('.')) + + " clean up + bw! +endfunc + +" Test for ( and ) sentence movements +func Test_normal28_parenthesis() + new + call append(0, ['This is a test. With some sentences!', '', 'Even with a question? And one more. And no sentence here']) + + $ + norm! d( + call assert_equal(['This is a test. With some sentences!', '', 'Even with a question? And one more. ', ''], getline(1, '$')) + norm! 2d( + call assert_equal(['This is a test. With some sentences!', '', ' ', ''], getline(1, '$')) + 1 + norm! 0d) + call assert_equal(['With some sentences!', '', ' ', ''], getline(1, '$')) + + call append('$', ['This is a long sentence', '', 'spanning', 'over several lines. ']) + $ + norm! $d( + call assert_equal(['With some sentences!', '', ' ', '', 'This is a long sentence', ''], getline(1, '$')) + + " Move to the next sentence from a paragraph macro + %d + call setline(1, ['.LP', 'blue sky!. blue sky.', 'blue sky. blue sky.']) + call cursor(1, 1) + normal ) + call assert_equal([2, 1], [line('.'), col('.')]) + normal ) + call assert_equal([2, 12], [line('.'), col('.')]) + normal (( + call assert_equal([1, 1], [line('.'), col('.')]) + + " It is an error if a next sentence is not found + %d + call setline(1, '.SH') + call assert_beeps('normal )') + + " If only dot is present, don't treat that as a sentence + call setline(1, '. This is a sentence.') + normal $(( + call assert_equal(3, col('.')) + + " Jumping to a fold should open the fold + call setline(1, ['', '', 'one', 'two', 'three']) + set foldenable + 2,$fold + call feedkeys(')', 'xt') + call assert_equal(3, line('.')) + call assert_equal(1, foldlevel('.')) + call assert_equal(-1, foldclosed('.')) + set foldenable& + + " clean up + bw! +endfunc + +" Test for { and } paragraph movements +func Test_normal29_brace() + let text =<< trim [DATA] + A paragraph begins after each empty line, and also at each of a set of + paragraph macros, specified by the pairs of characters in the 'paragraphs' + option. The default is "IPLPPPQPP TPHPLIPpLpItpplpipbp", which corresponds to + the macros ".IP", ".LP", etc. (These are nroff macros, so the dot must be in + the first column). A section boundary is also a paragraph boundary. + Note that a blank line (only containing white space) is NOT a paragraph + boundary. + + + Also note that this does not include a '{' or '}' in the first column. When + the '{' flag is in 'cpoptions' then '{' in the first column is used as a + paragraph boundary |posix|. + { + This is no paragraph + unless the '{' is set + in 'cpoptions' + } + .IP + The nroff macros IP separates a paragraph + That means, it must be a '.' + followed by IP + .LPIt does not matter, if afterwards some + more characters follow. + .SHAlso section boundaries from the nroff + macros terminate a paragraph. That means + a character like this: + .NH + End of text here + [DATA] + + new + call append(0, text) + 1 + norm! 0d2} + + let expected =<< trim [DATA] + .IP + The nroff macros IP separates a paragraph + That means, it must be a '.' + followed by IP + .LPIt does not matter, if afterwards some + more characters follow. + .SHAlso section boundaries from the nroff + macros terminate a paragraph. That means + a character like this: + .NH + End of text here + + [DATA] + call assert_equal(expected, getline(1, '$')) + + norm! 0d} + + let expected =<< trim [DATA] + .LPIt does not matter, if afterwards some + more characters follow. + .SHAlso section boundaries from the nroff + macros terminate a paragraph. That means + a character like this: + .NH + End of text here + + [DATA] + call assert_equal(expected, getline(1, '$')) + + $ + norm! d{ + + let expected =<< trim [DATA] + .LPIt does not matter, if afterwards some + more characters follow. + .SHAlso section boundaries from the nroff + macros terminate a paragraph. That means + a character like this: + + [DATA] + call assert_equal(expected, getline(1, '$')) + + norm! d{ + + let expected =<< trim [DATA] + .LPIt does not matter, if afterwards some + more characters follow. + + [DATA] + call assert_equal(expected, getline(1, '$')) + + " Test with { in cpooptions + %d + call append(0, text) + " Nvim: no "{" flag in 'cpoptions'. + " set cpo+={ + " 1 + " norm! 0d2} + + let expected =<< trim [DATA] + { + This is no paragraph + unless the '{' is set + in 'cpoptions' + } + .IP + The nroff macros IP separates a paragraph + That means, it must be a '.' + followed by IP + .LPIt does not matter, if afterwards some + more characters follow. + .SHAlso section boundaries from the nroff + macros terminate a paragraph. That means + a character like this: + .NH + End of text here + + [DATA] + " call assert_equal(expected, getline(1, '$')) + + " $ + " norm! d} + + let expected =<< trim [DATA] + { + This is no paragraph + unless the '{' is set + in 'cpoptions' + } + .IP + The nroff macros IP separates a paragraph + That means, it must be a '.' + followed by IP + .LPIt does not matter, if afterwards some + more characters follow. + .SHAlso section boundaries from the nroff + macros terminate a paragraph. That means + a character like this: + .NH + End of text here + + [DATA] + " call assert_equal(expected, getline(1, '$')) + + " norm! gg} + " norm! d5} + + let expected =<< trim [DATA] + { + This is no paragraph + unless the '{' is set + in 'cpoptions' + } + + [DATA] + " call assert_equal(expected, getline(1, '$')) + + " Jumping to a fold should open the fold + " %d + " call setline(1, ['', 'one', 'two', '']) + " set foldenable + " 2,$fold + " call feedkeys('}', 'xt') + " call assert_equal(4, line('.')) + " call assert_equal(1, foldlevel('.')) + " call assert_equal(-1, foldclosed('.')) + " set foldenable& + + " clean up + set cpo-={ + bw! +endfunc + +" Test for section movements +func Test_normal_section() + new + let lines =<< trim [END] + int foo() + { + if (1) + { + a = 1; + } + } + [END] + call setline(1, lines) + + " jumping to a folded line using [[ should open the fold + 2,3fold + call cursor(5, 1) + call feedkeys("[[", 'xt') + call assert_equal(2, line('.')) + call assert_equal(-1, foldclosedend(line('.'))) + + bwipe! +endfunc + +" Test for changing case using u, U, gu, gU and ~ (tilde) commands +func Test_normal30_changecase() + new + call append(0, 'This is a simple test: äüöß') + norm! 1ggVu + call assert_equal('this is a simple test: äüöß', getline('.')) + norm! VU + call assert_equal('THIS IS A SIMPLE TEST: ÄÜÖSS', getline('.')) + norm! guu + call assert_equal('this is a simple test: äüöss', getline('.')) + norm! gUgU + call assert_equal('THIS IS A SIMPLE TEST: ÄÜÖSS', getline('.')) + norm! gugu + call assert_equal('this is a simple test: äüöss', getline('.')) + norm! gUU + call assert_equal('THIS IS A SIMPLE TEST: ÄÜÖSS', getline('.')) + norm! 010~ + call assert_equal('this is a SIMPLE TEST: ÄÜÖSS', getline('.')) + norm! V~ + call assert_equal('THIS IS A simple test: äüöss', getline('.')) + call assert_beeps('norm! c~') + %d + call assert_beeps('norm! ~') + + " Test for changing case across lines using 'whichwrap' + call setline(1, ['aaaaaa', 'aaaaaa']) + normal! gg10~ + call assert_equal(['AAAAAA', 'aaaaaa'], getline(1, 2)) + set whichwrap+=~ + normal! gg10~ + call assert_equal(['aaaaaa', 'AAAAaa'], getline(1, 2)) + set whichwrap& + + " try changing the case with a double byte encoding (DBCS) + %bw! + let enc = &enc + " set encoding=cp932 + call setline(1, "\u8470") + normal ~ + normal gU$gu$gUgUg~g~gugu + call assert_equal("\u8470", getline(1)) + let &encoding = enc + + " clean up + bw! +endfunc + +" Turkish ASCII turns to multi-byte. On some systems Turkish locale +" is available but toupper()/tolower() don't do the right thing. +func Test_normal_changecase_turkish() + new + try + lang tr_TR.UTF-8 + set casemap= + let iupper = toupper('i') + if iupper == "\u0130" + call setline(1, 'iI') + 1normal gUU + call assert_equal("\u0130I", getline(1)) + call assert_equal("\u0130I", toupper("iI")) + + call setline(1, 'iI') + 1normal guu + call assert_equal("i\u0131", getline(1)) + call assert_equal("i\u0131", tolower("iI")) + elseif iupper == "I" + call setline(1, 'iI') + 1normal gUU + call assert_equal("II", getline(1)) + call assert_equal("II", toupper("iI")) + + call setline(1, 'iI') + 1normal guu + call assert_equal("ii", getline(1)) + call assert_equal("ii", tolower("iI")) + else + call assert_true(false, "expected toupper('i') to be either 'I' or '\u0131'") + endif + set casemap& + call setline(1, 'iI') + 1normal gUU + call assert_equal("II", getline(1)) + call assert_equal("II", toupper("iI")) + + call setline(1, 'iI') + 1normal guu + call assert_equal("ii", getline(1)) + call assert_equal("ii", tolower("iI")) + + lang en_US.UTF-8 + catch /E197:/ + " can't use Turkish locale + throw 'Skipped: Turkish locale not available' + endtry + + bwipe! +endfunc + +" Test for r (replace) command +func Test_normal31_r_cmd() + new + call append(0, 'This is a simple test: abcd') + exe "norm! 1gg$r\<cr>" + call assert_equal(['This is a simple test: abc', '', ''], getline(1,'$')) + exe "norm! 1gg2wlr\<cr>" + call assert_equal(['This is a', 'simple test: abc', '', ''], getline(1,'$')) + exe "norm! 2gg0W5r\<cr>" + call assert_equal(['This is a', 'simple ', ' abc', '', ''], getline('1', '$')) + set autoindent + call setline(2, ['simple test: abc', '']) + exe "norm! 2gg0W5r\<cr>" + call assert_equal(['This is a', 'simple ', 'abc', '', '', ''], getline('1', '$')) + exe "norm! 1ggVr\<cr>" + call assert_equal('^M^M^M^M^M^M^M^M^M', strtrans(getline(1))) + call setline(1, 'This is a') + exe "norm! 1gg05rf" + call assert_equal('fffffis a', getline(1)) + + " When replacing characters, copy characters from above and below lines + " using CTRL-Y and CTRL-E. + " Different code paths are used for utf-8 and latin1 encodings + set showmatch + " for enc in ['latin1', 'utf-8'] + for enc in ['utf-8'] + enew! + let &encoding = enc + call setline(1, [' {a}', 'xxxxxxxxxx', ' [b]']) + exe "norm! 2gg5r\<C-Y>l5r\<C-E>" + call assert_equal(' {a}x [b]x', getline(2)) + endfor + set showmatch& + + " r command should fail in operator pending mode + call assert_beeps('normal! cr') + + " replace a tab character in visual mode + %d + call setline(1, ["a\tb", "c\td", "e\tf"]) + normal gglvjjrx + call assert_equal(['axx', 'xxx', 'xxf'], getline(1, '$')) + + " replace with a multibyte character (with multiple composing characters) + %d + new + call setline(1, 'aaa') + exe "normal $ra\u0328\u0301" + call assert_equal("aaa\u0328\u0301", getline(1)) + + " clean up + set noautoindent + bw! +endfunc + +" Test for g*, g# +func Test_normal32_g_cmd1() + new + call append(0, ['abc.x_foo', 'x_foobar.abc']) + 1 + norm! $g* + call assert_equal('x_foo', @/) + call assert_equal('x_foobar.abc', getline('.')) + norm! $g# + call assert_equal('abc', @/) + call assert_equal('abc.x_foo', getline('.')) + + " clean up + bw! +endfunc + +" Test for g`, g;, g,, g&, gv, gk, gj, gJ, g0, g^, g_, gm, g$, gM, g CTRL-G, +" gi and gI commands +func Test_normal33_g_cmd2() + call Setup_NewWindow() + " Test for g` + clearjumps + norm! ma10j + let a=execute(':jumps') + " empty jumplist + call assert_equal('>', a[-1:]) + norm! g`a + call assert_equal('>', a[-1:]) + call assert_equal(1, line('.')) + call assert_equal('1', getline('.')) + call cursor(10, 1) + norm! g'a + call assert_equal('>', a[-1:]) + call assert_equal(1, line('.')) + let v:errmsg = '' + call assert_nobeep("normal! g`\<Esc>") + call assert_equal('', v:errmsg) + call assert_nobeep("normal! g'\<Esc>") + call assert_equal('', v:errmsg) + + " Test for g; and g, + norm! g; + " there is only one change in the changelist + " currently, when we setup the window + call assert_equal(2, line('.')) + call assert_fails(':norm! g;', 'E662') + call assert_fails(':norm! g,', 'E663') + let &ul = &ul + call append('$', ['a', 'b', 'c', 'd']) + let &ul = &ul + call append('$', ['Z', 'Y', 'X', 'W']) + let a = execute(':changes') + call assert_match('2\s\+0\s\+2', a) + call assert_match('101\s\+0\s\+a', a) + call assert_match('105\s\+0\s\+Z', a) + norm! 3g; + call assert_equal(2, line('.')) + norm! 2g, + call assert_equal(105, line('.')) + + " Test for g& - global substitute + %d + call setline(1, range(1,10)) + call append('$', ['a', 'b', 'c', 'd']) + $s/\w/&&/g + exe "norm! /[1-8]\<cr>" + norm! g& + call assert_equal(['11', '22', '33', '44', '55', '66', '77', '88', '9', '110', 'a', 'b', 'c', 'dd'], getline(1, '$')) + + " Jumping to a fold using gg should open the fold + set foldenable + set foldopen+=jump + 5,8fold + call feedkeys('6gg', 'xt') + call assert_equal(1, foldlevel('.')) + call assert_equal(-1, foldclosed('.')) + set foldopen-=jump + set foldenable& + + " Test for gv + %d + call append('$', repeat(['abcdefgh'], 8)) + exe "norm! 2gg02l\<c-v>2j2ly" + call assert_equal(['cde', 'cde', 'cde'], getreg(0, 1, 1)) + " in visual mode, gv swaps current and last selected region + exe "norm! G0\<c-v>4k4lgvd" + call assert_equal(['', 'abfgh', 'abfgh', 'abfgh', 'abcdefgh', 'abcdefgh', 'abcdefgh', 'abcdefgh', 'abcdefgh'], getline(1,'$')) + exe "norm! G0\<c-v>4k4ly" + exe "norm! gvood" + call assert_equal(['', 'abfgh', 'abfgh', 'abfgh', 'fgh', 'fgh', 'fgh', 'fgh', 'fgh'], getline(1,'$')) + " gv cannot be used in operator pending mode + call assert_beeps('normal! cgv') + " gv should beep without a previously selected visual area + new + call assert_beeps('normal! gv') + close + + " Test for gk/gj + %d + 15vsp + set wrap listchars= sbr= + let lineA = 'abcdefghijklmnopqrstuvwxyz' + let lineB = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + let lineC = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' + $put =lineA + $put =lineB + + norm! 3gg0dgk + call assert_equal(['', 'abcdefghijklmno', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'], getline(1, '$')) + set nu + norm! 3gg0gjdgj + call assert_equal(['', 'abcdefghijklmno', '0123456789AMNOPQRSTUVWXYZ'], getline(1,'$')) + + " Test for gJ + norm! 2gggJ + call assert_equal(['', 'abcdefghijklmno0123456789AMNOPQRSTUVWXYZ'], getline(1,'$')) + call assert_equal(16, col('.')) + " shouldn't do anything + norm! 10gJ + call assert_equal(1, col('.')) + + " Test for g0 g^ gm g$ + exe "norm! 2gg0gji " + call assert_equal(['', 'abcdefghijk lmno0123456789AMNOPQRSTUVWXYZ'], getline(1,'$')) + norm! g0yl + call assert_equal(12, col('.')) + call assert_equal(' ', getreg(0)) + norm! g$yl + call assert_equal(22, col('.')) + call assert_equal('3', getreg(0)) + norm! gmyl + call assert_equal(17, col('.')) + call assert_equal('n', getreg(0)) + norm! g^yl + call assert_equal(15, col('.')) + call assert_equal('l', getreg(0)) + call assert_beeps('normal 5g$') + + " Test for g$ with double-width character half displayed + vsplit + 9wincmd | + setlocal nowrap nonumber + call setline(2, 'asdfasdfヨ') + 2 + normal 0g$ + call assert_equal(8, col('.')) + 10wincmd | + normal 0g$ + call assert_equal(9, col('.')) + + setlocal signcolumn=yes + 11wincmd | + normal 0g$ + call assert_equal(8, col('.')) + 12wincmd | + normal 0g$ + call assert_equal(9, col('.')) + + close + + " Test for g_ + call assert_beeps('normal! 100g_') + call setline(2, [' foo ', ' foobar ']) + normal! 2ggg_ + call assert_equal(5, col('.')) + normal! 2g_ + call assert_equal(8, col('.')) + + norm! 2ggdG + $put =lineC + + " Test for gM + norm! gMyl + call assert_equal(73, col('.')) + call assert_equal('0', getreg(0)) + " Test for 20gM + norm! 20gMyl + call assert_equal(29, col('.')) + call assert_equal('S', getreg(0)) + " Test for 60gM + norm! 60gMyl + call assert_equal(87, col('.')) + call assert_equal('E', getreg(0)) + + " Test for gM with Tab characters + call setline('.', "\ta\tb\tc\td\te\tf") + norm! gMyl + call assert_equal(6, col('.')) + call assert_equal("c", getreg(0)) + + " Test for g Ctrl-G + call setline('.', lineC) + norm! 60gMyl + set ff=unix + let a=execute(":norm! g\<c-g>") + call assert_match('Col 87 of 144; Line 2 of 2; Word 1 of 1; Byte 88 of 146', a) + + " Test for gI + norm! gIfoo + call assert_equal(['', 'foo0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'], getline(1,'$')) + + " Test for gi + wincmd c + %d + set tw=0 + call setline(1, ['foobar', 'new line']) + norm! A next word + $put ='third line' + norm! gi another word + call assert_equal(['foobar next word another word', 'new line', 'third line'], getline(1,'$')) + call setline(1, 'foobar') + normal! Ggifirst line + call assert_equal('foobarfirst line', getline(1)) + " Test gi in 'virtualedit' mode with cursor after the end of the line + set virtualedit=all + call setline(1, 'foo') + exe "normal! Abar\<Right>\<Right>\<Right>\<Right>" + call setline(1, 'foo') + normal! Ggifirst line + call assert_equal('foo first line', getline(1)) + set virtualedit& + + " Test for aboring a g command using CTRL-\ CTRL-G + exe "normal! g\<C-\>\<C-G>" + call assert_equal('foo first line', getline('.')) + + " clean up + bw! +endfunc + +func Test_normal_ex_substitute() + " This was hanging on the substitute prompt. + new + call setline(1, 'a') + exe "normal! gggQs/a/b/c\<CR>" + call assert_equal('a', getline(1)) + bwipe! +endfunc + +" Test for g CTRL-G +func Test_g_ctrl_g() + new + + let a = execute(":norm! g\<c-g>") + call assert_equal("\n--No lines in buffer--", a) + + " Test for CTRL-G (same as :file) + let a = execute(":norm! \<c-g>") + call assert_equal("\n\n\"[No Name]\" --No lines in buffer--", a) + + call setline(1, ['first line', 'second line']) + + " Test g CTRL-g with dos, mac and unix file type. + norm! gojll + set ff=dos + let a = execute(":norm! g\<c-g>") + call assert_equal("\nCol 3 of 11; Line 2 of 2; Word 3 of 4; Byte 15 of 25", a) + + set ff=mac + let a = execute(":norm! g\<c-g>") + call assert_equal("\nCol 3 of 11; Line 2 of 2; Word 3 of 4; Byte 14 of 23", a) + + set ff=unix + let a = execute(":norm! g\<c-g>") + call assert_equal("\nCol 3 of 11; Line 2 of 2; Word 3 of 4; Byte 14 of 23", a) + + " Test g CTRL-g in visual mode (v) + let a = execute(":norm! gojllvlg\<c-g>") + call assert_equal("\nSelected 1 of 2 Lines; 1 of 4 Words; 2 of 23 Bytes", a) + + " Test g CTRL-g in visual mode (CTRL-V) with end col > start col + let a = execute(":norm! \<Esc>gojll\<C-V>kllg\<c-g>") + call assert_equal("\nSelected 3 Cols; 2 of 2 Lines; 2 of 4 Words; 6 of 23 Bytes", a) + + " Test g_CTRL-g in visual mode (CTRL-V) with end col < start col + let a = execute(":norm! \<Esc>goll\<C-V>jhhg\<c-g>") + call assert_equal("\nSelected 3 Cols; 2 of 2 Lines; 2 of 4 Words; 6 of 23 Bytes", a) + + " Test g CTRL-g in visual mode (CTRL-V) with end_vcol being MAXCOL + let a = execute(":norm! \<Esc>gojll\<C-V>k$g\<c-g>") + call assert_equal("\nSelected 2 of 2 Lines; 4 of 4 Words; 17 of 23 Bytes", a) + + " There should be one byte less with noeol + set bin noeol + let a = execute(":norm! \<Esc>gog\<c-g>") + call assert_equal("\nCol 1 of 10; Line 1 of 2; Word 1 of 4; Char 1 of 23; Byte 1 of 22", a) + set bin & eol& + + call setline(1, ['Français', '日本語']) + + let a = execute(":norm! \<Esc>gojlg\<c-g>") + call assert_equal("\nCol 4-3 of 9-6; Line 2 of 2; Word 2 of 2; Char 11 of 13; Byte 16 of 20", a) + + let a = execute(":norm! \<Esc>gojvlg\<c-g>") + call assert_equal("\nSelected 1 of 2 Lines; 1 of 2 Words; 2 of 13 Chars; 6 of 20 Bytes", a) + + let a = execute(":norm! \<Esc>goll\<c-v>jlg\<c-g>") + call assert_equal("\nSelected 4 Cols; 2 of 2 Lines; 2 of 2 Words; 6 of 13 Chars; 11 of 20 Bytes", a) + + set fenc=utf8 bomb + let a = execute(":norm! \<Esc>gojlg\<c-g>") + call assert_equal("\nCol 4-3 of 9-6; Line 2 of 2; Word 2 of 2; Char 11 of 13; Byte 16 of 20(+3 for BOM)", a) + + set fenc=utf16 bomb + let a = execute(":norm! g\<c-g>") + call assert_equal("\nCol 4-3 of 9-6; Line 2 of 2; Word 2 of 2; Char 11 of 13; Byte 16 of 20(+2 for BOM)", a) + + set fenc=utf32 bomb + let a = execute(":norm! g\<c-g>") + call assert_equal("\nCol 4-3 of 9-6; Line 2 of 2; Word 2 of 2; Char 11 of 13; Byte 16 of 20(+4 for BOM)", a) + + set fenc& bomb& + + set ff& + bwipe! +endfunc + +" Test for g8 +func Test_normal34_g_cmd3() + new + let a=execute(':norm! 1G0g8') + call assert_equal("\nNUL", a) + + call setline(1, 'abcdefghijklmnopqrstuvwxyzäüö') + let a=execute(':norm! 1G$g8') + call assert_equal("\nc3 b6 ", a) + + call setline(1, "a\u0302") + let a=execute(':norm! 1G0g8') + call assert_equal("\n61 + cc 82 ", a) + + " clean up + bw! +endfunc + +" Test 8g8 which finds invalid utf8 at or after the cursor. +func Test_normal_8g8() + new + + " With invalid byte. + call setline(1, "___\xff___") + norm! 1G08g8g + call assert_equal([0, 1, 4, 0, 1], getcurpos()) + + " With invalid byte before the cursor. + call setline(1, "___\xff___") + norm! 1G$h8g8g + call assert_equal([0, 1, 6, 0, 9], getcurpos()) + + " With truncated sequence. + call setline(1, "___\xE2\x82___") + norm! 1G08g8g + call assert_equal([0, 1, 4, 0, 1], getcurpos()) + + " With overlong sequence. + call setline(1, "___\xF0\x82\x82\xAC___") + norm! 1G08g8g + call assert_equal([0, 1, 4, 0, 1], getcurpos()) + + " With valid utf8. + call setline(1, "café") + norm! 1G08g8 + call assert_equal([0, 1, 1, 0, 1], getcurpos()) + + bw! +endfunc + +" Test for g< +func Test_normal35_g_cmd4() + " Cannot capture its output, + " probably a bug, therefore, test disabled: + throw "Skipped: output of g< can't be tested currently" + echo "a\nb\nc\nd" + let b=execute(':norm! g<') + call assert_true(!empty(b), 'failed `execute(g<)`') +endfunc + +" Test for gp gP go +func Test_normal36_g_cmd5() + new + call append(0, 'abcdefghijklmnopqrstuvwxyz') + set ff=unix + " Test for gp gP + call append(1, range(1,10)) + 1 + norm! 1yy + 3 + norm! gp + call assert_equal([0, 5, 1, 0, 1], getcurpos()) + $ + norm! gP + call assert_equal([0, 14, 1, 0, 1], getcurpos()) + + " Test for go + norm! 26go + call assert_equal([0, 1, 26, 0, 26], getcurpos()) + norm! 27go + call assert_equal([0, 1, 26, 0, 26], getcurpos()) + norm! 28go + call assert_equal([0, 2, 1, 0, 1], getcurpos()) + set ff=dos + norm! 29go + call assert_equal([0, 2, 1, 0, 1], getcurpos()) + set ff=unix + norm! gg0 + norm! 101go + call assert_equal([0, 13, 26, 0, 26], getcurpos()) + norm! 103go + call assert_equal([0, 14, 1, 0, 1], getcurpos()) + " count > buffer content + norm! 120go + call assert_equal([0, 14, 1, 0, v:maxcol], getcurpos()) + " clean up + bw! +endfunc + +" Test for gt and gT +func Test_normal37_g_cmd6() + tabnew 1.txt + tabnew 2.txt + tabnew 3.txt + norm! 1gt + call assert_equal(1, tabpagenr()) + norm! 3gt + call assert_equal(3, tabpagenr()) + norm! 1gT + " count gT goes not to the absolute tabpagenumber + " but, but goes to the count previous tabpagenumber + call assert_equal(2, tabpagenr()) + " wrap around + norm! 3gT + call assert_equal(3, tabpagenr()) + " gt does not wrap around + norm! 5gt + call assert_equal(3, tabpagenr()) + + for i in range(3) + tabclose + endfor + " clean up + call assert_fails(':tabclose', 'E784:') +endfunc + +" Test for <Home> and <C-Home> key +func Test_normal38_nvhome() + new + call setline(1, range(10)) + $ + setl et sw=2 + norm! V10>$ + " count is ignored + exe "norm! 10\<home>" + call assert_equal(1, col('.')) + exe "norm! \<home>" + call assert_equal([0, 10, 1, 0, 1], getcurpos()) + exe "norm! 5\<c-home>" + call assert_equal([0, 5, 1, 0, 1], getcurpos()) + exe "norm! \<c-home>" + call assert_equal([0, 1, 1, 0, 1], getcurpos()) + exe "norm! G\<c-kHome>" + call assert_equal([0, 1, 1, 0, 1], getcurpos()) + + " clean up + bw! +endfunc + +" Test for <End> and <C-End> keys +func Test_normal_nvend() + new + call setline(1, map(range(1, 10), '"line" .. v:val')) + exe "normal! \<End>" + call assert_equal(5, col('.')) + exe "normal! 4\<End>" + call assert_equal([4, 5], [line('.'), col('.')]) + exe "normal! \<C-End>" + call assert_equal([10, 6], [line('.'), col('.')]) + + bwipe! +endfunc + +" Test for cw cW ce +func Test_normal39_cw() + " Test for cw and cW on whitespace + new + set tw=0 + call append(0, 'here are some words') + norm! 1gg0elcwZZZ + call assert_equal('hereZZZare some words', getline('.')) + norm! 1gg0elcWYYY + call assert_equal('hereZZZareYYYsome words', getline('.')) + norm! 2gg0cwfoo + call assert_equal('foo', getline('.')) + + call setline(1, 'one; two') + call cursor(1, 1) + call feedkeys('cwvim', 'xt') + call assert_equal('vim; two', getline(1)) + call feedkeys('0cWone', 'xt') + call assert_equal('one two', getline(1)) + "When cursor is at the end of a word 'ce' will change until the end of the + "next word, but 'cw' will change only one character + call setline(1, 'one two') + call feedkeys('0ecwce', 'xt') + call assert_equal('once two', getline(1)) + call setline(1, 'one two') + call feedkeys('0ecely', 'xt') + call assert_equal('only', getline(1)) + + " clean up + bw! +endfunc + +" Test for CTRL-\ commands +func Test_normal40_ctrl_bsl() + new + call append(0, 'here are some words') + exe "norm! 1gg0a\<C-\>\<C-N>" + call assert_equal('n', mode()) + call assert_equal(1, col('.')) + call assert_equal('', visualmode()) + exe "norm! 1gg0viw\<C-\>\<C-N>" + call assert_equal('n', mode()) + call assert_equal(4, col('.')) + exe "norm! 1gg0a\<C-\>\<C-G>" + call assert_equal('n', mode()) + call assert_equal(1, col('.')) + "imap <buffer> , <c-\><c-n> + " set im + exe ":norm! \<c-\>\<c-n>dw" + " set noim + call assert_equal('are some words', getline(1)) + call assert_false(&insertmode) + call assert_beeps("normal! \<C-\>\<C-A>") + + " Using CTRL-\ CTRL-N in cmd window should close the window + call feedkeys("q:\<C-\>\<C-N>", 'xt') + call assert_equal('', getcmdwintype()) + + " clean up + bw! +endfunc + +" Test for <c-r>=, <c-r><c-r>= and <c-r><c-o>= in insert mode +func Test_normal41_insert_reg() + new + set sts=2 sw=2 ts=8 tw=0 + call append(0, ["aaa\tbbb\tccc", '', '', '']) + let a=getline(1) + norm! 2gg0 + exe "norm! a\<c-r>=a\<cr>" + norm! 3gg0 + exe "norm! a\<c-r>\<c-r>=a\<cr>" + norm! 4gg0 + exe "norm! a\<c-r>\<c-o>=a\<cr>" + call assert_equal(['aaa bbb ccc', 'aaa bbb ccc', 'aaa bbb ccc', 'aaa bbb ccc', ''], getline(1, '$')) + + " clean up + set sts=0 sw=8 ts=8 + bw! +endfunc + +" Test for Ctrl-D and Ctrl-U +func Test_normal42_halfpage() + call Setup_NewWindow() + call assert_equal(5, &scroll) + exe "norm! \<c-d>" + call assert_equal('6', getline('.')) + exe "norm! 2\<c-d>" + call assert_equal('8', getline('.')) + call assert_equal(2, &scroll) + set scroll=5 + exe "norm! \<c-u>" + call assert_equal('3', getline('.')) + 1 + set scrolloff=5 + exe "norm! \<c-d>" + call assert_equal('10', getline('.')) + exe "norm! \<c-u>" + call assert_equal('5', getline('.')) + 1 + set scrolloff=99 + exe "norm! \<c-d>" + call assert_equal('10', getline('.')) + set scrolloff=0 + 100 + exe "norm! $\<c-u>" + call assert_equal('95', getline('.')) + call assert_equal([0, 95, 1, 0, 1], getcurpos()) + 100 + set nostartofline + exe "norm! $\<c-u>" + call assert_equal('95', getline('.')) + call assert_equal([0, 95, 2, 0, v:maxcol], getcurpos()) + " cleanup + set startofline + bw! +endfunc + +func Test_normal45_drop() + if !has('dnd') + " The ~ register does not exist + call assert_beeps('norm! "~') + return + endif + + " basic test for drag-n-drop + " unfortunately, without a gui, we can't really test much here, + " so simply test that ~p fails (which uses the drop register) + new + call assert_fails(':norm! "~p', 'E353') + call assert_equal([], getreg('~', 1, 1)) + " the ~ register is read only + call assert_fails(':let @~="1"', 'E354') + bw! +endfunc + +func Test_normal46_ignore() + new + " How to test this? + " let's just for now test, that the buffer + " does not change + call feedkeys("\<c-s>", 't') + call assert_equal([''], getline(1,'$')) + + " no valid commands + exe "norm! \<char-0x100>" + call assert_equal([''], getline(1,'$')) + + exe "norm! ä" + call assert_equal([''], getline(1,'$')) + + " clean up + bw! +endfunc + +func Test_normal47_visual_buf_wipe() + " This was causing a crash or ml_get error. + enew! + call setline(1,'xxx') + normal $ + new + call setline(1, range(1,2)) + 2 + exe "norm \<C-V>$" + bw! + norm yp + set nomodified +endfunc + +func Test_normal48_wincmd() + new + exe "norm! \<c-w>c" + call assert_equal(1, winnr('$')) + call assert_fails(":norm! \<c-w>c", "E444") +endfunc + +func Test_normal49_counts() + new + call setline(1, 'one two three four five six seven eight nine ten') + 1 + norm! 3d2w + call assert_equal('seven eight nine ten', getline(1)) + bw! +endfunc + +func Test_normal50_commandline() + CheckFeature timers + CheckFeature cmdline_hist + func! DoTimerWork(id) + call assert_equal('[Command Line]', bufname('')) + " should fail, with E11, but does fail with E23? + "call feedkeys("\<c-^>", 'tm') + + " should also fail with E11 + call assert_fails(":wincmd p", 'E11') + " return from commandline window + call feedkeys("\<cr>") + endfunc + + let oldlang=v:lang + lang C + set updatetime=20 + call timer_start(100, 'DoTimerWork') + try + " throws E23, for whatever reason... + call feedkeys('q:', 'x!') + catch /E23/ + " no-op + endtry + " clean up + set updatetime=4000 + exe "lang" oldlang + bw! +endfunc + +func Test_normal51_FileChangedRO() + CheckFeature autocmd + call writefile(['foo'], 'Xreadonly.log') + new Xreadonly.log + setl ro + au FileChangedRO <buffer> :call feedkeys("\<c-^>", 'tix') + call assert_fails(":norm! Af", 'E788') + call assert_equal(['foo'], getline(1,'$')) + call assert_equal('Xreadonly.log', bufname('')) + + " cleanup + bw! + call delete("Xreadonly.log") +endfunc + +func Test_normal52_rl() + CheckFeature rightleft + new + call setline(1, 'abcde fghij klmnopq') + norm! 1gg$ + set rl + call assert_equal(19, col('.')) + call feedkeys('l', 'tx') + call assert_equal(18, col('.')) + call feedkeys('h', 'tx') + call assert_equal(19, col('.')) + call feedkeys("\<right>", 'tx') + call assert_equal(18, col('.')) + call feedkeys("\<left>", 'tx') + call assert_equal(19, col('.')) + call feedkeys("\<s-right>", 'tx') + call assert_equal(13, col('.')) + call feedkeys("\<c-right>", 'tx') + call assert_equal(7, col('.')) + call feedkeys("\<c-left>", 'tx') + call assert_equal(13, col('.')) + call feedkeys("\<s-left>", 'tx') + call assert_equal(19, col('.')) + call feedkeys("<<", 'tx') + call assert_equal(' abcde fghij klmnopq',getline(1)) + call feedkeys(">>", 'tx') + call assert_equal('abcde fghij klmnopq',getline(1)) + + " cleanup + set norl + bw! +endfunc + +func Test_normal54_Ctrl_bsl() + new + call setline(1, 'abcdefghijklmn') + exe "norm! df\<c-\>\<c-n>" + call assert_equal(['abcdefghijklmn'], getline(1,'$')) + exe "norm! df\<c-\>\<c-g>" + call assert_equal(['abcdefghijklmn'], getline(1,'$')) + exe "norm! df\<c-\>m" + call assert_equal(['abcdefghijklmn'], getline(1,'$')) + + call setline(2, 'abcdefghijklmnāf') + norm! 2gg0 + exe "norm! df\<Char-0x101>" + call assert_equal(['abcdefghijklmn', 'f'], getline(1,'$')) + norm! 1gg0 + exe "norm! df\<esc>" + call assert_equal(['abcdefghijklmn', 'f'], getline(1,'$')) + + " clean up + bw! +endfunc + +func Test_normal_large_count() + " This may fail with 32bit long, how do we detect that? + new + normal o + normal 6666666666dL + bwipe! +endfunc + +func Test_delete_until_paragraph() + new + normal grádv} + call assert_equal('á', getline(1)) + normal grád} + call assert_equal('', getline(1)) + bwipe! +endfunc + +" Test for the gr (virtual replace) command +func Test_gr_command() + enew! + " Test for the bug fixed by 7.4.387 + let save_cpo = &cpo + call append(0, ['First line', 'Second line', 'Third line']) + exe "normal i\<C-G>u" + call cursor(2, 1) + set cpo-=X + normal 4gro + call assert_equal('oooond line', getline(2)) + undo + set cpo+=X + normal 4gro + call assert_equal('ooooecond line', getline(2)) + let &cpo = save_cpo + + normal! ggvegrx + call assert_equal('xxxxx line', getline(1)) + exe "normal! gggr\<C-V>122" + call assert_equal('zxxxx line', getline(1)) + + set virtualedit=all + normal! 15|grl + call assert_equal('zxxxx line l', getline(1)) + set virtualedit& + set nomodifiable + call assert_fails('normal! grx', 'E21:') + call assert_fails('normal! gRx', 'E21:') + call assert_nobeep("normal! gr\<Esc>") + set modifiable& + + call assert_nobeep("normal! gr\<Esc>") + call assert_nobeep("normal! cgr\<Esc>") + call assert_beeps("normal! cgrx") + + call assert_equal('zxxxx line l', getline(1)) + exe "normal! 2|gr\<C-V>\<Esc>" + call assert_equal("z\<Esc>xx line l", getline(1)) + + call setline(1, 'abcdef') + exe "normal! 0gr\<C-O>lx" + call assert_equal("\<C-O>def", getline(1)) + + call setline(1, 'abcdef') + exe "normal! 0gr\<C-G>lx" + call assert_equal("\<C-G>def", getline(1)) + + bwipe! +endfunc + +func Test_nv_hat_count() + %bwipeout! + let l:nr = bufnr('%') + 1 + call assert_fails(':execute "normal! ' . l:nr . '\<C-^>"', 'E92:') + + edit Xfoo + let l:foo_nr = bufnr('Xfoo') + + edit Xbar + let l:bar_nr = bufnr('Xbar') + + " Make sure we are not just using the alternate file. + edit Xbaz + + call feedkeys(l:foo_nr . "\<C-^>", 'tx') + call assert_equal('Xfoo', fnamemodify(bufname('%'), ':t')) + + call feedkeys(l:bar_nr . "\<C-^>", 'tx') + call assert_equal('Xbar', fnamemodify(bufname('%'), ':t')) + + %bwipeout! +endfunc + +func Test_message_when_using_ctrl_c() + " Make sure no buffers are changed. + %bwipe! + + exe "normal \<C-C>" + call assert_match("Type :qa and press <Enter> to exit Nvim", Screenline(&lines)) + + new + cal setline(1, 'hi!') + exe "normal \<C-C>" + call assert_match("Type :qa! and press <Enter> to abandon all changes and exit Nvim", Screenline(&lines)) + + bwipe! +endfunc + +func Test_mode_updated_after_ctrl_c() + CheckScreendump + + let buf = RunVimInTerminal('', {'rows': 5}) + call term_sendkeys(buf, "i") + call term_sendkeys(buf, "\<C-O>") + " wait a moment so that the "-- (insert) --" message is displayed + call TermWait(buf, 50) + call term_sendkeys(buf, "\<C-C>") + call VerifyScreenDump(buf, 'Test_mode_updated_1', {}) + + call StopVimInTerminal(buf) +endfunc + +" Test for '[m', ']m', '[M' and ']M' +" Jumping to beginning and end of methods in Java-like languages +func Test_java_motion() + new + call assert_beeps('normal! [m') + call assert_beeps('normal! ]m') + call assert_beeps('normal! [M') + call assert_beeps('normal! ]M') + let lines =<< trim [CODE] + Piece of Java + { + tt m1 { + t1; + } e1 + + tt m2 { + t2; + } e2 + + tt m3 { + if (x) + { + t3; + } + } e3 + } + [CODE] + call setline(1, lines) + + normal gg + + normal 2]maA + call assert_equal("\ttt m1 {A", getline('.')) + call assert_equal([3, 9, 16], [line('.'), col('.'), virtcol('.')]) + + normal j]maB + call assert_equal("\ttt m2 {B", getline('.')) + call assert_equal([7, 9, 16], [line('.'), col('.'), virtcol('.')]) + + normal ]maC + call assert_equal("\ttt m3 {C", getline('.')) + call assert_equal([11, 9, 16], [line('.'), col('.'), virtcol('.')]) + + normal [maD + call assert_equal("\ttt m3 {DC", getline('.')) + call assert_equal([11, 9, 16], [line('.'), col('.'), virtcol('.')]) + + normal k2[maE + call assert_equal("\ttt m1 {EA", getline('.')) + call assert_equal([3, 9, 16], [line('.'), col('.'), virtcol('.')]) + + normal 3[maF + call assert_equal("{F", getline('.')) + call assert_equal([2, 2, 2], [line('.'), col('.'), virtcol('.')]) + + normal ]MaG + call assert_equal("\t}G e1", getline('.')) + call assert_equal([5, 3, 10], [line('.'), col('.'), virtcol('.')]) + + normal j2]MaH + call assert_equal("\t}H e3", getline('.')) + call assert_equal([16, 3, 10], [line('.'), col('.'), virtcol('.')]) + + normal ]M]M + normal aI + call assert_equal("}I", getline('.')) + call assert_equal([17, 2, 2], [line('.'), col('.'), virtcol('.')]) + + normal 2[MaJ + call assert_equal("\t}JH e3", getline('.')) + call assert_equal([16, 3, 10], [line('.'), col('.'), virtcol('.')]) + + normal k[MaK + call assert_equal("\t}K e2", getline('.')) + call assert_equal([9, 3, 10], [line('.'), col('.'), virtcol('.')]) + + normal 3[MaL + call assert_equal("{LF", getline('.')) + call assert_equal([2, 2, 2], [line('.'), col('.'), virtcol('.')]) + + call cursor(2, 1) + call assert_beeps('norm! 5]m') + + " jumping to a method in a fold should open the fold + 6,10fold + call feedkeys("gg3]m", 'xt') + call assert_equal([7, 8, 15], [line('.'), col('.'), virtcol('.')]) + call assert_equal(-1, foldclosedend(7)) + + bwipe! +endfunc + +" Tests for g cmds +func Test_normal_gdollar_cmd() + call Setup_NewWindow() + " Make long lines that will wrap + %s/$/\=repeat(' foobar', 10)/ + 20vsp + set wrap + " Test for g$ with count + norm! gg + norm! 0vg$y + call assert_equal(20, col("'>")) + call assert_equal('1 foobar foobar foob', getreg(0)) + norm! gg + norm! 0v4g$y + call assert_equal(72, col("'>")) + call assert_equal('1 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.."\n", getreg(0)) + norm! gg + norm! 0v6g$y + call assert_equal(40, col("'>")) + call assert_equal('1 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.. "\n".. + \ '2 foobar foobar foobar foobar foobar foo', getreg(0)) + set nowrap + " clean up + norm! gg + norm! 0vg$y + call assert_equal(20, col("'>")) + call assert_equal('1 foobar foobar foob', getreg(0)) + norm! gg + norm! 0v4g$y + call assert_equal(20, col("'>")) + call assert_equal('1 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.. "\n".. + \ '2 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.. "\n".. + \ '3 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.. "\n".. + \ '4 foobar foobar foob', getreg(0)) + norm! gg + norm! 0v6g$y + call assert_equal(20, col("'>")) + call assert_equal('1 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.. "\n".. + \ '2 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.. "\n".. + \ '3 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.. "\n".. + \ '4 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.. "\n".. + \ '5 foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar'.. "\n".. + \ '6 foobar foobar foob', getreg(0)) + " Move to last line, also down movement is not possible, should still move + " the cursor to the last visible char + norm! G + norm! 0v6g$y + call assert_equal(20, col("'>")) + call assert_equal('100 foobar foobar fo', getreg(0)) + bw! +endfunc + +func Test_normal_gk_gj() + " needs 80 column new window + new + vert 80new + call assert_beeps('normal gk') + put =[repeat('x',90)..' {{{1', 'x {{{1'] + norm! gk + " In a 80 column wide terminal the window will be only 78 char + " (because Vim will leave space for the other window), + " but if the terminal is larger, it will be 80 chars, so verify the + " cursor column correctly. + call assert_equal(winwidth(0)+1, col('.')) + call assert_equal(winwidth(0)+1, virtcol('.')) + norm! j + call assert_equal(6, col('.')) + call assert_equal(6, virtcol('.')) + norm! gk + call assert_equal(95, col('.')) + call assert_equal(95, virtcol('.')) + %bw! + + " needs 80 column new window + new + vert 80new + call assert_beeps('normal gj') + set number + set numberwidth=10 + set cpoptions+=n + put =[repeat('0',90), repeat('1',90)] + norm! 075l + call assert_equal(76, col('.')) + norm! gk + call assert_equal(1, col('.')) + norm! gk + call assert_equal(76, col('.')) + norm! gk + call assert_equal(1, col('.')) + norm! gj + call assert_equal(76, col('.')) + norm! gj + call assert_equal(1, col('.')) + norm! gj + call assert_equal(76, col('.')) + " When 'nowrap' is set, gk and gj behave like k and j + set nowrap + normal! gk + call assert_equal([2, 76], [line('.'), col('.')]) + normal! gj + call assert_equal([3, 76], [line('.'), col('.')]) + %bw! + set cpoptions& number& numberwidth& wrap& +endfunc + +" Test for using : to run a multi-line Ex command in operator pending mode +func Test_normal_yank_with_excmd() + new + call setline(1, ['foo', 'bar', 'baz']) + let @a = '' + call feedkeys("\"ay:if v:true\<CR>normal l\<CR>endif\<CR>", 'xt') + call assert_equal('f', @a) + + bwipe! +endfunc + +" Test for supplying a count to a normal-mode command across a cursorhold call +func Test_normal_cursorhold_with_count() + throw 'Skipped: Nvim removed <CursorHold> key' + func s:cHold() + let g:cHold_Called += 1 + endfunc + new + augroup normalcHoldTest + au! + au CursorHold <buffer> call s:cHold() + augroup END + let g:cHold_Called = 0 + call feedkeys("3\<CursorHold>2ix", 'xt') + call assert_equal(1, g:cHold_Called) + call assert_equal(repeat('x', 32), getline(1)) + augroup normalcHoldTest + au! + augroup END + au! normalcHoldTest + + bwipe! + delfunc s:cHold +endfunc + +" Test for using a count and a command with CTRL-W +func Test_wincmd_with_count() + call feedkeys("\<C-W>12n", 'xt') + call assert_equal(12, winheight(0)) +endfunc + +" Test for 'b', 'B' 'ge' and 'gE' commands +func Test_horiz_motion() + new + normal! gg + call assert_beeps('normal! b') + call assert_beeps('normal! B') + call assert_beeps('normal! gE') + call assert_beeps('normal! ge') + " <S-Backspace> moves one word left and <C-Backspace> moves one WORD left + call setline(1, 'one ,two ,three') + exe "normal! $\<S-BS>" + call assert_equal(11, col('.')) + exe "normal! $\<C-BS>" + call assert_equal(10, col('.')) + + bwipe! +endfunc + +" Test for using a ":" command in operator pending mode +func Test_normal_colon_op() + new + call setline(1, ['one', 'two']) + call assert_beeps("normal! Gc:d\<CR>") + call assert_equal(['one'], getline(1, '$')) + + call setline(1, ['one…two…three!']) + normal! $ + " Using ":" as a movement is characterwise exclusive + call feedkeys("d:normal! F…\<CR>", 'xt') + call assert_equal(['one…two!'], getline(1, '$')) + " Check that redoing a command with 0x80 bytes works + call feedkeys('.', 'xt') + call assert_equal(['one!'], getline(1, '$')) + + call setline(1, ['one', 'two', 'three', 'four', 'five']) + " Add this to the command history + call feedkeys(":normal! G0\<CR>", 'xt') + " Use :normal! with control characters in operator pending mode + call feedkeys("d:normal! \<C-V>\<C-P>\<C-V>\<C-P>\<CR>", 'xt') + call assert_equal(['one', 'two', 'five'], getline(1, '$')) + " Check that redoing a command with control characters works + call feedkeys('.', 'xt') + call assert_equal(['five'], getline(1, '$')) + + bwipe! +endfunc + +" Test for d and D commands +func Test_normal_delete_cmd() + new + " D in an empty line + call setline(1, '') + normal D + call assert_equal('', getline(1)) + " D in an empty line in virtualedit mode + set virtualedit=all + normal D + call assert_equal('', getline(1)) + set virtualedit& + " delete to a readonly register + call setline(1, ['abcd']) + call assert_beeps('normal ":d2l') + + " D and d with 'nomodifiable' + call setline(1, ['abcd']) + setlocal nomodifiable + call assert_fails('normal D', 'E21:') + call assert_fails('normal d$', 'E21:') + + bwipe! +endfunc + +" Test for deleting or changing characters across lines with 'whichwrap' +" containing 's'. Should count <EOL> as one character. +func Test_normal_op_across_lines() + new + set whichwrap& + call setline(1, ['one two', 'three four']) + exe "norm! $3d\<Space>" + call assert_equal(['one twhree four'], getline(1, '$')) + + call setline(1, ['one two', 'three four']) + exe "norm! $3c\<Space>x" + call assert_equal(['one twxhree four'], getline(1, '$')) + + set whichwrap+=l + call setline(1, ['one two', 'three four']) + exe "norm! $3x" + call assert_equal(['one twhree four'], getline(1, '$')) + + bwipe! + set whichwrap& +endfunc + +" Test for 'w' and 'b' commands +func Test_normal_word_move() + new + call setline(1, ['foo bar a', '', 'foo bar b']) + " copy a single character word at the end of a line + normal 1G$yw + call assert_equal('a', @") + " copy a single character word at the end of a file + normal G$yw + call assert_equal('b', @") + " check for a word movement handling an empty line properly + normal 1G$vwy + call assert_equal("a\n\n", @") + + " copy using 'b' command + %d + " non-empty blank line at the start of file + call setline(1, [' ', 'foo bar']) + normal 2Gyb + call assert_equal(" \n", @") + " try to copy backwards from the start of the file + call setline(1, ['one two', 'foo bar']) + call assert_beeps('normal ggyb') + " 'b' command should stop at an empty line + call setline(1, ['one two', '', 'foo bar']) + normal 3Gyb + call assert_equal("\n", @") + normal 3Gy2b + call assert_equal("two\n", @") + " 'b' command should not stop at a non-empty blank line + call setline(1, ['one two', ' ', 'foo bar']) + normal 3Gyb + call assert_equal("two\n ", @") + + bwipe! +endfunc + +" Test for 'scrolloff' with a long line that doesn't fit in the screen +func Test_normal_scrolloff() + 10new + 60vnew + call setline(1, ' 1 ' .. repeat('a', 57) + \ .. ' 2 ' .. repeat('b', 57) + \ .. ' 3 ' .. repeat('c', 57) + \ .. ' 4 ' .. repeat('d', 57) + \ .. ' 5 ' .. repeat('e', 57) + \ .. ' 6 ' .. repeat('f', 57) + \ .. ' 7 ' .. repeat('g', 57) + \ .. ' 8 ' .. repeat('h', 57) + \ .. ' 9 ' .. repeat('i', 57) + \ .. '10 ' .. repeat('j', 57) + \ .. '11 ' .. repeat('k', 57) + \ .. '12 ' .. repeat('l', 57) + \ .. '13 ' .. repeat('m', 57) + \ .. '14 ' .. repeat('n', 57) + \ .. '15 ' .. repeat('o', 57) + \ .. '16 ' .. repeat('p', 57) + \ .. '17 ' .. repeat('q', 57) + \ .. '18 ' .. repeat('r', 57) + \ .. '19 ' .. repeat('s', 57) + \ .. '20 ' .. repeat('t', 57) + \ .. '21 ' .. repeat('u', 57) + \ .. '22 ' .. repeat('v', 57) + \ .. '23 ' .. repeat('w', 57) + \ .. '24 ' .. repeat('x', 57) + \ .. '25 ' .. repeat('y', 57) + \ .. '26 ' .. repeat('z', 57) + \ ) + set scrolloff=10 + normal gg10gj + call assert_equal(6, winline()) + normal 10gj + call assert_equal(6, winline()) + normal 10gk + call assert_equal(6, winline()) + normal 0 + call assert_equal(1, winline()) + normal $ + call assert_equal(10, winline()) + + set scrolloff& + bwipe! +endfunc + +" Test for vertical scrolling with CTRL-F and CTRL-B with a long line +func Test_normal_vert_scroll_longline() + 10new + 80vnew + call setline(1, range(1, 10)) + call append(5, repeat('a', 1000)) + exe "normal gg\<C-F>" + call assert_equal(6, line('.')) + exe "normal \<C-F>\<C-F>" + call assert_equal(11, line('.')) + call assert_equal(1, winline()) + exe "normal \<C-B>" + call assert_equal(10, line('.')) + call assert_equal(3, winline()) + exe "normal \<C-B>\<C-B>" + call assert_equal(5, line('.')) + call assert_equal(5, winline()) + + bwipe! +endfunc + +" Test for jumping in a file using % +func Test_normal_percent_jump() + new + call setline(1, range(1, 100)) + + " jumping to a folded line should open the fold + 25,75fold + call feedkeys('50%', 'xt') + call assert_equal(50, line('.')) + call assert_equal(-1, foldclosedend(50)) + + bwipe! +endfunc + +" Test for << and >> commands to shift text by 'shiftwidth' +func Test_normal_shift_rightleft() + new + call setline(1, ['one', '', "\t", ' two', "\tthree", ' four']) + set shiftwidth=2 tabstop=8 + normal gg6>> + call assert_equal([' one', '', "\t ", ' two', "\t three", "\tfour"], + \ getline(1, '$')) + normal ggVG2>> + call assert_equal([' one', '', "\t ", "\ttwo", + \ "\t three", "\t four"], getline(1, '$')) + normal gg6<< + call assert_equal([' one', '', "\t ", ' two', "\t three", + \ "\t four"], getline(1, '$')) + normal ggVG2<< + call assert_equal(['one', '', "\t", ' two', "\tthree", ' four'], + \ getline(1, '$')) + set shiftwidth& tabstop& + bw! +endfunc + +" Some commands like yy, cc, dd, >>, << and !! accept a count after +" typing the first letter of the command. +func Test_normal_count_after_operator() + new + setlocal shiftwidth=4 tabstop=8 autoindent + call setline(1, ['one', 'two', 'three', 'four', 'five']) + let @a = '' + normal! j"ay4y + call assert_equal("two\nthree\nfour\nfive\n", @a) + normal! 3G>2> + call assert_equal(['one', 'two', ' three', ' four', 'five'], + \ getline(1, '$')) + exe "normal! 3G0c2cred\nblue" + call assert_equal(['one', 'two', ' red', ' blue', 'five'], + \ getline(1, '$')) + exe "normal! gg<8<" + call assert_equal(['one', 'two', 'red', 'blue', 'five'], + \ getline(1, '$')) + exe "normal! ggd3d" + call assert_equal(['blue', 'five'], getline(1, '$')) + call setline(1, range(1, 4)) + call feedkeys("gg!3!\<C-B>\"\<CR>", 'xt') + call assert_equal('".,.+2!', @:) + call feedkeys("gg!1!\<C-B>\"\<CR>", 'xt') + call assert_equal('".!', @:) + call feedkeys("gg!9!\<C-B>\"\<CR>", 'xt') + call assert_equal('".,$!', @:) + bw! +endfunc + +func Test_normal_gj_on_extra_wide_char() + new | 25vsp + let text='1 foooooooo ar e inszwe1 foooooooo inszwei' . + \ ' i drei vier fünf sechs sieben acht un zehn elf zwöfl' . + \ ' dreizehn v ierzehn fünfzehn' + put =text + call cursor(2,1) + norm! gj + call assert_equal([0,2,25,0], getpos('.')) + bw! +endfunc + +func Test_normal_count_out_of_range() + new + call setline(1, 'text') + normal 44444444444| + call assert_equal(999999999, v:count) + normal 444444444444| + call assert_equal(999999999, v:count) + normal 4444444444444| + call assert_equal(999999999, v:count) + normal 4444444444444444444| + call assert_equal(999999999, v:count) + + normal 9y99999999| + call assert_equal(899999991, v:count) + normal 10y99999999| + call assert_equal(999999999, v:count) + normal 44444444444y44444444444| + call assert_equal(999999999, v:count) + bwipe! +endfunc + +" Test that mouse shape is restored to Normal mode after failed "c" operation. +func Test_mouse_shape_after_failed_change() + CheckFeature mouseshape + CheckCanRunGui + + let lines =<< trim END + vim9script + set mouseshape+=o:busy + setlocal nomodifiable + var mouse_shapes = [] + + feedkeys('c') + timer_start(50, (_) => { + mouse_shapes += [getmouseshape()] + timer_start(50, (_) => { + feedkeys('c') + timer_start(50, (_) => { + mouse_shapes += [getmouseshape()] + timer_start(50, (_) => { + writefile(mouse_shapes, 'Xmouseshapes') + quit + }) + }) + }) + }) + END + call writefile(lines, 'Xmouseshape.vim', 'D') + call RunVim([], [], "-g -S Xmouseshape.vim") + sleep 300m + call assert_equal(['busy', 'arrow'], readfile('Xmouseshapes')) + + call delete('Xmouseshapes') +endfunc + +" Test that mouse shape is restored to Normal mode after cancelling "gr". +func Test_mouse_shape_after_cancelling_gr() + CheckFeature mouseshape + CheckCanRunGui + + let lines =<< trim END + vim9script + var mouse_shapes = [] + + feedkeys('gr') + timer_start(50, (_) => { + mouse_shapes += [getmouseshape()] + timer_start(50, (_) => { + feedkeys("\<Esc>") + timer_start(50, (_) => { + mouse_shapes += [getmouseshape()] + timer_start(50, (_) => { + writefile(mouse_shapes, 'Xmouseshapes') + quit + }) + }) + }) + }) + END + call writefile(lines, 'Xmouseshape.vim', 'D') + call RunVim([], [], "-g -S Xmouseshape.vim") + sleep 300m + call assert_equal(['beam', 'arrow'], readfile('Xmouseshapes')) + + call delete('Xmouseshapes') +endfunc + +" Test that "j" does not skip lines when scrolling below botline and +" 'foldmethod' is not "manual". +func Test_normal_j_below_botline() + CheckScreendump + + let lines =<< trim END + set number foldmethod=diff scrolloff=0 + call setline(1, map(range(1, 9), 'repeat(v:val, 200)')) + norm Lj + END + call writefile(lines, 'XNormalJBelowBotline', 'D') + let buf = RunVimInTerminal('-S XNormalJBelowBotline', #{rows: 19, cols: 40}) + + call VerifyScreenDump(buf, 'Test_normal_j_below_botline', {}) + + call StopVimInTerminal(buf) +endfunc + +" Test for r (replace) command with CTRL_V and CTRL_Q +func Test_normal_r_ctrl_v_cmd() + new + call append(0, 'This is a simple test: abcd') + exe "norm! 1gg$r\<C-V>\<C-V>" + call assert_equal(['This is a simple test: abc', ''], getline(1,'$')) + exe "norm! 1gg$hr\<C-Q>\<C-Q>" + call assert_equal(['This is a simple test: ab', ''], getline(1,'$')) + exe "norm! 1gg$2hr\<C-V>x7e" + call assert_equal(['This is a simple test: a~', ''], getline(1,'$')) + exe "norm! 1gg$3hr\<C-Q>x7e" + call assert_equal(['This is a simple test: ~~', ''], getline(1,'$')) + + if &encoding == 'utf-8' + exe "norm! 1gg$4hr\<C-V>u20ac" + call assert_equal(['This is a simple test:€~~', ''], getline(1,'$')) + exe "norm! 1gg$5hr\<C-Q>u20ac" + call assert_equal(['This is a simple test€€~~', ''], getline(1,'$')) + exe "norm! 1gg0R\<C-V>xff WAS \<esc>" + call assert_equal(['ÿ WAS a simple test€€~~', ''], getline(1,'$')) + exe "norm! 1gg0elR\<C-Q>xffNOT\<esc>" + call assert_equal(['ÿ WASÿNOT simple test€€~~', ''], getline(1,'$')) + endif + + call setline(1, 'This is a simple test: abcd') + exe "norm! 1gg$gr\<C-V>\<C-V>" + call assert_equal(['This is a simple test: abc', ''], getline(1,'$')) + exe "norm! 1gg$hgr\<C-Q>\<C-Q>" + call assert_equal(['This is a simple test: ab ', ''], getline(1,'$')) + exe "norm! 1gg$2hgr\<C-V>x7e" + call assert_equal(['This is a simple test: a~ ', ''], getline(1,'$')) + exe "norm! 1gg$3hgr\<C-Q>x7e" + call assert_equal(['This is a simple test: ~~ ', ''], getline(1,'$')) + + " clean up + bw! +endfunc + +" Test clicking on a TAB or an unprintable character in Normal mode +func Test_normal_click_on_ctrl_char() + let save_mouse = &mouse + set mouse=a + new + + call setline(1, "a\<Tab>b\<C-K>c") + redraw + call Ntest_setmouse(1, 1) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 1, 0, 1], getcurpos()) + call Ntest_setmouse(1, 2) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 2, 0, 2], getcurpos()) + call Ntest_setmouse(1, 3) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 2, 0, 3], getcurpos()) + call Ntest_setmouse(1, 7) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 2, 0, 7], getcurpos()) + call Ntest_setmouse(1, 8) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 2, 0, 8], getcurpos()) + call Ntest_setmouse(1, 9) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 3, 0, 9], getcurpos()) + call Ntest_setmouse(1, 10) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 4, 0, 10], getcurpos()) + call Ntest_setmouse(1, 11) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 4, 0, 11], getcurpos()) + call Ntest_setmouse(1, 12) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 5, 0, 12], getcurpos()) + call Ntest_setmouse(1, 13) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 5, 0, 13], getcurpos()) + + bwipe! + let &mouse = save_mouse +endfunc + +" Test clicking on a double-width character in Normal mode +func Test_normal_click_on_double_width_char() + let save_mouse = &mouse + set mouse=a + new + + call setline(1, "口口") + redraw + call Ntest_setmouse(1, 1) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 1, 0, 1], getcurpos()) + call Ntest_setmouse(1, 2) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 1, 0, 2], getcurpos()) + call Ntest_setmouse(1, 3) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 4, 0, 3], getcurpos()) + call Ntest_setmouse(1, 4) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 1, 4, 0, 4], getcurpos()) + + bwipe! + let &mouse = save_mouse +endfunc + +func Test_normal_click_on_empty_line() + let save_mouse = &mouse + set mouse=a + botright new + call setline(1, ['', '', '']) + let row = win_screenpos(0)[0] + 2 + 20vsplit + redraw + + call Ntest_setmouse(row, 1) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 3, 1, 0, 1], getcurpos()) + call Ntest_setmouse(row, 2) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 3, 1, 0, 2], getcurpos()) + call Ntest_setmouse(row, 10) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 3, 1, 0, 10], getcurpos()) + + call Ntest_setmouse(row, 21 + 1) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 3, 1, 0, 1], getcurpos()) + call Ntest_setmouse(row, 21 + 2) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 3, 1, 0, 2], getcurpos()) + call Ntest_setmouse(row, 21 + 10) + call feedkeys("\<LeftMouse>", 'xt') + call assert_equal([0, 3, 1, 0, 10], getcurpos()) + + bwipe! + let &mouse = save_mouse +endfunc + +func Test_normal33_g_cmd_nonblank() + " Test that g<End> goes to the last non-blank char and g$ to the last + " visible column + 20vnew + setlocal nowrap nonumber signcolumn=no + call setline(1, ['fooo fooo fooo fooo fooo fooo fooo fooo ']) + exe "normal 0g\<End>" + call assert_equal(11, col('.')) + normal 0g$ + call assert_equal(20, col('.')) + exe "normal 0g\<kEnd>" + call assert_equal(11, col('.')) + setlocal wrap + exe "normal 0g\<End>" + call assert_equal(11, col('.')) + normal 0g$ + call assert_equal(20, col('.')) + exe "normal 0g\<kEnd>" + call assert_equal(11, col('.')) + bw! +endfunc + +func Test_normal34_zet_large() + " shouldn't cause overflow + norm! z9765405999999999999 +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_number.vim b/test/old/testdir/test_number.vim new file mode 100644 index 0000000000..1232db80c5 --- /dev/null +++ b/test/old/testdir/test_number.vim @@ -0,0 +1,359 @@ +" Test for 'number' and 'relativenumber' + +source check.vim +source view_util.vim + +source screendump.vim + +func s:screen_lines(start, end) abort + return ScreenLines([a:start, a:end], 8) +endfunc + +func s:compare_lines(expect, actual) + call assert_equal(a:expect, a:actual) +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:validate_cursor() abort + " update skipcol. + " wincol(): + " f_wincol + " -> validate_cursor + " -> curs_columns + call wincol() +endfunc + +func Test_set_options() + set nu rnu + call assert_equal(1, &nu) + call assert_equal(1, &rnu) + + call s:test_windows(10, 20) + call assert_equal(1, &nu) + call assert_equal(1, &rnu) + call s:close_windows() + + set nu& rnu& +endfunc + +func Test_set_global_and_local() + " setlocal must NOT reset the other global value + set nonu nornu + setglobal nu + setlocal rnu + call assert_equal(1, &g:nu) + + set nonu nornu + setglobal rnu + setlocal nu + call assert_equal(1, &g:rnu) + + " setglobal MUST reset the other global value + set nonu nornu + setglobal nu + setglobal rnu + call assert_equal(1, &g:nu) + + set nonu nornu + setglobal rnu + setglobal nu + call assert_equal(1, &g:rnu) + + " set MUST reset the other global value + set nonu nornu + set nu + set rnu + call assert_equal(1, &g:nu) + + set nonu nornu + set rnu + set nu + call assert_equal(1, &g:rnu) + + set nu& rnu& +endfunc + +func Test_number() + call s:test_windows(10, 20) + call setline(1, ["abcdefghij", "klmnopqrst", "uvwxyzABCD", "EFGHIJKLMN", "OPQRSTUVWX", "YZ"]) + setl number + let lines = s:screen_lines(1, 4) + let expect = [ +\ " 1 abcd", +\ " 2 klmn", +\ " 3 uvwx", +\ " 4 EFGH", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_relativenumber() + call s:test_windows(10, 20) + call setline(1, ["abcdefghij", "klmnopqrst", "uvwxyzABCD", "EFGHIJKLMN", "OPQRSTUVWX", "YZ"]) + 3 + setl relativenumber + let lines = s:screen_lines(1, 6) + let expect = [ +\ " 2 abcd", +\ " 1 klmn", +\ " 0 uvwx", +\ " 1 EFGH", +\ " 2 OPQR", +\ " 3 YZ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_number_with_relativenumber() + call s:test_windows(10, 20) + call setline(1, ["abcdefghij", "klmnopqrst", "uvwxyzABCD", "EFGHIJKLMN", "OPQRSTUVWX", "YZ"]) + 4 + setl number relativenumber + let lines = s:screen_lines(1, 6) + let expect = [ +\ " 3 abcd", +\ " 2 klmn", +\ " 1 uvwx", +\ "4 EFGH", +\ " 1 OPQR", +\ " 2 YZ ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_number_with_linewrap1() + call s:test_windows(3, 20) + normal! 61ia + setl number wrap + call s:validate_cursor() + let lines = s:screen_lines(1, 3) + let expect = [ +\ "<<< aaaa", +\ " aaaa", +\ " aaaa", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +" Pending: https://groups.google.com/forum/#!topic/vim_dev/tzNKP7EDWYI +func XTest_number_with_linewrap2() + call s:test_windows(3, 20) + normal! 61ia + setl number wrap + call s:validate_cursor() + 0 + call s:validate_cursor() + let lines = s:screen_lines(1, 3) + let expect = [ +\ " 1 aaaa", +\ " aaaa", +\ " aaaa", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +" Pending: https://groups.google.com/forum/#!topic/vim_dev/tzNKP7EDWYI +func XTest_number_with_linewrap3() + call s:test_windows(4, 20) + normal! 81ia + setl number wrap + call s:validate_cursor() + setl nonumber + call s:validate_cursor() + let lines = s:screen_lines(1, 4) + let expect = [ +\ "aaaaaaaa", +\ "aaaaaaaa", +\ "aaaaaaaa", +\ "a ", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_numberwidth() + call s:test_windows(10, 20) + call setline(1, repeat(['aaaa'], 10)) + setl number numberwidth=6 + let lines = s:screen_lines(1, 3) + let expect = [ +\ " 1 aa", +\ " 2 aa", +\ " 3 aa", +\ ] + call s:compare_lines(expect, lines) + + set relativenumber + let lines = s:screen_lines(1, 3) + let expect = [ +\ "1 aa", +\ " 1 aa", +\ " 2 aa", +\ ] + call s:compare_lines(expect, lines) + + set nonumber + let lines = s:screen_lines(1, 3) + let expect = [ +\ " 0 aa", +\ " 1 aa", +\ " 2 aa", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +func Test_numberwidth_adjusted() + call s:test_windows(10, 20) + call setline(1, repeat(['aaaa'], 10000)) + setl number numberwidth=4 + let lines = s:screen_lines(1, 3) + let expect = [ +\ " 1 aa", +\ " 2 aa", +\ " 3 aa", +\ ] + call s:compare_lines(expect, lines) + + $ + let lines = s:screen_lines(8, 10) + let expect = [ +\ " 9998 aa", +\ " 9999 aa", +\ "10000 aa", +\ ] + call s:compare_lines(expect, lines) + + setl relativenumber + let lines = s:screen_lines(8, 10) + let expect = [ +\ " 2 aa", +\ " 1 aa", +\ "10000 aa", +\ ] + call s:compare_lines(expect, lines) + + setl nonumber + let lines = s:screen_lines(8, 10) + let expect = [ +\ " 2 aaaa", +\ " 1 aaaa", +\ " 0 aaaa", +\ ] + call s:compare_lines(expect, lines) + call s:close_windows() +endfunc + +" This was causing a memcheck error +func Test_relativenumber_uninitialised() + new + set rnu + call setline(1, ["a", "b"]) + redraw + call feedkeys("j", 'xt') + redraw + bwipe! +endfunc + +func Test_relativenumber_colors() + CheckScreendump + + let lines =<< trim [CODE] + call setline(1, range(200)) + 111 + set number relativenumber + hi LineNr ctermfg=red + [CODE] + call writefile(lines, 'XTest_relnr') + + " Check that the balloon shows up after a mouse move + let buf = RunVimInTerminal('-S XTest_relnr', {'rows': 10, 'cols': 50}) + call TermWait(buf, 50) + " Default colors + call VerifyScreenDump(buf, 'Test_relnr_colors_1', {}) + + call term_sendkeys(buf, ":hi LineNrAbove ctermfg=blue\<CR>:\<CR>") + call VerifyScreenDump(buf, 'Test_relnr_colors_2', {}) + + call term_sendkeys(buf, ":hi LineNrBelow ctermfg=green\<CR>:\<CR>") + call VerifyScreenDump(buf, 'Test_relnr_colors_3', {}) + + call term_sendkeys(buf, ":hi clear LineNrAbove\<CR>") + call VerifyScreenDump(buf, 'Test_relnr_colors_4', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XTest_relnr') +endfunc + +func Test_relativenumber_callback() + CheckScreendump + CheckFeature timers + + let lines =<< trim END + call setline(1, ['aaaaa', 'bbbbb', 'ccccc', 'ddddd']) + set relativenumber + call cursor(4, 1) + + func Func(timer) + call cursor(1, 1) + endfunc + + call timer_start(300, 'Func') + END + call writefile(lines, 'Xrnu_timer') + + let buf = RunVimInTerminal('-S Xrnu_timer', #{rows: 8}) + call TermWait(buf, 310) + call VerifyScreenDump(buf, 'Test_relativenumber_callback_1', {}) + + call StopVimInTerminal(buf) + call delete('Xrnu_timer') +endfunc + +" Test for displaying line numbers with 'rightleft' +func Test_number_rightleft() + CheckFeature rightleft + new + setlocal number + setlocal rightleft + call setline(1, range(1, 1000)) + normal! 9Gzt + redraw! + call assert_match('^\s\+9 9$', Screenline(1)) + normal! 10Gzt + redraw! + call assert_match('^\s\+01 10$', Screenline(1)) + normal! 100Gzt + redraw! + call assert_match('^\s\+001 100$', Screenline(1)) + normal! 1000Gzt + redraw! + call assert_match('^\s\+0001 1000$', Screenline(1)) + bw! +endfunc + +" This used to cause a divide by zero +func Test_number_no_text_virtual_edit() + vnew + call setline(1, ['line one', 'line two']) + set number virtualedit=all + normal w + 4wincmd | + normal j + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_options.vim b/test/old/testdir/test_options.vim new file mode 100644 index 0000000000..d69828dc2e --- /dev/null +++ b/test/old/testdir/test_options.vim @@ -0,0 +1,2212 @@ +" Test for options + +source check.vim +source view_util.vim + +func Test_whichwrap() + set whichwrap=b,s + call assert_equal('b,s', &whichwrap) + + set whichwrap+=h,l + call assert_equal('b,s,h,l', &whichwrap) + + set whichwrap+=h,l + call assert_equal('b,s,h,l', &whichwrap) + + set whichwrap+=h,l + call assert_equal('b,s,h,l', &whichwrap) + + set whichwrap=h,h + call assert_equal('h', &whichwrap) + + set whichwrap=h,h,h + call assert_equal('h', &whichwrap) + + " " For compatibility with Vim 3.0 and before, number values are also + " " supported for 'whichwrap' + " set whichwrap=1 + " call assert_equal('b', &whichwrap) + " set whichwrap=2 + " call assert_equal('s', &whichwrap) + " set whichwrap=4 + " call assert_equal('h,l', &whichwrap) + " set whichwrap=8 + " call assert_equal('<,>', &whichwrap) + " set whichwrap=16 + " call assert_equal('[,]', &whichwrap) + " set whichwrap=31 + " call assert_equal('b,s,h,l,<,>,[,]', &whichwrap) + + set whichwrap& +endfunc + +func Test_isfname() + " This used to cause Vim to access uninitialized memory. + set isfname= + call assert_equal("~X", expand("~X")) + set isfname& + " Test for setting 'isfname' to an unsupported character + let save_isfname = &isfname + call assert_fails('exe $"set isfname+={"\u1234"}"', 'E474:') + call assert_equal(save_isfname, &isfname) +endfunc + +" Test for getting the value of 'pastetoggle' +func Test_pastetoggle() + throw "Skipped: 'pastetoggle' is removed from Nvim" + " character with K_SPECIAL byte + let &pastetoggle = '…' + call assert_equal('…', &pastetoggle) + call assert_equal("\n pastetoggle=…", execute('set pastetoggle?')) + + " modified character with K_SPECIAL byte + let &pastetoggle = '<M-…>' + call assert_equal('<M-…>', &pastetoggle) + call assert_equal("\n pastetoggle=<M-…>", execute('set pastetoggle?')) + + " illegal bytes + let str = ":\x7f:\x80:\x90:\xd0:" + let &pastetoggle = str + call assert_equal(str, &pastetoggle) + call assert_equal("\n pastetoggle=" .. strtrans(str), execute('set pastetoggle?')) + + unlet str + set pastetoggle& +endfunc + +func Test_wildchar() + " Empty 'wildchar' used to access invalid memory. + call assert_fails('set wildchar=', 'E521:') + call assert_fails('set wildchar=abc', 'E521:') + set wildchar=<Esc> + let a=execute('set wildchar?') + call assert_equal("\n wildchar=<Esc>", a) + set wildchar=27 + let a=execute('set wildchar?') + call assert_equal("\n wildchar=<Esc>", a) + set wildchar& +endfunc + +func Test_wildoptions() + set wildoptions= + set wildoptions+=tagfile + set wildoptions+=tagfile + call assert_equal('tagfile', &wildoptions) +endfunc + +func Test_options_command() + let caught = 'ok' + try + options + catch + let caught = v:throwpoint . "\n" . v:exception + endtry + call assert_equal('ok', caught) + + " Check if the option-window is opened horizontally. + wincmd j + call assert_notequal('option-window', bufname('')) + wincmd k + call assert_equal('option-window', bufname('')) + " close option-window + close + + " Open the option-window vertically. + vert options + " Check if the option-window is opened vertically. + wincmd l + call assert_notequal('option-window', bufname('')) + wincmd h + call assert_equal('option-window', bufname('')) + " close option-window + close + + " Open the option-window at the top. + set splitbelow + topleft options + call assert_equal(1, winnr()) + close + + " Open the option-window at the bottom. + set nosplitbelow + botright options + call assert_equal(winnr('$'), winnr()) + close + set splitbelow& + + " Open the option-window in a new tab. + tab options + " Check if the option-window is opened in a tab. + normal gT + call assert_notequal('option-window', bufname('')) + normal gt + call assert_equal('option-window', bufname('')) + " close option-window + close + + " Open the options window browse + if has('browse') + browse set + call assert_equal('option-window', bufname('')) + close + endif +endfunc + +func Test_path_keep_commas() + " Test that changing 'path' keeps two commas. + set path=foo,,bar + set path-=bar + set path+=bar + call assert_equal('foo,,bar', &path) + + set path& +endfunc + +func Test_path_too_long() + exe 'set path=' .. repeat('x', 10000) + call assert_fails('find x', 'E854:') + set path& +endfunc + +func Test_signcolumn() + CheckFeature signs + call assert_equal("auto", &signcolumn) + set signcolumn=yes + set signcolumn=no + call assert_fails('set signcolumn=nope') +endfunc + +func Test_filetype_valid() + set ft=valid_name + call assert_equal("valid_name", &filetype) + set ft=valid-name + call assert_equal("valid-name", &filetype) + + call assert_fails(":set ft=wrong;name", "E474:") + call assert_fails(":set ft=wrong\\\\name", "E474:") + call assert_fails(":set ft=wrong\\|name", "E474:") + call assert_fails(":set ft=wrong/name", "E474:") + call assert_fails(":set ft=wrong\\\nname", "E474:") + call assert_equal("valid-name", &filetype) + + exe "set ft=trunc\x00name" + call assert_equal("trunc", &filetype) +endfunc + +func Test_syntax_valid() + if !has('syntax') + return + endif + set syn=valid_name + call assert_equal("valid_name", &syntax) + set syn=valid-name + call assert_equal("valid-name", &syntax) + + call assert_fails(":set syn=wrong;name", "E474:") + call assert_fails(":set syn=wrong\\\\name", "E474:") + call assert_fails(":set syn=wrong\\|name", "E474:") + call assert_fails(":set syn=wrong/name", "E474:") + call assert_fails(":set syn=wrong\\\nname", "E474:") + call assert_equal("valid-name", &syntax) + + exe "set syn=trunc\x00name" + call assert_equal("trunc", &syntax) +endfunc + +func Test_keymap_valid() + if !has('keymap') + return + endif + call assert_fails(":set kmp=valid_name", "E544:") + call assert_fails(":set kmp=valid_name", "valid_name") + call assert_fails(":set kmp=valid-name", "E544:") + call assert_fails(":set kmp=valid-name", "valid-name") + + call assert_fails(":set kmp=wrong;name", "E474:") + call assert_fails(":set kmp=wrong\\\\name", "E474:") + call assert_fails(":set kmp=wrong\\|name", "E474:") + call assert_fails(":set kmp=wrong/name", "E474:") + call assert_fails(":set kmp=wrong\\\nname", "E474:") + + call assert_fails(":set kmp=trunc\x00name", "E544:") + call assert_fails(":set kmp=trunc\x00name", "trunc") +endfunc + +func Test_wildchar_valid() + call assert_fails("set wildchar=<CR>", "E474:") + call assert_fails("set wildcharm=<C-C>", "E474:") +endfunc + +func Check_dir_option(name) + " Check that it's possible to set the option. + exe 'set ' . a:name . '=/usr/share/dict/words' + call assert_equal('/usr/share/dict/words', eval('&' . a:name)) + exe 'set ' . a:name . '=/usr/share/dict/words,/and/there' + call assert_equal('/usr/share/dict/words,/and/there', eval('&' . a:name)) + exe 'set ' . a:name . '=/usr/share/dict\ words' + call assert_equal('/usr/share/dict words', eval('&' . a:name)) + + " Check rejecting weird characters. + call assert_fails("set " . a:name . "=/not&there", "E474:") + call assert_fails("set " . a:name . "=/not>there", "E474:") + call assert_fails("set " . a:name . "=/not.*there", "E474:") +endfunc + +func Test_cinkeys() + " This used to cause invalid memory access + set cindent cinkeys=0 + norm a + set cindent& cinkeys& +endfunc + +func Test_dictionary() + call Check_dir_option('dictionary') +endfunc + +func Test_thesaurus() + call Check_dir_option('thesaurus') +endfun + +func Test_complete() + " Trailing single backslash used to cause invalid memory access. + set complete=s\ + new + call feedkeys("i\<C-N>\<Esc>", 'xt') + bwipe! + call assert_fails('set complete=ix', 'E535:') + set complete& +endfun + +func Test_set_completion() + call feedkeys(":set di\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set dictionary diff diffexpr diffopt digraph directory display', @:) + + call feedkeys(":setlocal di\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"setlocal dictionary diff diffexpr diffopt digraph directory display', @:) + + call feedkeys(":setglobal di\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"setglobal dictionary diff diffexpr diffopt digraph directory display', @:) + + " Expand boolean options. When doing :set no<Tab> Vim prefixes the option + " names with "no". + call feedkeys(":set nodi\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set nodiff nodigraph', @:) + + call feedkeys(":set invdi\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set invdiff invdigraph', @:) + + " Expanding "set noinv" does nothing. + call feedkeys(":set noinv\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set noinv', @:) + + " Expand abbreviation of options. + call feedkeys(":set ts\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set tabstop thesaurus thesaurusfunc', @:) + + " Expand current value + call feedkeys(":set suffixes=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set suffixes=.bak,~,.o,.h,.info,.swp,.obj', @:) + + call feedkeys(":set suffixes:\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set suffixes:.bak,~,.o,.h,.info,.swp,.obj', @:) + + " Expand key codes. + " call feedkeys(":set <H\<C-A>\<C-B>\"\<CR>", 'tx') + " call assert_equal('"set <Help> <Home>', @:) + + " Expand terminal options. + " call feedkeys(":set t_A\<C-A>\<C-B>\"\<CR>", 'tx') + " call assert_equal('"set t_AB t_AF t_AU t_AL', @:) + " call assert_fails('call feedkeys(":set <t_afoo>=\<C-A>\<CR>", "xt")', 'E474:') + + " Expand directories. + call feedkeys(":set cdpath=./\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_match(' ./samples/ ', @:) + call assert_notmatch(' ./summarize.vim ', @:) + set cdpath& + + " Expand files and directories. + call feedkeys(":set tags=./\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_match(' ./samples/.* ./summarize.vim', @:) + + call feedkeys(":set tags=./\\\\ dif\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set tags=./\\ diff diffexpr diffopt', @:) + + " Expand files with spaces/commas in them. Make sure we delimit correctly. + " + " 'tags' allow for for spaces/commas to both act as delimiters, with actual + " spaces requiring double escape, and commas need a single escape. + " 'dictionary' is a normal comma-separated option where only commas act as + " delimiters, and both space/comma need one single escape. + " 'makeprg' is a non-comma-separated option. Commas don't need escape. + defer delete('Xfoo Xspace.txt') + defer delete('Xsp_dummy') + defer delete('Xbar,Xcomma.txt') + defer delete('Xcom_dummy') + call writefile([], 'Xfoo Xspace.txt') + call writefile([], 'Xsp_dummy') + call writefile([], 'Xbar,Xcomma.txt') + call writefile([], 'Xcom_dummy') + + call feedkeys(':set tags=./Xfoo\ Xsp' .. "\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set tags=./Xfoo\ Xsp_dummy', @:) + call feedkeys(':set tags=./Xfoo\\\ Xsp' .. "\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set tags=./Xfoo\\\ Xspace.txt', @:) + call feedkeys(':set dictionary=./Xfoo\ Xsp' .. "\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set dictionary=./Xfoo\ Xspace.txt', @:) + + call feedkeys(':set dictionary=./Xbar,Xcom' .. "\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set dictionary=./Xbar,Xcom_dummy', @:) + if has('win32') + " In Windows, '\,' is literal, see `:help filename-backslash`, so this + " means we treat it as one file name. + call feedkeys(':set dictionary=Xbar\,Xcom' .. "\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set dictionary=Xbar\,Xcomma.txt', @:) + else + " In other platforms, '\,' simply escape to ',', and indicate a delimiter + " to split into a separate file name. You need '\\,' to escape the comma + " as part of the file name. + call feedkeys(':set dictionary=Xbar\,Xcom' .. "\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set dictionary=Xbar\,Xcom_dummy', @:) + + call feedkeys(':set dictionary=Xbar\\,Xcom' .. "\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set dictionary=Xbar\\,Xcomma.txt', @:) + endif + call feedkeys(":set makeprg=./Xbar,Xcom\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set makeprg=./Xbar,Xcomma.txt', @:) + set tags& dictionary& makeprg& + + " Expanding the option names + call feedkeys(":set \<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set all', @:) + + " Expanding a second set of option names + call feedkeys(":set wrapscan \<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set wrapscan all', @:) + + " Expanding a special keycode + " call feedkeys(":set <Home>\<Tab>\<C-B>\"\<CR>", 'xt') + " call assert_equal('"set <Home>', @:) + + " Expanding an invalid special keycode + call feedkeys(":set <abcd>\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"set <abcd>\<Tab>", @:) + + " Expanding a terminal keycode + " call feedkeys(":set t_AB\<Tab>\<C-B>\"\<CR>", 'xt') + " call assert_equal("\"set t_AB", @:) + + " Expanding an invalid option name + call feedkeys(":set abcde=\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"set abcde=\<Tab>", @:) + + " Expanding after a = for a boolean option + call feedkeys(":set wrapscan=\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"set wrapscan=\<Tab>", @:) + + " Expanding a numeric option + call feedkeys(":set tabstop+=\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"set tabstop+=" .. &tabstop, @:) + + " Expanding a non-boolean option + call feedkeys(":set invtabstop=\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"set invtabstop=", @:) + + " Expand options for 'spellsuggest' + call feedkeys(":set spellsuggest=file:test_options.v\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"set spellsuggest=file:test_options.vim", @:) + call feedkeys(":set spellsuggest=best,file:test_options.v\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal("\"set spellsuggest=best,file:test_options.vim", @:) + + " Expanding value for 'key' is disallowed + if exists('+key') + set key=abcd + call feedkeys(":set key=\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set key=', @:) + call feedkeys(":set key-=\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set key-=', @:) + set key= + endif + + " Expand values for 'filetype' + call feedkeys(":set filetype=sshdconfi\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set filetype=sshdconfig', @:) + call feedkeys(":set filetype=a\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set filetype=' .. getcompletion('a*', 'filetype')->join(), @:) + + " Expand values for 'syntax' + call feedkeys(":set syntax=sshdconfi\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set syntax=sshdconfig', @:) + call feedkeys(":set syntax=a\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set syntax=' .. getcompletion('a*', 'syntax')->join(), @:) +endfunc + +" Test handling of expanding individual string option values +func Test_set_completion_string_values() + " + " Test basic enum string options that have well-defined enum names + " + + " call assert_equal(['lastline', 'truncate', 'uhex'], getcompletion('set display=', 'cmdline')) + call assert_equal(['lastline', 'truncate', 'uhex', 'msgsep'], getcompletion('set display=', 'cmdline')) + call assert_equal(['truncate'], getcompletion('set display=t', 'cmdline')) + call assert_equal(['uhex'], getcompletion('set display=*ex*', 'cmdline')) + + " Test that if a value is set, it will populate the results, but only if + " typed value is empty. + set display=uhex,lastline + " call assert_equal(['uhex,lastline', 'lastline', 'truncate', 'uhex'], getcompletion('set display=', 'cmdline')) + call assert_equal(['uhex,lastline', 'lastline', 'truncate', 'uhex', 'msgsep'], getcompletion('set display=', 'cmdline')) + call assert_equal(['uhex'], getcompletion('set display=u', 'cmdline')) + " If the set value is part of the enum list, it will show as the first + " result with no duplicate. + set display=uhex + " call assert_equal(['uhex', 'lastline', 'truncate'], getcompletion('set display=', 'cmdline')) + call assert_equal(['uhex', 'lastline', 'truncate', 'msgsep'], getcompletion('set display=', 'cmdline')) + " If empty value, will just show the normal list without an empty item + set display= + " call assert_equal(['lastline', 'truncate', 'uhex'], getcompletion('set display=', 'cmdline')) + call assert_equal(['lastline', 'truncate', 'uhex', 'msgsep'], getcompletion('set display=', 'cmdline')) + " Test escaping of the values + " call assert_equal('vert:\|,fold:-,eob:~,lastline:@', getcompletion('set fillchars=', 'cmdline')[0]) + call assert_equal('vert:\|,foldsep:\|,fold:-', getcompletion('set fillchars=', 'cmdline')[0]) + + " Test comma-separated lists will expand after a comma. + call assert_equal(['uhex'], getcompletion('set display=truncate,*ex*', 'cmdline')) + " Also test the positioning of the expansion is correct + call feedkeys(":set display=truncate,l\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set display=truncate,lastline', @:) + set display& + + " Test single-value options will not expand after a comma + call assert_equal([], getcompletion('set ambw=single,', 'cmdline')) + + " Test the other simple options to make sure they have basic auto-complete, + " but don't exhaustively validate their results. + call assert_equal('single', getcompletion('set ambw=', 'cmdline')[0]) + call assert_match('light\|dark', getcompletion('set bg=', 'cmdline')[1]) + call assert_equal('indent', getcompletion('set backspace=', 'cmdline')[0]) + call assert_equal('yes', getcompletion('set backupcopy=', 'cmdline')[1]) + call assert_equal('backspace', getcompletion('set belloff=', 'cmdline')[1]) + call assert_equal('min:', getcompletion('set briopt=', 'cmdline')[1]) + if exists('+browsedir') + call assert_equal('current', getcompletion('set browsedir=', 'cmdline')[1]) + endif + call assert_equal('unload', getcompletion('set bufhidden=', 'cmdline')[1]) + call assert_equal('nowrite', getcompletion('set buftype=', 'cmdline')[1]) + call assert_equal('internal', getcompletion('set casemap=', 'cmdline')[1]) + if exists('+clipboard') + " call assert_match('unnamed', getcompletion('set clipboard=', 'cmdline')[1]) + call assert_match('unnamed', getcompletion('set clipboard=', 'cmdline')[0]) + endif + call assert_equal('.', getcompletion('set complete=', 'cmdline')[1]) + call assert_equal('menu', getcompletion('set completeopt=', 'cmdline')[1]) + if exists('+completeslash') + call assert_equal('backslash', getcompletion('set completeslash=', 'cmdline')[1]) + endif + if exists('+cryptmethod') + call assert_equal('zip', getcompletion('set cryptmethod=', 'cmdline')[1]) + endif + if exists('+cursorlineopt') + call assert_equal('line', getcompletion('set cursorlineopt=', 'cmdline')[1]) + endif + call assert_equal('throw', getcompletion('set debug=', 'cmdline')[1]) + call assert_equal('ver', getcompletion('set eadirection=', 'cmdline')[1]) + call assert_equal('mac', getcompletion('set fileformat=', 'cmdline')[2]) + if exists('+foldclose') + call assert_equal('all', getcompletion('set foldclose=', 'cmdline')[0]) + endif + if exists('+foldmethod') + call assert_equal('expr', getcompletion('set foldmethod=', 'cmdline')[1]) + endif + if exists('+foldopen') + call assert_equal('all', getcompletion('set foldopen=', 'cmdline')[1]) + endif + call assert_equal('stack', getcompletion('set jumpoptions=', 'cmdline')[0]) + call assert_equal('stopsel', getcompletion('set keymodel=', 'cmdline')[1]) + call assert_equal('expr:1', getcompletion('set lispoptions=', 'cmdline')[1]) + call assert_match('popup', getcompletion('set mousemodel=', 'cmdline')[2]) + call assert_equal('bin', getcompletion('set nrformats=', 'cmdline')[1]) + if exists('+rightleftcmd') + call assert_equal('search', getcompletion('set rightleftcmd=', 'cmdline')[0]) + endif + call assert_equal('ver', getcompletion('set scrollopt=', 'cmdline')[1]) + call assert_equal('exclusive', getcompletion('set selection=', 'cmdline')[1]) + call assert_equal('key', getcompletion('set selectmode=', 'cmdline')[1]) + if exists('+ssop') + call assert_equal('buffers', getcompletion('set ssop=', 'cmdline')[1]) + endif + call assert_equal('statusline', getcompletion('set showcmdloc=', 'cmdline')[1]) + if exists('+signcolumn') + call assert_equal('yes', getcompletion('set signcolumn=', 'cmdline')[1]) + endif + if exists('+spelloptions') + call assert_equal('camel', getcompletion('set spelloptions=', 'cmdline')[0]) + endif + if exists('+spellsuggest') + call assert_equal('best', getcompletion('set spellsuggest+=', 'cmdline')[0]) + endif + call assert_equal('screen', getcompletion('set splitkeep=', 'cmdline')[1]) + " call assert_equal('sync', getcompletion('set swapsync=', 'cmdline')[1]) + call assert_equal('usetab', getcompletion('set switchbuf=', 'cmdline')[1]) + call assert_equal('ignore', getcompletion('set tagcase=', 'cmdline')[1]) + if exists('+termwintype') + call assert_equal('conpty', getcompletion('set termwintype=', 'cmdline')[1]) + endif + if exists('+toolbar') + call assert_equal('text', getcompletion('set toolbar=', 'cmdline')[1]) + endif + if exists('+tbis') + call assert_equal('medium', getcompletion('set tbis=', 'cmdline')[2]) + endif + if exists('+ttymouse') + set ttymouse= + call assert_equal('xterm2', getcompletion('set ttymouse=', 'cmdline')[1]) + set ttymouse& + endif + call assert_equal('insert', getcompletion('set virtualedit=', 'cmdline')[1]) + call assert_equal('longest', getcompletion('set wildmode=', 'cmdline')[1]) + call assert_equal('full', getcompletion('set wildmode=list,longest:', 'cmdline')[0]) + call assert_equal('tagfile', getcompletion('set wildoptions=', 'cmdline')[1]) + if exists('+winaltkeys') + call assert_equal('yes', getcompletion('set winaltkeys=', 'cmdline')[1]) + endif + + " Other string options that queries the system rather than fixed enum names + call assert_equal(['all', 'BufAdd'], getcompletion('set eventignore=', 'cmdline')[0:1]) + call assert_equal('latin1', getcompletion('set fileencodings=', 'cmdline')[1]) + " call assert_equal('top', getcompletion('set printoptions=', 'cmdline')[0]) + " call assert_equal('SpecialKey', getcompletion('set wincolor=', 'cmdline')[0]) + + call assert_equal('eol', getcompletion('set listchars+=', 'cmdline')[0]) + call assert_equal(['multispace', 'leadmultispace'], getcompletion('set listchars+=', 'cmdline')[-2:]) + call assert_equal('eol', getcompletion('setl listchars+=', 'cmdline')[0]) + call assert_equal(['multispace', 'leadmultispace'], getcompletion('setl listchars+=', 'cmdline')[-2:]) + call assert_equal('stl', getcompletion('set fillchars+=', 'cmdline')[0]) + call assert_equal('stl', getcompletion('setl fillchars+=', 'cmdline')[0]) + + " + " Unique string options below + " + + " keyprotocol: only auto-complete when after ':' with known protocol types + " call assert_equal([&keyprotocol], getcompletion('set keyprotocol=', 'cmdline')) + " call feedkeys(":set keyprotocol+=someterm:m\<Tab>\<C-B>\"\<CR>", 'xt') + " call assert_equal('"set keyprotocol+=someterm:mok2', @:) + " set keyprotocol& + + " previewpopup / completepopup + " call assert_equal('height:', getcompletion('set previewpopup=', 'cmdline')[0]) + " call assert_equal('EndOfBuffer', getcompletion('set previewpopup=highlight:End*Buffer', 'cmdline')[0]) + " call feedkeys(":set previewpopup+=border:\<Tab>\<C-B>\"\<CR>", 'xt') + " call assert_equal('"set previewpopup+=border:on', @:) + " call feedkeys(":set completepopup=height:10,align:\<Tab>\<C-B>\"\<CR>", 'xt') + " call assert_equal('"set completepopup=height:10,align:item', @:) + " call assert_equal([], getcompletion('set completepopup=bogusname:', 'cmdline')) + " set previewpopup& completepopup& + + " diffopt: special handling of algorithm:<alg_list> + call assert_equal('filler', getcompletion('set diffopt+=', 'cmdline')[0]) + call assert_equal([], getcompletion('set diffopt+=iblank,foldcolumn:', 'cmdline')) + call assert_equal('patience', getcompletion('set diffopt+=iblank,algorithm:pat*', 'cmdline')[0]) + + " highlight: special parsing, including auto-completing highlight groups + " after ':' + " call assert_equal([&hl, '8'], getcompletion('set hl=', 'cmdline')[0:1]) + " call assert_equal('8', getcompletion('set hl+=', 'cmdline')[0]) + " call assert_equal(['8:', '8b', '8i'], getcompletion('set hl+=8', 'cmdline')[0:2]) + " call assert_equal('8bi', getcompletion('set hl+=8b', 'cmdline')[0]) + " call assert_equal('NonText', getcompletion('set hl+=8:No*ext', 'cmdline')[0]) + " If all the display modes are used up we should be suggesting nothing. Make + " a hl typed option with all the modes which will look like '8bi-nrsuc2d=t', + " and make sure nothing is suggested from that. + " let hl_display_modes = join( + " \ filter(map(getcompletion('set hl+=8', 'cmdline'), + " \ {idx, val -> val[1]}), + " \ {idx, val -> val != ':'}), + " \ '') + " call assert_equal([], getcompletion('set hl+=8'..hl_display_modes, 'cmdline')) + " Test completion in middle of the line + " call feedkeys(":set hl=8b i\<Left>\<Left>\<Tab>\<C-B>\"\<CR>", 'xt') + " call assert_equal("\"set hl=8bi i", @:) + + " + " Test flag lists + " + + " Test set=. Show the original value if nothing is typed after '='. + " Otherwise, the list should avoid showing what's already typed. + set mouse=v + call assert_equal(['v','a','n','i','c','h','r'], getcompletion('set mouse=', 'cmdline')) + set mouse=nvi + call assert_equal(['nvi','a','n','v','i','c','h','r'], getcompletion('set mouse=', 'cmdline')) + call assert_equal(['a','v','i','c','r'], getcompletion('set mouse=hn', 'cmdline')) + + " Test set+=. Never show original value, and it also tries to avoid listing + " flags that's already in the option value. + call assert_equal(['a','c','h','r'], getcompletion('set mouse+=', 'cmdline')) + call assert_equal(['a','c','r'], getcompletion('set mouse+=hn', 'cmdline')) + call assert_equal([], getcompletion('set mouse+=acrhn', 'cmdline')) + + " Test that the position of the expansion is correct (even if there are + " additional values after the current cursor) + call feedkeys(":set mouse=hn\<Left>\<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"set mouse=han', @:) + set mouse& + + " Test that other flag list options have auto-complete, but don't + " exhaustively validate their results. + if exists('+concealcursor') + call assert_equal('n', getcompletion('set cocu=', 'cmdline')[0]) + endif + call assert_equal('a', getcompletion('set cpo=', 'cmdline')[1]) + call assert_equal('t', getcompletion('set fo=', 'cmdline')[1]) + if exists('+guioptions') + call assert_equal('!', getcompletion('set go=', 'cmdline')[1]) + endif + call assert_equal('r', getcompletion('set shortmess=', 'cmdline')[1]) + call assert_equal('b', getcompletion('set whichwrap=', 'cmdline')[1]) + + " + "Test set-= + " + + " Normal single-value option just shows the existing value + set ambiwidth=double + call assert_equal(['double'], getcompletion('set ambw-=', 'cmdline')) + set ambiwidth& + + " Works on numbers and term options as well + call assert_equal([string(&laststatus)], getcompletion('set laststatus-=', 'cmdline')) + set t_Ce=testCe + " call assert_equal(['testCe'], getcompletion('set t_Ce-=', 'cmdline')) + set t_Ce& + + " Comma-separated lists should present each option + set diffopt=context:123,,,,,iblank,iwhiteall + call assert_equal(['context:123', 'iblank', 'iwhiteall'], getcompletion('set diffopt-=', 'cmdline')) + call assert_equal(['context:123', 'iblank'], getcompletion('set diffopt-=*n*', 'cmdline')) + call assert_equal(['iblank', 'iwhiteall'], getcompletion('set diffopt-=i', 'cmdline')) + " Don't present more than one option as it doesn't make sense in set-= + call assert_equal([], getcompletion('set diffopt-=iblank,', 'cmdline')) + " Test empty option + set diffopt= + call assert_equal([], getcompletion('set diffopt-=', 'cmdline')) + set diffopt& + + " Test escaping output + call assert_equal('vert:\|', getcompletion('set fillchars-=', 'cmdline')[0]) + + " Test files with commas in name are being parsed and escaped properly + set path=has\\\ space,file\\,with\\,comma,normal_file + if exists('+completeslash') + call assert_equal(['has\\\ space', 'file\,with\,comma', 'normal_file'], getcompletion('set path-=', 'cmdline')) + else + call assert_equal(['has\\\ space', 'file\\,with\\,comma', 'normal_file'], getcompletion('set path-=', 'cmdline')) + endif + set path& + + " Flag list should present orig value, then individual flags + set mouse=v + call assert_equal(['v'], getcompletion('set mouse-=', 'cmdline')) + set mouse=avn + call assert_equal(['avn','a','v','n'], getcompletion('set mouse-=', 'cmdline')) + " Don't auto-complete when we have at least one flags already + call assert_equal([], getcompletion('set mouse-=n', 'cmdline')) + " Test empty option + set mouse= + call assert_equal([], getcompletion('set mouse-=', 'cmdline')) + set mouse& + + " 'whichwrap' is an odd case where it's both flag list and comma-separated + set ww=b,h + call assert_equal(['b','h'], getcompletion('set ww-=', 'cmdline')) + set ww& +endfunc + +func Test_set_option_errors() + call assert_fails('set scroll=-1', 'E49:') + call assert_fails('set backupcopy=', 'E474:') + call assert_fails('set regexpengine=3', 'E474:') + call assert_fails('set history=10001', 'E474:') + call assert_fails('set numberwidth=21', 'E474:') + call assert_fails('set colorcolumn=-a', 'E474:') + call assert_fails('set colorcolumn=a', 'E474:') + call assert_fails('set colorcolumn=1,', 'E474:') + call assert_fails('set colorcolumn=1;', 'E474:') + call assert_fails('set cmdheight=-1', 'E487:') + call assert_fails('set cmdwinheight=-1', 'E487:') + if has('conceal') + call assert_fails('set conceallevel=-1', 'E487:') + call assert_fails('set conceallevel=4', 'E474:') + endif + call assert_fails('set helpheight=-1', 'E487:') + call assert_fails('set history=-1', 'E487:') + call assert_fails('set report=-1', 'E487:') + call assert_fails('set shiftwidth=-1', 'E487:') + call assert_fails('set sidescroll=-1', 'E487:') + call assert_fails('set tabstop=-1', 'E487:') + call assert_fails('set tabstop=10000', 'E474:') + call assert_fails('let &tabstop = 10000', 'E474:') + call assert_fails('set tabstop=5500000000', 'E474:') + call assert_fails('set textwidth=-1', 'E487:') + call assert_fails('set timeoutlen=-1', 'E487:') + call assert_fails('set updatecount=-1', 'E487:') + call assert_fails('set updatetime=-1', 'E487:') + call assert_fails('set winheight=-1', 'E487:') + call assert_fails('set tabstop!', 'E488:') + call assert_fails('set xxx', 'E518:') + call assert_fails('set beautify?', 'E518:') + call assert_fails('set undolevels=x', 'E521:') + call assert_fails('set tabstop=', 'E521:') + call assert_fails('set comments=-', 'E524:') + call assert_fails('set comments=a', 'E525:') + call assert_fails('set foldmarker=x', 'E536:') + call assert_fails('set commentstring=x', 'E537:') + call assert_fails('let &commentstring = "x"', 'E537:') + call assert_fails('set complete=x', 'E539:') + call assert_fails('set rulerformat=%-', 'E539:') + call assert_fails('set rulerformat=%(', 'E542:') + call assert_fails('set rulerformat=%15(%%', 'E542:') + call assert_fails('set statusline=%$', 'E539:') + call assert_fails('set statusline=%{', 'E540:') + call assert_fails('set statusline=%{%', 'E540:') + call assert_fails('set statusline=%{%}', 'E539:') + call assert_fails('set statusline=%(', 'E542:') + call assert_fails('set statusline=%)', 'E542:') + call assert_fails('set tabline=%$', 'E539:') + call assert_fails('set tabline=%{', 'E540:') + call assert_fails('set tabline=%{%', 'E540:') + call assert_fails('set tabline=%{%}', 'E539:') + call assert_fails('set tabline=%(', 'E542:') + call assert_fails('set tabline=%)', 'E542:') + + if has('cursorshape') + " This invalid value for 'guicursor' used to cause Vim to crash. + call assert_fails('set guicursor=i-ci,r-cr:h', 'E545:') + call assert_fails('set guicursor=i-ci', 'E545:') + call assert_fails('set guicursor=x', 'E545:') + call assert_fails('set guicursor=x:', 'E546:') + call assert_fails('set guicursor=r-cr:horx', 'E548:') + call assert_fails('set guicursor=r-cr:hor0', 'E549:') + endif + if has('mouseshape') + call assert_fails('se mouseshape=i-r:x', 'E547:') + endif + + " Test for 'backupext' and 'patchmode' set to the same value + set backupext=.bak + set patchmode=.patch + call assert_fails('set patchmode=.bak', 'E589:') + call assert_equal('.patch', &patchmode) + call assert_fails('set backupext=.patch', 'E589:') + call assert_equal('.bak', &backupext) + set backupext& patchmode& + + call assert_fails('set winminheight=10 winheight=9', 'E591:') + set winminheight& winheight& + set winheight=10 winminheight=10 + call assert_fails('set winheight=9', 'E591:') + set winminheight& winheight& + call assert_fails('set winminwidth=10 winwidth=9', 'E592:') + set winminwidth& winwidth& + call assert_fails('set winwidth=9 winminwidth=10', 'E592:') + set winwidth& winminwidth& + call assert_fails("set showbreak=\x01", 'E595:') + call assert_fails('set t_foo=', 'E846:') + call assert_fails('set tabstop??', 'E488:') + call assert_fails('set wrapscan!!', 'E488:') + call assert_fails('set tabstop&&', 'E488:') + call assert_fails('set wrapscan<<', 'E488:') + call assert_fails('set wrapscan=1', 'E474:') + call assert_fails('set autoindent@', 'E488:') + call assert_fails('set wildchar=<abc>', 'E474:') + call assert_fails('set cmdheight=1a', 'E521:') + call assert_fails('set invcmdheight', 'E474:') + if has('python') || has('python3') + call assert_fails('set pyxversion=6', 'E474:') + endif + call assert_fails("let &tabstop='ab'", ['E521:', 'E521:']) + call assert_fails('set spellcapcheck=%\\(', 'E54:') + call assert_fails('set sessionoptions=curdir,sesdir', 'E474:') + call assert_fails('set foldmarker={{{,', 'E474:') + call assert_fails('set sessionoptions=sesdir,curdir', 'E474:') + setlocal listchars=trail:· + call assert_fails('set ambiwidth=double', 'E834:') + setlocal listchars=trail:- + setglobal listchars=trail:· + call assert_fails('set ambiwidth=double', 'E834:') + set listchars& + setlocal fillchars=stl:· + call assert_fails('set ambiwidth=double', 'E835:') + setlocal fillchars=stl:- + setglobal fillchars=stl:· + call assert_fails('set ambiwidth=double', 'E835:') + set fillchars& + call assert_fails('set fileencoding=latin1,utf-8', 'E474:') + set nomodifiable + call assert_fails('set fileencoding=latin1', 'E21:') + set modifiable& + " call assert_fails('set t_#-&', 'E522:') + call assert_fails('let &formatoptions = "?"', 'E539:') + call assert_fails('call setbufvar("", "&formatoptions", "?")', 'E539:') + call assert_fails('call setwinvar(0, "&scrolloff", [])', ['E745:', 'E745:']) + call assert_fails('call setwinvar(0, "&list", [])', ['E745:', 'E745:']) + call assert_fails('call setwinvar(0, "&listchars", [])', ['E730:', 'E730:']) + call assert_fails('call setwinvar(0, "&nosuchoption", 0)', ['E355:', 'E355:']) + call assert_fails('call setwinvar(0, "&nosuchoption", "")', ['E355:', 'E355:']) + call assert_fails('call setwinvar(0, "&nosuchoption", [])', ['E355:', 'E355:']) +endfunc + +func CheckWasSet(name) + let verb_cm = execute('verbose set ' .. a:name .. '?') + call assert_match('Last set from.*test_options.vim', verb_cm) +endfunc +func CheckWasNotSet(name) + let verb_cm = execute('verbose set ' .. a:name .. '?') + call assert_notmatch('Last set from', verb_cm) +endfunc + +" Must be executed before other tests that set 'term'. +func Test_000_term_option_verbose() + throw "Skipped: Nvim does not support setting 'term'" + CheckNotGui + + call CheckWasNotSet('t_cm') + + let term_save = &term + set term=ansi + call CheckWasSet('t_cm') + let &term = term_save +endfunc + +func Test_copy_context() + setlocal list + call CheckWasSet('list') + split + call CheckWasSet('list') + quit + setlocal nolist + + set ai + call CheckWasSet('ai') + set filetype=perl + call CheckWasSet('filetype') + set fo=tcroq + call CheckWasSet('fo') + + split Xsomebuf + call CheckWasSet('ai') + call CheckWasNotSet('filetype') + call CheckWasSet('fo') +endfunc + +func Test_set_ttytype() + throw "Skipped: Nvim does not support 'ttytype'" + CheckUnix + CheckNotGui + + " Setting 'ttytype' used to cause a double-free when exiting vim and + " when vim is compiled with -DEXITFREE. + set ttytype=ansi + call assert_equal('ansi', &ttytype) + call assert_equal(&ttytype, &term) + set ttytype=xterm + call assert_equal('xterm', &ttytype) + call assert_equal(&ttytype, &term) + try + set ttytype= + call assert_report('set ttytype= did not fail') + catch /E529/ + endtry + + " Some systems accept any terminal name and return dumb settings, + " check for failure of finding the entry and for missing 'cm' entry. + try + set ttytype=xxx + call assert_report('set ttytype=xxx did not fail') + catch /E522\|E437/ + endtry + + set ttytype& + call assert_equal(&ttytype, &term) + + if has('gui') && !has('gui_running') + call assert_fails('set term=gui', 'E531:') + endif +endfunc + +func Test_set_all() + set tw=75 + set iskeyword=a-z,A-Z + set nosplitbelow + let out = execute('set all') + call assert_match('textwidth=75', out) + call assert_match('iskeyword=a-z,A-Z', out) + call assert_match('nosplitbelow', out) + set tw& iskeyword& splitbelow& +endfunc + +func Test_set_one_column() + let out_mult = execute('set all')->split("\n") + let out_one = execute('set! all')->split("\n") + " one column should be two to four times as many lines + call assert_inrange(len(out_mult) * 2, len(out_mult) * 4, len(out_one)) +endfunc + +func Test_set_values() + " opt_test.vim is generated from ../optiondefs.h using gen_opt_test.vim + if filereadable('opt_test.vim') + source opt_test.vim + else + throw 'Skipped: opt_test.vim does not exist' + endif +endfunc + +func Test_renderoptions() + throw 'skipped: Nvim does not support renderoptions' + " Only do this for Windows Vista and later, fails on Windows XP and earlier. + " Doesn't hurt to do this on a non-Windows system. + if windowsversion() !~ '^[345]\.' + set renderoptions=type:directx + set rop=type:directx + endif +endfunc + +func ResetIndentexpr() + set indentexpr= +endfunc + +func Test_set_indentexpr() + " this was causing usage of freed memory + set indentexpr=ResetIndentexpr() + new + call feedkeys("i\<c-f>", 'x') + call assert_equal('', &indentexpr) + bwipe! +endfunc + +func Test_backupskip() + " Option 'backupskip' may contain several comma-separated path + " specifications if one or more of the environment variables TMPDIR, TMP, + " or TEMP is defined. To simplify testing, convert the string value into a + " list. + let bsklist = split(&bsk, ',') + + if has("mac") + let found = (index(bsklist, '/private/tmp/*') >= 0) + call assert_true(found, '/private/tmp not in option bsk: ' . &bsk) + elseif has("unix") + let found = (index(bsklist, '/tmp/*') >= 0) + call assert_true(found, '/tmp not in option bsk: ' . &bsk) + endif + + " If our test platform is Windows, the path(s) in option bsk will use + " backslash for the path separator and the components could be in short + " (8.3) format. As such, we need to replace the backslashes with forward + " slashes and convert the path components to long format. The expand() + " function will do this but it cannot handle comma-separated paths. This is + " why bsk was converted from a string into a list of strings above. + " + " One final complication is that the wildcard "/*" is at the end of each + " path and so expand() might return a list of matching files. To prevent + " this, we need to remove the wildcard before calling expand() and then + " append it afterwards. + if has('win32') + let item_nbr = 0 + while item_nbr < len(bsklist) + let path_spec = bsklist[item_nbr] + let path_spec = strcharpart(path_spec, 0, strlen(path_spec)-2) + let path_spec = substitute(expand(path_spec), '\\', '/', 'g') + let bsklist[item_nbr] = path_spec . '/*' + let item_nbr += 1 + endwhile + endif + + " Option bsk will also include these environment variables if defined. + " If they're defined, verify they appear in the option value. + for var in ['$TMPDIR', '$TMP', '$TEMP'] + if exists(var) + let varvalue = substitute(expand(var), '\\', '/', 'g') + let varvalue = substitute(varvalue, '/$', '', '') + let varvalue .= '/*' + let found = (index(bsklist, varvalue) >= 0) + call assert_true(found, var . ' (' . varvalue . ') not in option bsk: ' . &bsk) + endif + endfor + + " Duplicates from environment variables should be filtered out (option has + " P_NODUP). Run this in a separate instance and write v:errors in a file, + " so that we see what happens on startup. + let after =<< trim [CODE] + let bsklist = split(&backupskip, ',') + call assert_equal(uniq(copy(bsklist)), bsklist) + call writefile(['errors:'] + v:errors, 'Xtestout') + qall + [CODE] + call writefile(after, 'Xafter') + " let cmd = GetVimProg() . ' --not-a-term -S Xafter --cmd "set enc=utf8"' + let cmd = GetVimProg() . ' -S Xafter --cmd "set enc=utf8"' + + let saveenv = {} + for var in ['TMPDIR', 'TMP', 'TEMP'] + let saveenv[var] = getenv(var) + call setenv(var, '/duplicate/path') + endfor + + exe 'silent !' . cmd + call assert_equal(['errors:'], readfile('Xtestout')) + + " restore environment variables + for var in ['TMPDIR', 'TMP', 'TEMP'] + call setenv(var, saveenv[var]) + endfor + + call delete('Xtestout') + call delete('Xafter') + + " Duplicates should be filtered out (option has P_NODUP) + let backupskip = &backupskip + set backupskip= + set backupskip+=/test/dir + set backupskip+=/other/dir + set backupskip+=/test/dir + call assert_equal('/test/dir,/other/dir', &backupskip) + let &backupskip = backupskip +endfunc + +func Test_buf_copy_winopt() + set hidden + + " Test copy option from current buffer in window + split + enew + setlocal numberwidth=5 + wincmd w + call assert_equal(4,&numberwidth) + bnext + call assert_equal(5,&numberwidth) + bw! + call assert_equal(4,&numberwidth) + + " Test copy value from window that used to be display the buffer + split + enew + setlocal numberwidth=6 + bnext + wincmd w + call assert_equal(4,&numberwidth) + bnext + call assert_equal(6,&numberwidth) + bw! + + " Test that if buffer is current, don't use the stale cached value + " from the last time the buffer was displayed. + split + enew + setlocal numberwidth=7 + bnext + bnext + setlocal numberwidth=8 + wincmd w + call assert_equal(4,&numberwidth) + bnext + call assert_equal(8,&numberwidth) + bw! + + " Test value is not copied if window already has seen the buffer + enew + split + setlocal numberwidth=9 + bnext + setlocal numberwidth=10 + wincmd w + call assert_equal(4,&numberwidth) + bnext + call assert_equal(4,&numberwidth) + bw! + + set hidden& +endfunc + +func Test_split_copy_options() + let values = [ + \['cursorbind', 1, 0], + \['fillchars', '"vert:-"', '"' .. &fillchars .. '"'], + \['list', 1, 0], + \['listchars', '"space:-"', '"' .. &listchars .. '"'], + \['number', 1, 0], + \['relativenumber', 1, 0], + \['scrollbind', 1, 0], + \['smoothscroll', 1, 0], + \['virtualedit', '"block"', '"' .. &virtualedit .. '"'], + "\ ['wincolor', '"Search"', '"' .. &wincolor .. '"'], + \['wrap', 0, 1], + \] + if has('linebreak') + let values += [ + \['breakindent', 1, 0], + \['breakindentopt', '"min:5"', '"' .. &breakindentopt .. '"'], + \['linebreak', 1, 0], + \['numberwidth', 7, 4], + \['showbreak', '"++"', '"' .. &showbreak .. '"'], + \] + endif + if has('rightleft') + let values += [ + \['rightleft', 1, 0], + \['rightleftcmd', '"search"', '"' .. &rightleftcmd .. '"'], + \] + endif + if has('statusline') + let values += [ + \['statusline', '"---%f---"', '"' .. &statusline .. '"'], + \] + endif + if has('spell') + let values += [ + \['spell', 1, 0], + \] + endif + if has('syntax') + let values += [ + \['cursorcolumn', 1, 0], + \['cursorline', 1, 0], + \['cursorlineopt', '"screenline"', '"' .. &cursorlineopt .. '"'], + \['colorcolumn', '"+1"', '"' .. &colorcolumn .. '"'], + \] + endif + if has('diff') + let values += [ + \['diff', 1, 0], + \] + endif + if has('conceal') + let values += [ + \['concealcursor', '"nv"', '"' .. &concealcursor .. '"'], + \['conceallevel', '3', &conceallevel], + \] + endif + if has('terminal') + let values += [ + \['termwinkey', '"<C-X>"', '"' .. &termwinkey .. '"'], + \['termwinsize', '"10x20"', '"' .. &termwinsize .. '"'], + \] + endif + if has('folding') + let values += [ + \['foldcolumn', '"5"', &foldcolumn], + \['foldenable', 0, 1], + \['foldexpr', '"2 + 3"', '"' .. &foldexpr .. '"'], + \['foldignore', '"+="', '"' .. &foldignore .. '"'], + \['foldlevel', 4, &foldlevel], + \['foldmarker', '">>,<<"', '"' .. &foldmarker .. '"'], + \['foldmethod', '"marker"', '"' .. &foldmethod .. '"'], + \['foldminlines', 3, &foldminlines], + \['foldnestmax', 17, &foldnestmax], + \['foldtext', '"closed"', '"' .. &foldtext .. '"'], + \] + endif + if has('signs') + let values += [ + \['signcolumn', '"number"', '"' .. &signcolumn .. '"'], + \] + endif + + " set options to non-default value + for item in values + exe $"let &{item[0]} = {item[1]}" + endfor + + " check values are set in new window + split + for item in values + exe $'call assert_equal({item[1]}, &{item[0]}, "{item[0]}")' + endfor + + " restore + close + for item in values + exe $"let &{item[0]} = {item[1]}" + endfor +endfunc + +func Test_shortmess_F() + new + call assert_match('\[No Name\]', execute('file')) + set shortmess+=F + call assert_match('\[No Name\]', execute('file')) + call assert_match('^\s*$', execute('file foo')) + call assert_match('foo', execute('file')) + set shortmess-=F + call assert_match('bar', execute('file bar')) + call assert_match('bar', execute('file')) + set shortmess& + bwipe +endfunc + +func Test_shortmess_F2() + e file1 + e file2 + call assert_match('file1', execute('bn', '')) + call assert_match('file2', execute('bn', '')) + set shortmess+=F + call assert_true(empty(execute('bn', ''))) + " call assert_false(test_getvalue('need_fileinfo')) + call assert_true(empty(execute('bn', ''))) + " call assert_false(test_getvalue('need_fileinfo')) + set hidden + call assert_true(empty(execute('bn', ''))) + " call assert_false(test_getvalue('need_fileinfo')) + call assert_true(empty(execute('bn', ''))) + " call assert_false(test_getvalue('need_fileinfo')) + set nohidden + call assert_true(empty(execute('bn', ''))) + " call assert_false(test_getvalue('need_fileinfo')) + call assert_true(empty(execute('bn', ''))) + " call assert_false(test_getvalue('need_fileinfo')) + set shortmess-=F " Accommodate Nvim default. + call assert_match('file1', execute('bn', '')) + call assert_match('file2', execute('bn', '')) + bwipe + bwipe + " call assert_fails('call test_getvalue("abc")', 'E475:') +endfunc + +func Test_local_scrolloff() + set so=5 + set siso=7 + split + call assert_equal(5, &so) + setlocal so=3 + call assert_equal(3, &so) + wincmd w + call assert_equal(5, &so) + wincmd w + call assert_equal(3, &so) + setlocal so< + call assert_equal(5, &so) + setglob so=8 + call assert_equal(8, &so) + call assert_equal(-1, &l:so) + setlocal so=0 + call assert_equal(0, &so) + setlocal so=-1 + call assert_equal(8, &so) + + call assert_equal(7, &siso) + setlocal siso=3 + call assert_equal(3, &siso) + wincmd w + call assert_equal(7, &siso) + wincmd w + call assert_equal(3, &siso) + setlocal siso< + call assert_equal(7, &siso) + setglob siso=4 + call assert_equal(4, &siso) + call assert_equal(-1, &l:siso) + setlocal siso=0 + call assert_equal(0, &siso) + setlocal siso=-1 + call assert_equal(4, &siso) + + close + set so& + set siso& +endfunc + +func Test_visualbell() + set belloff= + set visualbell + call assert_beeps('normal 0h') + set novisualbell + set belloff=all +endfunc + +" Test for the 'write' option +func Test_write() + new + call setline(1, ['L1']) + set nowrite + call assert_fails('write Xfile', 'E142:') + set write + close! +endfunc + +" Test for 'buftype' option +func Test_buftype() + new + call setline(1, ['L1']) + set buftype=nowrite + call assert_fails('write', 'E382:') + + " for val in ['', 'nofile', 'nowrite', 'acwrite', 'quickfix', 'help', 'terminal', 'prompt', 'popup'] + for val in ['', 'nofile', 'nowrite', 'acwrite', 'quickfix', 'help', 'prompt'] + exe 'set buftype=' .. val + call writefile(['something'], 'XBuftype') + call assert_fails('write XBuftype', 'E13:', 'with buftype=' .. val) + endfor + + call delete('XBuftype') + bwipe! +endfunc + +" Test for the 'shell' option +func Test_shell() + throw 'Skipped: Nvim does not have :shell' + CheckUnix + let save_shell = &shell + set shell= + let caught_e91 = 0 + try + shell + catch /E91:/ + let caught_e91 = 1 + endtry + call assert_equal(1, caught_e91) + let &shell = save_shell +endfunc + +" Test for the 'shellquote' option +func Test_shellquote() + CheckUnix + set shellquote=# + set verbose=20 + redir => v + silent! !echo Hello + redir END + set verbose& + set shellquote& + call assert_match(': "#echo Hello#"', v) +endfunc + +" Test for the 'rightleftcmd' option +func Test_rightleftcmd() + CheckFeature rightleft + set rightleft + + let g:l = [] + func AddPos() + call add(g:l, screencol()) + return '' + endfunc + cmap <expr> <F2> AddPos() + + set rightleftcmd= + call feedkeys("/\<F2>abc\<Right>\<F2>\<Left>\<Left>\<F2>" .. + \ "\<Right>\<F2>\<Esc>", 'xt') + call assert_equal([2, 5, 3, 4], g:l) + + let g:l = [] + set rightleftcmd=search + call feedkeys("/\<F2>abc\<Left>\<F2>\<Right>\<Right>\<F2>" .. + \ "\<Left>\<F2>\<Esc>", 'xt') + call assert_equal([&co - 1, &co - 4, &co - 2, &co - 3], g:l) + + cunmap <F2> + unlet g:l + set rightleftcmd& + set rightleft& +endfunc + +" Test for the 'debug' option +func Test_debug_option() + " redraw to avoid matching previous messages + redraw + set debug=beep + exe "normal \<C-c>" + call assert_equal('Beep!', Screenline(&lines)) + call assert_equal('line 4:', Screenline(&lines - 1)) + " also check a line above, with a certain window width the colon is there + call assert_match('Test_debug_option:$', + \ Screenline(&lines - 3) .. Screenline(&lines - 2)) + set debug& +endfunc + +" Test for the default CDPATH option +func Test_opt_default_cdpath() + let after =<< trim [CODE] + call assert_equal(',/path/to/dir1,/path/to/dir2', &cdpath) + call writefile(v:errors, 'Xtestout') + qall + [CODE] + if has('unix') + let $CDPATH='/path/to/dir1:/path/to/dir2' + else + let $CDPATH='/path/to/dir1;/path/to/dir2' + endif + if RunVim([], after, '') + call assert_equal([], readfile('Xtestout')) + call delete('Xtestout') + endif +endfunc + +" Test for setting keycodes using set +func Test_opt_set_keycode() + call assert_fails('set <t_k1=l', 'E474:') + call assert_fails('set <Home=l', 'E474:') + set <t_k9>=abcd + " call assert_equal('abcd', &t_k9) + set <t_k9>& + set <F9>=xyz + " call assert_equal('xyz', &t_k9) + set <t_k9>& +endfunc + +" Test for changing options in a sandbox +func Test_opt_sandbox() + for opt in ['backupdir', 'cdpath', 'exrc'] + call assert_fails('sandbox set ' .. opt .. '?', 'E48:') + call assert_fails('sandbox let &' .. opt .. ' = 1', 'E48:') + endfor + call assert_fails('sandbox let &modelineexpr = 1', 'E48:') +endfunc + +" Test for setting an option with local value to global value +func Test_opt_local_to_global() + setglobal equalprg=gprg + setlocal equalprg=lprg + call assert_equal('gprg', &g:equalprg) + call assert_equal('lprg', &l:equalprg) + call assert_equal('lprg', &equalprg) + set equalprg< + call assert_equal('', &l:equalprg) + call assert_equal('gprg', &equalprg) + setglobal equalprg=gnewprg + setlocal equalprg=lnewprg + setlocal equalprg< + call assert_equal('gnewprg', &l:equalprg) + call assert_equal('gnewprg', &equalprg) + set equalprg& + + " Test for setting the global/local value of a boolean option + setglobal autoread + setlocal noautoread + call assert_false(&autoread) + set autoread< + call assert_true(&autoread) + setglobal noautoread + setlocal autoread + setlocal autoread< + call assert_false(&autoread) + set autoread& +endfunc + +func Test_set_in_sandbox() + " Some boolean options cannot be set in sandbox, some can. + call assert_fails('sandbox set modelineexpr', 'E48:') + sandbox set number + call assert_true(&number) + set number& + + " Some boolean options cannot be set in sandbox, some can. + if has('python') || has('python3') + call assert_fails('sandbox set pyxversion=3', 'E48:') + endif + sandbox set tabstop=4 + call assert_equal(4, &tabstop) + set tabstop& + + " Some string options cannot be set in sandbox, some can. + call assert_fails('sandbox set backupdir=/tmp', 'E48:') + sandbox set filetype=perl + call assert_equal('perl', &filetype) + set filetype& +endfunc + +" Test for incrementing, decrementing and multiplying a number option value +func Test_opt_num_op() + set shiftwidth=4 + set sw+=2 + call assert_equal(6, &sw) + set sw-=2 + call assert_equal(4, &sw) + set sw^=2 + call assert_equal(8, &sw) + set shiftwidth& +endfunc + +" Test for setting option values using v:false and v:true +func Test_opt_boolean() + set number& + set number + call assert_equal(1, &nu) + set nonu + call assert_equal(0, &nu) + let &nu = v:true + call assert_equal(1, &nu) + let &nu = v:false + call assert_equal(0, &nu) + set number& +endfunc + +" Test for the 'window' option +func Test_window_opt() + " Needs only one open widow + %bw! + call setline(1, range(1, 8)) + set window=5 + exe "normal \<C-F>" + call assert_equal(4, line('w0')) + exe "normal \<C-F>" + call assert_equal(7, line('w0')) + exe "normal \<C-F>" + call assert_equal(8, line('w0')) + exe "normal \<C-B>" + call assert_equal(5, line('w0')) + exe "normal \<C-B>" + call assert_equal(2, line('w0')) + exe "normal \<C-B>" + call assert_equal(1, line('w0')) + set window=1 + exe "normal gg\<C-F>" + call assert_equal(2, line('w0')) + exe "normal \<C-F>" + call assert_equal(3, line('w0')) + exe "normal \<C-B>" + call assert_equal(2, line('w0')) + exe "normal \<C-B>" + call assert_equal(1, line('w0')) + enew! + set window& +endfunc + +" Test for the 'winminheight' option +func Test_opt_winminheight() + only! + let &winheight = &lines + 4 + call assert_fails('let &winminheight = &lines + 2', 'E36:') + call assert_true(&winminheight <= &lines) + set winminheight& + set winheight& +endfunc + +func Test_opt_winminheight_term() + " See test/functional/legacy/options_spec.lua + CheckRunVimInTerminal + + " The tabline should be taken into account. + let lines =<< trim END + set wmh=0 stal=2 + below sp | wincmd _ + below sp | wincmd _ + below sp | wincmd _ + below sp + END + call writefile(lines, 'Xwinminheight') + let buf = RunVimInTerminal('-S Xwinminheight', #{rows: 11}) + call term_sendkeys(buf, ":set wmh=1\n") + call WaitForAssert({-> assert_match('E36: Not enough room', term_getline(buf, 11))}) + + call StopVimInTerminal(buf) + call delete('Xwinminheight') +endfunc + +func Test_opt_winminheight_term_tabs() + " See test/functional/legacy/options_spec.lua + CheckRunVimInTerminal + + " The tabline should be taken into account. + let lines =<< trim END + set wmh=0 stal=2 + split + split + split + split + tabnew + END + call writefile(lines, 'Xwinminheight') + let buf = RunVimInTerminal('-S Xwinminheight', #{rows: 11}) + call term_sendkeys(buf, ":set wmh=1\n") + call WaitForAssert({-> assert_match('E36: Not enough room', term_getline(buf, 11))}) + + call StopVimInTerminal(buf) + call delete('Xwinminheight') +endfunc + +" Test for the 'winminwidth' option +func Test_opt_winminwidth() + only! + let &winwidth = &columns + 4 + call assert_fails('let &winminwidth = &columns + 2', 'E36:') + call assert_true(&winminwidth <= &columns) + set winminwidth& + set winwidth& +endfunc + +" Test for setting option value containing spaces with isfname+=32 +func Test_isfname_with_options() + set isfname+=32 + setlocal keywordprg=:term\ help.exe + call assert_equal(':term help.exe', &keywordprg) + set isfname& + setlocal keywordprg& +endfunc + +" Test that resetting laststatus does change scroll option +func Test_opt_reset_scroll() + " See test/functional/legacy/options_spec.lua + CheckRunVimInTerminal + let vimrc =<< trim [CODE] + set scroll=2 + set laststatus=2 + [CODE] + call writefile(vimrc, 'Xscroll') + let buf = RunVimInTerminal('-S Xscroll', {'rows': 16, 'cols': 45}) + call term_sendkeys(buf, ":verbose set scroll?\n") + call WaitForAssert({-> assert_match('Last set.*window size', term_getline(buf, 15))}) + call assert_match('^\s*scroll=7$', term_getline(buf, 14)) + call StopVimInTerminal(buf) + + " clean up + call delete('Xscroll') +endfunc + +" Check that VIM_POSIX env variable influences default value of 'cpo' and 'shm' +func Test_VIM_POSIX() + throw 'Skipped: Nvim does not support $VIM_POSIX' + let saved_VIM_POSIX = getenv("VIM_POSIX") + + call setenv('VIM_POSIX', "1") + let after =<< trim [CODE] + call writefile([&cpo, &shm], 'X_VIM_POSIX') + qall + [CODE] + if RunVim([], after, '') + call assert_equal(['aAbBcCdDeEfFgHiIjJkKlLmMnoOpPqrRsStuvwWxXyZ$!%*-+<>#{|&/\.;', + \ 'AS'], readfile('X_VIM_POSIX')) + endif + + call setenv('VIM_POSIX', v:null) + let after =<< trim [CODE] + call writefile([&cpo, &shm], 'X_VIM_POSIX') + qall + [CODE] + if RunVim([], after, '') + call assert_equal(['aAbBcCdDeEfFgHiIjJkKlLmMnoOpPqrRsStuvwWxXyZ$!%*-+<>;', + \ 'S'], readfile('X_VIM_POSIX')) + endif + + call delete('X_VIM_POSIX') + call setenv('VIM_POSIX', saved_VIM_POSIX) +endfunc + +" Test for setting an option to a Vi or Vim default +func Test_opt_default() + throw 'Skipped: Nvim has different defaults' + set formatoptions&vi + call assert_equal('vt', &formatoptions) + set formatoptions&vim + call assert_equal('tcq', &formatoptions) +endfunc + +" Test for the 'cmdheight' option +func Test_cmdheight() + %bw! + let ht = &lines + set cmdheight=9999 + call assert_equal(1, winheight(0)) + call assert_equal(ht - 1, &cmdheight) + set cmdheight& +endfunc + +" To specify a control character as a option value, '^' can be used +func Test_opt_control_char() + set wildchar=^v + call assert_equal("\<C-V>", nr2char(&wildchar)) + set wildcharm=^r + call assert_equal("\<C-R>", nr2char(&wildcharm)) + " Bug: This doesn't work for the 'cedit' and 'termwinkey' options + set wildchar& wildcharm& +endfunc + +" Test for the 'errorbells' option +func Test_opt_errorbells() + set errorbells + call assert_beeps('s/a1b2/x1y2/') + set noerrorbells +endfunc + +func Test_opt_scrolljump() + help + resize 10 + + " Test with positive 'scrolljump'. + set scrolljump=2 + norm! Lj + call assert_equal({'lnum':11, 'leftcol':0, 'col':0, 'topfill':0, + \ 'topline':3, 'coladd':0, 'skipcol':0, 'curswant':0}, + \ winsaveview()) + + " Test with negative 'scrolljump' (percentage of window height). + set scrolljump=-40 + norm! ggLj + call assert_equal({'lnum':11, 'leftcol':0, 'col':0, 'topfill':0, + \ 'topline':5, 'coladd':0, 'skipcol':0, 'curswant':0}, + \ winsaveview()) + + set scrolljump& + bw +endfunc + +" Test for the 'cdhome' option +func Test_opt_cdhome() + if has('unix') || has('vms') + throw 'Skipped: only works on non-Unix' + endif + + set cdhome& + call assert_equal(0, &cdhome) + set cdhome + + " This paragraph is copied from Test_cd_no_arg(). + let path = getcwd() + cd + call assert_equal($HOME, getcwd()) + call assert_notequal(path, getcwd()) + exe 'cd ' .. fnameescape(path) + call assert_equal(path, getcwd()) + + set cdhome& +endfunc + +func Test_set_completion_fuzzy() + CheckOption termguicolors + + " Test default option completion + set wildoptions= + call feedkeys(":set termg\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set termguicolors', @:) + + call feedkeys(":set notermg\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set notermguicolors', @:) + + " Test fuzzy option completion + set wildoptions=fuzzy + call feedkeys(":set termg\<C-A>\<C-B>\"\<CR>", 'tx') + " Nvim doesn't have 'termencoding' + " call assert_equal('"set termguicolors termencoding', @:) + call assert_equal('"set termguicolors', @:) + + call feedkeys(":set notermg\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"set notermguicolors', @:) + + set wildoptions= +endfunc + +func Test_switchbuf_reset() + set switchbuf=useopen + sblast + call assert_equal(1, winnr('$')) + set all& + " Nvim has a different default for 'switchbuf' + " call assert_equal('', &switchbuf) + call assert_equal('uselast', &switchbuf) + sblast + call assert_equal(2, winnr('$')) + only! +endfunc + +" :set empty string for global 'keywordprg' falls back to ":help" +func Test_keywordprg_empty() + let k = &keywordprg + set keywordprg=man + call assert_equal('man', &keywordprg) + set keywordprg= + call assert_equal(':help', &keywordprg) + set keywordprg=man + call assert_equal('man', &keywordprg) + call assert_equal("\n keywordprg=:help", execute('set kp= kp?')) + let &keywordprg = k +endfunc + +" check that the very first buffer created does not have 'endoffile' set +func Test_endoffile_default() + let after =<< trim [CODE] + call writefile([execute('set eof?')], 'Xtestout') + qall! + [CODE] + if RunVim([], after, '') + call assert_equal(["\nnoendoffile"], readfile('Xtestout')) + endif + call delete('Xtestout') +endfunc + +" Test for setting the 'lines' and 'columns' options to a minimum value +func Test_set_min_lines_columns() + let save_lines = &lines + let save_columns = &columns + + let after =<< trim END + set laststatus=1 + set nomore + let msg = [] + let v:errmsg = '' + silent! let &columns=0 + call add(msg, v:errmsg) + silent! set columns=0 + call add(msg, v:errmsg) + silent! call setbufvar('', '&columns', 0) + call add(msg, v:errmsg) + "call writefile(msg, 'XResultsetminlines') + silent! let &lines=0 + call add(msg, v:errmsg) + silent! set lines=0 + call add(msg, v:errmsg) + silent! call setbufvar('', '&lines', 0) + call add(msg, v:errmsg) + call writefile(msg, 'XResultsetminlines') + qall! + END + if RunVim([], after, '') + call assert_equal(['E594: Need at least 12 columns', + \ 'E594: Need at least 12 columns: columns=0', + \ 'E594: Need at least 12 columns', + \ 'E593: Need at least 2 lines', + \ 'E593: Need at least 2 lines: lines=0', + \ 'E593: Need at least 2 lines',], readfile('XResultsetminlines')) + endif + + call delete('XResultsetminlines') + let &lines = save_lines + let &columns = save_columns +endfunc + +" Test for reverting a string option value if the new value is invalid. +func Test_string_option_revert_on_failure() + new + let optlist = [ + \ ['ambiwidth', 'double', 'a123'], + \ ['background', 'dark', 'a123'], + \ ['backspace', 'eol', 'a123'], + \ ['backupcopy', 'no', 'a123'], + \ ['belloff', 'showmatch', 'a123'], + \ ['breakindentopt', 'min:10', 'list'], + \ ['bufhidden', 'wipe', 'a123'], + \ ['buftype', 'nowrite', 'a123'], + \ ['casemap', 'keepascii', 'a123'], + \ ['cedit', "\<C-Y>", 'z'], + \ ['colorcolumn', '10', 'z'], + \ ['commentstring', '#%s', 'a123'], + \ ['complete', '.,t', 'a'], + \ ['completefunc', 'MyCmplFunc', '1a-'], + "\ ['completeopt', 'popup', 'a123'], + \ ['completeopt', 'preview', 'a123'], + "\ ['completepopup', 'width:20', 'border'], + \ ['concealcursor', 'v', 'xyz'], + "\ ['cpoptions', 'HJ', '~'], + \ ['cpoptions', 'J', '~'], + "\ ['cryptmethod', 'zip', 'a123'], + \ ['cursorlineopt', 'screenline', 'a123'], + \ ['debug', 'throw', 'a123'], + \ ['diffopt', 'iwhite', 'a123'], + \ ['display', 'uhex', 'a123'], + \ ['eadirection', 'hor', 'a123'], + \ ['encoding', 'utf-8', 'a123'], + \ ['eventignore', 'TextYankPost', 'a123'], + \ ['fileencoding', 'utf-8', 'a123,'], + \ ['fileformat', 'mac', 'a123'], + \ ['fileformats', 'mac', 'a123'], + \ ['filetype', 'abc', 'a^b'], + \ ['fillchars', 'diff:~', 'a123'], + \ ['foldclose', 'all', 'a123'], + \ ['foldmarker', '[[[,]]]', '[[['], + \ ['foldmethod', 'marker', 'a123'], + \ ['foldopen', 'percent', 'a123'], + \ ['formatoptions', 'an', '*'], + \ ['guicursor', 'n-v-c:block-Cursor/lCursor', 'n-v-c'], + \ ['helplang', 'en', 'a'], + "\ ['highlight', '!:CursorColumn', '8:'], + \ ['keymodel', 'stopsel', 'a123'], + "\ ['keyprotocol', 'kitty:kitty', 'kitty:'], + \ ['lispoptions', 'expr:1', 'a123'], + \ ['listchars', 'tab:->', 'tab:'], + \ ['matchpairs', '<:>', '<:'], + \ ['mkspellmem', '100000,1000,100', '100000'], + \ ['mouse', 'nvi', 'z'], + \ ['mousemodel', 'extend', 'a123'], + \ ['nrformats', 'alpha', 'a123'], + \ ['omnifunc', 'MyOmniFunc', '1a-'], + \ ['operatorfunc', 'MyOpFunc', '1a-'], + "\ ['previewpopup', 'width:20', 'a123'], + "\ ['printoptions', 'paper:A4', 'a123:'], + \ ['quickfixtextfunc', 'MyQfFunc', '1a-'], + \ ['rulerformat', '%l', '%['], + \ ['scrollopt', 'hor,jump', 'a123'], + \ ['selection', 'exclusive', 'a123'], + \ ['selectmode', 'cmd', 'a123'], + \ ['sessionoptions', 'options', 'a123'], + \ ['shortmess', 'w', '2'], + \ ['showbreak', '>>', "\x01"], + \ ['showcmdloc', 'statusline', 'a123'], + \ ['signcolumn', 'no', 'a123'], + \ ['spellcapcheck', '[.?!]\+', '%\{'], + \ ['spellfile', 'MySpell.en.add', "\x01"], + \ ['spelllang', 'en', "#"], + \ ['spelloptions', 'camel', 'a123'], + \ ['spellsuggest', 'double', 'a123'], + \ ['splitkeep', 'topline', 'a123'], + \ ['statusline', '%f', '%['], + "\ ['swapsync', 'sync', 'a123'], + \ ['switchbuf', 'usetab', 'a123'], + \ ['syntax', 'abc', 'a^b'], + \ ['tabline', '%f', '%['], + \ ['tagcase', 'ignore', 'a123'], + \ ['tagfunc', 'MyTagFunc', '1a-'], + \ ['thesaurusfunc', 'MyThesaurusFunc', '1a-'], + \ ['viewoptions', 'options', 'a123'], + \ ['virtualedit', 'onemore', 'a123'], + \ ['whichwrap', '<,>', '{,}'], + \ ['wildmode', 'list', 'a123'], + \ ['wildoptions', 'pum', 'a123'] + \ ] + if has('gui') + call add(optlist, ['browsedir', 'buffer', 'a123']) + endif + if has('clipboard_working') + call add(optlist, ['clipboard', 'unnamed', 'a123']) + endif + if has('win32') + call add(optlist, ['completeslash', 'slash', 'a123']) + endif + if has('cscope') + call add(optlist, ['cscopequickfix', 't-', 'z-']) + endif + if !has('win32') && !has('nvim') + call add(optlist, ['imactivatefunc', 'MyActFunc', '1a-']) + call add(optlist, ['imstatusfunc', 'MyStatusFunc', '1a-']) + endif + if has('keymap') + call add(optlist, ['keymap', 'greek', '[]']) + endif + if has('mouseshape') + call add(optlist, ['mouseshape', 'm:no', 'a123:']) + endif + if has('win32') && has('gui') + call add(optlist, ['renderoptions', 'type:directx', 'type:directx,a123']) + endif + if has('rightleft') + call add(optlist, ['rightleftcmd', 'search', 'a123']) + endif + if has('terminal') + call add(optlist, ['termwinkey', '<C-L>', '<C']) + call add(optlist, ['termwinsize', '24x80', '100']) + endif + if has('win32') && has('terminal') + call add(optlist, ['termwintype', 'winpty', 'a123']) + endif + if exists('+toolbar') + call add(optlist, ['toolbar', 'text', 'a123']) + endif + if exists('+toolbariconsize') + call add(optlist, ['toolbariconsize', 'medium', 'a123']) + endif + if exists('+ttymouse') && !has('gui') + call add(optlist, ['ttymouse', 'xterm', 'a123']) + endif + if exists('+vartabs') + call add(optlist, ['varsofttabstop', '12', 'a123']) + call add(optlist, ['vartabstop', '4,20', '4,']) + endif + if exists('+winaltkeys') + call add(optlist, ['winaltkeys', 'no', 'a123']) + endif + for opt in optlist + exe $"let save_opt = &{opt[0]}" + try + exe $"let &{opt[0]} = '{opt[1]}'" + catch + call assert_report($"Caught {v:exception} with {opt->string()}") + endtry + call assert_fails($"let &{opt[0]} = '{opt[2]}'", '', opt[0]) + call assert_equal(opt[1], eval($"&{opt[0]}"), opt[0]) + exe $"let &{opt[0]} = save_opt" + endfor + bw! +endfunc + +func Test_set_option_window_global_local() + new Xbuffer1 + let [ _gso, _lso ] = [ &g:scrolloff, &l:scrolloff ] + setlocal scrolloff=2 + setglobal scrolloff=3 + setl modified + " A new buffer has its own window-local options + hide enew + call assert_equal(-1, &l:scrolloff) + call assert_equal(3, &g:scrolloff) + " A new window opened with its own buffer-local options + new + call assert_equal(-1, &l:scrolloff) + call assert_equal(3, &g:scrolloff) + " Re-open Xbuffer1 and it should use + " the previous set window-local options + b Xbuffer1 + call assert_equal(2, &l:scrolloff) + call assert_equal(3, &g:scrolloff) + bw! + bw! + let &g:scrolloff = _gso +endfunc + +func GetGlobalLocalWindowOptions() + new + sil! r $VIMRUNTIME/doc/options.txt + " Filter for global or local to window + v/^'.*'.*\n.*global or local to window |global-local/d + " get option value and type + sil %s/^'\([^']*\)'.*'\s\+\(\w\+\)\s\+(default \%(\(".*"\|\d\+\|empty\)\).*/\1 \2 \3/g + " sil %s/empty/""/g + " split the result + " let result=getline(1,'$')->map({_, val -> split(val, ' ')}) + let result = getline(1, '$')->map({_, val -> matchlist(val, '\([^ ]\+\) \+\([^ ]\+\) \+\(.*\)')[1:3]}) + bw! + return result +endfunc + +func Test_set_option_window_global_local_all() + new Xbuffer2 + + let optionlist = GetGlobalLocalWindowOptions() + for [opt, type, default] in optionlist + let _old = eval('&g:' .. opt) + if type == 'string' + if opt == 'fillchars' + exe 'setl ' .. opt .. '=vert:+' + exe 'setg ' .. opt .. '=vert:+,fold:+' + elseif opt == 'listchars' + exe 'setl ' .. opt .. '=tab:>>' + exe 'setg ' .. opt .. '=tab:++' + elseif opt == 'virtualedit' + exe 'setl ' .. opt .. '=all' + exe 'setg ' .. opt .. '=block' + else + exe 'setl ' .. opt .. '=Local' + exe 'setg ' .. opt .. '=Global' + endif + elseif type == 'number' + exe 'setl ' .. opt .. '=5' + exe 'setg ' .. opt .. '=10' + endif + setl modified + hide enew + if type == 'string' + call assert_equal('', eval('&l:' .. opt)) + if opt == 'fillchars' + call assert_equal('vert:+,fold:+', eval('&g:' .. opt), 'option:' .. opt) + elseif opt == 'listchars' + call assert_equal('tab:++', eval('&g:' .. opt), 'option:' .. opt) + elseif opt == 'virtualedit' + call assert_equal('block', eval('&g:' .. opt), 'option:' .. opt) + else + call assert_equal('Global', eval('&g:' .. opt), 'option:' .. opt) + endif + elseif type == 'number' + call assert_equal(-1, eval('&l:' .. opt), 'option:' .. opt) + call assert_equal(10, eval('&g:' .. opt), 'option:' .. opt) + endif + bw! + exe 'let &g:' .. opt .. '=' .. default + endfor + bw! +endfunc + +func Test_paste_depending_options() + " setting the paste option, resets all dependent options + " and will be reported correctly using :verbose set <option>? + let lines =<< trim [CODE] + " set paste test + set autoindent + set expandtab + " disabled, because depends on compiled feature set + " set hkmap + " set revins + " set varsofttabstop=8,32,8 + set ruler + set showmatch + set smarttab + set softtabstop=4 + set textwidth=80 + set wrapmargin=10 + + source Xvimrc_paste2 + + redir > Xoutput_paste + verbose set expandtab? + verbose setg expandtab? + verbose setl expandtab? + redir END + + qall! + [CODE] + + call writefile(lines, 'Xvimrc_paste', 'D') + call writefile(['set paste'], 'Xvimrc_paste2', 'D') + if !RunVim([], lines, '--clean') + return + endif + + let result = readfile('Xoutput_paste')->filter('!empty(v:val)') + call assert_equal('noexpandtab', result[0]) + call assert_match("^\tLast set from .*Xvimrc_paste2 line 1$", result[1]) + call assert_equal('noexpandtab', result[2]) + call assert_match("^\tLast set from .*Xvimrc_paste2 line 1$", result[3]) + call assert_equal('noexpandtab', result[4]) + call assert_match("^\tLast set from .*Xvimrc_paste2 line 1$", result[5]) + + call delete('Xoutput_paste') +endfunc + +func Test_binary_depending_options() + " setting the paste option, resets all dependent options + " and will be reported correctly using :verbose set <option>? + let lines =<< trim [CODE] + " set binary test + set expandtab + + source Xvimrc_bin2 + + redir > Xoutput_bin + verbose set expandtab? + verbose setg expandtab? + verbose setl expandtab? + redir END + + qall! + [CODE] + + call writefile(lines, 'Xvimrc_bin', 'D') + call writefile(['set binary'], 'Xvimrc_bin2', 'D') + if !RunVim([], lines, '--clean') + return + endif + + let result = readfile('Xoutput_bin')->filter('!empty(v:val)') + call assert_equal('noexpandtab', result[0]) + call assert_match("^\tLast set from .*Xvimrc_bin2 line 1$", result[1]) + call assert_equal('noexpandtab', result[2]) + call assert_match("^\tLast set from .*Xvimrc_bin2 line 1$", result[3]) + call assert_equal('noexpandtab', result[4]) + call assert_match("^\tLast set from .*Xvimrc_bin2 line 1$", result[5]) + + call delete('Xoutput_bin') +endfunc + +func Test_set_wrap() + " Unsetting 'wrap' when 'smoothscroll' is set does not result in incorrect + " cursor position. + set wrap smoothscroll scrolloff=5 + + call setline(1, ['', 'aaaa'->repeat(500)]) + 20 split + 20 vsplit + norm 2G$ + redraw + set nowrap + call assert_equal(2, winline()) + + set wrap& smoothscroll& scrolloff& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_packadd.vim b/test/old/testdir/test_packadd.vim new file mode 100644 index 0000000000..730cb3278b --- /dev/null +++ b/test/old/testdir/test_packadd.vim @@ -0,0 +1,511 @@ +" Tests for 'packpath' and :packadd + + +func SetUp() + let s:topdir = getcwd() . '/Xdir' + exe 'set packpath=' . s:topdir + let s:plugdir = s:topdir . '/pack/mine/opt/mytest' +endfunc + +func TearDown() + call delete(s:topdir, 'rf') +endfunc + +func Test_packadd() + if !exists('s:plugdir') + echomsg 'when running this test manually, call SetUp() first' + return + endif + + call mkdir(s:plugdir . '/plugin/also', 'p') + call mkdir(s:plugdir . '/ftdetect', 'p') + call mkdir(s:plugdir . '/after', 'p') + + " This used to crash Vim + let &rtp = 'nosuchdir,' . s:plugdir . '/after' + packadd mytest + " plugdir should be inserted before plugdir/after + call assert_match('^nosuchdir,' . s:plugdir . ',', &rtp) + + set rtp& + let rtp = &rtp + filetype on + + let rtp_entries = split(rtp, ',') + for entry in rtp_entries + if entry =~? '\<after\>' + let first_after_entry = entry + break + endif + endfor + + exe 'split ' . s:plugdir . '/plugin/test.vim' + call setline(1, 'let g:plugin_works = 42') + wq + + exe 'split ' . s:plugdir . '/plugin/also/loaded.vim' + call setline(1, 'let g:plugin_also_works = 77') + wq + + exe 'split ' . s:plugdir . '/ftdetect/test.vim' + call setline(1, 'let g:ftdetect_works = 17') + wq + + packadd mytest + + call assert_equal(42, g:plugin_works) + call assert_equal(77, g:plugin_also_works) + call assert_equal(17, g:ftdetect_works) + call assert_true(len(&rtp) > len(rtp)) + call assert_match('/testdir/Xdir/pack/mine/opt/mytest\($\|,\)', &rtp) + + let new_after = match(&rtp, '/testdir/Xdir/pack/mine/opt/mytest/after,') + let forwarded = substitute(first_after_entry, '\\', '[/\\\\]', 'g') + let old_after = match(&rtp, ',' . forwarded . '\>') + call assert_true(new_after > 0, 'rtp is ' . &rtp) + call assert_true(old_after > 0, 'match ' . forwarded . ' in ' . &rtp) + call assert_true(new_after < old_after, 'rtp is ' . &rtp) + + " NOTE: '/.../opt/myte' forwardly matches with '/.../opt/mytest' + call mkdir(fnamemodify(s:plugdir, ':h') . '/myte', 'p') + let rtp = &rtp + packadd myte + + " Check the path of 'myte' is added + call assert_true(len(&rtp) > len(rtp)) + call assert_match('/testdir/Xdir/pack/mine/opt/myte\($\|,\)', &rtp) + + " Check exception + call assert_fails("packadd directorynotfound", 'E919:') + call assert_fails("packadd", 'E471:') +endfunc + +func Test_packadd_start() + let plugdir = s:topdir . '/pack/mine/start/other' + call mkdir(plugdir . '/plugin', 'p') + set rtp& + let rtp = &rtp + filetype on + + exe 'split ' . plugdir . '/plugin/test.vim' + call setline(1, 'let g:plugin_works = 24') + wq + + packadd other + + call assert_equal(24, g:plugin_works) + call assert_true(len(&rtp) > len(rtp)) + call assert_match('/testdir/Xdir/pack/mine/start/other\($\|,\)', &rtp) +endfunc + +func Test_packadd_noload() + call mkdir(s:plugdir . '/plugin', 'p') + call mkdir(s:plugdir . '/syntax', 'p') + set rtp& + let rtp = &rtp + + exe 'split ' . s:plugdir . '/plugin/test.vim' + call setline(1, 'let g:plugin_works = 42') + wq + let g:plugin_works = 0 + + packadd! mytest + + call assert_true(len(&rtp) > len(rtp)) + call assert_match('testdir/Xdir/pack/mine/opt/mytest\($\|,\)', &rtp) + call assert_equal(0, g:plugin_works) + + " check the path is not added twice + let new_rtp = &rtp + packadd! mytest + call assert_equal(new_rtp, &rtp) +endfunc + +func Test_packadd_symlink_dir() + if !has('unix') + return + endif + let top2_dir = s:topdir . '/Xdir2' + let real_dir = s:topdir . '/Xsym' + call mkdir(real_dir, 'p') + exec "silent !ln -s Xsym" top2_dir + let &rtp = top2_dir . ',' . top2_dir . '/after' + let &packpath = &rtp + + let s:plugdir = top2_dir . '/pack/mine/opt/mytest' + call mkdir(s:plugdir . '/plugin', 'p') + + exe 'split ' . s:plugdir . '/plugin/test.vim' + call setline(1, 'let g:plugin_works = 44') + wq + let g:plugin_works = 0 + + packadd mytest + + " Must have been inserted in the middle, not at the end + call assert_match('/pack/mine/opt/mytest,', &rtp) + call assert_equal(44, g:plugin_works) + + " No change when doing it again. + let rtp_before = &rtp + packadd mytest + call assert_equal(rtp_before, &rtp) + + set rtp& + let rtp = &rtp + exec "silent !rm" top2_dir +endfunc + +func Test_packadd_symlink_dir2() + if !has('unix') + return + endif + let top2_dir = s:topdir . '/Xdir2' + let real_dir = s:topdir . '/Xsym/pack' + call mkdir(top2_dir, 'p') + call mkdir(real_dir, 'p') + let &rtp = top2_dir . ',' . top2_dir . '/after' + let &packpath = &rtp + + exec "silent !ln -s ../Xsym/pack" top2_dir . '/pack' + let s:plugdir = top2_dir . '/pack/mine/opt/mytest' + call mkdir(s:plugdir . '/plugin', 'p') + + exe 'split ' . s:plugdir . '/plugin/test.vim' + call setline(1, 'let g:plugin_works = 48') + wq + let g:plugin_works = 0 + + packadd mytest + + " Must have been inserted in the middle, not at the end + call assert_match('/Xdir2/pack/mine/opt/mytest,', &rtp) + call assert_equal(48, g:plugin_works) + + " No change when doing it again. + let rtp_before = &rtp + packadd mytest + call assert_equal(rtp_before, &rtp) + + set rtp& + let rtp = &rtp + exec "silent !rm" top2_dir . '/pack' + exec "silent !rmdir" top2_dir +endfunc + +" Check command-line completion for :packadd +func Test_packadd_completion() + let optdir1 = &packpath . '/pack/mine/opt' + let optdir2 = &packpath . '/pack/candidate/opt' + + call mkdir(optdir1 . '/pluginA', 'p') + call mkdir(optdir1 . '/pluginC', 'p') + call writefile([], optdir1 . '/unrelated') + call mkdir(optdir2 . '/pluginB', 'p') + call mkdir(optdir2 . '/pluginC', 'p') + call writefile([], optdir2 . '/unrelated') + + let li = [] + call feedkeys(":packadd \<Tab>')\<C-B>call add(li, '\<CR>", 't') + call feedkeys(":packadd " . repeat("\<Tab>", 2) . "')\<C-B>call add(li, '\<CR>", 't') + call feedkeys(":packadd " . repeat("\<Tab>", 3) . "')\<C-B>call add(li, '\<CR>", 't') + call feedkeys(":packadd " . repeat("\<Tab>", 4) . "')\<C-B>call add(li, '\<CR>", 'tx') + call assert_equal("packadd pluginA", li[0]) + call assert_equal("packadd pluginB", li[1]) + call assert_equal("packadd pluginC", li[2]) + call assert_equal("packadd ", li[3]) +endfunc + +func Test_packloadall() + " plugin foo with an autoload directory + let fooplugindir = &packpath . '/pack/mine/start/foo/plugin' + call mkdir(fooplugindir, 'p') + call writefile(['let g:plugin_foo_number = 1234', + \ 'let g:plugin_foo_auto = bbb#value', + \ 'let g:plugin_extra_auto = extra#value'], fooplugindir . '/bar.vim') + let fooautodir = &packpath . '/pack/mine/start/foo/autoload' + call mkdir(fooautodir, 'p') + call writefile(['let bar#value = 77'], fooautodir . '/bar.vim') + + " plugin aaa with an autoload directory + let aaaplugindir = &packpath . '/pack/mine/start/aaa/plugin' + call mkdir(aaaplugindir, 'p') + call writefile(['let g:plugin_aaa_number = 333', + \ 'let g:plugin_aaa_auto = bar#value'], aaaplugindir . '/bbb.vim') + let aaaautodir = &packpath . '/pack/mine/start/aaa/autoload' + call mkdir(aaaautodir, 'p') + call writefile(['let bbb#value = 55'], aaaautodir . '/bbb.vim') + + " plugin extra with only an autoload directory + let extraautodir = &packpath . '/pack/mine/start/extra/autoload' + call mkdir(extraautodir, 'p') + call writefile(['let extra#value = 99'], extraautodir . '/extra.vim') + + packloadall + call assert_equal(1234, g:plugin_foo_number) + call assert_equal(55, g:plugin_foo_auto) + call assert_equal(99, g:plugin_extra_auto) + call assert_equal(333, g:plugin_aaa_number) + call assert_equal(77, g:plugin_aaa_auto) + + " only works once + call writefile(['let g:plugin_bar_number = 4321'], fooplugindir . '/bar2.vim') + packloadall + call assert_false(exists('g:plugin_bar_number')) + + " works when ! used + packloadall! + call assert_equal(4321, g:plugin_bar_number) +endfunc + +func Test_helptags() + let docdir1 = &packpath . '/pack/mine/start/foo/doc' + let docdir2 = &packpath . '/pack/mine/start/bar/doc' + call mkdir(docdir1, 'p') + call mkdir(docdir2, 'p') + call writefile(['look here: *look-here*'], docdir1 . '/bar.txt') + call writefile(['look away: *look-away*'], docdir2 . '/foo.txt') + exe 'set rtp=' . &packpath . '/pack/mine/start/foo,' . &packpath . '/pack/mine/start/bar' + + helptags ALL + + let tags1 = readfile(docdir1 . '/tags') + call assert_match('look-here', tags1[0]) + let tags2 = readfile(docdir2 . '/tags') + call assert_match('look-away', tags2[0]) + + call assert_fails('helptags abcxyz', 'E150:') +endfunc + +func Test_colorscheme() + let colordirrun = &packpath . '/runtime/colors' + let colordirstart = &packpath . '/pack/mine/start/foo/colors' + let colordiropt = &packpath . '/pack/mine/opt/bar/colors' + call mkdir(colordirrun, 'p') + call mkdir(colordirstart, 'p') + call mkdir(colordiropt, 'p') + call writefile(['let g:found_one = 1'], colordirrun . '/one.vim') + call writefile(['let g:found_two = 1'], colordirstart . '/two.vim') + call writefile(['let g:found_three = 1'], colordiropt . '/three.vim') + exe 'set rtp=' . &packpath . '/runtime' + + colorscheme one + call assert_equal(1, g:found_one) + colorscheme two + call assert_equal(1, g:found_two) + colorscheme three + call assert_equal(1, g:found_three) +endfunc + +func Test_colorscheme_completion() + let colordirrun = &packpath . '/runtime/colors' + let colordirstart = &packpath . '/pack/mine/start/foo/colors' + let colordiropt = &packpath . '/pack/mine/opt/bar/colors' + call mkdir(colordirrun, 'p') + call mkdir(colordirstart, 'p') + call mkdir(colordiropt, 'p') + call writefile(['let g:found_one = 1'], colordirrun . '/one.vim') + call writefile(['let g:found_two = 1'], colordirstart . '/two.vim') + call writefile(['let g:found_three = 1'], colordiropt . '/three.vim') + exe 'set rtp=' . &packpath . '/runtime' + + let li=[] + call feedkeys(":colorscheme " . repeat("\<Tab>", 1) . "')\<C-B>call add(li, '\<CR>", 't') + call feedkeys(":colorscheme " . repeat("\<Tab>", 2) . "')\<C-B>call add(li, '\<CR>", 't') + call feedkeys(":colorscheme " . repeat("\<Tab>", 3) . "')\<C-B>call add(li, '\<CR>", 't') + call feedkeys(":colorscheme " . repeat("\<Tab>", 4) . "')\<C-B>call add(li, '\<CR>", 'tx') + call assert_equal("colorscheme one", li[0]) + call assert_equal("colorscheme three", li[1]) + call assert_equal("colorscheme two", li[2]) + call assert_equal("colorscheme ", li[3]) +endfunc + +func Test_runtime() + let rundir = &packpath . '/runtime/extra' + let startdir = &packpath . '/pack/mine/start/foo/extra' + let optdir = &packpath . '/pack/mine/opt/bar/extra' + call mkdir(rundir, 'p') + call mkdir(startdir, 'p') + call mkdir(optdir, 'p') + call writefile(['let g:sequence .= "run"'], rundir . '/bar.vim') + call writefile(['let g:sequence .= "start"'], startdir . '/bar.vim') + call writefile(['let g:sequence .= "foostart"'], startdir . '/foo.vim') + call writefile(['let g:sequence .= "opt"'], optdir . '/bar.vim') + call writefile(['let g:sequence .= "xxxopt"'], optdir . '/xxx.vim') + exe 'set rtp=' . &packpath . '/runtime' + + let g:sequence = '' + runtime extra/bar.vim + call assert_equal('run', g:sequence) + let g:sequence = '' + runtime NoSuchFile extra/bar.vim + call assert_equal('run', g:sequence) + + let g:sequence = '' + runtime START extra/bar.vim + call assert_equal('start', g:sequence) + let g:sequence = '' + runtime START NoSuchFile extra/bar.vim extra/foo.vim + call assert_equal('start', g:sequence) + let g:sequence = '' + runtime START NoSuchFile extra/foo.vim extra/bar.vim + call assert_equal('foostart', g:sequence) + let g:sequence = '' + runtime! START NoSuchFile extra/bar.vim extra/foo.vim + call assert_equal('startfoostart', g:sequence) + + let g:sequence = '' + runtime OPT extra/bar.vim + call assert_equal('opt', g:sequence) + let g:sequence = '' + runtime OPT NoSuchFile extra/bar.vim extra/xxx.vim + call assert_equal('opt', g:sequence) + let g:sequence = '' + runtime OPT NoSuchFile extra/xxx.vim extra/bar.vim + call assert_equal('xxxopt', g:sequence) + let g:sequence = '' + runtime! OPT NoSuchFile extra/bar.vim extra/xxx.vim + call assert_equal('optxxxopt', g:sequence) + + let g:sequence = '' + runtime PACK extra/bar.vim + call assert_equal('start', g:sequence) + let g:sequence = '' + runtime! PACK extra/bar.vim + call assert_equal('startopt', g:sequence) + let g:sequence = '' + runtime PACK extra/xxx.vim + call assert_equal('xxxopt', g:sequence) + let g:sequence = '' + runtime PACK extra/xxx.vim extra/foo.vim extra/bar.vim + call assert_equal('foostart', g:sequence) + let g:sequence = '' + runtime! PACK extra/bar.vim extra/xxx.vim extra/foo.vim + call assert_equal('startfoostartoptxxxopt', g:sequence) + + let g:sequence = '' + runtime ALL extra/bar.vim + call assert_equal('run', g:sequence) + let g:sequence = '' + runtime ALL extra/foo.vim + call assert_equal('foostart', g:sequence) + let g:sequence = '' + runtime! ALL extra/xxx.vim + call assert_equal('xxxopt', g:sequence) + let g:sequence = '' + runtime! ALL extra/bar.vim + call assert_equal('runstartopt', g:sequence) + let g:sequence = '' + runtime ALL extra/xxx.vim extra/foo.vim extra/bar.vim + call assert_equal('run', g:sequence) + let g:sequence = '' + runtime! ALL extra/bar.vim extra/xxx.vim extra/foo.vim + call assert_equal('runstartfoostartoptxxxopt', g:sequence) +endfunc + +func Test_runtime_completion() + let rundir = &packpath . '/runtime/Aextra' + let startdir = &packpath . '/pack/mine/start/foo/Aextra' + let optdir = &packpath . '/pack/mine/opt/bar/Aextra' + call mkdir(rundir . '/Arunbaz', 'p') + call mkdir(startdir . '/Astartbaz', 'p') + call mkdir(optdir . '/Aoptbaz', 'p') + call writefile([], rundir . '/../Arunfoo.vim') + call writefile([], rundir . '/Arunbar.vim') + call writefile([], rundir . '/Aunrelated') + call writefile([], rundir . '/../Aunrelated') + call writefile([], startdir . '/../Astartfoo.vim') + call writefile([], startdir . '/Astartbar.vim') + call writefile([], startdir . '/Aunrelated') + call writefile([], startdir . '/../Aunrelated') + call writefile([], optdir . '/../Aoptfoo.vim') + call writefile([], optdir . '/Aoptbar.vim') + call writefile([], optdir . '/Aunrelated') + call writefile([], optdir . '/../Aunrelated') + exe 'set rtp=' . &packpath . '/runtime' + + func Check_runtime_completion(arg, arg_prev, res) + call feedkeys(':runtime ' .. a:arg .. "\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"runtime ' .. a:arg_prev .. join(a:res), @:) + call assert_equal(a:res, getcompletion(a:arg, 'runtime')) + endfunc + + call Check_runtime_completion('', '', + \ ['Aextra/', 'Arunfoo.vim', 'START', 'OPT', 'PACK', 'ALL']) + call Check_runtime_completion('S', '', + \ ['START']) + call Check_runtime_completion('O', '', + \ ['OPT']) + call Check_runtime_completion('P', '', + \ ['PACK']) + call Check_runtime_completion('A', '', + \ ['Aextra/', 'Arunfoo.vim', 'ALL']) + call Check_runtime_completion('Other.vim ', 'Other.vim ', + \ ['Aextra/', 'Arunfoo.vim']) + call Check_runtime_completion('Aextra/', '', + \ ['Aextra/Arunbar.vim', 'Aextra/Arunbaz/']) + call Check_runtime_completion('Other.vim Aextra/', 'Other.vim ', + \ ['Aextra/Arunbar.vim', 'Aextra/Arunbaz/']) + + call Check_runtime_completion('START ', 'START ', + \ ['Aextra/', 'Astartfoo.vim']) + call Check_runtime_completion('START Other.vim ', 'START Other.vim ', + \ ['Aextra/', 'Astartfoo.vim']) + call Check_runtime_completion('START A', 'START ', + \ ['Aextra/', 'Astartfoo.vim']) + call Check_runtime_completion('START Other.vim A', 'START Other.vim ', + \ ['Aextra/', 'Astartfoo.vim']) + call Check_runtime_completion('START Aextra/', 'START ', + \ ['Aextra/Astartbar.vim', 'Aextra/Astartbaz/']) + call Check_runtime_completion('START Other.vim Aextra/', 'START Other.vim ', + \ ['Aextra/Astartbar.vim', 'Aextra/Astartbaz/']) + + call Check_runtime_completion('OPT ', 'OPT ', + \ ['Aextra/', 'Aoptfoo.vim']) + call Check_runtime_completion('OPT Other.vim ', 'OPT Other.vim ', + \ ['Aextra/', 'Aoptfoo.vim']) + call Check_runtime_completion('OPT A', 'OPT ', + \ ['Aextra/', 'Aoptfoo.vim']) + call Check_runtime_completion('OPT Other.vim A', 'OPT Other.vim ', + \ ['Aextra/', 'Aoptfoo.vim']) + call Check_runtime_completion('OPT Aextra/', 'OPT ', + \ ['Aextra/Aoptbar.vim', 'Aextra/Aoptbaz/']) + call Check_runtime_completion('OPT Other.vim Aextra/', 'OPT Other.vim ', + \ ['Aextra/Aoptbar.vim', 'Aextra/Aoptbaz/']) + + call Check_runtime_completion('PACK ', 'PACK ', + \ ['Aextra/', 'Aoptfoo.vim', 'Astartfoo.vim']) + call Check_runtime_completion('PACK Other.vim ', 'PACK Other.vim ', + \ ['Aextra/', 'Aoptfoo.vim', 'Astartfoo.vim']) + call Check_runtime_completion('PACK A', 'PACK ', + \ ['Aextra/', 'Aoptfoo.vim', 'Astartfoo.vim']) + call Check_runtime_completion('PACK Other.vim A', 'PACK Other.vim ', + \ ['Aextra/', 'Aoptfoo.vim', 'Astartfoo.vim']) + call Check_runtime_completion('PACK Aextra/', 'PACK ', + \ ['Aextra/Aoptbar.vim', 'Aextra/Aoptbaz/', + \ 'Aextra/Astartbar.vim', 'Aextra/Astartbaz/']) + call Check_runtime_completion('PACK Other.vim Aextra/', 'PACK Other.vim ', + \ ['Aextra/Aoptbar.vim', 'Aextra/Aoptbaz/', + \ 'Aextra/Astartbar.vim', 'Aextra/Astartbaz/']) + + call Check_runtime_completion('ALL ', 'ALL ', + \ ['Aextra/', 'Aoptfoo.vim', 'Arunfoo.vim', 'Astartfoo.vim']) + call Check_runtime_completion('ALL Other.vim ', 'ALL Other.vim ', + \ ['Aextra/', 'Aoptfoo.vim', 'Arunfoo.vim', 'Astartfoo.vim']) + call Check_runtime_completion('ALL A', 'ALL ', + \ ['Aextra/', 'Aoptfoo.vim', 'Arunfoo.vim', 'Astartfoo.vim']) + call Check_runtime_completion('ALL Other.vim A', 'ALL Other.vim ', + \ ['Aextra/', 'Aoptfoo.vim', 'Arunfoo.vim', 'Astartfoo.vim']) + call Check_runtime_completion('ALL Aextra/', 'ALL ', + \ ['Aextra/Aoptbar.vim', 'Aextra/Aoptbaz/', + \ 'Aextra/Arunbar.vim', 'Aextra/Arunbaz/', + \ 'Aextra/Astartbar.vim', 'Aextra/Astartbaz/']) + call Check_runtime_completion('ALL Other.vim Aextra/', 'ALL Other.vim ', + \ ['Aextra/Aoptbar.vim', 'Aextra/Aoptbaz/', + \ 'Aextra/Arunbar.vim', 'Aextra/Arunbaz/', + \ 'Aextra/Astartbar.vim', 'Aextra/Astartbaz/']) + + delfunc Check_runtime_completion +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_partial.vim b/test/old/testdir/test_partial.vim new file mode 100644 index 0000000000..8b62e4a0e5 --- /dev/null +++ b/test/old/testdir/test_partial.vim @@ -0,0 +1,384 @@ +" Test binding arguments to a Funcref. + +func MyFunc(arg1, arg2, arg3) + return a:arg1 . '/' . a:arg2 . '/' . a:arg3 +endfunc + +func MySort(up, one, two) + if a:one == a:two + return 0 + endif + if a:up + return a:one > a:two ? 1 : -1 + endif + return a:one < a:two ? 1 : -1 +endfunc + +func MyMap(sub, index, val) + return a:val - a:sub +endfunc + +func MyFilter(threshold, index, val) + return a:val > a:threshold +endfunc + +func Test_partial_args() + let Cb = function('MyFunc', ["foo", "bar"]) + + call Cb("zzz") + call assert_equal("foo/bar/xxx", Cb("xxx")) + call assert_equal("foo/bar/yyy", call(Cb, ["yyy"])) + let Cb2 = function(Cb) + call assert_equal("foo/bar/zzz", Cb2("zzz")) + let Cb3 = function(Cb, ["www"]) + call assert_equal("foo/bar/www", Cb3()) + + let Cb = function('MyFunc', []) + call assert_equal("a/b/c", Cb("a", "b", "c")) + let Cb2 = function(Cb, []) + call assert_equal("a/b/d", Cb2("a", "b", "d")) + let Cb3 = function(Cb, ["a", "b"]) + call assert_equal("a/b/e", Cb3("e")) + + let Sort = function('MySort', [1]) + call assert_equal([1, 2, 3], sort([3, 1, 2], Sort)) + let Sort = function('MySort', [0]) + call assert_equal([3, 2, 1], sort([3, 1, 2], Sort)) + + let Map = function('MyMap', [2]) + call assert_equal([-1, 0, 1], map([1, 2, 3], Map)) + let Map = function('MyMap', [3]) + call assert_equal([-2, -1, 0], map([1, 2, 3], Map)) + + let Filter = function('MyFilter', [1]) + call assert_equal([2, 3], filter([1, 2, 3], Filter)) + let Filter = function('MyFilter', [2]) + call assert_equal([3], filter([1, 2, 3], Filter)) +endfunc + +func MyDictFunc(arg1, arg2) dict + return self.name . '/' . a:arg1 . '/' . a:arg2 +endfunc + +func Test_partial_dict() + let dict = {'name': 'hello'} + let Cb = function('MyDictFunc', ["foo", "bar"], dict) + call test_garbagecollect_now() + call assert_equal("hello/foo/bar", Cb()) + call assert_fails('Cb("xxx")', 'E492:') + + let Cb = function('MyDictFunc', ["foo"], dict) + call assert_equal("hello/foo/xxx", Cb("xxx")) + call assert_fails('Cb()', 'E492:') + + let Cb = function('MyDictFunc', [], dict) + call assert_equal("hello/ttt/xxx", Cb("ttt", "xxx")) + call assert_fails('Cb("yyy")', 'E492:') + + let Cb = function('MyDictFunc', dict) + call assert_equal("hello/xxx/yyy", Cb("xxx", "yyy")) + call assert_fails('Cb("fff")', 'E492:') + + let Cb = function('MyDictFunc', dict) + call assert_equal({"foo": "hello/foo/1", "bar": "hello/bar/2"}, map({"foo": 1, "bar": 2}, Cb)) + + let dict = {"tr": function('tr', ['hello', 'h', 'H'])} + call assert_equal("Hello", dict.tr()) + + call assert_fails("let F=function('setloclist', 10)", "E923:") + call assert_fails("let F=function('setloclist', [], [])", "E1206:") +endfunc + +func Test_partial_implicit() + let dict = {'name': 'foo'} + func dict.MyFunc(arg) dict + return self.name . '/' . a:arg + endfunc + + call assert_equal('foo/bar', dict.MyFunc('bar')) + + call assert_fails('let func = dict.MyFunc', 'E704:') + let Func = dict.MyFunc + call assert_equal('foo/aaa', Func('aaa')) + + let Func = function(dict.MyFunc, ['bbb']) + call assert_equal('foo/bbb', Func()) +endfunc + +fun InnerCall(funcref) + return a:funcref +endfu + +fun OuterCall() + let opt = { 'func' : function('max') } + call InnerCall(opt.func) +endfu + +func Test_function_in_dict() + call OuterCall() +endfunc + +func s:cache_clear() dict + return self.name +endfunc + +func Test_script_function_in_dict() + let s:obj = {'name': 'foo'} + let s:obj2 = {'name': 'bar'} + + let s:obj['clear'] = function('s:cache_clear') + + call assert_equal('foo', s:obj.clear()) + let F = s:obj.clear + call assert_equal('foo', F()) + call assert_equal('foo', call(s:obj.clear, [], s:obj)) + call assert_equal('bar', call(s:obj.clear, [], s:obj2)) + + let s:obj2['clear'] = function('s:cache_clear') + call assert_equal('bar', s:obj2.clear()) + let B = s:obj2.clear + call assert_equal('bar', B()) +endfunc + +func s:cache_arg(arg) dict + let s:result = self.name . '/' . a:arg + return s:result +endfunc + +func Test_script_function_in_dict_arg() + let s:obj = {'name': 'foo'} + let s:obj['clear'] = function('s:cache_arg') + + call assert_equal('foo/bar', s:obj.clear('bar')) + let F = s:obj.clear + let s:result = '' + call assert_equal('foo/bar', F('bar')) + call assert_equal('foo/bar', s:result) + + let s:obj['clear'] = function('s:cache_arg', ['bar']) + call assert_equal('foo/bar', s:obj.clear()) + let s:result = '' + call s:obj.clear() + call assert_equal('foo/bar', s:result) + + let F = s:obj.clear + call assert_equal('foo/bar', F()) + let s:result = '' + call F() + call assert_equal('foo/bar', s:result) + + call assert_equal('foo/bar', call(s:obj.clear, [], s:obj)) +endfunc + +func Test_partial_exists() + let F = function('MyFunc') + call assert_true(exists('*F')) + let lF = [F] + call assert_true(exists('*lF[0]')) + + let F = function('MyFunc', ['arg']) + call assert_true(exists('*F')) + let lF = [F] + call assert_true(exists('*lF[0]')) +endfunc + +func Test_partial_string() + let F = function('MyFunc') + call assert_equal("function('MyFunc')", string(F)) + let F = function('MyFunc', ['foo']) + call assert_equal("function('MyFunc', ['foo'])", string(F)) + let F = function('MyFunc', ['foo', 'bar']) + call assert_equal("function('MyFunc', ['foo', 'bar'])", string(F)) + let d = {'one': 1} + let F = function('MyFunc', d) + call assert_equal("function('MyFunc', {'one': 1})", string(F)) + let F = function('MyFunc', ['foo'], d) + call assert_equal("function('MyFunc', ['foo'], {'one': 1})", string(F)) + " Nvim doesn't have null functions + " call assert_equal("function('')", string(test_null_function())) + " Nvim doesn't have null partials + " call assert_equal("function('')", string(test_null_partial())) +endfunc + +func Test_func_unref() + let obj = {} + function! obj.func() abort + endfunction + let funcnumber = matchstr(string(obj.func), '^function(''\zs.\{-}\ze''') + call assert_true(exists('*{' . funcnumber . '}')) + unlet obj + call assert_false(exists('*{' . funcnumber . '}')) +endfunc + +func Test_redefine_dict_func() + let d = {} + function d.test4() + endfunction + let d.test4 = d.test4 + try + function! d.test4(name) + endfunction + catch + call assert_true(v:errmsg, v:exception) + endtry +endfunc + +" This caused double free on exit if EXITFREE is defined. +func Test_cyclic_list_arg() + let l = [] + let Pt = function('string', [l]) + call add(l, Pt) + unlet l + unlet Pt +endfunc + +" This caused double free on exit if EXITFREE is defined. +func Test_cyclic_dict_arg() + let d = {} + let Pt = function('string', [d]) + let d.Pt = Pt + unlet d + unlet Pt +endfunc + +func Ignored(job1, job2, status) +endfunc + +func Test_cycle_partial_job() + if has('job') + let job = job_start('echo') + call job_setoptions(job, {'exit_cb': function('Ignored', [job])}) + unlet job + endif +endfunc + +func Test_ref_job_partial_dict() + if has('job') + let g:ref_job = job_start('echo') + let d = {'a': 'b'} + call job_setoptions(g:ref_job, {'exit_cb': function('string', [], d)}) + call test_garbagecollect_now() + endif +endfunc + +func Test_auto_partial_rebind() + let dict1 = {'name': 'dict1'} + func! dict1.f1() + return self.name + endfunc + let dict1.f2 = function(dict1.f1, dict1) + + call assert_equal('dict1', dict1.f1()) + call assert_equal('dict1', dict1['f1']()) + call assert_equal('dict1', dict1.f2()) + call assert_equal('dict1', dict1['f2']()) + + let dict2 = {'name': 'dict2'} + let dict2.f1 = dict1.f1 + let dict2.f2 = dict1.f2 + + call assert_equal('dict2', dict2.f1()) + call assert_equal('dict2', dict2['f1']()) + call assert_equal('dict1', dict2.f2()) + call assert_equal('dict1', dict2['f2']()) +endfunc + +func Test_get_partial_items() + let dict = {'name': 'hello'} + let args = ["foo", "bar"] + let Func = function('MyDictFunc') + let Cb = function('MyDictFunc', args, dict) + + call assert_equal(Func, get(Cb, 'func')) + call assert_equal('MyDictFunc', get(Cb, 'name')) + call assert_equal(args, get(Cb, 'args')) + call assert_equal(dict, get(Cb, 'dict')) + call assert_fails('call get(Cb, "xxx")', 'E475:') + + call assert_equal(Func, get(Func, 'func')) + call assert_equal('MyDictFunc', get(Func, 'name')) + call assert_equal([], get(Func, 'args')) + call assert_true(empty( get(Func, 'dict'))) + + let P = function('substitute', ['hello there', 'there']) + let dict = {'partial has': 'no dict'} + call assert_equal(dict, get(P, 'dict', dict)) + call assert_equal(0, get(l:P, 'dict')) +endfunc + +func Test_compare_partials() + let d1 = {} + let d2 = {} + + function d1.f1() dict + endfunction + + function d1.f2() dict + endfunction + + let F1 = get(d1, 'f1') + let F2 = get(d1, 'f2') + + let F1d1 = function(F1, d1) + let F2d1 = function(F2, d2) + let F1d1a1 = function(F1d1, [1]) + let F1d1a12 = function(F1d1, [1, 2]) + let F1a1 = function(F1, [1]) + let F1a2 = function(F1, [2]) + let F1d2 = function(F1, d2) + let d3 = {'f1': F1, 'f2': F2} + let F1d3 = function(F1, d3) + let F1ad1 = function(F1, [d1]) + let F1ad3 = function(F1, [d3]) + + call assert_match('^function(''\d\+'')$', string(F1)) " Not a partial + call assert_match('^function(''\d\+'')$', string(F2)) " Not a partial + call assert_match('^function(''\d\+'', {.*})$', string(F1d1)) " A partial + call assert_match('^function(''\d\+'', {.*})$', string(F2d1)) " A partial + call assert_match('^function(''\d\+'', \[.*\])$', string(F1a1)) " No dict + + " != + let X = F1 + call assert_false(F1 != X) " same function + let X = F1d1 + call assert_false(F1d1 != X) " same partial + let X = F1d1a1 + call assert_false(F1d1a1 != X) " same partial + let X = F1a1 + call assert_false(F1a1 != X) " same partial + + call assert_true(F1 != F2) " Different functions + call assert_true(F1 != F1d1) " Partial /= non-partial + call assert_true(F1d1a1 != F1d1a12) " Different number of arguments + call assert_true(F1a1 != F1d1a12) " One has no dict + call assert_true(F1a1 != F1a2) " Different arguments + call assert_true(F1d2 != F1d1) " Different dictionaries + call assert_false(F1d1 != F1d3) " Equal dictionaries, even though d1 isnot d3 + + " isnot, option 1 + call assert_true(F1 isnot# F2) " Different functions + call assert_true(F1 isnot# F1d1) " Partial /= non-partial + call assert_true(F1d1 isnot# F1d3) " d1 isnot d3, even though d1 == d3 + call assert_true(F1a1 isnot# F1d1a12) " One has no dict + call assert_true(F1a1 isnot# F1a2) " Different number of arguments + call assert_true(F1ad1 isnot# F1ad3) " In arguments d1 isnot d3 + + " isnot, option 2 + call assert_true(F1 isnot# F2) " Different functions + call assert_true(F1 isnot# F1d1) " Partial /= non-partial + call assert_true(d1.f1 isnot# d1.f1) " handle_subscript creates new partial each time + + " compare two null partials + " Nvim doesn't have null partials + " let N1 = test_null_partial() + let N1 = function('min') + let N2 = N1 + call assert_true(N1 is N2) + call assert_true(N1 == N2) + + " compare a partial and a null partial + call assert_false(N1 == F1) + call assert_false(F1 is N1) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_paste.vim b/test/old/testdir/test_paste.vim new file mode 100644 index 0000000000..9ed3adca9b --- /dev/null +++ b/test/old/testdir/test_paste.vim @@ -0,0 +1,60 @@ + +" Test for restoring option values when 'paste' is disabled +func Test_paste_opt_restore() + set autoindent expandtab ruler showmatch + if has('rightleft') + " set hkmap + set revins + endif + set smarttab softtabstop=3 textwidth=27 wrapmargin=12 + if has('vartabs') + set varsofttabstop=10,20 + endif + + " enabling 'paste' should reset the above options + set paste + call assert_false(&autoindent) + call assert_false(&expandtab) + if has('rightleft') + call assert_false(&revins) + " call assert_false(&hkmap) + endif + call assert_false(&ruler) + call assert_false(&showmatch) + call assert_false(&smarttab) + call assert_equal(0, &softtabstop) + call assert_equal(0, &textwidth) + call assert_equal(0, &wrapmargin) + if has('vartabs') + call assert_equal('', &varsofttabstop) + endif + + " disabling 'paste' should restore the option values + set nopaste + call assert_true(&autoindent) + call assert_true(&expandtab) + if has('rightleft') + call assert_true(&revins) + " call assert_true(&hkmap) + endif + call assert_true(&ruler) + call assert_true(&showmatch) + call assert_true(&smarttab) + call assert_equal(3, &softtabstop) + call assert_equal(27, &textwidth) + call assert_equal(12, &wrapmargin) + if has('vartabs') + call assert_equal('10,20', &varsofttabstop) + endif + + set autoindent& expandtab& ruler& showmatch& + if has('rightleft') + set revins& hkmap& + endif + set smarttab& softtabstop& textwidth& wrapmargin& + if has('vartabs') + set varsofttabstop& + endif +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_perl.vim b/test/old/testdir/test_perl.vim new file mode 100644 index 0000000000..ce2a566f62 --- /dev/null +++ b/test/old/testdir/test_perl.vim @@ -0,0 +1,320 @@ +" Tests for Perl interface + +source check.vim +CheckFeature perl +CheckNotMSWindows + +" FIXME: RunTest don't see any error when Perl abort... +perl $SIG{__WARN__} = sub { die "Unexpected warnings from perl: @_" }; + +func Test_change_buffer() + call setline(line('$'), ['1 line 1']) + perl VIM::DoCommand("normal /^1\n") + perl $curline = VIM::Eval("line('.')") + perl $curbuf->Set($curline, "1 changed line 1") + call assert_equal('1 changed line 1', getline('$')) +endfunc + +func Test_evaluate_list() + call setline(line('$'), ['2 line 2']) + perl VIM::DoCommand("normal /^2\n") + perl $curline = VIM::Eval("line('.')") + let l = ["abc", "def"] + perl << EOF + $l = VIM::Eval("l"); + $curbuf->Append($curline, $l); +EOF + normal j + .perldo s|\n|/|g + " call assert_equal('abc/def/', getline('$')) + call assert_equal('def', getline('$')) +endfunc + +funct Test_VIM_Blob() + call assert_equal('0z', perleval('VIM::Blob("")')) + call assert_equal('0z31326162', 'VIM::Blob("12ab")'->perleval()) + call assert_equal('0z00010203', perleval('VIM::Blob("\x00\x01\x02\x03")')) + call assert_equal('0z8081FEFF', perleval('VIM::Blob("\x80\x81\xfe\xff")')) +endfunc + +func Test_buffer_Delete() + new + call setline(1, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) + perl $curbuf->Delete(7) + perl $curbuf->Delete(2, 5) + perl $curbuf->Delete(10) + call assert_equal(['a', 'f', 'h'], getline(1, '$')) + bwipe! +endfunc + +func Test_buffer_Append() + new + perl $curbuf->Append(1, '1') + perl $curbuf->Append(2, '2', '3', '4') + perl @l = ('5' ..'7') + perl $curbuf->Append(0, @l) + call assert_equal(['5', '6', '7', '', '1', '2', '3', '4'], getline(1, '$')) + bwipe! +endfunc + +func Test_buffer_Set() + new + call setline(1, ['1', '2', '3', '4', '5']) + perl $curbuf->Set(2, 'a', 'b', 'c') + perl $curbuf->Set(4, 'A', 'B', 'C') + call assert_equal(['1', 'a', 'b', 'A', 'B'], getline(1, '$')) + bwipe! +endfunc + +func Test_buffer_Get() + new + call setline(1, ['1', '2', '3', '4']) + call assert_equal('2:3', perleval('join(":", $curbuf->Get(2, 3))')) + bwipe! +endfunc + +func Test_buffer_Count() + new + call setline(1, ['a', 'b', 'c']) + call assert_equal(3, perleval('$curbuf->Count()')) + bwipe! +endfunc + +func Test_buffer_Name() + new + call assert_equal('', perleval('$curbuf->Name()')) + bwipe! + new Xfoo + call assert_equal('Xfoo', perleval('$curbuf->Name()')) + bwipe! +endfunc + +func Test_buffer_Number() + call assert_equal(bufnr('%'), perleval('$curbuf->Number()')) +endfunc + +func Test_window_Cursor() + new + call setline(1, ['line1', 'line2']) + perl $curwin->Cursor(2, 3) + call assert_equal('2:3', perleval('join(":", $curwin->Cursor())')) + " Col is numbered from 0 in Perl, and from 1 in Vim script. + call assert_equal([0, 2, 4, 0], getpos('.')) + bwipe! +endfunc + +func Test_window_SetHeight() + new + perl $curwin->SetHeight(2) + call assert_equal(2, winheight(0)) + bwipe! +endfunc + +func Test_VIM_Windows() + new + " VIM::Windows() without argument in scalar and list context. + perl $winnr = VIM::Windows() + perl @winlist = VIM::Windows() + perl $curbuf->Append(0, $winnr, scalar(@winlist)) + call assert_equal(['2', '2', ''], getline(1, '$')) + + " VIM::Windows() with window number argument. + perl (VIM::Windows(VIM::Eval('winnr()')))[0]->Buffer()->Set(1, 'bar') + call assert_equal('bar', getline(1)) + bwipe! +endfunc + +func Test_VIM_Buffers() + new Xbar + " VIM::Buffers() without argument in scalar and list context. + perl $nbuf = VIM::Buffers() + perl @buflist = VIM::Buffers() + + " VIM::Buffers() with argument. + perl $curbuf = (VIM::Buffers('Xbar'))[0] + perl $curbuf->Append(0, $nbuf, scalar(@buflist)) + call assert_equal(['2', '2', ''], getline(1, '$')) + bwipe! +endfunc + +func <SID>catch_peval(expr) + try + call perleval(a:expr) + catch + return v:exception + endtry + call assert_report('no exception for `perleval("'.a:expr.'")`') + return '' +endfunc + +func Test_perleval() + call assert_false(perleval('undef')) + + " scalar + call assert_equal(0, perleval('0')) + call assert_equal(2, perleval('2')) + call assert_equal(-2, perleval('-2')) + if has('float') + call assert_equal(2.5, perleval('2.5')) + else + call assert_equal(2, perleval('2.5')) + end + + " sandbox call assert_equal(2, perleval('2')) + + call assert_equal('abc', perleval('"abc"')) + " call assert_equal("abc\ndef", perleval('"abc\0def"')) + + " ref + call assert_equal([], perleval('[]')) + call assert_equal(['word', 42, [42],{}], perleval('["word", 42, [42], {}]')) + + call assert_equal({}, perleval('{}')) + call assert_equal({'foo': 'bar'}, perleval('{foo => "bar"}')) + + perl our %h; our @a; + let a = perleval('[\(%h, %h, @a, @a)]') + " call assert_true((a[0] is a[1])) + call assert_equal(a[0], a[1]) + " call assert_true((a[2] is a[3])) + call assert_equal(a[2], a[3]) + perl undef %h; undef @a; + + " call assert_true(<SID>catch_peval('{"" , 0}') =~ 'Malformed key Dictionary') + " call assert_true(<SID>catch_peval('{"\0" , 0}') =~ 'Malformed key Dictionary') + " call assert_true(<SID>catch_peval('{"foo\0bar" , 0}') =~ 'Malformed key Dictionary') + + call assert_equal('*VIM', perleval('"*VIM"')) + " call assert_true(perleval('\\0') =~ 'SCALAR(0x\x\+)') +endfunc + +func Test_perldo() + sp __TEST__ + exe 'read ' g:testname + perldo s/perl/vieux_chameau/g + 1 + call assert_false(search('\Cperl')) + bw! + + " Check deleting lines does not trigger ml_get error. + new + call setline(1, ['one', 'two', 'three']) + perldo VIM::DoCommand("%d_") + bwipe! + + " Check switching to another buffer does not trigger ml_get error. + new + let wincount = winnr('$') + call setline(1, ['one', 'two', 'three']) + perldo VIM::DoCommand("new") + call assert_equal(wincount + 1, winnr('$')) + bwipe! + bwipe! +endfunc + +func Test_VIM_package() + perl VIM::DoCommand('let l:var = "foo"') + call assert_equal(l:var, 'foo') + + set noet + perl VIM::SetOption('et') + call assert_true(&et) +endfunc + +func Test_stdio() + throw 'skipped: TODO: ' + redir =>l:out + perl << trim EOF + VIM::Msg("&VIM::Msg"); + print "STDOUT"; + print STDERR "STDERR"; + EOF + redir END + call assert_equal(['&VIM::Msg', 'STDOUT', 'STDERR'], split(l:out, "\n")) +endfunc + +" Run first to get a clean namespace +func Test_000_SvREFCNT() + throw 'skipped: TODO: ' + for i in range(8) + exec 'new X'.i + endfor + new t + perl <<--perl +#line 5 "Test_000_SvREFCNT()" + my ($b, $w); + + my $num = 0; + for ( 0 .. 100 ) { + if ( ++$num >= 8 ) { $num = 0 } + VIM::DoCommand("buffer X$num"); + $b = $curbuf; + } + + VIM::DoCommand("buffer t"); + + $b = $curbuf for 0 .. 100; + $w = $curwin for 0 .. 100; + () = VIM::Buffers for 0 .. 100; + () = VIM::Windows for 0 .. 100; + + VIM::DoCommand('bw! t'); + if (exists &Internals::SvREFCNT) { + my $cb = Internals::SvREFCNT($$b); + my $cw = Internals::SvREFCNT($$w); + VIM::Eval("assert_equal(2, $cb, 'T1')"); + VIM::Eval("assert_equal(2, $cw, 'T2')"); + my $strongref; + foreach ( VIM::Buffers, VIM::Windows ) { + VIM::DoCommand("%bw!"); + my $c = Internals::SvREFCNT($_); + VIM::Eval("assert_equal(2, $c, 'T3')"); + $c = Internals::SvREFCNT($$_); + next if $c == 2 && !$strongref++; + VIM::Eval("assert_equal(1, $c, 'T4')"); + } + $cb = Internals::SvREFCNT($$curbuf); + $cw = Internals::SvREFCNT($$curwin); + VIM::Eval("assert_equal(3, $cb, 'T5')"); + VIM::Eval("assert_equal(3, $cw, 'T6')"); + } + VIM::Eval("assert_false($$b)"); + VIM::Eval("assert_false($$w)"); +--perl + %bw! +endfunc + +func Test_set_cursor() + " Check that setting the cursor position works. + new + call setline(1, ['first line', 'second line']) + normal gg + perldo $curwin->Cursor(1, 5) + call assert_equal([1, 6], [line('.'), col('.')]) + + " Check that movement after setting cursor position keeps current column. + normal j + call assert_equal([2, 6], [line('.'), col('.')]) +endfunc + +" Test for various heredoc syntax +func Test_perl_heredoc() + perl << END +VIM::DoCommand('let s = "A"') +END + perl << +VIM::DoCommand('let s ..= "B"') +. + perl << trim END + VIM::DoCommand('let s ..= "C"') + END + perl << trim + VIM::DoCommand('let s ..= "D"') + . + perl << trim eof + VIM::DoCommand('let s ..= "E"') + eof + call assert_equal('ABCDE', s) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_plus_arg_edit.vim b/test/old/testdir/test_plus_arg_edit.vim new file mode 100644 index 0000000000..c52044d064 --- /dev/null +++ b/test/old/testdir/test_plus_arg_edit.vim @@ -0,0 +1,47 @@ +" Tests for complicated + argument to :edit command +function Test_edit() + call writefile(["foo|bar"], "Xfile1") + call writefile(["foo/bar"], "Xfile2") + edit +1|s/|/PIPE/|w Xfile1| e Xfile2|1 | s/\//SLASH/|w + call assert_equal(["fooPIPEbar"], readfile("Xfile1")) + call assert_equal(["fooSLASHbar"], readfile("Xfile2")) + call delete('Xfile1') + call delete('Xfile2') +endfunction + +func Test_edit_bad() + " Test loading a utf8 file with bad utf8 sequences. + call writefile(["[\xff][\xc0][\xe2\x89\xf0][\xc2\xc2]"], "Xfile") + new + + " Without ++bad=..., the default behavior is like ++bad=? + e! ++enc=utf8 Xfile + call assert_equal('[?][?][???][??]', getline(1)) + + e! ++encoding=utf8 ++bad=_ Xfile + call assert_equal('[_][_][___][__]', getline(1)) + + e! ++enc=utf8 ++bad=drop Xfile + call assert_equal('[][][][]', getline(1)) + + e! ++enc=utf8 ++bad=keep Xfile + call assert_equal("[\xff][\xc0][\xe2\x89\xf0][\xc2\xc2]", getline(1)) + + call assert_fails('e! ++enc=utf8 ++bad=foo Xfile', 'E474:') + + bw! + call delete('Xfile') +endfunc + +" Test for ++bin and ++nobin arguments +func Test_binary_arg() + new + edit ++bin Xfile1 + call assert_equal(1, &binary) + edit ++nobin Xfile2 + call assert_equal(0, &binary) + call assert_fails('edit ++binabc Xfile3', 'E474:') + close! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_popup.vim b/test/old/testdir/test_popup.vim new file mode 100644 index 0000000000..fa0df77ab5 --- /dev/null +++ b/test/old/testdir/test_popup.vim @@ -0,0 +1,1331 @@ +" Test for completion menu + +source shared.vim +source screendump.vim +source check.vim + +let g:months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] +let g:setting = '' + +func ListMonths() + if g:setting != '' + exe ":set" g:setting + endif + let mth = copy(g:months) + let entered = strcharpart(getline('.'),0,col('.')) + if !empty(entered) + let mth = filter(mth, 'v:val=~"^".entered') + endif + call complete(1, mth) + return '' +endfunc + +func Test_popup_complete2() + " Although the popupmenu is not visible, this does not mean completion mode + " has ended. After pressing <f5> to complete the currently typed char, Vim + " still stays in the first state of the completion (:h ins-completion-menu), + " although the popupmenu wasn't shown <c-e> will remove the inserted + " completed text (:h complete_CTRL-E), while the following <c-e> will behave + " like expected (:h i_CTRL-E) + new + inoremap <f5> <c-r>=ListMonths()<cr> + call append(1, ["December2015"]) + :1 + call feedkeys("aD\<f5>\<C-E>\<C-E>\<C-E>\<C-E>\<enter>\<esc>", 'tx') + call assert_equal(["Dece", "", "December2015"], getline(1,3)) + %d + bw! +endfunc + +func Test_popup_complete() + new + inoremap <f5> <c-r>=ListMonths()<cr> + + " <C-E> - select original typed text before the completion started + call feedkeys("aJu\<f5>\<down>\<c-e>\<esc>", 'tx') + call assert_equal(["Ju"], getline(1,2)) + %d + + " <C-Y> - accept current match + call feedkeys("a\<f5>". repeat("\<down>",7). "\<c-y>\<esc>", 'tx') + call assert_equal(["August"], getline(1,2)) + %d + + " <BS> - Delete one character from the inserted text (state: 1) + " TODO: This should not end the completion, but it does. + " This should according to the documentation: + " January + " but instead, this does + " Januar + " (idea is, C-L inserts the match from the popup menu + " but if the menu is closed, it will insert the character <c-l> + call feedkeys("aJ\<f5>\<bs>\<c-l>\<esc>", 'tx') + call assert_equal(["Januar"], getline(1,2)) + %d + + " any-non special character: Stop completion without changing the match + " and insert the typed character + call feedkeys("a\<f5>20", 'tx') + call assert_equal(["January20"], getline(1,2)) + %d + + " any-non printable, non-white character: Add this character and + " reduce number of matches + call feedkeys("aJu\<f5>\<c-p>l\<c-y>", 'tx') + call assert_equal(["Jul"], getline(1,2)) + %d + + " any-non printable, non-white character: Add this character and + " reduce number of matches + call feedkeys("aJu\<f5>\<c-p>l\<c-n>\<c-y>", 'tx') + call assert_equal(["July"], getline(1,2)) + %d + + " any-non printable, non-white character: Add this character and + " reduce number of matches + call feedkeys("aJu\<f5>\<c-p>l\<c-e>", 'tx') + call assert_equal(["Jul"], getline(1,2)) + %d + + " <BS> - Delete one character from the inserted text (state: 2) + call feedkeys("a\<f5>\<c-n>\<bs>", 'tx') + call assert_equal(["Februar"], getline(1,2)) + %d + + " <c-l> - Insert one character from the current match + call feedkeys("aJ\<f5>".repeat("\<c-n>",3)."\<c-l>\<esc>", 'tx') + call assert_equal(["J"], getline(1,2)) + %d + + " <c-l> - Insert one character from the current match + call feedkeys("aJ\<f5>".repeat("\<c-n>",4)."\<c-l>\<esc>", 'tx') + call assert_equal(["January"], getline(1,2)) + %d + + " <c-y> - Accept current selected match + call feedkeys("aJ\<f5>\<c-y>\<esc>", 'tx') + call assert_equal(["January"], getline(1,2)) + %d + + " <c-e> - End completion, go back to what was there before selecting a match + call feedkeys("aJu\<f5>\<c-e>\<esc>", 'tx') + call assert_equal(["Ju"], getline(1,2)) + %d + + " <PageUp> - Select a match several entries back + call feedkeys("a\<f5>\<PageUp>\<c-y>\<esc>", 'tx') + call assert_equal([""], getline(1,2)) + %d + + " <PageUp><PageUp> - Select a match several entries back + call feedkeys("a\<f5>\<PageUp>\<PageUp>\<c-y>\<esc>", 'tx') + call assert_equal(["December"], getline(1,2)) + %d + + " <PageUp><PageUp><PageUp> - Select a match several entries back + call feedkeys("a\<f5>\<PageUp>\<PageUp>\<PageUp>\<c-y>\<esc>", 'tx') + call assert_equal(["February"], getline(1,2)) + %d + + " <PageDown> - Select a match several entries further + call feedkeys("a\<f5>\<PageDown>\<c-y>\<esc>", 'tx') + call assert_equal(["November"], getline(1,2)) + %d + + " <PageDown><PageDown> - Select a match several entries further + call feedkeys("a\<f5>\<PageDown>\<PageDown>\<c-y>\<esc>", 'tx') + call assert_equal(["December"], getline(1,2)) + %d + + " <PageDown><PageDown><PageDown> - Select a match several entries further + call feedkeys("a\<f5>\<PageDown>\<PageDown>\<PageDown>\<c-y>\<esc>", 'tx') + call assert_equal([""], getline(1,2)) + %d + + " <PageDown><PageDown><PageDown><PageDown> - Select a match several entries further + call feedkeys("a\<f5>".repeat("\<PageDown>",4)."\<c-y>\<esc>", 'tx') + call assert_equal(["October"], getline(1,2)) + %d + + " <Up> - Select a match don't insert yet + call feedkeys("a\<f5>\<Up>\<c-y>\<esc>", 'tx') + call assert_equal([""], getline(1,2)) + %d + + " <Up><Up> - Select a match don't insert yet + call feedkeys("a\<f5>\<Up>\<Up>\<c-y>\<esc>", 'tx') + call assert_equal(["December"], getline(1,2)) + %d + + " <Up><Up><Up> - Select a match don't insert yet + call feedkeys("a\<f5>\<Up>\<Up>\<Up>\<c-y>\<esc>", 'tx') + call assert_equal(["November"], getline(1,2)) + %d + + " <Tab> - Stop completion and insert the match + call feedkeys("a\<f5>\<Tab>\<c-y>\<esc>", 'tx') + call assert_equal(["January "], getline(1,2)) + %d + + " <Space> - Stop completion and insert the match + call feedkeys("a\<f5>".repeat("\<c-p>",5)." \<esc>", 'tx') + call assert_equal(["September "], getline(1,2)) + %d + + " <Enter> - Use the text and insert line break (state: 1) + call feedkeys("a\<f5>\<enter>\<esc>", 'tx') + call assert_equal(["January", ''], getline(1,2)) + %d + + " <Enter> - Insert the current selected text (state: 2) + call feedkeys("a\<f5>".repeat("\<Up>",5)."\<enter>\<esc>", 'tx') + call assert_equal(["September"], getline(1,2)) + %d + + " Insert match immediately, if there is only one match + " <c-y> selects a character from the line above + call append(0, ["December2015"]) + call feedkeys("aD\<f5>\<C-Y>\<C-Y>\<C-Y>\<C-Y>\<enter>\<esc>", 'tx') + call assert_equal(["December2015", "December2015", ""], getline(1,3)) + %d + + " use menuone for 'completeopt' + " Since for the first <c-y> the menu is still shown, will only select + " three letters from the line above + set completeopt&vim + set completeopt+=menuone + call append(0, ["December2015"]) + call feedkeys("aD\<f5>\<C-Y>\<C-Y>\<C-Y>\<C-Y>\<enter>\<esc>", 'tx') + call assert_equal(["December2015", "December201", ""], getline(1,3)) + %d + + " use longest for 'completeopt' + set completeopt&vim + call feedkeys("aM\<f5>\<C-N>\<C-P>\<c-e>\<enter>\<esc>", 'tx') + set completeopt+=longest + call feedkeys("aM\<f5>\<C-N>\<C-P>\<c-e>\<enter>\<esc>", 'tx') + call assert_equal(["M", "Ma", ""], getline(1,3)) + %d + + " use noselect/noinsert for 'completeopt' + set completeopt&vim + call feedkeys("aM\<f5>\<enter>\<esc>", 'tx') + set completeopt+=noselect + call feedkeys("aM\<f5>\<enter>\<esc>", 'tx') + set completeopt-=noselect completeopt+=noinsert + call feedkeys("aM\<f5>\<enter>\<esc>", 'tx') + call assert_equal(["March", "M", "March"], getline(1,4)) + %d +endfunc + + +func Test_popup_completion_insertmode() + new + inoremap <F5> <C-R>=ListMonths()<CR> + + call feedkeys("a\<f5>\<down>\<enter>\<esc>", 'tx') + call assert_equal('February', getline(1)) + %d + " Set noinsertmode + let g:setting = 'noinsertmode' + call feedkeys("a\<f5>\<down>\<enter>\<esc>", 'tx') + call assert_equal('February', getline(1)) + call assert_false(pumvisible()) + %d + " Go through all matches, until none is selected + let g:setting = '' + call feedkeys("a\<f5>". repeat("\<c-n>",12)."\<enter>\<esc>", 'tx') + call assert_equal('', getline(1)) + %d + " select previous entry + call feedkeys("a\<f5>\<c-p>\<enter>\<esc>", 'tx') + call assert_equal('', getline(1)) + %d + " select last entry + call feedkeys("a\<f5>\<c-p>\<c-p>\<enter>\<esc>", 'tx') + call assert_equal('December', getline(1)) + + iunmap <F5> +endfunc + +func Test_noinsert_complete() + func! s:complTest1() abort + eval ['source', 'soundfold']->complete(1) + return '' + endfunc + + func! s:complTest2() abort + call complete(1, ['source', 'soundfold']) + return '' + endfunc + + new + set completeopt+=noinsert + inoremap <F5> <C-R>=s:complTest1()<CR> + call feedkeys("i\<F5>soun\<CR>\<CR>\<ESC>.", 'tx') + call assert_equal('soundfold', getline(1)) + call assert_equal('soundfold', getline(2)) + bwipe! + + new + inoremap <F5> <C-R>=s:complTest2()<CR> + call feedkeys("i\<F5>\<CR>\<ESC>", 'tx') + call assert_equal('source', getline(1)) + bwipe! + + set completeopt-=noinsert + iunmap <F5> +endfunc + +func Test_complete_no_filter() + func! s:complTest1() abort + call complete(1, [{'word': 'foobar'}]) + return '' + endfunc + func! s:complTest2() abort + call complete(1, [{'word': 'foobar', 'equal': 1}]) + return '' + endfunc + + let completeopt = &completeopt + + " without equal=1 + new + set completeopt=menuone,noinsert,menu + inoremap <F5> <C-R>=s:complTest1()<CR> + call feedkeys("i\<F5>z\<CR>\<CR>\<ESC>.", 'tx') + call assert_equal('z', getline(1)) + bwipe! + + " with equal=1 + new + set completeopt=menuone,noinsert,menu + inoremap <F5> <C-R>=s:complTest2()<CR> + call feedkeys("i\<F5>z\<CR>\<CR>\<ESC>.", 'tx') + call assert_equal('foobar', getline(1)) + bwipe! + + let &completeopt = completeopt + iunmap <F5> +endfunc + +func Test_compl_vim_cmds_after_register_expr() + func! s:test_func() + return 'autocmd ' + endfunc + augroup AAAAA_Group + au! + augroup END + + new + call feedkeys("i\<c-r>=s:test_func()\<CR>\<C-x>\<C-v>\<Esc>", 'tx') + call assert_equal('autocmd AAAAA_Group', getline(1)) + autocmd! AAAAA_Group + augroup! AAAAA_Group + bwipe! +endfunc + +func Test_compl_ignore_mappings() + call setline(1, ['foo', 'bar', 'baz', 'foobar']) + inoremap <C-P> (C-P) + inoremap <C-N> (C-N) + normal! G + call feedkeys("o\<C-X>\<C-N>\<C-N>\<C-N>\<C-P>\<C-N>\<C-Y>", 'tx') + call assert_equal('baz', getline('.')) + " Also test with unsimplified keys + call feedkeys("o\<C-X>\<*C-N>\<*C-N>\<*C-N>\<*C-P>\<*C-N>\<C-Y>", 'tx') + call assert_equal('baz', getline('.')) + iunmap <C-P> + iunmap <C-N> + bwipe! +endfunc + +func DummyCompleteOne(findstart, base) + if a:findstart + return 0 + else + wincmd n + return ['onedef', 'oneDEF'] + endif +endfunc + +" Test that nothing happens if the 'completefunc' tries to open +" a new window (fails to open window, continues) +func Test_completefunc_opens_new_window_one() + new + let winid = win_getid() + setlocal completefunc=DummyCompleteOne + call setline(1, 'one') + /^one + call assert_fails('call feedkeys("A\<C-X>\<C-U>\<C-N>\<Esc>", "x")', 'E565:') + call assert_equal(winid, win_getid()) + call assert_equal('onedef', getline(1)) + q! +endfunc + +" Test that nothing happens if the 'completefunc' opens +" a new window (no completion, no crash) +func DummyCompleteTwo(findstart, base) + if a:findstart + wincmd n + return 0 + else + return ['twodef', 'twoDEF'] + endif +endfunc + +" Test that nothing happens if the 'completefunc' opens +" a new window (no completion, no crash) +func Test_completefunc_opens_new_window_two() + new + let winid = win_getid() + setlocal completefunc=DummyCompleteTwo + call setline(1, 'two') + /^two + call assert_fails('call feedkeys("A\<C-X>\<C-U>\<C-N>\<Esc>", "x")', 'E565:') + call assert_equal(winid, win_getid()) + call assert_equal('twodef', getline(1)) + q! +endfunc + +func DummyCompleteThree(findstart, base) + if a:findstart + return 0 + else + return ['threedef', 'threeDEF'] + endif +endfunc + +:"Test that 'completefunc' works when it's OK. +func Test_completefunc_works() + new + let winid = win_getid() + setlocal completefunc=DummyCompleteThree + call setline(1, 'three') + /^three + call feedkeys("A\<C-X>\<C-U>\<C-N>\<Esc>", "x") + call assert_equal(winid, win_getid()) + call assert_equal('threeDEF', getline(1)) + q! +endfunc + +func DummyCompleteFour(findstart, base) + if a:findstart + return 0 + else + call complete_add('four1') + eval 'four2'->complete_add() + call complete_check() + call complete_add('four3') + call complete_add('four4') + call complete_check() + call complete_add('four5') + call complete_add('four6') + return [] + endif +endfunc + +" Test that 'omnifunc' works when it's OK. +func Test_omnifunc_with_check() + new + setlocal omnifunc=DummyCompleteFour + call setline(1, 'four') + /^four + call feedkeys("A\<C-X>\<C-O>\<C-N>\<Esc>", "x") + call assert_equal('four2', getline(1)) + + call setline(1, 'four') + /^four + call feedkeys("A\<C-X>\<C-O>\<C-N>\<C-N>\<Esc>", "x") + call assert_equal('four3', getline(1)) + + call setline(1, 'four') + /^four + call feedkeys("A\<C-X>\<C-O>\<C-N>\<C-N>\<C-N>\<C-N>\<Esc>", "x") + call assert_equal('four5', getline(1)) + + q! +endfunc + +func UndoComplete() + call complete(1, ['January', 'February', 'March', + \ 'April', 'May', 'June', 'July', 'August', 'September', + \ 'October', 'November', 'December']) + return '' +endfunc + +" Test that no undo item is created when no completion is inserted +func Test_complete_no_undo() + set completeopt=menu,preview,noinsert,noselect + inoremap <Right> <C-R>=UndoComplete()<CR> + new + call feedkeys("ixxx\<CR>\<CR>yyy\<Esc>k", 'xt') + call feedkeys("iaaa\<Esc>0", 'xt') + call assert_equal('aaa', getline(2)) + call feedkeys("i\<Right>\<Esc>", 'xt') + call assert_equal('aaa', getline(2)) + call feedkeys("u", 'xt') + call assert_equal('', getline(2)) + + call feedkeys("ibbb\<Esc>0", 'xt') + call assert_equal('bbb', getline(2)) + call feedkeys("A\<Right>\<Down>\<CR>\<Esc>", 'xt') + call assert_equal('January', getline(2)) + call feedkeys("u", 'xt') + call assert_equal('bbb', getline(2)) + + call feedkeys("A\<Right>\<C-N>\<Esc>", 'xt') + call assert_equal('January', getline(2)) + call feedkeys("u", 'xt') + call assert_equal('bbb', getline(2)) + + iunmap <Right> + set completeopt& + q! +endfunc + +func DummyCompleteFive(findstart, base) + if a:findstart + return 0 + else + return [ + \ { 'word': 'January', 'info': "info1-1\n1-2\n1-3" }, + \ { 'word': 'February', 'info': "info2-1\n2-2\n2-3" }, + \ { 'word': 'March', 'info': "info3-1\n3-2\n3-3" }, + \ { 'word': 'April', 'info': "info4-1\n4-2\n4-3" }, + \ { 'word': 'May', 'info': "info5-1\n5-2\n5-3" }, + \ ] + endif +endfunc + +" Test that 'completefunc' on Scratch buffer with preview window works when +" it's OK. +func Test_completefunc_with_scratch_buffer() + CheckFeature quickfix + + new +setlocal\ buftype=nofile\ bufhidden=wipe\ noswapfile + set completeopt+=preview + setlocal completefunc=DummyCompleteFive + call feedkeys("A\<C-X>\<C-U>\<C-N>\<C-N>\<C-N>\<Esc>", "x") + call assert_equal(['April'], getline(1, '$')) + pclose + q! + set completeopt& +endfunc + +" <C-E> - select original typed text before the completion started without +" auto-wrap text. +func Test_completion_ctrl_e_without_autowrap() + new + let tw_save = &tw + set tw=78 + let li = [ + \ '" zzz', + \ '" zzzyyyyyyyyyyyyyyyyyyy'] + call setline(1, li) + 0 + call feedkeys("A\<C-X>\<C-N>\<C-E>\<Esc>", "tx") + call assert_equal(li, getline(1, '$')) + + let &tw = tw_save + q! +endfunc + +func DummyCompleteSix() + call complete(1, ['Hello', 'World']) + return '' +endfunction + +" complete() correctly clears the list of autocomplete candidates +" See #1411 +func Test_completion_clear_candidate_list() + new + %d + " select first entry from the completion popup + call feedkeys("a xxx\<C-N>\<C-R>=DummyCompleteSix()\<CR>", "tx") + call assert_equal('Hello', getline(1)) + %d + " select second entry from the completion popup + call feedkeys("a xxx\<C-N>\<C-R>=DummyCompleteSix()\<CR>\<C-N>", "tx") + call assert_equal('World', getline(1)) + %d + " select original text + call feedkeys("a xxx\<C-N>\<C-R>=DummyCompleteSix()\<CR>\<C-N>\<C-N>", "tx") + call assert_equal(' xxx', getline(1)) + %d + " back at first entry from completion list + call feedkeys("a xxx\<C-N>\<C-R>=DummyCompleteSix()\<CR>\<C-N>\<C-N>\<C-N>", "tx") + call assert_equal('Hello', getline(1)) + + bw! +endfunc + +func Test_completion_respect_bs_option() + new + let li = ["aaa", "aaa12345", "aaaabcdef", "aaaABC"] + + set bs=indent,eol + call setline(1, li) + 1 + call feedkeys("A\<C-X>\<C-N>\<C-P>\<BS>\<BS>\<BS>\<Esc>", "tx") + call assert_equal('aaa', getline(1)) + + %d + set bs=indent,eol,start + call setline(1, li) + 1 + call feedkeys("A\<C-X>\<C-N>\<C-P>\<BS>\<BS>\<BS>\<Esc>", "tx") + call assert_equal('', getline(1)) + + bw! +endfunc + +func CompleteUndo() abort + call complete(1, g:months) + return '' +endfunc + +func Test_completion_can_undo() + inoremap <Right> <c-r>=CompleteUndo()<cr> + set completeopt+=noinsert,noselect + + new + call feedkeys("a\<Right>a\<Esc>", 'xt') + call assert_equal('a', getline(1)) + undo + call assert_equal('', getline(1)) + + bwipe! + set completeopt& + iunmap <Right> +endfunc + +func Test_completion_comment_formatting() + new + setl formatoptions=tcqro + call feedkeys("o/*\<cr>\<cr>/\<esc>", 'tx') + call assert_equal(['', '/*', ' *', ' */'], getline(1,4)) + %d + call feedkeys("o/*\<cr>foobar\<cr>/\<esc>", 'tx') + call assert_equal(['', '/*', ' * foobar', ' */'], getline(1,4)) + %d + try + call feedkeys("o/*\<cr>\<cr>\<c-x>\<c-u>/\<esc>", 'tx') + call assert_report('completefunc not set, should have failed') + catch + call assert_exception('E764:') + endtry + call assert_equal(['', '/*', ' *', ' */'], getline(1,4)) + bwipe! +endfunc + +func MessCompleteMonths() + for m in split("Jan Feb Mar Apr May Jun Jul Aug Sep") + call complete_add(m) + if complete_check() + break + endif + endfor + return [] +endfunc + +func MessCompleteMore() + call complete(1, split("Oct Nov Dec")) + return [] +endfunc + +func MessComplete(findstart, base) + if a:findstart + let line = getline('.') + let start = col('.') - 1 + while start > 0 && line[start - 1] =~ '\a' + let start -= 1 + endwhile + return start + else + call MessCompleteMonths() + call MessCompleteMore() + return [] + endif +endfunc + +func Test_complete_func_mess() + " Calling complete() after complete_add() in 'completefunc' is wrong, but it + " should not crash. + set completefunc=MessComplete + new + call setline(1, 'Ju') + call assert_fails('call feedkeys("A\<c-x>\<c-u>/\<esc>", "tx")', 'E565:') + call assert_equal('Jan/', getline(1)) + bwipe! + set completefunc= +endfunc + +func Test_complete_CTRLN_startofbuffer() + new + call setline(1, [ 'organize(cupboard, 3, 2);', + \ 'prioritize(bureau, 8, 7);', + \ 'realize(bannister, 4, 4);', + \ 'moralize(railing, 3,9);']) + let expected=['cupboard.organize(3, 2);', + \ 'bureau.prioritize(8, 7);', + \ 'bannister.realize(4, 4);', + \ 'railing.moralize(3,9);'] + call feedkeys("qai\<c-n>\<c-n>.\<esc>3wdW\<cr>q3@a", 'tx') + call assert_equal(expected, getline(1,'$')) + bwipe! +endfunc + +func Test_popup_and_window_resize() + CheckFeature terminal + CheckFeature quickfix + CheckNotGui + let g:test_is_flaky = 1 + + let h = winheight(0) + if h < 15 + return + endif + let rows = h / 3 + let buf = term_start([GetVimProg(), '--clean', '-c', 'set noswapfile'], {'term_rows': rows}) + call term_sendkeys(buf, (h / 3 - 1) . "o\<esc>") + " Wait for the nested Vim to exit insert mode, where it will show the ruler. + " Need to trigger a redraw. + call WaitFor({-> execute("redraw") == "" && term_getline(buf, rows) =~ '\<' . rows . ',.*Bot'}) + + call term_sendkeys(buf, "Gi\<c-x>") + call term_sendkeys(buf, "\<c-v>") + call TermWait(buf, 50) + " popup first entry "!" must be at the top + call WaitForAssert({-> assert_match('^!\s*$', term_getline(buf, 1))}) + exe 'resize +' . (h - 1) + call TermWait(buf, 50) + redraw! + " popup shifted down, first line is now empty + call WaitForAssert({-> assert_equal('', term_getline(buf, 1))}) + sleep 100m + " popup is below cursor line and shows first match "!" + call WaitForAssert({-> assert_match('^!\s*$', term_getline(buf, term_getcursor(buf)[0] + 1))}) + " cursor line also shows ! + call assert_match('^!\s*$', term_getline(buf, term_getcursor(buf)[0])) + bwipe! +endfunc + +func Test_popup_and_preview_autocommand() + CheckFeature python + CheckFeature quickfix + if winheight(0) < 15 + throw 'Skipped: window height insufficient' + endif + + " This used to crash Vim + new + augroup MyBufAdd + au! + au BufAdd * nested tab sball + augroup END + set omnifunc=pythoncomplete#Complete + call setline(1, 'import os') + " make the line long + call setline(2, ' os.') + $ + call feedkeys("A\<C-X>\<C-O>\<C-N>\<C-N>\<C-N>\<enter>\<esc>", 'tx') + call assert_equal("import os", getline(1)) + call assert_match(' os.\(EX_IOERR\|O_CREAT\)$', getline(2)) + call assert_equal(1, winnr('$')) + " previewwindow option is not set + call assert_equal(0, &previewwindow) + norm! gt + call assert_equal(0, &previewwindow) + norm! gT + call assert_equal(10, tabpagenr('$')) + tabonly + pclose + augroup MyBufAdd + au! + augroup END + augroup! MyBufAdd + bw! +endfunc + +func Test_popup_and_previewwindow_dump() + CheckScreendump + CheckFeature quickfix + + let lines =<< trim END + set previewheight=9 + silent! pedit + call setline(1, map(repeat(["ab"], 10), "v:val .. v:key")) + exec "norm! G\<C-E>\<C-E>" + END + call writefile(lines, 'Xscript') + let buf = RunVimInTerminal('-S Xscript', {}) + + " wait for the script to finish + call TermWait(buf) + + " Test that popup and previewwindow do not overlap. + call term_sendkeys(buf, "o") + call TermWait(buf, 50) + call term_sendkeys(buf, "\<C-X>\<C-N>") + call VerifyScreenDump(buf, 'Test_popup_and_previewwindow_01', {}) + + call term_sendkeys(buf, "\<Esc>u") + call StopVimInTerminal(buf) + call delete('Xscript') +endfunc + +func Test_balloon_split() + CheckFunction balloon_split + + call assert_equal([ + \ 'tempname: 0x555555e380a0 "/home/mool/.viminfz.tmp"', + \ ], balloon_split( + \ 'tempname: 0x555555e380a0 "/home/mool/.viminfz.tmp"')) + call assert_equal([ + \ 'one two three four one two three four one two thre', + \ 'e four', + \ ], balloon_split( + \ 'one two three four one two three four one two three four')) + + eval 'struct = {one = 1, two = 2, three = 3}' + \ ->balloon_split() + \ ->assert_equal([ + \ 'struct = {', + \ ' one = 1,', + \ ' two = 2,', + \ ' three = 3}', + \ ]) + + call assert_equal([ + \ 'struct = {', + \ ' one = 1,', + \ ' nested = {', + \ ' n1 = "yes",', + \ ' n2 = "no"}', + \ ' two = 2}', + \ ], balloon_split( + \ 'struct = {one = 1, nested = {n1 = "yes", n2 = "no"} two = 2}')) + call assert_equal([ + \ 'struct = 0x234 {', + \ ' long = 2343 "\\"some long string that will be wr', + \ 'apped in two\\"",', + \ ' next = 123}', + \ ], balloon_split( + \ 'struct = 0x234 {long = 2343 "\\"some long string that will be wrapped in two\\"", next = 123}')) + call assert_equal([ + \ 'Some comment', + \ '', + \ 'typedef this that;', + \ ], balloon_split( + \ "Some comment\n\ntypedef this that;")) +endfunc + +func Test_popup_position() + CheckScreendump + + let lines =<< trim END + 123456789_123456789_123456789_a + 123456789_123456789_123456789_b + 123 + END + call writefile(lines, 'Xtest') + let buf = RunVimInTerminal('Xtest', {}) + call term_sendkeys(buf, ":vsplit\<CR>") + + " default pumwidth in left window: overlap in right window + call term_sendkeys(buf, "GA\<C-N>") + call VerifyScreenDump(buf, 'Test_popup_position_01', {'rows': 8}) + call term_sendkeys(buf, "\<Esc>u") + + " default pumwidth: fill until right of window + call term_sendkeys(buf, "\<C-W>l") + call term_sendkeys(buf, "GA\<C-N>") + call VerifyScreenDump(buf, 'Test_popup_position_02', {'rows': 8}) + + " larger pumwidth: used as minimum width + call term_sendkeys(buf, "\<Esc>u") + call term_sendkeys(buf, ":set pumwidth=30\<CR>") + call term_sendkeys(buf, "GA\<C-N>") + call VerifyScreenDump(buf, 'Test_popup_position_03', {'rows': 8}) + + " completed text wider than the window and 'pumwidth' smaller than available + " space + call term_sendkeys(buf, "\<Esc>u") + call term_sendkeys(buf, ":set pumwidth=20\<CR>") + call term_sendkeys(buf, "ggI123456789_\<Esc>") + call term_sendkeys(buf, "jI123456789_\<Esc>") + call term_sendkeys(buf, "GA\<C-N>") + call VerifyScreenDump(buf, 'Test_popup_position_04', {'rows': 10}) + + call term_sendkeys(buf, "\<Esc>u") + call StopVimInTerminal(buf) + call delete('Xtest') +endfunc + +func Test_popup_command() + CheckFeature menu + + menu Test.Foo Foo + call assert_fails('popup Test.Foo', 'E336:') + call assert_fails('popup Test.Foo.X', 'E327:') + call assert_fails('popup Foo', 'E337:') + unmenu Test.Foo +endfunc + +func Test_popup_command_dump() + CheckFeature menu + CheckScreendump + + let script =<< trim END + func StartTimer() + call timer_start(100, {-> ChangeMenu()}) + endfunc + func ChangeMenu() + aunmenu PopUp.&Paste + nnoremenu 1.40 PopUp.&Paste :echomsg "pasted"<CR> + echomsg 'changed' + endfunc + END + call writefile(script, 'XtimerScript', 'D') + + let lines =<< trim END + one two three four five + and one two Xthree four five + one more two three four five + END + call writefile(lines, 'Xtest', 'D') + let buf = RunVimInTerminal('-S XtimerScript Xtest', {}) + call term_sendkeys(buf, ":source $VIMRUNTIME/menu.vim\<CR>") + call term_sendkeys(buf, "/X\<CR>:popup PopUp\<CR>") + call VerifyScreenDump(buf, 'Test_popup_command_01', {}) + + " go to the Paste entry in the menu + call term_sendkeys(buf, "jj") + call VerifyScreenDump(buf, 'Test_popup_command_02', {}) + + " Select a word + call term_sendkeys(buf, "j\<CR>") + call VerifyScreenDump(buf, 'Test_popup_command_03', {}) + + call term_sendkeys(buf, "\<Esc>") + + " Set a timer to change a menu entry while it's displayed. The text should + " not change but the command does. Making the screendump also verifies that + " "changed" shows up, which means the timer triggered. + call term_sendkeys(buf, "/X\<CR>:call StartTimer() | popup PopUp\<CR>") + call VerifyScreenDump(buf, 'Test_popup_command_04', {}) + + " Select the Paste entry, executes the changed menu item. + call term_sendkeys(buf, "jj\<CR>") + call VerifyScreenDump(buf, 'Test_popup_command_05', {}) + + call term_sendkeys(buf, "\<Esc>") + + " Add a window toolbar to the window and check the :popup menu position. + call term_sendkeys(buf, ":nnoremenu WinBar.TEST :\<CR>") + call term_sendkeys(buf, "/X\<CR>:popup PopUp\<CR>") + call VerifyScreenDump(buf, 'Test_popup_command_06', {}) + + call term_sendkeys(buf, "\<Esc>") + + call StopVimInTerminal(buf) +endfunc + +func Test_popup_complete_backwards() + new + call setline(1, ['Post', 'Port', 'Po']) + let expected=['Post', 'Port', 'Port'] + call cursor(3,2) + call feedkeys("A\<C-X>". repeat("\<C-P>", 3). "rt\<cr>", 'tx') + call assert_equal(expected, getline(1,'$')) + bwipe! +endfunc + +func Test_popup_complete_backwards_ctrl_p() + new + call setline(1, ['Post', 'Port', 'Po']) + let expected=['Post', 'Port', 'Port'] + call cursor(3,2) + call feedkeys("A\<C-P>\<C-N>rt\<cr>", 'tx') + call assert_equal(expected, getline(1,'$')) + bwipe! +endfunc + +func Test_complete_o_tab() + CheckFunction test_override + let s:o_char_pressed = 0 + + fun! s:act_on_text_changed() + if s:o_char_pressed + let s:o_char_pressed = 0 + call feedkeys("\<c-x>\<c-n>", 'i') + endif + endfunc + + set completeopt=menu,noselect + new + imap <expr> <buffer> <tab> pumvisible() ? "\<c-p>" : "X" + autocmd! InsertCharPre <buffer> let s:o_char_pressed = (v:char ==# 'o') + autocmd! TextChangedI <buffer> call <sid>act_on_text_changed() + call setline(1, ['hoard', 'hoax', 'hoarse', '']) + let l:expected = ['hoard', 'hoax', 'hoarse', 'hoax', 'hoax'] + call cursor(4,1) + call test_override("char_avail", 1) + call feedkeys("Ahoa\<tab>\<tab>\<c-y>\<esc>", 'tx') + call feedkeys("oho\<tab>\<tab>\<c-y>\<esc>", 'tx') + call assert_equal(l:expected, getline(1,'$')) + + call test_override("char_avail", 0) + bwipe! + set completeopt& + delfunc s:act_on_text_changed +endfunc + +func Test_menu_only_exists_in_terminal() + CheckCommand tlmenu + CheckNotGui + + tlnoremenu &Edit.&Paste<Tab>"+gP <C-W>"+ + aunmenu * + try + popup Edit + call assert_false(1, 'command should have failed') + catch + call assert_exception('E328:') + endtry +endfunc + +" This used to crash before patch 8.1.1424 +func Test_popup_delete_when_shown() + CheckFeature menu + CheckNotGui + + func Func() + popup Foo + return "\<Ignore>" + endfunc + + nmenu Foo.Bar : + nnoremap <expr> <F2> Func() + call feedkeys("\<F2>\<F2>\<Esc>", 'xt') + + delfunc Func + nunmenu Foo.Bar + nunmap <F2> +endfunc + +func Test_popup_complete_info_01() + new + inoremap <buffer><F5> <C-R>=complete_info().mode<CR> + func s:complTestEval() abort + call complete(1, ['aa', 'ab']) + return '' + endfunc + inoremap <buffer><F6> <C-R>=s:complTestEval()<CR> + call writefile([ + \ 'dummy dummy.txt 1', + \], 'Xdummy.txt') + setlocal tags=Xdummy.txt + setlocal dictionary=Xdummy.txt + setlocal thesaurus=Xdummy.txt + setlocal omnifunc=syntaxcomplete#Complete + setlocal completefunc=syntaxcomplete#Complete + setlocal spell + for [keys, mode_name] in [ + \ ["", ''], + \ ["\<C-X>", 'ctrl_x'], + \ ["\<C-X>\<C-N>", 'keyword'], + \ ["\<C-X>\<C-P>", 'keyword'], + \ ["\<C-X>\<C-E>", 'scroll'], + \ ["\<C-X>\<C-Y>", 'scroll'], + \ ["\<C-X>\<C-E>\<C-E>\<C-Y>", 'scroll'], + \ ["\<C-X>\<C-Y>\<C-E>\<C-Y>", 'scroll'], + \ ["\<C-X>\<C-L>", 'whole_line'], + \ ["\<C-X>\<C-F>", 'files'], + \ ["\<C-X>\<C-]>", 'tags'], + \ ["\<C-X>\<C-D>", 'path_defines'], + \ ["\<C-X>\<C-I>", 'path_patterns'], + \ ["\<C-X>\<C-K>", 'dictionary'], + \ ["\<C-X>\<C-T>", 'thesaurus'], + \ ["\<C-X>\<C-V>", 'cmdline'], + \ ["\<C-X>\<C-U>", 'function'], + \ ["\<C-X>\<C-O>", 'omni'], + \ ["\<C-X>s", 'spell'], + \ ["\<F6>", 'eval'], + \] + call feedkeys("i" . keys . "\<F5>\<Esc>", 'tx') + call assert_equal(mode_name, getline('.')) + %d + endfor + call delete('Xdummy.txt') + bwipe! +endfunc + +func UserDefinedComplete(findstart, base) + if a:findstart + return 0 + else + return [ + \ { 'word': 'Jan', 'menu': 'January' }, + \ { 'word': 'Feb', 'menu': 'February' }, + \ { 'word': 'Mar', 'menu': 'March' }, + \ { 'word': 'Apr', 'menu': 'April' }, + \ { 'word': 'May', 'menu': 'May' }, + \ ] + endif +endfunc + +func GetCompleteInfo() + if empty(g:compl_what) + let g:compl_info = complete_info() + else + let g:compl_info = g:compl_what->complete_info() + endif + return '' +endfunc + +func Test_popup_complete_info_02() + new + inoremap <buffer><F5> <C-R>=GetCompleteInfo()<CR> + setlocal completefunc=UserDefinedComplete + + let d = { + \ 'mode': 'function', + \ 'pum_visible': 1, + \ 'items': [ + \ {'word': 'Jan', 'menu': 'January', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}, + \ {'word': 'Feb', 'menu': 'February', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}, + \ {'word': 'Mar', 'menu': 'March', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}, + \ {'word': 'Apr', 'menu': 'April', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''}, + \ {'word': 'May', 'menu': 'May', 'user_data': '', 'info': '', 'kind': '', 'abbr': ''} + \ ], + \ 'selected': 0, + \ } + + let g:compl_what = [] + call feedkeys("i\<C-X>\<C-U>\<F5>", 'tx') + call assert_equal(d, g:compl_info) + + let g:compl_what = ['mode', 'pum_visible', 'selected'] + call remove(d, 'items') + call feedkeys("i\<C-X>\<C-U>\<F5>", 'tx') + call assert_equal(d, g:compl_info) + + let g:compl_what = ['mode'] + call remove(d, 'selected') + call remove(d, 'pum_visible') + call feedkeys("i\<C-X>\<C-U>\<F5>", 'tx') + call assert_equal(d, g:compl_info) + bwipe! +endfunc + +func Test_popup_complete_info_no_pum() + new + call assert_false( pumvisible() ) + let no_pum_info = complete_info() + let d = { + \ 'mode': '', + \ 'pum_visible': 0, + \ 'items': [], + \ 'selected': -1, + \ } + call assert_equal( d, complete_info() ) + bwipe! +endfunc + +func Test_CompleteChanged() + new + call setline(1, ['foo', 'bar', 'foobar', '']) + set complete=. completeopt=noinsert,noselect,menuone + function! OnPumChange() + let g:event = copy(v:event) + let g:item = get(v:event, 'completed_item', {}) + let g:word = get(g:item, 'word', v:null) + endfunction + augroup AAAAA_Group + au! + autocmd CompleteChanged * :call OnPumChange() + augroup END + call cursor(4, 1) + + call feedkeys("Sf\<C-N>", 'tx') + call assert_equal({'completed_item': {}, 'width': 15.0, + \ 'height': 2.0, 'size': 2, + \ 'col': 0.0, 'row': 4.0, 'scrollbar': v:false}, g:event) + call feedkeys("a\<C-N>\<C-N>\<C-E>", 'tx') + call assert_equal('foo', g:word) + call feedkeys("a\<C-N>\<C-N>\<C-N>\<C-E>", 'tx') + call assert_equal('foobar', g:word) + call feedkeys("a\<C-N>\<C-N>\<C-N>\<C-N>\<C-E>", 'tx') + call assert_equal(v:null, g:word) + call feedkeys("a\<C-N>\<C-N>\<C-N>\<C-N>\<C-P>", 'tx') + call assert_equal('foobar', g:word) + + autocmd! AAAAA_Group + set complete& completeopt& + delfunc! OnPumChange + bw! +endfunc + +func GetPumPosition() + call assert_true( pumvisible() ) + let g:pum_pos = pum_getpos() + return '' +endfunc + +func Test_pum_getpos() + new + inoremap <buffer><F5> <C-R>=GetPumPosition()<CR> + setlocal completefunc=UserDefinedComplete + + let d = { + \ 'height': 5.0, + \ 'width': 15.0, + \ 'row': 1.0, + \ 'col': 0.0, + \ 'size': 5, + \ 'scrollbar': v:false, + \ } + call feedkeys("i\<C-X>\<C-U>\<F5>", 'tx') + call assert_equal(d, g:pum_pos) + + call assert_false( pumvisible() ) + call assert_equal( {}, pum_getpos() ) + bw! + unlet g:pum_pos +endfunc + +" Test for the popup menu with the 'rightleft' option set +func Test_pum_rightleft() + CheckFeature rightleft + CheckScreendump + + let lines =<< trim END + abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz + vim + victory + END + call writefile(lines, 'Xtest1') + let buf = RunVimInTerminal('--cmd "set rightleft" Xtest1', {}) + call term_wait(buf) + call term_sendkeys(buf, "Go\<C-P>") + call VerifyScreenDump(buf, 'Test_pum_rightleft_01', {'rows': 8}) + call term_sendkeys(buf, "\<C-P>\<C-Y>") + call term_wait(buf) + redraw! + call assert_match('\s*miv', Screenline(5)) + + " Test for expanding tabs to spaces in the popup menu + let lines =<< trim END + one two + one three + four + END + call writefile(lines, 'Xtest2') + call term_sendkeys(buf, "\<Esc>:e! Xtest2\<CR>") + call term_wait(buf) + call term_sendkeys(buf, "Goone\<C-X>\<C-L>") + call term_wait(buf) + redraw! + call VerifyScreenDump(buf, 'Test_pum_rightleft_02', {'rows': 7}) + call term_sendkeys(buf, "\<C-Y>") + call term_wait(buf) + redraw! + call assert_match('\s*eerht eno', Screenline(4)) + + call StopVimInTerminal(buf) + call delete('Xtest1') + call delete('Xtest2') +endfunc + +" Test for a popup menu with a scrollbar +func Test_pum_scrollbar() + CheckScreendump + let lines =<< trim END + one + two + three + END + call writefile(lines, 'Xtest1') + let buf = RunVimInTerminal('--cmd "set pumheight=2" Xtest1', {}) + call term_wait(buf) + call term_sendkeys(buf, "Go\<C-P>\<C-P>\<C-P>") + call VerifyScreenDump(buf, 'Test_pum_scrollbar_01', {'rows': 7}) + call term_sendkeys(buf, "\<C-E>\<Esc>dd") + call term_wait(buf) + + if has('rightleft') + call term_sendkeys(buf, ":set rightleft\<CR>") + call term_wait(buf) + call term_sendkeys(buf, "Go\<C-P>\<C-P>\<C-P>") + call VerifyScreenDump(buf, 'Test_pum_scrollbar_02', {'rows': 7}) + endif + + call StopVimInTerminal(buf) + call delete('Xtest1') +endfunc + +" Test default highlight groups for popup menu +func Test_pum_highlights_default() + CheckScreendump + let lines =<< trim END + func CompleteFunc( findstart, base ) + if a:findstart + return 0 + endif + return { + \ 'words': [ + \ { 'word': 'aword1', 'menu': 'extra text 1', 'kind': 'W', }, + \ { 'word': 'aword2', 'menu': 'extra text 2', 'kind': 'W', }, + \ { 'word': 'aword3', 'menu': 'extra text 3', 'kind': 'W', }, + \]} + endfunc + set completeopt=menu + set completefunc=CompleteFunc + END + call writefile(lines, 'Xscript', 'D') + let buf = RunVimInTerminal('-S Xscript', {}) + call TermWait(buf) + call term_sendkeys(buf, "iaw\<C-X>\<C-u>") + call TermWait(buf, 50) + call VerifyScreenDump(buf, 'Test_pum_highlights_01', {}) + call term_sendkeys(buf, "\<C-E>\<Esc>u") + call TermWait(buf) + call StopVimInTerminal(buf) +endfunc + +" Test custom highlight groups for popup menu +func Test_pum_highlights_custom() + CheckScreendump + let lines =<< trim END + func CompleteFunc( findstart, base ) + if a:findstart + return 0 + endif + return { + \ 'words': [ + \ { 'word': 'aword1', 'menu': 'extra text 1', 'kind': 'W', }, + \ { 'word': 'aword2', 'menu': 'extra text 2', 'kind': 'W', }, + \ { 'word': 'aword3', 'menu': 'extra text 3', 'kind': 'W', }, + \]} + endfunc + set completeopt=menu + set completefunc=CompleteFunc + hi PmenuKind ctermfg=1 ctermbg=225 + hi PmenuKindSel ctermfg=1 ctermbg=7 + hi PmenuExtra ctermfg=243 ctermbg=225 + hi PmenuExtraSel ctermfg=0 ctermbg=7 + END + call writefile(lines, 'Xscript', 'D') + let buf = RunVimInTerminal('-S Xscript', {}) + call TermWait(buf) + call term_sendkeys(buf, "iaw\<C-X>\<C-u>") + call TermWait(buf, 50) + call VerifyScreenDump(buf, 'Test_pum_highlights_02', {}) + call term_sendkeys(buf, "\<C-E>\<Esc>u") + call TermWait(buf) + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_preview.vim b/test/old/testdir/test_preview.vim new file mode 100644 index 0000000000..b7b908e761 --- /dev/null +++ b/test/old/testdir/test_preview.vim @@ -0,0 +1,64 @@ +" Tests for the preview window + +source check.vim +CheckFeature quickfix + +func Test_Psearch() + " this used to cause ml_get errors + help + let wincount = winnr('$') + 0f + ps. + call assert_equal(wincount + 1, winnr('$')) + pclose + call assert_equal(wincount, winnr('$')) + bwipe +endfunc + +func Test_window_preview() + CheckFeature quickfix + + " Open a preview window + pedit Xa + call assert_equal(2, winnr('$')) + call assert_equal(0, &previewwindow) + + " Go to the preview window + wincmd P + call assert_equal(1, &previewwindow) + call assert_equal('preview', win_gettype()) + + " Close preview window + wincmd z + call assert_equal(1, winnr('$')) + call assert_equal(0, &previewwindow) + + call assert_fails('wincmd P', 'E441:') +endfunc + +func Test_window_preview_from_help() + CheckFeature quickfix + + filetype on + call writefile(['/* some C code */'], 'Xpreview.c') + help + pedit Xpreview.c + wincmd P + call assert_equal(1, &previewwindow) + call assert_equal('c', &filetype) + wincmd z + + filetype off + close + call delete('Xpreview.c') +endfunc + +func Test_multiple_preview_windows() + new + set previewwindow + new + call assert_fails('set previewwindow', 'E590:') + %bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_profile.vim b/test/old/testdir/test_profile.vim new file mode 100644 index 0000000000..8b4ca74342 --- /dev/null +++ b/test/old/testdir/test_profile.vim @@ -0,0 +1,597 @@ +" Test Vim profiler + +source check.vim +CheckFeature profile + +source shared.vim +source screendump.vim + +func Test_profile_func() + let lines =<< trim [CODE] + profile start Xprofile_func.log + profile func Foo* + func! Foo1() + endfunc + func! Foo2() + let l:count = 100 + while l:count > 0 + let l:count = l:count - 1 + endwhile + sleep 1m + endfunc + func! Foo3() + endfunc + func! Bar() + endfunc + call Foo1() + call Foo1() + profile pause + call Foo1() + profile continue + call Foo2() + call Foo3() + call Bar() + if !v:profiling + delfunc Foo2 + endif + delfunc Foo3 + [CODE] + + call writefile(lines, 'Xprofile_func.vim') + call system(GetVimCommand() + \ . ' -es --clean' + \ . ' --cmd "so Xprofile_func.vim"' + \ . ' --cmd "qall!"') + call assert_equal(0, v:shell_error) + + sleep 50m + let lines = readfile('Xprofile_func.log') + + " - Foo1() is called 3 times but should be reported as called twice + " since one call is in between "profile pause" .. "profile continue". + " - Foo2() should come before Foo1() since Foo1() does much more work. + " - Foo3() is not reported because function is deleted. + " - Unlike Foo3(), Foo2() should not be deleted since there is a check + " for v:profiling. + " - Bar() is not reported since it does not match "profile func Foo*". + call assert_equal(31, len(lines)) + + call assert_equal('FUNCTION Foo1()', lines[0]) + call assert_match('Defined:.*Xprofile_func.vim:3', lines[1]) + call assert_equal('Called 2 times', lines[2]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[3]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[4]) + call assert_equal('', lines[5]) + call assert_equal('count total (s) self (s)', lines[6]) + call assert_equal('', lines[7]) + call assert_equal('FUNCTION Foo2()', lines[8]) + call assert_equal('Called 1 time', lines[10]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[11]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[12]) + call assert_equal('', lines[13]) + call assert_equal('count total (s) self (s)', lines[14]) + call assert_match('^\s*1\s\+.*\slet l:count = 100$', lines[15]) + call assert_match('^\s*101\s\+.*\swhile l:count > 0$', lines[16]) + call assert_match('^\s*100\s\+.*\s let l:count = l:count - 1$', lines[17]) + call assert_match('^\s*101\s\+.*\sendwhile$', lines[18]) + call assert_match('^\s*1\s\+.\+sleep 1m$', lines[19]) + call assert_equal('', lines[20]) + call assert_equal('FUNCTIONS SORTED ON TOTAL TIME', lines[21]) + call assert_equal('count total (s) self (s) function', lines[22]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo2()$', lines[23]) + call assert_match('^\s*2\s\+\d\+\.\d\+\s\+Foo1()$', lines[24]) + call assert_equal('', lines[25]) + call assert_equal('FUNCTIONS SORTED ON SELF TIME', lines[26]) + call assert_equal('count total (s) self (s) function', lines[27]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo2()$', lines[28]) + call assert_match('^\s*2\s\+\d\+\.\d\+\s\+Foo1()$', lines[29]) + call assert_equal('', lines[30]) + + call delete('Xprofile_func.vim') + call delete('Xprofile_func.log') +endfunc + +func Test_profile_func_with_ifelse() + let lines =<< trim [CODE] + func! Foo1() + if 1 + let x = 0 + elseif 1 + let x = 1 + else + let x = 2 + endif + endfunc + func! Foo2() + if 0 + let x = 0 + elseif 1 + let x = 1 + else + let x = 2 + endif + endfunc + func! Foo3() + if 0 + let x = 0 + elseif 0 + let x = 1 + else + let x = 2 + endif + endfunc + call Foo1() + call Foo2() + call Foo3() + [CODE] + + call writefile(lines, 'Xprofile_func.vim') + call system(GetVimCommand() + \ . ' -es -i NONE --noplugin' + \ . ' -c "profile start Xprofile_func.log"' + \ . ' -c "profile func Foo*"' + \ . ' -c "so Xprofile_func.vim"' + \ . ' -c "qall!"') + call assert_equal(0, v:shell_error) + + let lines = readfile('Xprofile_func.log') + + " - Foo1() should pass 'if' block. + " - Foo2() should pass 'elseif' block. + " - Foo3() should pass 'else' block. + call assert_equal(57, len(lines)) + + call assert_equal('FUNCTION Foo1()', lines[0]) + call assert_match('Defined:.*Xprofile_func.vim', lines[1]) + call assert_equal('Called 1 time', lines[2]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[3]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[4]) + call assert_equal('', lines[5]) + call assert_equal('count total (s) self (s)', lines[6]) + call assert_match('^\s*1\s\+.*\sif 1$', lines[7]) + call assert_match('^\s*1\s\+.*\s let x = 0$', lines[8]) + call assert_match( '^\s\+elseif 1$', lines[9]) + call assert_match( '^\s\+let x = 1$', lines[10]) + call assert_match( '^\s\+else$', lines[11]) + call assert_match( '^\s\+let x = 2$', lines[12]) + call assert_match('^\s*1\s\+.*\sendif$', lines[13]) + call assert_equal('', lines[14]) + call assert_equal('FUNCTION Foo2()', lines[15]) + call assert_equal('Called 1 time', lines[17]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[18]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[19]) + call assert_equal('', lines[20]) + call assert_equal('count total (s) self (s)', lines[21]) + call assert_match('^\s*1\s\+.*\sif 0$', lines[22]) + call assert_match( '^\s\+let x = 0$', lines[23]) + call assert_match('^\s*1\s\+.*\selseif 1$', lines[24]) + call assert_match('^\s*1\s\+.*\s let x = 1$', lines[25]) + call assert_match( '^\s\+else$', lines[26]) + call assert_match( '^\s\+let x = 2$', lines[27]) + call assert_match('^\s*1\s\+.*\sendif$', lines[28]) + call assert_equal('', lines[29]) + call assert_equal('FUNCTION Foo3()', lines[30]) + call assert_equal('Called 1 time', lines[32]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[33]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[34]) + call assert_equal('', lines[35]) + call assert_equal('count total (s) self (s)', lines[36]) + call assert_match('^\s*1\s\+.*\sif 0$', lines[37]) + call assert_match( '^\s\+let x = 0$', lines[38]) + call assert_match('^\s*1\s\+.*\selseif 0$', lines[39]) + call assert_match( '^\s\+let x = 1$', lines[40]) + call assert_match('^\s*1\s\+.*\selse$', lines[41]) + call assert_match('^\s*1\s\+.*\s let x = 2$', lines[42]) + call assert_match('^\s*1\s\+.*\sendif$', lines[43]) + call assert_equal('', lines[44]) + call assert_equal('FUNCTIONS SORTED ON TOTAL TIME', lines[45]) + call assert_equal('count total (s) self (s) function', lines[46]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[47]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[48]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[49]) + call assert_equal('', lines[50]) + call assert_equal('FUNCTIONS SORTED ON SELF TIME', lines[51]) + call assert_equal('count total (s) self (s) function', lines[52]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[53]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[54]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[55]) + call assert_equal('', lines[56]) + + call delete('Xprofile_func.vim') + call delete('Xprofile_func.log') +endfunc + +func Test_profile_func_with_trycatch() + let lines =<< trim [CODE] + func! Foo1() + try + let x = 0 + catch + let x = 1 + finally + let x = 2 + endtry + endfunc + func! Foo2() + try + throw 0 + catch + let x = 1 + finally + let x = 2 + endtry + endfunc + func! Foo3() + try + throw 0 + catch + throw 1 + finally + let x = 2 + endtry + endfunc + call Foo1() + call Foo2() + try + call Foo3() + catch + endtry + [CODE] + + call writefile(lines, 'Xprofile_func.vim') + call system(GetVimCommand() + \ . ' -es -i NONE --noplugin' + \ . ' -c "profile start Xprofile_func.log"' + \ . ' -c "profile func Foo*"' + \ . ' -c "so Xprofile_func.vim"' + \ . ' -c "qall!"') + call assert_equal(0, v:shell_error) + + let lines = readfile('Xprofile_func.log') + + " - Foo1() should pass 'try' 'finally' blocks. + " - Foo2() should pass 'catch' 'finally' blocks. + " - Foo3() should not pass 'endtry'. + call assert_equal(57, len(lines)) + + call assert_equal('FUNCTION Foo1()', lines[0]) + call assert_match('Defined:.*Xprofile_func.vim', lines[1]) + call assert_equal('Called 1 time', lines[2]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[3]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[4]) + call assert_equal('', lines[5]) + call assert_equal('count total (s) self (s)', lines[6]) + call assert_match('^\s*1\s\+.*\stry$', lines[7]) + call assert_match('^\s*1\s\+.*\s let x = 0$', lines[8]) + call assert_match( '^\s\+catch$', lines[9]) + call assert_match( '^\s\+let x = 1$', lines[10]) + call assert_match('^\s*1\s\+.*\sfinally$', lines[11]) + call assert_match('^\s*1\s\+.*\s let x = 2$', lines[12]) + call assert_match('^\s*1\s\+.*\sendtry$', lines[13]) + call assert_equal('', lines[14]) + call assert_equal('FUNCTION Foo2()', lines[15]) + call assert_equal('Called 1 time', lines[17]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[18]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[19]) + call assert_equal('', lines[20]) + call assert_equal('count total (s) self (s)', lines[21]) + call assert_match('^\s*1\s\+.*\stry$', lines[22]) + call assert_match('^\s*1\s\+.*\s throw 0$', lines[23]) + call assert_match('^\s*1\s\+.*\scatch$', lines[24]) + call assert_match('^\s*1\s\+.*\s let x = 1$', lines[25]) + call assert_match('^\s*1\s\+.*\sfinally$', lines[26]) + call assert_match('^\s*1\s\+.*\s let x = 2$', lines[27]) + call assert_match('^\s*1\s\+.*\sendtry$', lines[28]) + call assert_equal('', lines[29]) + call assert_equal('FUNCTION Foo3()', lines[30]) + call assert_equal('Called 1 time', lines[32]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[33]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[34]) + call assert_equal('', lines[35]) + call assert_equal('count total (s) self (s)', lines[36]) + call assert_match('^\s*1\s\+.*\stry$', lines[37]) + call assert_match('^\s*1\s\+.*\s throw 0$', lines[38]) + call assert_match('^\s*1\s\+.*\scatch$', lines[39]) + call assert_match('^\s*1\s\+.*\s throw 1$', lines[40]) + call assert_match('^\s*1\s\+.*\sfinally$', lines[41]) + call assert_match('^\s*1\s\+.*\s let x = 2$', lines[42]) + call assert_match( '^\s\+endtry$', lines[43]) + call assert_equal('', lines[44]) + call assert_equal('FUNCTIONS SORTED ON TOTAL TIME', lines[45]) + call assert_equal('count total (s) self (s) function', lines[46]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[47]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[48]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[49]) + call assert_equal('', lines[50]) + call assert_equal('FUNCTIONS SORTED ON SELF TIME', lines[51]) + call assert_equal('count total (s) self (s) function', lines[52]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[53]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[54]) + call assert_match('^\s*1\s\+\d\+\.\d\+\s\+Foo.()$', lines[55]) + call assert_equal('', lines[56]) + + call delete('Xprofile_func.vim') + call delete('Xprofile_func.log') +endfunc + +func Test_profile_file() + let lines =<< trim [CODE] + func! Foo() + endfunc + for i in range(10) + " a comment + call Foo() + endfor + call Foo() + [CODE] + + call writefile(lines, 'Xprofile_file.vim') + call system(GetVimCommandClean() + \ . ' -es' + \ . ' -c "profile start Xprofile_file.log"' + \ . ' -c "profile file Xprofile_file.vim"' + \ . ' -c "so Xprofile_file.vim"' + \ . ' -c "so Xprofile_file.vim"' + \ . ' -c "qall!"') + call assert_equal(0, v:shell_error) + + let lines = readfile('Xprofile_file.log') + + call assert_equal(14, len(lines)) + + call assert_match('^SCRIPT .*Xprofile_file.vim$', lines[0]) + call assert_equal('Sourced 2 times', lines[1]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[2]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[3]) + call assert_equal('', lines[4]) + call assert_equal('count total (s) self (s)', lines[5]) + call assert_match(' 2 0.\d\+ func! Foo()', lines[6]) + call assert_equal(' endfunc', lines[7]) + " Loop iterates 10 times. Since script runs twice, body executes 20 times. + " First line of loop executes one more time than body to detect end of loop. + call assert_match('^\s*22\s\+\d\+\.\d\+\s\+for i in range(10)$', lines[8]) + call assert_equal(' " a comment', lines[9]) + " if self and total are equal we only get one number + call assert_match('^\s*20\s\+\(\d\+\.\d\+\s\+\)\=\d\+\.\d\+\s\+call Foo()$', lines[10]) + call assert_match('^\s*22\s\+\d\+\.\d\+\s\+endfor$', lines[11]) + " if self and total are equal we only get one number + call assert_match('^\s*2\s\+\(\d\+\.\d\+\s\+\)\=\d\+\.\d\+\s\+call Foo()$', lines[12]) + call assert_equal('', lines[13]) + + call delete('Xprofile_file.vim') + call delete('Xprofile_file.log') +endfunc + +func Test_profile_file_with_cont() + let lines = [ + \ 'echo "hello', + \ ' \ world"', + \ 'echo "foo ', + \ ' \bar"', + \ ] + + call writefile(lines, 'Xprofile_file.vim') + call system(GetVimCommandClean() + \ . ' -es' + \ . ' -c "profile start Xprofile_file.log"' + \ . ' -c "profile file Xprofile_file.vim"' + \ . ' -c "so Xprofile_file.vim"' + \ . ' -c "qall!"') + call assert_equal(0, v:shell_error) + + let lines = readfile('Xprofile_file.log') + call assert_equal(11, len(lines)) + + call assert_match('^SCRIPT .*Xprofile_file.vim$', lines[0]) + call assert_equal('Sourced 1 time', lines[1]) + call assert_match('^Total time:\s\+\d\+\.\d\+$', lines[2]) + call assert_match('^ Self time:\s\+\d\+\.\d\+$', lines[3]) + call assert_equal('', lines[4]) + call assert_equal('count total (s) self (s)', lines[5]) + call assert_match(' 1 0.\d\+ echo "hello', lines[6]) + call assert_equal(' \ world"', lines[7]) + call assert_match(' 1 0.\d\+ echo "foo ', lines[8]) + call assert_equal(' \bar"', lines[9]) + call assert_equal('', lines[10]) + + call delete('Xprofile_file.vim') + call delete('Xprofile_file.log') +endfunc + +func Test_profile_completion() + call feedkeys(":profile \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profile continue dump file func pause start stop', @:) + + call feedkeys(":profile start test_prof\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_match('^"profile start.* test_profile\.vim', @:) + + call feedkeys(":profile file test_prof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"profile file test_profile\.vim', @:) + call feedkeys(":profile file test_prof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"profile file test_profile\.vim', @:) + call feedkeys(":profile file test_prof \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"profile file test_prof ', @:) + call feedkeys(":profile file X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_match('"profile file X1B2C3', @:) + + func Xprof_test() + endfunc + call feedkeys(":profile func Xprof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profile func Xprof_test', @:) + call feedkeys(":profile func Xprof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profile func Xprof_test', @:) + call feedkeys(":profile func Xprof \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profile func Xprof ', @:) + call feedkeys(":profile func X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profile func X1B2C3', @:) + + call feedkeys(":profdel \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel file func', @:) + call feedkeys(":profdel fu\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel func', @:) + call feedkeys(":profdel he\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel he', @:) + call feedkeys(":profdel here \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel here ', @:) + call feedkeys(":profdel file test_prof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel file test_profile.vim', @:) + call feedkeys(":profdel file X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel file X1B2C3', @:) + call feedkeys(":profdel func Xprof\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel func Xprof_test', @:) + call feedkeys(":profdel func Xprof_test \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel func Xprof_test ', @:) + call feedkeys(":profdel func X1B2C3\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"profdel func X1B2C3', @:) + + delfunc Xprof_test +endfunc + +func Test_profile_errors() + call assert_fails("profile func Foo", 'E750:') + call assert_fails("profile pause", 'E750:') + call assert_fails("profile continue", 'E750:') +endfunc + +func Test_profile_truncate_mbyte() + if &enc !=# 'utf-8' + return + endif + + let lines = [ + \ 'scriptencoding utf-8', + \ 'func! Foo()', + \ ' return [', + \ ' \ "' . join(map(range(0x4E00, 0x4E00 + 340), 'nr2char(v:val)'), '') . '",', + \ ' \ "' . join(map(range(0x4F00, 0x4F00 + 340), 'nr2char(v:val)'), '') . '",', + \ ' \ ]', + \ 'endfunc', + \ 'call Foo()', + \ ] + + call writefile(lines, 'Xprofile_file.vim') + call system(GetVimCommandClean() + \ . ' -es --cmd "set enc=utf-8"' + \ . ' -c "profile start Xprofile_file.log"' + \ . ' -c "profile file Xprofile_file.vim"' + \ . ' -c "so Xprofile_file.vim"' + \ . ' -c "qall!"') + call assert_equal(0, v:shell_error) + + split Xprofile_file.log + if &fenc != '' + call assert_equal('utf-8', &fenc) + endif + /func! Foo() + let lnum = line('.') + call assert_match('^\s*return \[$', getline(lnum + 1)) + call assert_match("\u4F52$", getline(lnum + 2)) + call assert_match("\u5052$", getline(lnum + 3)) + call assert_match('^\s*\\ \]$', getline(lnum + 4)) + bwipe! + + call delete('Xprofile_file.vim') + call delete('Xprofile_file.log') +endfunc + +func Test_profdel_func() + let lines =<< trim [CODE] + profile start Xprofile_file.log + func! Foo1() + endfunc + func! Foo2() + endfunc + func! Foo3() + endfunc + + profile func Foo1 + profile func Foo2 + call Foo1() + call Foo2() + + profile func Foo3 + profdel func Foo2 + profdel func Foo3 + call Foo1() + call Foo2() + call Foo3() + [CODE] + call writefile(lines, 'Xprofile_file.vim') + call system(GetVimCommandClean() . ' -es --cmd "so Xprofile_file.vim" --cmd q') + call assert_equal(0, v:shell_error) + + let lines = readfile('Xprofile_file.log') + call assert_equal(26, len(lines)) + + " Check that: + " - Foo1() is called twice (profdel not invoked) + " - Foo2() is called once (profdel invoked after it was called) + " - Foo3() is not called (profdel invoked before it was called) + call assert_equal('FUNCTION Foo1()', lines[0]) + call assert_match('Defined:.*Xprofile_file.vim', lines[1]) + call assert_equal('Called 2 times', lines[2]) + call assert_equal('FUNCTION Foo2()', lines[8]) + call assert_equal('Called 1 time', lines[10]) + call assert_equal('FUNCTIONS SORTED ON TOTAL TIME', lines[16]) + call assert_equal('FUNCTIONS SORTED ON SELF TIME', lines[21]) + + call delete('Xprofile_file.vim') + call delete('Xprofile_file.log') +endfunc + +func Test_profdel_star() + " Foo() is invoked once before and once after 'profdel *'. + " So profiling should report it only once. + let lines =<< trim [CODE] + profile start Xprofile_file.log + func! Foo() + endfunc + profile func Foo + call Foo() + profdel * + call Foo() + [CODE] + call writefile(lines, 'Xprofile_file.vim') + call system(GetVimCommandClean() . ' -es -c "so Xprofile_file.vim" -c q') + call assert_equal(0, v:shell_error) + + let lines = readfile('Xprofile_file.log') + call assert_equal(16, len(lines)) + + call assert_equal('FUNCTION Foo()', lines[0]) + call assert_match('Defined:.*Xprofile_file.vim', lines[1]) + call assert_equal('Called 1 time', lines[2]) + call assert_equal('FUNCTIONS SORTED ON TOTAL TIME', lines[8]) + call assert_equal('FUNCTIONS SORTED ON SELF TIME', lines[12]) + + call delete('Xprofile_file.vim') + call delete('Xprofile_file.log') +endfunc + +" When typing the function it won't have a script ID, test that this works. +func Test_profile_typed_func() + if !CanRunVimInTerminal() + throw 'Skipped: cannot run Vim in a terminal window' + endif + + let lines =<< trim END + profile start XprofileTypedFunc + END + call writefile(lines, 'XtestProfile') + let buf = RunVimInTerminal('-S XtestProfile', #{}) + + call term_sendkeys(buf, ":func DoSomething()\<CR>" + \ .. "echo 'hello'\<CR>" + \ .. "endfunc\<CR>") + call term_sendkeys(buf, ":profile func DoSomething\<CR>") + call term_sendkeys(buf, ":call DoSomething()\<CR>") + call TermWait(buf, 100) + call StopVimInTerminal(buf) + let lines = readfile('XprofileTypedFunc') + call assert_equal("FUNCTION DoSomething()", lines[0]) + call assert_equal("Called 1 time", lines[1]) + + " clean up + call delete('XprofileTypedFunc') + call delete('XtestProfile') +endfunc diff --git a/test/old/testdir/test_prompt_buffer.vim b/test/old/testdir/test_prompt_buffer.vim new file mode 100644 index 0000000000..3dfbbcece6 --- /dev/null +++ b/test/old/testdir/test_prompt_buffer.vim @@ -0,0 +1,301 @@ +" Tests for setting 'buftype' to "prompt" + +source check.vim +" Nvim's channel implementation differs from Vim's +" CheckFeature channel + +source shared.vim +source screendump.vim + +func CanTestPromptBuffer() + " We need to use a terminal window to be able to feed keys without leaving + " Insert mode. + CheckFeature terminal + + " TODO: make the tests work on MS-Windows + CheckNotMSWindows +endfunc + +func WriteScript(name) + call writefile([ + \ 'func TextEntered(text)', + \ ' if a:text == "exit"', + \ ' " Reset &modified to allow the buffer to be closed.', + \ ' set nomodified', + \ ' stopinsert', + \ ' close', + \ ' else', + \ ' " Add the output above the current prompt.', + \ ' call append(line("$") - 1, "Command: \"" . a:text . "\"")', + \ ' " Reset &modified to allow the buffer to be closed.', + \ ' set nomodified', + \ ' call timer_start(20, {id -> TimerFunc(a:text)})', + \ ' endif', + \ 'endfunc', + \ '', + \ 'func TimerFunc(text)', + \ ' " Add the output above the current prompt.', + \ ' call append(line("$") - 1, "Result: \"" . a:text . "\"")', + \ ' " Reset &modified to allow the buffer to be closed.', + \ ' set nomodified', + \ 'endfunc', + \ '', + \ 'func SwitchWindows()', + \ ' call timer_start(0, {-> execute("wincmd p|wincmd p", "")})', + \ 'endfunc', + \ '', + \ 'call setline(1, "other buffer")', + \ 'set nomodified', + \ 'new', + \ 'set buftype=prompt', + \ 'call prompt_setcallback(bufnr(""), function("TextEntered"))', + \ 'eval bufnr("")->prompt_setprompt("cmd: ")', + \ 'startinsert', + \ ], a:name) +endfunc + +func Test_prompt_basic() + call CanTestPromptBuffer() + let scriptName = 'XpromptscriptBasic' + call WriteScript(scriptName) + + let buf = RunVimInTerminal('-S ' . scriptName, {}) + call WaitForAssert({-> assert_equal('cmd:', term_getline(buf, 1))}) + + call term_sendkeys(buf, "hello\<CR>") + call WaitForAssert({-> assert_equal('cmd: hello', term_getline(buf, 1))}) + call WaitForAssert({-> assert_equal('Command: "hello"', term_getline(buf, 2))}) + call WaitForAssert({-> assert_equal('Result: "hello"', term_getline(buf, 3))}) + + call term_sendkeys(buf, "exit\<CR>") + call WaitForAssert({-> assert_equal('other buffer', term_getline(buf, 1))}) + + call StopVimInTerminal(buf) + call delete(scriptName) +endfunc + +func Test_prompt_editing() + call CanTestPromptBuffer() + let scriptName = 'XpromptscriptEditing' + call WriteScript(scriptName) + + let buf = RunVimInTerminal('-S ' . scriptName, {}) + call WaitForAssert({-> assert_equal('cmd:', term_getline(buf, 1))}) + + let bs = "\<BS>" + call term_sendkeys(buf, "hello" . bs . bs) + call WaitForAssert({-> assert_equal('cmd: hel', term_getline(buf, 1))}) + + let left = "\<Left>" + call term_sendkeys(buf, left . left . left . bs . '-') + call WaitForAssert({-> assert_equal('cmd: -hel', term_getline(buf, 1))}) + + call term_sendkeys(buf, "\<C-O>lz") + call WaitForAssert({-> assert_equal('cmd: -hzel', term_getline(buf, 1))}) + + let end = "\<End>" + call term_sendkeys(buf, end . "x") + call WaitForAssert({-> assert_equal('cmd: -hzelx', term_getline(buf, 1))}) + + call term_sendkeys(buf, "\<C-U>exit\<CR>") + call WaitForAssert({-> assert_equal('other buffer', term_getline(buf, 1))}) + + call StopVimInTerminal(buf) + call delete(scriptName) +endfunc + +func Test_prompt_switch_windows() + call CanTestPromptBuffer() + let scriptName = 'XpromptSwitchWindows' + call WriteScript(scriptName) + + let buf = RunVimInTerminal('-S ' . scriptName, {'rows': 12}) + call WaitForAssert({-> assert_equal('cmd:', term_getline(buf, 1))}) + call WaitForAssert({-> assert_match('-- INSERT --', term_getline(buf, 12))}) + + call term_sendkeys(buf, "\<C-O>:call SwitchWindows()\<CR>") + call term_wait(buf, 50) + call WaitForAssert({-> assert_match('-- INSERT --', term_getline(buf, 12))}) + + call term_sendkeys(buf, "\<Esc>") + call term_wait(buf, 50) + call WaitForAssert({-> assert_match('^ *$', term_getline(buf, 12))}) + + call StopVimInTerminal(buf) + call delete(scriptName) +endfunc + +func Test_prompt_garbage_collect() + func MyPromptCallback(x, text) + " NOP + endfunc + func MyPromptInterrupt(x) + " NOP + endfunc + + new + set buftype=prompt + eval bufnr('')->prompt_setcallback(function('MyPromptCallback', [{}])) + eval bufnr('')->prompt_setinterrupt(function('MyPromptInterrupt', [{}])) + call test_garbagecollect_now() + " Must not crash + call feedkeys("\<CR>\<C-C>", 'xt') + call assert_true(v:true) + + call assert_fails("call prompt_setcallback(bufnr(), [])", 'E921:') + call assert_equal(0, prompt_setcallback({}, '')) + call assert_fails("call prompt_setinterrupt(bufnr(), [])", 'E921:') + call assert_equal(0, prompt_setinterrupt({}, '')) + + delfunc MyPromptCallback + bwipe! +endfunc + +func Test_prompt_backspace() + new + set buftype=prompt + call feedkeys("A123456\<Left>\<BS>\<Esc>", 'xt') + call assert_equal('% 12346', getline(1)) + bwipe! +endfunc + +" Test for editing the prompt buffer +func Test_prompt_buffer_edit() + new + set buftype=prompt + normal! i + call assert_beeps('normal! dd') + call assert_beeps('normal! ~') + call assert_beeps('normal! o') + call assert_beeps('normal! O') + call assert_beeps('normal! p') + call assert_beeps('normal! P') + call assert_beeps('normal! u') + call assert_beeps('normal! ra') + call assert_beeps('normal! s') + call assert_beeps('normal! S') + call assert_beeps("normal! \<C-A>") + call assert_beeps("normal! \<C-X>") + call assert_beeps("normal! dp") + call assert_beeps("normal! do") + " pressing CTRL-W in the prompt buffer should trigger the window commands + call assert_equal(1, winnr()) + exe "normal A\<C-W>\<C-W>" + call assert_equal(2, winnr()) + wincmd w + close! + call assert_equal(0, prompt_setprompt([], '')) +endfunc + +func Test_prompt_buffer_getbufinfo() + new + call assert_equal('', prompt_getprompt('%')) + call assert_equal('', prompt_getprompt(bufnr('%'))) + let another_buffer = bufnr('%') + + set buftype=prompt + call assert_equal('% ', prompt_getprompt('%')) + call prompt_setprompt( bufnr( '%' ), 'This is a test: ' ) + call assert_equal('This is a test: ', prompt_getprompt('%')) + + call prompt_setprompt( bufnr( '%' ), '' ) + call assert_equal('', '%'->prompt_getprompt()) + + call prompt_setprompt( bufnr( '%' ), 'Another: ' ) + call assert_equal('Another: ', prompt_getprompt('%')) + let another = bufnr('%') + + new + + call assert_equal('', prompt_getprompt('%')) + call assert_equal('Another: ', prompt_getprompt(another)) + + " Doesn't exist + let buffers_before = len( getbufinfo() ) + call assert_equal('', prompt_getprompt( bufnr('$') + 1)) + call assert_equal(buffers_before, len( getbufinfo())) + + " invalid type + call assert_fails('call prompt_getprompt({})', 'E728:') + + %bwipe! +endfunc + +func Test_prompt_while_writing_to_hidden_buffer() + call CanTestPromptBuffer() + CheckUnix + + " Make a job continuously write to a hidden buffer, check that the prompt + " buffer is not affected. + let scriptName = 'XpromptscriptHiddenBuf' + let script =<< trim END + set buftype=prompt + call prompt_setprompt( bufnr(), 'cmd:' ) + let job = job_start(['/bin/sh', '-c', + \ 'while true; + \ do echo line; + \ sleep 0.1; + \ done'], #{out_io: 'buffer', out_name: ''}) + startinsert + END + eval script->writefile(scriptName, 'D') + + let buf = RunVimInTerminal('-S ' .. scriptName, {}) + call WaitForAssert({-> assert_equal('cmd:', term_getline(buf, 1))}) + + call term_sendkeys(buf, 'test') + call WaitForAssert({-> assert_equal('cmd:test', term_getline(buf, 1))}) + call term_sendkeys(buf, 'test') + call WaitForAssert({-> assert_equal('cmd:testtest', term_getline(buf, 1))}) + call term_sendkeys(buf, 'test') + call WaitForAssert({-> assert_equal('cmd:testtesttest', term_getline(buf, 1))}) + + call StopVimInTerminal(buf) +endfunc + +func Test_prompt_appending_while_hidden() + call CanTestPromptBuffer() + + let script =<< trim END + new prompt + set buftype=prompt + set bufhidden=hide + + func s:TextEntered(text) + if a:text == 'exit' + close + endif + echowin 'Entered:' a:text + endfunc + call prompt_setcallback(bufnr(), function('s:TextEntered')) + + func DoAppend() + call appendbufline('prompt', '$', 'Test') + return '' + endfunc + END + call writefile(script, 'XpromptBuffer', 'D') + + let buf = RunVimInTerminal('-S XpromptBuffer', {'rows': 10}) + call TermWait(buf) + + call term_sendkeys(buf, "asomething\<CR>") + call TermWait(buf) + + call term_sendkeys(buf, "exit\<CR>") + call WaitForAssert({-> assert_notmatch('-- INSERT --', term_getline(buf, 10))}) + + call term_sendkeys(buf, ":call DoAppend()\<CR>") + call WaitForAssert({-> assert_notmatch('-- INSERT --', term_getline(buf, 10))}) + + call term_sendkeys(buf, "i") + call WaitForAssert({-> assert_match('-- INSERT --', term_getline(buf, 10))}) + + call term_sendkeys(buf, "\<C-R>=DoAppend()\<CR>") + call WaitForAssert({-> assert_match('-- INSERT --', term_getline(buf, 10))}) + + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_put.vim b/test/old/testdir/test_put.vim new file mode 100644 index 0000000000..6c4bd28386 --- /dev/null +++ b/test/old/testdir/test_put.vim @@ -0,0 +1,288 @@ +" Tests for put commands, e.g. ":put", "p", "gp", "P", "gP", etc. + +source check.vim +source screendump.vim + +func Test_put_block() + new + call feedkeys("i\<C-V>u2500\<CR>x\<ESC>", 'x') + call feedkeys("\<C-V>y", 'x') + call feedkeys("gg0p", 'x') + call assert_equal("\u2500x", getline(1)) + bwipe! +endfunc + +func Test_put_char_block() + new + call setline(1, ['Line 1', 'Line 2']) + f Xfile_put + " visually select both lines and put the cursor at the top of the visual + " selection and then put the buffer name over it + exe "norm! G0\<c-v>ke\"%p" + call assert_equal(['Xfile_put 1', 'Xfile_put 2'], getline(1,2)) + bw! +endfunc + +func Test_put_char_block2() + new + call setreg('a', ' one ', 'v') + call setline(1, ['Line 1', '', 'Line 3', '']) + " visually select the first 3 lines and put register a over it + exe "norm! ggl\<c-v>2j2l\"ap" + call assert_equal(['L one 1', '', 'L one 3', ''], getline(1, 4)) + " clean up + bw! +endfunc + +func Test_put_lines() + new + let a = [ getreg('a'), getregtype('a') ] + call setline(1, ['Line 1', 'Line2', 'Line 3', '']) + exe 'norm! gg"add"AddG""p' + call assert_equal(['Line 3', '', 'Line 1', 'Line2'], getline(1, '$')) + " clean up + bw! + eval a[0]->setreg('a', a[1]) +endfunc + +func Test_put_expr() + new + call setline(1, repeat(['A'], 6)) + exec "1norm! \"=line('.')\<cr>p" + norm! j0. + norm! j0. + exec "4norm! \"=\<cr>P" + norm! j0. + norm! j0. + call assert_equal(['A1','A2','A3','4A','5A','6A'], getline(1, '$')) + bw! +endfunc + +func Test_put_fails_when_nomodifiable() + new + setlocal nomodifiable + + normal! yy + call assert_fails(':put', 'E21') + call assert_fails(':put!', 'E21') + call assert_fails(':normal! p', 'E21') + call assert_fails(':normal! gp', 'E21') + call assert_fails(':normal! P', 'E21') + call assert_fails(':normal! gP', 'E21') + + if has('mouse') + set mouse=n + call assert_fails('execute "normal! \<MiddleMouse>"', 'E21') + set mouse& + endif + + bwipeout! +endfunc + +" A bug was discovered where the Normal mode put commands (e.g., "p") would +" output duplicate error messages when invoked in a non-modifiable buffer. +func Test_put_p_errmsg_nodup() + new + setlocal nomodifiable + + normal! yy + + func Capture_p_error() + redir => s:p_err + normal! p + redir END + endfunc + + silent! call Capture_p_error() + + " Error message output within a function should be three lines (the function + " name, the line number, and the error message). + call assert_equal(3, count(s:p_err, "\n")) + + delfunction Capture_p_error + bwipeout! +endfunc + +func Test_put_p_indent_visual() + new + call setline(1, ['select this text', 'select that text']) + " yank "that" from the second line + normal 2Gwvey + " select "this" in the first line and put + normal k0wve[p + call assert_equal('select that text', getline(1)) + call assert_equal('select that text', getline(2)) + bwipe! +endfunc + +" Test for deleting all the contents of a buffer with a put +func Test_put_visual_delete_all_lines() + new + call setline(1, ['one', 'two', 'three']) + let @r = '' + normal! VG"rgp + call assert_equal(1, line('$')) + close! +endfunc + +func Test_gp_with_count_leaves_cursor_at_end() + new + call setline(1, '<---->') + call setreg('@', "foo\nbar", 'c') + normal 1G3|3gp + call assert_equal([0, 4, 4, 0], getpos(".")) + call assert_equal(['<--foo', 'barfoo', 'barfoo', 'bar-->'], getline(1, '$')) + call assert_equal([0, 4, 3, 0], getpos("']")) + + bwipe! +endfunc + +func Test_p_with_count_leaves_mark_at_end() + new + call setline(1, '<---->') + call setreg('@', "start\nend", 'c') + normal 1G3|3p + call assert_equal([0, 1, 4, 0], getpos(".")) + call assert_equal(['<--start', 'endstart', 'endstart', 'end-->'], getline(1, '$')) + call assert_equal([0, 4, 3, 0], getpos("']")) + + bwipe! +endfunc + +func Test_very_large_count() + new + " total put-length (21474837 * 100) brings 32 bit int overflow + let @" = repeat('x', 100) + call assert_fails('norm 21474837p', 'E1240:') + bwipe! +endfunc + +func Test_very_large_count_64bit() + throw 'Skipped: v:sizeoflong is N/A' " use legacy/put_spec.lua instead + + if v:sizeoflong < 8 + throw 'Skipped: only works with 64 bit long ints' + endif + + new + let @" = repeat('x', 100) + call assert_fails('norm 999999999p', 'E1240:') + bwipe! +endfunc + +func Test_very_large_count_block() + new + " total put-length (21474837 * 100) brings 32 bit int overflow + call setline(1, repeat('x', 100)) + exe "norm \<C-V>99ly" + call assert_fails('norm 21474837p', 'E1240:') + bwipe! +endfunc + +func Test_very_large_count_block_64bit() + throw 'Skipped: v:sizeoflong is N/A' " use legacy/put_spec.lua instead + + if v:sizeoflong < 8 + throw 'Skipped: only works with 64 bit long ints' + endif + + new + call setline(1, repeat('x', 100)) + exe "norm \<C-V>$y" + call assert_fails('norm 999999999p', 'E1240:') + bwipe! +endfunc + +func Test_put_above_first_line() + new + let @" = 'text' + silent! normal 0o00 + 0put + call assert_equal('text', getline(1)) + bwipe! +endfunc + +func Test_multibyte_op_end_mark() + new + call setline(1, 'тест') + normal viwdp + call assert_equal([0, 1, 7, 0], getpos("'>")) + call assert_equal([0, 1, 7, 0], getpos("']")) + + normal Vyp + call assert_equal([0, 1, v:maxcol, 0], getpos("'>")) + call assert_equal([0, 2, 7, 0], getpos("']")) + bwipe! +endfunc + +" this was putting a mark before the start of a line +func Test_put_empty_register() + new + norm yy + norm [Pi00ggv)s0 + sil! norm [P + bwipe! +endfunc + +" this was putting the end mark after the end of the line +func Test_put_visual_mode() + edit! SomeNewBuffer + set selection=exclusive + exe "norm o\t" + m0 + sil! norm
p
p + + bwipe! + set selection& +endfunc + +func Test_put_visual_block_mode() + enew + exe "norm 0R\<CR>\<C-C>V" + sil exe "norm \<C-V>c \<MiddleDrag>" + set ve=all + sil norm vz=p + + bwipe! + set ve= +endfunc + +func Test_put_other_window() + CheckRunVimInTerminal + + let lines =<< trim END + 40vsplit + 0put ='some text at the top' + put =' one more text' + put =' two more text' + put =' three more text' + put =' four more text' + END + call writefile(lines, 'Xtest_put_other', 'D') + let buf = RunVimInTerminal('-S Xtest_put_other', #{rows: 10}) + + call VerifyScreenDump(buf, 'Test_put_other_window_1', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_put_in_last_displayed_line() + CheckRunVimInTerminal + + let lines =<< trim END + vim9script + autocmd CursorMoved * eval line('w$') + @a = 'x'->repeat(&columns * 2 - 2) + range(&lines)->setline(1) + feedkeys('G"ap') + END + call writefile(lines, 'Xtest_put_last_line', 'D') + let buf = RunVimInTerminal('-S Xtest_put_last_line', #{rows: 10}) + + call VerifyScreenDump(buf, 'Test_put_in_last_displayed_line_1', {}) + + call StopVimInTerminal(buf) +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_python3.vim b/test/old/testdir/test_python3.vim new file mode 100644 index 0000000000..23c63f22d8 --- /dev/null +++ b/test/old/testdir/test_python3.vim @@ -0,0 +1,290 @@ +" Test for python 3 commands. +" TODO: move tests from test87.in here. + +source check.vim +CheckFeature python3 + +func Test_py3do() + " Check deleting lines does not trigger an ml_get error. + py3 import vim + new + call setline(1, ['one', 'two', 'three']) + py3do vim.command("%d_") + bwipe! + + " Disabled until neovim/neovim#8554 is resolved + if 0 + " Check switching to another buffer does not trigger an ml_get error. + new + let wincount = winnr('$') + call setline(1, ['one', 'two', 'three']) + py3do vim.command("new") + call assert_equal(wincount + 1, winnr('$')) + bwipe! + bwipe! + endif +endfunc + +func Test_set_cursor() + " Check that setting the cursor position works. + py3 import vim + new + call setline(1, ['first line', 'second line']) + normal gg + py3do vim.current.window.cursor = (1, 5) + call assert_equal([1, 6], [line('.'), col('.')]) + + " Check that movement after setting cursor position keeps current column. + normal j + call assert_equal([2, 6], [line('.'), col('.')]) +endfunc + +func Test_vim_function() + throw 'Skipped: Nvim does not support vim.bindeval()' + " Check creating vim.Function object + py3 import vim + + func s:foo() + return matchstr(expand('<sfile>'), '<SNR>\zs\d\+_foo$') + endfunc + let name = '<SNR>' . s:foo() + + try + py3 f = vim.bindeval('function("s:foo")') + call assert_equal(name, py3eval('f.name')) + catch + call assert_false(v:exception) + endtry + + try + py3 f = vim.Function(b'\x80\xfdR' + vim.eval('s:foo()').encode()) + call assert_equal(name, 'f.name'->py3eval()) + catch + call assert_false(v:exception) + endtry + + py3 del f + delfunc s:foo +endfunc + +func Test_skipped_python3_command_does_not_affect_pyxversion() + throw 'Skipped: Nvim hardcodes pyxversion=3' + set pyxversion=0 + if 0 + python3 import vim + endif + call assert_equal(0, &pyxversion) " This assertion would have failed with Vim 8.0.0251. (pyxversion was introduced in 8.0.0251.) +endfunc + +func _SetUpHiddenBuffer() + py3 import vim + new + edit hidden + setlocal bufhidden=hide + + enew + let lnum = 0 + while lnum < 10 + call append( 1, string( lnum ) ) + let lnum = lnum + 1 + endwhile + normal G + + call assert_equal( line( '.' ), 11 ) +endfunc + +func _CleanUpHiddenBuffer() + bwipe! hidden + bwipe! +endfunc + +func Test_Write_To_HiddenBuffer_Does_Not_Fix_Cursor_Clear() + call _SetUpHiddenBuffer() + py3 vim.buffers[ int( vim.eval( 'bufnr("hidden")' ) ) ][:] = None + call assert_equal( line( '.' ), 11 ) + call _CleanUpHiddenBuffer() +endfunc + +func Test_Write_To_HiddenBuffer_Does_Not_Fix_Cursor_List() + call _SetUpHiddenBuffer() + py3 vim.buffers[ int( vim.eval( 'bufnr("hidden")' ) ) ][:] = [ 'test' ] + call assert_equal( line( '.' ), 11 ) + call _CleanUpHiddenBuffer() +endfunc + +func Test_Write_To_HiddenBuffer_Does_Not_Fix_Cursor_Str() + call _SetUpHiddenBuffer() + py3 vim.buffers[ int( vim.eval( 'bufnr("hidden")' ) ) ][0] = 'test' + call assert_equal( line( '.' ), 11 ) + call _CleanUpHiddenBuffer() +endfunc + +func Test_Write_To_HiddenBuffer_Does_Not_Fix_Cursor_ClearLine() + call _SetUpHiddenBuffer() + py3 vim.buffers[ int( vim.eval( 'bufnr("hidden")' ) ) ][0] = None + call assert_equal( line( '.' ), 11 ) + call _CleanUpHiddenBuffer() +endfunc + +func _SetUpVisibleBuffer() + py3 import vim + new + let lnum = 0 + while lnum < 10 + call append( 1, string( lnum ) ) + let lnum = lnum + 1 + endwhile + normal G + call assert_equal( line( '.' ), 11 ) +endfunc + +func Test_Write_To_Current_Buffer_Fixes_Cursor_Clear() + call _SetUpVisibleBuffer() + + py3 vim.current.buffer[:] = None + call assert_equal( line( '.' ), 1 ) + + bwipe! +endfunc + +func Test_Write_To_Current_Buffer_Fixes_Cursor_List() + call _SetUpVisibleBuffer() + + py3 vim.current.buffer[:] = [ 'test' ] + call assert_equal( line( '.' ), 1 ) + + bwipe! +endfunction + +func Test_Write_To_Current_Buffer_Fixes_Cursor_Str() + call _SetUpVisibleBuffer() + + py3 vim.current.buffer[-1] = None + call assert_equal( line( '.' ), 10 ) + + bwipe! +endfunction + +func Test_Catch_Exception_Message() + try + py3 raise RuntimeError( 'TEST' ) + catch /.*/ + call assert_match('^Vim(.*):.*RuntimeError: TEST$', v:exception ) + endtry +endfunc + +func Test_unicode() + " this crashed Vim once + throw "Skipped: nvim does not support changing 'encoding'" + + set encoding=utf32 + py3 print('hello') + + if !has('win32') + set encoding=debug + py3 print('hello') + + set encoding=euc-tw + py3 print('hello') + endif + + set encoding=utf8 +endfunc + +" Test for resetting options with local values to global values +func Test_python3_opt_reset_local_to_global() + throw 'Skipped: Nvim does not support vim.bindeval()' + new + + py3 curbuf = vim.current.buffer + py3 curwin = vim.current.window + + " List of buffer-local options. Each list item has [option name, global + " value, buffer-local value, buffer-local value after reset] to use in the + " test. + let bopts = [ + \ ['autoread', 1, 0, -1], + \ ['equalprg', 'geprg', 'leprg', ''], + \ ['keywordprg', 'gkprg', 'lkprg', ''], + \ ['path', 'gpath', 'lpath', ''], + \ ['backupcopy', 'yes', 'no', ''], + \ ['tags', 'gtags', 'ltags', ''], + \ ['tagcase', 'ignore', 'match', ''], + \ ['define', 'gdef', 'ldef', ''], + \ ['include', 'ginc', 'linc', ''], + \ ['dict', 'gdict', 'ldict', ''], + \ ['thesaurus', 'gtsr', 'ltsr', ''], + \ ['formatprg', 'gfprg', 'lfprg', ''], + \ ['errorformat', '%f:%l:%m', '%s-%l-%m', ''], + \ ['grepprg', 'ggprg', 'lgprg', ''], + \ ['makeprg', 'gmprg', 'lmprg', ''], + \ ['balloonexpr', 'gbexpr', 'lbexpr', ''], + \ ['cryptmethod', 'blowfish2', 'zip', ''], + \ ['lispwords', 'abc', 'xyz', ''], + \ ['makeencoding', 'utf-8', 'latin1', ''], + \ ['undolevels', 100, 200, -123456]] + + " Set the global and buffer-local option values and then clear the + " buffer-local option value. + for opt in bopts + py3 << trim END + pyopt = vim.bindeval("opt") + vim.options[pyopt[0]] = pyopt[1] + curbuf.options[pyopt[0]] = pyopt[2] + END + exe "call assert_equal(opt[2], &" .. opt[0] .. ")" + exe "call assert_equal(opt[1], &g:" .. opt[0] .. ")" + exe "call assert_equal(opt[2], &l:" .. opt[0] .. ")" + py3 del curbuf.options[pyopt[0]] + exe "call assert_equal(opt[1], &" .. opt[0] .. ")" + exe "call assert_equal(opt[1], &g:" .. opt[0] .. ")" + exe "call assert_equal(opt[3], &l:" .. opt[0] .. ")" + exe "set " .. opt[0] .. "&" + endfor + + " Set the global and window-local option values and then clear the + " window-local option value. + let wopts = [ + \ ['scrolloff', 5, 10, -1], + \ ['sidescrolloff', 6, 12, -1], + \ ['statusline', '%<%f', '%<%F', '']] + for opt in wopts + py3 << trim + pyopt = vim.bindeval("opt") + vim.options[pyopt[0]] = pyopt[1] + curwin.options[pyopt[0]] = pyopt[2] + . + exe "call assert_equal(opt[2], &" .. opt[0] .. ")" + exe "call assert_equal(opt[1], &g:" .. opt[0] .. ")" + exe "call assert_equal(opt[2], &l:" .. opt[0] .. ")" + py3 del curwin.options[pyopt[0]] + exe "call assert_equal(opt[1], &" .. opt[0] .. ")" + exe "call assert_equal(opt[1], &g:" .. opt[0] .. ")" + exe "call assert_equal(opt[3], &l:" .. opt[0] .. ")" + exe "set " .. opt[0] .. "&" + endfor + + close! +endfunc + +" Test for various heredoc syntax +func Test_python3_heredoc() + python3 << END +s='A' +END + python3 << +s+='B' +. + python3 << trim END + s+='C' + END + python3 << trim + s+='D' + . + python3 << trim eof + s+='E' + eof + call assert_equal('ABCDE', pyxeval('s')) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_pyx3.vim b/test/old/testdir/test_pyx3.vim new file mode 100644 index 0000000000..09ece6f812 --- /dev/null +++ b/test/old/testdir/test_pyx3.vim @@ -0,0 +1,103 @@ +" Test for pyx* commands and functions with Python 3. + +set pyx=3 +source check.vim +CheckFeature python3 + +let s:py2pattern = '^2\.[0-7]\.\d\+' +let s:py3pattern = '^3\.\d\+\.\d\+' + + +func Test_has_pythonx() + call assert_true(has('pythonx')) +endfunc + + +func Test_pyx() + redir => var + pyx << trim EOF + import sys + print(sys.version) + EOF + redir END + call assert_match(s:py3pattern, split(var)[0]) +endfunc + + +func Test_pyxdo() + pyx import sys + enew + pyxdo return sys.version.split("\n")[0] + call assert_match(s:py3pattern, split(getline('.'))[0]) +endfunc + + +func Test_pyxeval() + pyx import sys + call assert_match(s:py3pattern, split(pyxeval('sys.version'))[0]) +endfunc + + +func Test_pyxfile() + " No special comments nor shebangs + redir => var + pyxfile pyxfile/pyx.py + redir END + call assert_match(s:py3pattern, split(var)[0]) + + " Python 3 special comment + redir => var + pyxfile pyxfile/py3_magic.py + redir END + call assert_match(s:py3pattern, split(var)[0]) + + " Python 3 shebang + redir => var + pyxfile pyxfile/py3_shebang.py + redir END + call assert_match(s:py3pattern, split(var)[0]) + + if has('python') + " Python 2 special comment + redir => var + pyxfile pyxfile/py2_magic.py + redir END + call assert_match(s:py2pattern, split(var)[0]) + + " Python 2 shebang + redir => var + pyxfile pyxfile/py2_shebang.py + redir END + call assert_match(s:py2pattern, split(var)[0]) + endif +endfunc + +func Test_Catch_Exception_Message() + try + pyx raise RuntimeError( 'TEST' ) + catch /.*/ + call assert_match('^Vim(.*):.*RuntimeError: TEST$', v:exception ) + endtry +endfunc + +" Test for various heredoc syntaxes +func Test_pyx3_heredoc() + pyx << END +result='A' +END + pyx << +result+='B' +. + pyx << trim END + result+='C' + END + pyx << trim + result+='D' + . + pyx << trim eof + result+='E' + eof + call assert_equal('ABCDE', pyxeval('result')) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_quickfix.vim b/test/old/testdir/test_quickfix.vim new file mode 100644 index 0000000000..b5abb08ed8 --- /dev/null +++ b/test/old/testdir/test_quickfix.vim @@ -0,0 +1,6372 @@ +" Test for the quickfix feature. + +source check.vim +source vim9.vim +CheckFeature quickfix + +source screendump.vim + +set encoding=utf-8 + +func s:setup_commands(cchar) + if a:cchar == 'c' + command! -nargs=* -bang Xlist <mods>clist<bang> <args> + command! -nargs=* Xgetexpr <mods>cgetexpr <args> + command! -nargs=* Xaddexpr <mods>caddexpr <args> + command! -nargs=* -count Xolder <mods><count>colder <args> + command! -nargs=* Xnewer <mods>cnewer <args> + command! -nargs=* Xopen <mods> copen <args> + command! -nargs=* Xwindow <mods>cwindow <args> + command! -nargs=* Xbottom <mods>cbottom <args> + command! -nargs=* Xclose <mods>cclose <args> + command! -nargs=* -bang Xfile <mods>cfile<bang> <args> + command! -nargs=* Xgetfile <mods>cgetfile <args> + command! -nargs=* Xaddfile <mods>caddfile <args> + command! -nargs=* -bang Xbuffer <mods>cbuffer<bang> <args> + command! -nargs=* Xgetbuffer <mods>cgetbuffer <args> + command! -nargs=* Xaddbuffer <mods>caddbuffer <args> + command! -nargs=* Xrewind <mods>crewind <args> + command! -count -nargs=* -bang Xnext <mods><count>cnext<bang> <args> + command! -count -nargs=* -bang Xprev <mods><count>cprev<bang> <args> + command! -nargs=* -bang Xfirst <mods>cfirst<bang> <args> + command! -nargs=* -bang Xlast <mods>clast<bang> <args> + command! -count -nargs=* -bang Xnfile <mods><count>cnfile<bang> <args> + command! -nargs=* -bang Xpfile <mods>cpfile<bang> <args> + command! -nargs=* Xexpr <mods>cexpr <args> + command! -count=999 -nargs=* Xvimgrep <mods> <count>vimgrep <args> + command! -nargs=* Xvimgrepadd <mods> vimgrepadd <args> + command! -nargs=* Xgrep <mods> grep <args> + command! -nargs=* Xgrepadd <mods> grepadd <args> + command! -nargs=* Xhelpgrep helpgrep <args> + command! -nargs=0 -count Xcc <count>cc + command! -count=1 -nargs=0 Xbelow <mods><count>cbelow + command! -count=1 -nargs=0 Xabove <mods><count>cabove + command! -count=1 -nargs=0 Xbefore <mods><count>cbefore + command! -count=1 -nargs=0 Xafter <mods><count>cafter + let g:Xgetlist = function('getqflist') + let g:Xsetlist = function('setqflist') + call setqflist([], 'f') + else + command! -nargs=* -bang Xlist <mods>llist<bang> <args> + command! -nargs=* Xgetexpr <mods>lgetexpr <args> + command! -nargs=* Xaddexpr <mods>laddexpr <args> + command! -nargs=* -count Xolder <mods><count>lolder <args> + command! -nargs=* Xnewer <mods>lnewer <args> + command! -nargs=* Xopen <mods> lopen <args> + command! -nargs=* Xwindow <mods>lwindow <args> + command! -nargs=* Xbottom <mods>lbottom <args> + command! -nargs=* Xclose <mods>lclose <args> + command! -nargs=* -bang Xfile <mods>lfile<bang> <args> + command! -nargs=* Xgetfile <mods>lgetfile <args> + command! -nargs=* Xaddfile <mods>laddfile <args> + command! -nargs=* -bang Xbuffer <mods>lbuffer<bang> <args> + command! -nargs=* Xgetbuffer <mods>lgetbuffer <args> + command! -nargs=* Xaddbuffer <mods>laddbuffer <args> + command! -nargs=* Xrewind <mods>lrewind <args> + command! -count -nargs=* -bang Xnext <mods><count>lnext<bang> <args> + command! -count -nargs=* -bang Xprev <mods><count>lprev<bang> <args> + command! -nargs=* -bang Xfirst <mods>lfirst<bang> <args> + command! -nargs=* -bang Xlast <mods>llast<bang> <args> + command! -count -nargs=* -bang Xnfile <mods><count>lnfile<bang> <args> + command! -nargs=* -bang Xpfile <mods>lpfile<bang> <args> + command! -nargs=* Xexpr <mods>lexpr <args> + command! -count=999 -nargs=* Xvimgrep <mods> <count>lvimgrep <args> + command! -nargs=* Xvimgrepadd <mods> lvimgrepadd <args> + command! -nargs=* Xgrep <mods> lgrep <args> + command! -nargs=* Xgrepadd <mods> lgrepadd <args> + command! -nargs=* Xhelpgrep lhelpgrep <args> + command! -nargs=0 -count Xcc <count>ll + command! -count=1 -nargs=0 Xbelow <mods><count>lbelow + command! -count=1 -nargs=0 Xabove <mods><count>labove + command! -count=1 -nargs=0 Xbefore <mods><count>lbefore + command! -count=1 -nargs=0 Xafter <mods><count>lafter + let g:Xgetlist = function('getloclist', [0]) + let g:Xsetlist = function('setloclist', [0]) + call setloclist(0, [], 'f') + endif +endfunc + +" This must be run before any error lists are created. +func Test_AA_cc_no_errors() + call assert_fails('cc', 'E42:') + call assert_fails('ll', 'E42:') +endfunc + +" Tests for the :clist and :llist commands +func XlistTests(cchar) + call s:setup_commands(a:cchar) + + if a:cchar == 'l' + call assert_fails('llist', 'E776:') + endif + " With an empty list, command should return error + Xgetexpr [] + silent! Xlist + call assert_true(v:errmsg ==# 'E42: No Errors') + + " Populate the list and then try + let lines =<< trim END + non-error 1 + Xtestfile1:1:3:Line1 + non-error 2 + Xtestfile2:2:2:Line2 + non-error| 3 + Xtestfile3:3:1:Line3 + END + Xgetexpr lines + + " List only valid entries + let l = split(execute('Xlist', ''), "\n") + call assert_equal([' 2 Xtestfile1:1 col 3: Line1', + \ ' 4 Xtestfile2:2 col 2: Line2', + \ ' 6 Xtestfile3:3 col 1: Line3'], l) + + " List all the entries + let l = split(execute('Xlist!', ''), "\n") + call assert_equal([' 1: non-error 1', ' 2 Xtestfile1:1 col 3: Line1', + \ ' 3: non-error 2', ' 4 Xtestfile2:2 col 2: Line2', + \ ' 5: non-error| 3', ' 6 Xtestfile3:3 col 1: Line3'], l) + + " List a range of errors + let l = split(execute('Xlist 3,6', ''), "\n") + call assert_equal([' 4 Xtestfile2:2 col 2: Line2', + \ ' 6 Xtestfile3:3 col 1: Line3'], l) + + let l = split(execute('Xlist! 3,4', ''), "\n") + call assert_equal([' 3: non-error 2', ' 4 Xtestfile2:2 col 2: Line2'], l) + + let l = split(execute('Xlist -6,-4', ''), "\n") + call assert_equal([' 2 Xtestfile1:1 col 3: Line1'], l) + + let l = split(execute('Xlist! -5,-3', ''), "\n") + call assert_equal([' 2 Xtestfile1:1 col 3: Line1', + \ ' 3: non-error 2', ' 4 Xtestfile2:2 col 2: Line2'], l) + + " Test for '+' + let l = split(execute('Xlist! +2', ''), "\n") + call assert_equal([' 2 Xtestfile1:1 col 3: Line1', + \ ' 3: non-error 2', ' 4 Xtestfile2:2 col 2: Line2'], l) + + " Ranged entries + call g:Xsetlist([{'lnum':10,'text':'Line1'}, + \ {'lnum':20,'col':10,'text':'Line2'}, + \ {'lnum':30,'col':15,'end_col':20,'text':'Line3'}, + \ {'lnum':40,'end_lnum':45,'text':'Line4'}, + \ {'lnum':50,'end_lnum':55,'col':15,'text':'Line5'}, + \ {'lnum':60,'end_lnum':65,'col':25,'end_col':35,'text':'Line6'}]) + let l = split(execute('Xlist', ""), "\n") + call assert_equal([' 1:10: Line1', + \ ' 2:20 col 10: Line2', + \ ' 3:30 col 15-20: Line3', + \ ' 4:40-45: Line4', + \ ' 5:50-55 col 15: Line5', + \ ' 6:60-65 col 25-35: Line6'], l) + + " Different types of errors + call g:Xsetlist([{'lnum':10,'col':5,'type':'W', 'text':'Warning','nr':11}, + \ {'lnum':20,'col':10,'type':'e','text':'Error','nr':22}, + \ {'lnum':30,'col':15,'type':'i','text':'Info','nr':33}, + \ {'lnum':40,'col':20,'type':'x', 'text':'Other','nr':44}, + \ {'lnum':50,'col':25,'type':"\<C-A>",'text':'one','nr':55}, + \ {'lnum':0,'type':'e','text':'Check type field is output even when lnum==0. ("error" was not output by v9.0.0736.)','nr':66}]) + let l = split(execute('Xlist', ""), "\n") + call assert_equal([' 1:10 col 5 warning 11: Warning', + \ ' 2:20 col 10 error 22: Error', + \ ' 3:30 col 15 info 33: Info', + \ ' 4:40 col 20 x 44: Other', + \ ' 5:50 col 25 55: one', + \ ' 6 error 66: Check type field is output even when lnum==0. ("error" was not output by v9.0.0736.)'], l) + + " Test for module names, one needs to explicitly set `'valid':v:true` so + call g:Xsetlist([ + \ {'lnum':10,'col':5,'type':'W','module':'Data.Text','text':'ModuleWarning','nr':11,'valid':v:true}, + \ {'lnum':20,'col':10,'type':'W','module':'Data.Text','filename':'Data/Text.hs','text':'ModuleWarning','nr':22,'valid':v:true}, + \ {'lnum':30,'col':15,'type':'W','filename':'Data/Text.hs','text':'FileWarning','nr':33,'valid':v:true}]) + let l = split(execute('Xlist', ""), "\n") + call assert_equal([' 1 Data.Text:10 col 5 warning 11: ModuleWarning', + \ ' 2 Data.Text:20 col 10 warning 22: ModuleWarning', + \ ' 3 Data/Text.hs:30 col 15 warning 33: FileWarning'], l) + + " Very long line should be displayed. + let text = 'Line' .. repeat('1234567890', 130) + let lines = ['Xtestfile9:2:9:' .. text] + Xgetexpr lines + + let l = split(execute('Xlist', ''), "\n") + call assert_equal([' 1 Xtestfile9:2 col 9: ' .. text] , l) + + " For help entries in the quickfix list, only the filename without directory + " should be displayed + Xhelpgrep setqflist() + let l = split(execute('Xlist 1', ''), "\n") + call assert_match('^ 1 [^\\/]\{-}:', l[0]) + + " Error cases + call assert_fails('Xlist abc', 'E488:') +endfunc + +func Test_clist() + call XlistTests('c') + call XlistTests('l') +endfunc + +" Tests for the :colder, :cnewer, :lolder and :lnewer commands +" Note that this test assumes that a quickfix/location list is +" already set by the caller. +func XageTests(cchar) + call s:setup_commands(a:cchar) + + if a:cchar == 'l' + " No location list for the current window + call assert_fails('lolder', 'E776:') + call assert_fails('lnewer', 'E776:') + endif + + let list = [{'bufnr': bufnr('%'), 'lnum': 1}] + call g:Xsetlist(list) + + " Jumping to a non existent list should return error + silent! Xolder 99 + call assert_true(v:errmsg ==# 'E380: At bottom of quickfix stack') + + silent! Xnewer 99 + call assert_true(v:errmsg ==# 'E381: At top of quickfix stack') + + " Add three quickfix/location lists + Xgetexpr ['Xtestfile1:1:3:Line1'] + Xgetexpr ['Xtestfile2:2:2:Line2'] + Xgetexpr ['Xtestfile3:3:1:Line3'] + + " Go back two lists + Xolder + let l = g:Xgetlist() + call assert_equal('Line2', l[0].text) + + " Go forward two lists + Xnewer + let l = g:Xgetlist() + call assert_equal('Line3', l[0].text) + + " Test for the optional count argument + Xolder 2 + let l = g:Xgetlist() + call assert_equal('Line1', l[0].text) + + Xnewer 2 + let l = g:Xgetlist() + call assert_equal('Line3', l[0].text) +endfunc + +func Test_cage() + call XageTests('c') + call XageTests('l') +endfunc + +" Tests for the :cwindow, :lwindow :cclose, :lclose, :copen and :lopen +" commands +func XwindowTests(cchar) + call s:setup_commands(a:cchar) + + " Opening the location list window without any errors should fail + if a:cchar == 'l' + call assert_fails('lopen', 'E776:') + call assert_fails('lwindow', 'E776:') + endif + + " Create a list with no valid entries + Xgetexpr ['non-error 1', 'non-error 2', 'non-error 3'] + + " Quickfix/Location window should not open with no valid errors + Xwindow + call assert_true(winnr('$') == 1) + + " Create a list with valid entries + let lines =<< trim END + Xtestfile1:1:3:Line1 + Xtestfile2:2:2:Line2 + Xtestfile3:3:1:Line3 + END + Xgetexpr lines + + " Open the window + Xwindow + call assert_true(winnr('$') == 2 && winnr() == 2 && + \ getline('.') ==# 'Xtestfile1|1 col 3| Line1') + redraw! + + " Close the window + Xclose + call assert_true(winnr('$') == 1) + + " Create a list with no valid entries + Xgetexpr ['non-error 1', 'non-error 2', 'non-error 3'] + + " Open the window + Xopen 5 + call assert_true(winnr('$') == 2 && getline('.') ==# '|| non-error 1' + \ && winheight(0) == 5) + + " Opening the window again, should move the cursor to that window + wincmd t + Xopen 7 + call assert_true(winnr('$') == 2 && winnr() == 2 && + \ winheight(0) == 7 && + \ getline('.') ==# '|| non-error 1') + + " :cnext in quickfix window should move to the next entry + Xnext + call assert_equal(2, g:Xgetlist({'idx' : 0}).idx) + + " Calling cwindow should close the quickfix window with no valid errors + Xwindow + call assert_true(winnr('$') == 1) + + " Specifying the width should adjust the width for a vertically split + " quickfix window. + vert Xopen + call assert_equal(10, winwidth(0)) + vert Xopen 12 + call assert_equal(12, winwidth(0)) + Xclose + + " Horizontally or vertically splitting the quickfix window should create a + " normal window/buffer + Xopen + wincmd s + call assert_equal(0, getwininfo(win_getid())[0].quickfix) + call assert_equal(0, getwininfo(win_getid())[0].loclist) + call assert_notequal('quickfix', &buftype) + close + Xopen + wincmd v + call assert_equal(0, getwininfo(win_getid())[0].quickfix) + call assert_equal(0, getwininfo(win_getid())[0].loclist) + call assert_notequal('quickfix', &buftype) + close + Xopen + Xclose + + if a:cchar == 'c' + " Opening the quickfix window in multiple tab pages should reuse the + " quickfix buffer + let lines =<< trim END + Xtestfile1:1:3:Line1 + Xtestfile2:2:2:Line2 + Xtestfile3:3:1:Line3 + END + Xgetexpr lines + Xopen + let qfbufnum = bufnr('%') + tabnew + Xopen + call assert_equal(qfbufnum, bufnr('%')) + new | only | tabonly + endif +endfunc + +func Test_cwindow() + call XwindowTests('c') + call XwindowTests('l') +endfunc + +func Test_copenHeight() + copen + wincmd H + let height = winheight(0) + copen 10 + call assert_equal(height, winheight(0)) + quit +endfunc + +func Test_copenHeight_tabline() + set tabline=foo showtabline=2 + copen + wincmd H + let height = winheight(0) + copen 10 + call assert_equal(height, winheight(0)) + quit + set tabline& showtabline& +endfunc + +" Tests for the :cfile, :lfile, :caddfile, :laddfile, :cgetfile and :lgetfile +" commands. +func XfileTests(cchar) + call s:setup_commands(a:cchar) + + let lines =<< trim END + Xtestfile1:700:10:Line 700 + Xtestfile2:800:15:Line 800 + END + call writefile(lines, 'Xqftestfile1') + + enew! + Xfile Xqftestfile1 + let l = g:Xgetlist() + call assert_true(len(l) == 2 && + \ l[0].lnum == 700 && l[0].col == 10 && l[0].text ==# 'Line 700' && + \ l[1].lnum == 800 && l[1].col == 15 && l[1].text ==# 'Line 800') + + " Test with a non existent file + call assert_fails('Xfile non_existent_file', 'E40') + + " Run cfile/lfile from a modified buffer + enew! + silent! put ='Quickfix' + silent! Xfile Xqftestfile1 + call assert_true(v:errmsg ==# 'E37: No write since last change (add ! to override)') + + call writefile(['Xtestfile3:900:30:Line 900'], 'Xqftestfile1') + Xaddfile Xqftestfile1 + let l = g:Xgetlist() + call assert_true(len(l) == 3 && + \ l[2].lnum == 900 && l[2].col == 30 && l[2].text ==# 'Line 900') + + let lines =<< trim END + Xtestfile1:222:77:Line 222 + Xtestfile2:333:88:Line 333 + END + call writefile(lines, 'Xqftestfile1') + + enew! + Xgetfile Xqftestfile1 + let l = g:Xgetlist() + call assert_true(len(l) == 2 && + \ l[0].lnum == 222 && l[0].col == 77 && l[0].text ==# 'Line 222' && + \ l[1].lnum == 333 && l[1].col == 88 && l[1].text ==# 'Line 333') + + " Test for a file with a long line and without a newline at the end + let text = repeat('x', 1024) + let t = 'a.txt:18:' . text + call writefile([t], 'Xqftestfile1', 'b') + silent! Xfile Xqftestfile1 + call assert_equal(text, g:Xgetlist()[0].text) + + call delete('Xqftestfile1') +endfunc + +func Test_cfile() + call XfileTests('c') + call XfileTests('l') +endfunc + +" Tests for the :cbuffer, :lbuffer, :caddbuffer, :laddbuffer, :cgetbuffer and +" :lgetbuffer commands. +func XbufferTests(cchar) + call s:setup_commands(a:cchar) + + enew! + let lines =<< trim END + Xtestfile7:700:10:Line 700 + Xtestfile8:800:15:Line 800 + END + silent! call setline(1, lines) + Xbuffer! + let l = g:Xgetlist() + call assert_true(len(l) == 2 && + \ l[0].lnum == 700 && l[0].col == 10 && l[0].text ==# 'Line 700' && + \ l[1].lnum == 800 && l[1].col == 15 && l[1].text ==# 'Line 800') + + enew! + let lines =<< trim END + Xtestfile9:900:55:Line 900 + Xtestfile10:950:66:Line 950 + END + silent! call setline(1, lines) + Xgetbuffer + let l = g:Xgetlist() + call assert_true(len(l) == 2 && + \ l[0].lnum == 900 && l[0].col == 55 && l[0].text ==# 'Line 900' && + \ l[1].lnum == 950 && l[1].col == 66 && l[1].text ==# 'Line 950') + + enew! + let lines =<< trim END + Xtestfile11:700:20:Line 700 + Xtestfile12:750:25:Line 750 + END + silent! call setline(1, lines) + Xaddbuffer + let l = g:Xgetlist() + call assert_true(len(l) == 4 && + \ l[1].lnum == 950 && l[1].col == 66 && l[1].text ==# 'Line 950' && + \ l[2].lnum == 700 && l[2].col == 20 && l[2].text ==# 'Line 700' && + \ l[3].lnum == 750 && l[3].col == 25 && l[3].text ==# 'Line 750') + enew! + + " Check for invalid buffer + call assert_fails('Xbuffer 199', 'E474:') + + " Check for unloaded buffer + edit Xtestfile1 + let bnr = bufnr('%') + enew! + call assert_fails('Xbuffer ' . bnr, 'E681:') + + " Check for invalid range + " Using Xbuffer will not run the range check in the cbuffer/lbuffer + " commands. So directly call the commands. + if (a:cchar == 'c') + call assert_fails('900,999cbuffer', 'E16:') + else + call assert_fails('900,999lbuffer', 'E16:') + endif +endfunc + +func Test_cbuffer() + call XbufferTests('c') + call XbufferTests('l') +endfunc + +func XexprTests(cchar) + call s:setup_commands(a:cchar) + + call assert_fails('Xexpr 10', 'E777:') +endfunc + +func Test_cexpr() + call XexprTests('c') + call XexprTests('l') +endfunc + +" Tests for :cnext, :cprev, :cfirst, :clast commands +func Xtest_browse(cchar) + call s:setup_commands(a:cchar) + + call g:Xsetlist([], 'f') + " Jumping to first or next location list entry without any error should + " result in failure + if a:cchar == 'c' + let err = 'E42:' + let cmd = '$cc' + else + let err = 'E776:' + let cmd = '$ll' + endif + call assert_fails('Xnext', err) + call assert_fails('Xprev', err) + call assert_fails('Xnfile', err) + call assert_fails('Xpfile', err) + call assert_fails(cmd, err) + + Xexpr '' + call assert_fails(cmd, 'E42:') + + call s:create_test_file('Xqftestfile1') + call s:create_test_file('Xqftestfile2') + + let lines =<< trim END + Xqftestfile1:5:Line5 + Xqftestfile1:6:Line6 + Xqftestfile2:10:Line10 + Xqftestfile2:11:Line11 + RegularLine1 + RegularLine2 + END + Xgetexpr lines + + Xfirst + call assert_fails('-5Xcc', 'E16:') + call assert_fails('Xprev', 'E553') + call assert_fails('Xpfile', 'E553') + Xnfile + call assert_equal('Xqftestfile2', @%) + call assert_equal(10, line('.')) + Xpfile + call assert_equal('Xqftestfile1', @%) + call assert_equal(6, line('.')) + 5Xcc + call assert_equal(5, g:Xgetlist({'idx':0}).idx) + 2Xcc + call assert_equal(2, g:Xgetlist({'idx':0}).idx) + if a:cchar == 'c' + cc + else + ll + endif + call assert_equal(2, g:Xgetlist({'idx':0}).idx) + 10Xcc + call assert_equal(6, g:Xgetlist({'idx':0}).idx) + Xlast + Xprev + call assert_equal('Xqftestfile2', @%) + call assert_equal(11, line('.')) + call assert_fails('Xnext', 'E553') + call assert_fails('Xnfile', 'E553') + " To process the range using quickfix list entries, directly use the + " quickfix commands (don't use the user defined commands) + if a:cchar == 'c' + $cc + else + $ll + endif + call assert_equal(6, g:Xgetlist({'idx':0}).idx) + Xrewind + call assert_equal('Xqftestfile1', @%) + call assert_equal(5, line('.')) + + 10Xnext + call assert_equal('Xqftestfile2', @%) + call assert_equal(11, line('.')) + 10Xprev + call assert_equal('Xqftestfile1', @%) + call assert_equal(5, line('.')) + + " Jumping to an error from the error window using cc command + let lines =<< trim END + Xqftestfile1:5:Line5 + Xqftestfile1:6:Line6 + Xqftestfile2:10:Line10 + Xqftestfile2:11:Line11 + END + Xgetexpr lines + Xopen + 10Xcc + call assert_equal(11, line('.')) + call assert_equal('Xqftestfile2', @%) + Xopen + call cursor(2, 1) + if a:cchar == 'c' + .cc + else + .ll + endif + call assert_equal(6, line('.')) + call assert_equal('Xqftestfile1', @%) + + " Jumping to an error from the error window (when only the error window is + " present) + Xopen | only + Xlast 1 + call assert_equal(5, line('.')) + call assert_equal('Xqftestfile1', @%) + + Xexpr "" + call assert_fails('Xnext', 'E42:') + + call delete('Xqftestfile1') + call delete('Xqftestfile2') + + " Should be able to use next/prev with invalid entries + Xexpr "" + call assert_equal(0, g:Xgetlist({'idx' : 0}).idx) + call assert_equal(0, g:Xgetlist({'size' : 0}).size) + Xaddexpr ['foo', 'bar', 'baz', 'quux', 'sh|moo'] + call assert_equal(5, g:Xgetlist({'size' : 0}).size) + Xlast + call assert_equal(5, g:Xgetlist({'idx' : 0}).idx) + Xfirst + call assert_equal(1, g:Xgetlist({'idx' : 0}).idx) + 2Xnext + call assert_equal(3, g:Xgetlist({'idx' : 0}).idx) +endfunc + +func Test_browse() + call Xtest_browse('c') + call Xtest_browse('l') +endfunc + +func s:test_xhelpgrep(cchar) + call s:setup_commands(a:cchar) + Xhelpgrep quickfix + Xopen + if a:cchar == 'c' + let title_text = ':helpgrep quickfix' + else + let title_text = ':lhelpgrep quickfix' + endif + call assert_true(w:quickfix_title =~ title_text, w:quickfix_title) + + " Jumping to a help topic should open the help window + only + Xnext + call assert_true(&buftype == 'help') + call assert_true(winnr('$') == 2) + " Jumping to the next match should reuse the help window + Xnext + call assert_true(&buftype == 'help') + call assert_true(winnr() == 1) + call assert_true(winnr('$') == 2) + " Jumping to the next match from the quickfix window should reuse the help + " window + Xopen + Xnext + call assert_true(&buftype == 'help') + call assert_true(winnr() == 1) + call assert_true(winnr('$') == 2) + call assert_match('|\d\+ col \d\+-\d\+|', getbufline(winbufnr(2), 1)[0]) + + " This wipes out the buffer, make sure that doesn't cause trouble. + Xclose + + " When the current window is vertically split, jumping to a help match + " should open the help window at the top. + only | enew + let w1 = win_getid() + vert new + let w2 = win_getid() + Xnext + let w3 = win_getid() + call assert_true(&buftype == 'help') + call assert_true(winnr() == 1) + " See jump_to_help_window() for details + let w2_width = winwidth(w2) + if w2_width != &columns && w2_width < 80 + call assert_equal(['col', [['leaf', w3], + \ ['row', [['leaf', w2], ['leaf', w1]]]]], winlayout()) + else + call assert_equal(['row', [['col', [['leaf', w3], ['leaf', w2]]], + \ ['leaf', w1]]] , winlayout()) + endif + + new | only + set buftype=help + set modified + call assert_fails('Xnext', 'E37:') + set nomodified + new | only + + if a:cchar == 'l' + " When a help window is present, running :lhelpgrep should reuse the + " help window and not the current window + new | only + call g:Xsetlist([], 'f') + help index.txt + wincmd w + lhelpgrep quickfix + call assert_equal(1, winnr()) + call assert_notequal([], getloclist(1)) + call assert_equal([], getloclist(2)) + endif + + new | only + + " Search for non existing help string + call assert_fails('Xhelpgrep a1b2c3', 'E480:') + " Invalid regular expression + call assert_fails('Xhelpgrep \@<!', 'E866:') +endfunc + +func Test_helpgrep() + call s:test_xhelpgrep('c') + helpclose + call s:test_xhelpgrep('l') +endfunc + +" When running the :helpgrep command, if an autocmd modifies the 'cpoptions' +" value, then Vim crashes. (issue fixed by 7.2b-004 and 8.2.4453) +func Test_helpgrep_restore_cpo_aucmd() + let save_cpo = &cpo + augroup QF_Test + au! + autocmd BufNew * set cpo=acd + augroup END + + helpgrep quickfix + call assert_equal('acd', &cpo) + %bw! + + set cpo&vim + augroup QF_Test + au! + autocmd BufReadPost * set cpo= + augroup END + + helpgrep buffer + call assert_equal('', &cpo) + + augroup QF_Test + au! + augroup END + %bw! + let &cpo = save_cpo +endfunc + +func Test_errortitle() + augroup QfBufWinEnter + au! + au BufWinEnter * :let g:a=get(w:, 'quickfix_title', 'NONE') + augroup END + copen + let a=[{'lnum': 308, 'bufnr': bufnr(''), 'col': 58, 'valid': 1, 'vcol': 0, 'nr': 0, 'type': '', 'pattern': '', 'text': ' au BufWinEnter * :let g:a=get(w:, ''quickfix_title'', ''NONE'')'}] + call setqflist(a) + call assert_equal(':setqflist()', g:a) + augroup QfBufWinEnter + au! + augroup END + augroup! QfBufWinEnter +endfunc + +func Test_vimgreptitle() + augroup QfBufWinEnter + au! + au BufWinEnter * :let g:a=get(w:, 'quickfix_title', 'NONE') + augroup END + try + vimgrep /pattern/j file + catch /E480/ + endtry + copen + call assert_equal(': vimgrep /pattern/j file', g:a) + augroup QfBufWinEnter + au! + augroup END + augroup! QfBufWinEnter +endfunc + +func Test_bufwinenter_once() + augroup QfBufWinEnter + au! + au BufWinEnter * let g:got_afile ..= 'got ' .. expand('<afile>') + augroup END + let g:got_afile = '' + copen + call assert_equal('got quickfix', g:got_afile) + + cclose + unlet g:got_afile + augroup QfBufWinEnter + au! + augroup END + augroup! QfBufWinEnter +endfunc + +func XqfTitleTests(cchar) + call s:setup_commands(a:cchar) + + Xgetexpr ['file:1:1:message'] + let l = g:Xgetlist() + if a:cchar == 'c' + call setqflist(l, 'r') + else + call setloclist(0, l, 'r') + endif + + Xopen + if a:cchar == 'c' + let title = ':setqflist()' + else + let title = ':setloclist()' + endif + call assert_equal(title, w:quickfix_title) + Xclose +endfunc + +" Tests for quickfix window's title +func Test_qf_title() + call XqfTitleTests('c') + call XqfTitleTests('l') +endfunc + +" Tests for 'errorformat' +func Test_efm() + let save_efm = &efm + set efm=%EEEE%m,%WWWW%m,%+CCCC%.%#,%-GGGG%.%# + cgetexpr ['WWWW', 'EEEE', 'CCCC'] + let l = strtrans(string(map(getqflist(), '[v:val.text, v:val.valid]'))) + call assert_equal("[['W', 1], ['E^@CCCC', 1]]", l) + cgetexpr ['WWWW', 'GGGG', 'EEEE', 'CCCC'] + let l = strtrans(string(map(getqflist(), '[v:val.text, v:val.valid]'))) + call assert_equal("[['W', 1], ['E^@CCCC', 1]]", l) + cgetexpr ['WWWW', 'GGGG', 'ZZZZ', 'EEEE', 'CCCC', 'YYYY'] + let l = strtrans(string(map(getqflist(), '[v:val.text, v:val.valid]'))) + call assert_equal("[['W', 1], ['ZZZZ', 0], ['E^@CCCC', 1], ['YYYY', 0]]", l) + let &efm = save_efm +endfunc + +" This will test for problems in quickfix: +" A. incorrectly copying location lists which caused the location list to show +" a different name than the file that was actually being displayed. +" B. not reusing the window for which the location list window is opened but +" instead creating new windows. +" C. make sure that the location list window is not reused instead of the +" window it belongs to. +" +" Set up the test environment: +func ReadTestProtocol(name) + let base = substitute(a:name, '\v^test://(.*)%(\.[^.]+)?', '\1', '') + let word = substitute(base, '\v(.*)\..*', '\1', '') + + setl modifiable + setl noreadonly + setl noswapfile + setl bufhidden=delete + %del _ + " For problem 2: + " 'buftype' has to be set to reproduce the constant opening of new windows + setl buftype=nofile + + call setline(1, word) + + setl nomodified + setl nomodifiable + setl readonly + exe 'doautocmd BufRead ' . substitute(a:name, '\v^test://(.*)', '\1', '') +endfunc + +func Test_locationlist() + enew + + augroup testgroup + au! + autocmd BufReadCmd test://* call ReadTestProtocol(expand("<amatch>")) + augroup END + + let words = [ "foo", "bar", "baz", "quux", "shmoo", "spam", "eggs" ] + + let qflist = [] + for word in words + call add(qflist, {'filename': 'test://' . word . '.txt', 'text': 'file ' . word . '.txt', }) + " NOTE: problem 1: + " intentionally not setting 'lnum' so that the quickfix entries are not + " valid + eval qflist->setloclist(0, ' ') + endfor + + " Test A + lrewind + enew + lopen + 4lnext + vert split + wincmd L + lopen + wincmd p + lnext + let fileName = expand("%") + wincmd p + let locationListFileName = substitute(getline(line('.')), '\([^|]*\)|.*', '\1', '') + let fileName = substitute(fileName, '\\', '/', 'g') + let locationListFileName = substitute(locationListFileName, '\\', '/', 'g') + call assert_equal("test://bar.txt", fileName) + call assert_equal("test://bar.txt", locationListFileName) + + wincmd n | only + + " Test B: + lrewind + lopen + 2 + exe "normal \<CR>" + wincmd p + 3 + exe "normal \<CR>" + wincmd p + 4 + exe "normal \<CR>" + call assert_equal(2, winnr('$')) + wincmd n | only + + " Test C: + lrewind + lopen + " Let's move the location list window to the top to check whether it (the + " first window found) will be reused when we try to open new windows: + wincmd K + 2 + exe "normal \<CR>" + wincmd p + 3 + exe "normal \<CR>" + wincmd p + 4 + exe "normal \<CR>" + 1wincmd w + call assert_equal('quickfix', &buftype) + 2wincmd w + let bufferName = expand("%") + let bufferName = substitute(bufferName, '\\', '/', 'g') + call assert_equal('test://quux.txt', bufferName) + + wincmd n | only + + augroup! testgroup +endfunc + +func Test_locationlist_curwin_was_closed() + augroup testgroup + au! + autocmd BufReadCmd test_curwin.txt call R(expand("<amatch>")) + augroup END + + func! R(n) + quit + endfunc + + new + let q = [] + call add(q, {'filename': 'test_curwin.txt' }) + call setloclist(0, q) + call assert_fails('lrewind', 'E924:') + + augroup! testgroup + delfunc R +endfunc + +func Test_locationlist_cross_tab_jump() + call writefile(['loclistfoo'], 'loclistfoo') + call writefile(['loclistbar'], 'loclistbar') + set switchbuf=usetab + + edit loclistfoo + tabedit loclistbar + silent lgrep loclistfoo loclist* + call assert_equal(1, tabpagenr()) + + enew | only | tabonly + set switchbuf&vim + call delete('loclistfoo') + call delete('loclistbar') +endfunc + +" More tests for 'errorformat' +func Test_efm1() + if !has('unix') + " The 'errorformat' setting is different on non-Unix systems. + " This test works only on Unix-like systems. + return + endif + + let l =<< trim [DATA] + "Xtestfile", line 4.12: 1506-045 (S) Undeclared identifier fd_set. + "Xtestfile", line 6 col 19; this is an error + gcc -c -DHAVE_CONFIsing-prototypes -I/usr/X11R6/include version.c + Xtestfile:9: parse error before `asd' + make: *** [src/vim/testdir/Makefile:100: test_quickfix] Error 1 + in file "Xtestfile" linenr 10: there is an error + + 2 returned + "Xtestfile", line 11 col 1; this is an error + "Xtestfile", line 12 col 2; this is another error + "Xtestfile", line 14:10; this is an error in column 10 + =Xtestfile=, line 15:10; this is another error, but in vcol 10 this time + "Xtestfile", linenr 16: yet another problem + Error in "Xtestfile" at line 17: + x should be a dot + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 17 + ^ + Error in "Xtestfile" at line 18: + x should be a dot + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 18 + .............^ + Error in "Xtestfile" at line 19: + x should be a dot + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 19 + --------------^ + Error in "Xtestfile" at line 20: + x should be a dot + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 20 + ^ + + Does anyone know what is the problem and how to correction it? + "Xtestfile", line 21 col 9: What is the title of the quickfix window? + "Xtestfile", line 22 col 9: What is the title of the quickfix window? + [DATA] + + call writefile(l, 'Xerrorfile1') + call writefile(l[:-2], 'Xerrorfile2') + + let m =<< [DATA] + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 2 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 3 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 4 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 5 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 6 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 7 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 8 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 9 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 10 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 11 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 12 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 13 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 14 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 15 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 16 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 17 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 18 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 19 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 20 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 21 + xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx line 22 +[DATA] + call writefile(m, 'Xtestfile') + + let save_efm = &efm + set efm+==%f=\\,\ line\ %l%*\\D%v%*[^\ ]\ %m + set efm^=%AError\ in\ \"%f\"\ at\ line\ %l:,%Z%p^,%C%m + + exe 'cf Xerrorfile2' + clast + copen + call assert_equal(':cf Xerrorfile2', w:quickfix_title) + wincmd p + + exe 'cf Xerrorfile1' + call assert_equal([4, 12], [line('.'), col('.')]) + cn + call assert_equal([6, 19], [line('.'), col('.')]) + cn + call assert_equal([9, 2], [line('.'), col('.')]) + cn + call assert_equal([10, 2], [line('.'), col('.')]) + cn + call assert_equal([11, 1], [line('.'), col('.')]) + cn + call assert_equal([12, 2], [line('.'), col('.')]) + cn + call assert_equal([14, 10], [line('.'), col('.')]) + cn + call assert_equal([15, 3, 10], [line('.'), col('.'), virtcol('.')]) + cn + call assert_equal([16, 2], [line('.'), col('.')]) + cn + call assert_equal([17, 6], [line('.'), col('.')]) + cn + call assert_equal([18, 7], [line('.'), col('.')]) + cn + call assert_equal([19, 8], [line('.'), col('.')]) + cn + call assert_equal([20, 9], [line('.'), col('.')]) + clast + cprev + cprev + wincmd w + call assert_equal(':cf Xerrorfile1', w:quickfix_title) + wincmd p + + let &efm = save_efm + call delete('Xerrorfile1') + call delete('Xerrorfile2') + call delete('Xtestfile') +endfunc + +" Test for quickfix directory stack support +func s:dir_stack_tests(cchar) + call s:setup_commands(a:cchar) + + let save_efm=&efm + set efm=%DEntering\ dir\ '%f',%f:%l:%m,%XLeaving\ dir\ '%f' + + let lines =<< trim END + Entering dir 'dir1/a' + habits2.txt:1:Nine Healthy Habits + Entering dir 'b' + habits3.txt:2:0 Hours of television + habits2.txt:7:5 Small meals + Entering dir 'dir1/c' + habits4.txt:3:1 Hour of exercise + Leaving dir 'dir1/c' + Leaving dir 'dir1/a' + habits1.txt:4:2 Liters of water + Entering dir 'dir2' + habits5.txt:5:3 Cups of hot green tea + Leaving dir 'dir2' + END + + Xexpr "" + for l in lines + Xaddexpr l + endfor + + let qf = g:Xgetlist() + + call assert_equal('dir1/a/habits2.txt', bufname(qf[1].bufnr)) + call assert_equal(1, qf[1].lnum) + call assert_equal('dir1/a/b/habits3.txt', bufname(qf[3].bufnr)) + call assert_equal(2, qf[3].lnum) + call assert_equal('dir1/a/habits2.txt', bufname(qf[4].bufnr)) + call assert_equal(7, qf[4].lnum) + call assert_equal('dir1/c/habits4.txt', bufname(qf[6].bufnr)) + call assert_equal(3, qf[6].lnum) + call assert_equal('habits1.txt', bufname(qf[9].bufnr)) + call assert_equal(4, qf[9].lnum) + call assert_equal('dir2/habits5.txt', bufname(qf[11].bufnr)) + call assert_equal(5, qf[11].lnum) + + let &efm=save_efm +endfunc + +" Tests for %D and %X errorformat options +func Test_efm_dirstack() + " Create the directory stack and files + call mkdir('dir1') + call mkdir('dir1/a') + call mkdir('dir1/a/b') + call mkdir('dir1/c') + call mkdir('dir2') + + let lines =<< trim END + Nine Healthy Habits + 0 Hours of television + 1 Hour of exercise + 2 Liters of water + 3 Cups of hot green tea + 4 Short mental breaks + 5 Small meals + 6 AM wake up time + 7 Minutes of laughter + 8 Hours of sleep (at least) + 9 PM end of the day and off to bed + END + call writefile(lines, 'habits1.txt') + call writefile(lines, 'dir1/a/habits2.txt') + call writefile(lines, 'dir1/a/b/habits3.txt') + call writefile(lines, 'dir1/c/habits4.txt') + call writefile(lines, 'dir2/habits5.txt') + + call s:dir_stack_tests('c') + call s:dir_stack_tests('l') + + call delete('dir1', 'rf') + call delete('dir2', 'rf') + call delete('habits1.txt') +endfunc + +" Test for resync after continuing an ignored message +func Xefm_ignore_continuations(cchar) + call s:setup_commands(a:cchar) + + let save_efm = &efm + + let &efm = + \ '%Eerror %m %l,' . + \ '%-Wignored %m %l,' . + \ '%+Cmore ignored %m %l,' . + \ '%Zignored end' + let lines =<< trim END + ignored warning 1 + more ignored continuation 2 + ignored end + error resync 4 + END + Xgetexpr lines + let l = map(g:Xgetlist(), '[v:val.text, v:val.valid, v:val.lnum, v:val.type]') + call assert_equal([['resync', 1, 4, 'E']], l) + + let &efm = save_efm +endfunc + +func Test_efm_ignore_continuations() + call Xefm_ignore_continuations('c') + call Xefm_ignore_continuations('l') +endfunc + +" Tests for invalid error format specifies +func Xinvalid_efm_Tests(cchar) + call s:setup_commands(a:cchar) + + let save_efm = &efm + + set efm=%f:%l:%m,%f:%f:%l:%m + call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E372:') + + set efm=%f:%l:%m,%f:%l:%r:%m + call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E373:') + + set efm=%f:%l:%m,%O:%f:%l:%m + call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E373:') + + set efm=%f:%l:%m,%f:%l:%*[^a-z + call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E374:') + + set efm=%f:%l:%m,%f:%l:%*c + call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E375:') + + set efm=%f:%l:%m,%L%M%N + call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E376:') + + set efm=%f:%l:%m,%f:%l:%m:%R + call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E377:') + + " Invalid regular expression + set efm=%\\%%k + call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E867:') + + set efm= + call assert_fails('Xexpr "abc.txt:1:Hello world"', 'E378:') + + " Empty directory name. When there is an error in parsing new entries, make + " sure the previous quickfix list is made the current list. + set efm& + cexpr ["one", "two"] + let qf_id = getqflist(#{id: 0}).id + set efm=%DEntering\ dir\ abc,%f:%l:%m + call assert_fails('Xexpr ["Entering dir abc", "abc.txt:1:Hello world"]', 'E379:') + call assert_equal(qf_id, getqflist(#{id: 0}).id) + + let &efm = save_efm +endfunc + +func Test_invalid_efm() + call Xinvalid_efm_Tests('c') + call Xinvalid_efm_Tests('l') +endfunc + +" TODO: +" Add tests for the following formats in 'errorformat' +" %r %O +func Test_efm2() + let save_efm = &efm + + " Test for %s format in efm + set efm=%f:%s + cexpr 'Xtestfile:Line search text' + let l = getqflist() + call assert_equal('^\VLine search text\$', l[0].pattern) + call assert_equal(0, l[0].lnum) + + let l = split(execute('clist', ''), "\n") + call assert_equal([' 1 Xtestfile:^\VLine search text\$: '], l) + + " Test for a long line + cexpr 'Xtestfile:' . repeat('a', 1026) + let l = getqflist() + call assert_equal('^\V' . repeat('a', 1019) . '\$', l[0].pattern) + + " Test for %P, %Q and %t format specifiers + let lines =<< trim [DATA] + [Xtestfile1] + (1,17) error: ';' missing + (21,2) warning: variable 'z' not defined + (67,3) error: end of file found before string ended + -- + + [Xtestfile2] + -- + + [Xtestfile3] + NEW compiler v1.1 + (2,2) warning: variable 'x' not defined + (67,3) warning: 's' already defined + -- + [DATA] + + set efm=%+P[%f]%r,(%l\\,%c)%*[\ ]%t%*[^:]:\ %m,%+Q--%r + " To exercise the push/pop file functionality in quickfix, the test files + " need to be created. + call writefile(['Line1'], 'Xtestfile1') + call writefile(['Line2'], 'Xtestfile2') + call writefile(['Line3'], 'Xtestfile3') + cexpr "" + for l in lines + caddexpr l + endfor + let l = getqflist() + call assert_equal(12, len(l)) + call assert_equal(21, l[2].lnum) + call assert_equal(2, l[2].col) + call assert_equal('w', l[2].type) + call assert_equal('e', l[3].type) + call delete('Xtestfile1') + call delete('Xtestfile2') + call delete('Xtestfile3') + + " Test for %P, %Q with non-existing files + cexpr lines + let l = getqflist() + call assert_equal(14, len(l)) + call assert_equal('[Xtestfile1]', l[0].text) + call assert_equal('[Xtestfile2]', l[6].text) + call assert_equal('[Xtestfile3]', l[9].text) + + " Tests for %E, %C and %Z format specifiers + let lines =<< trim [DATA] + Error 275 + line 42 + column 3 + ' ' expected after '--' + [DATA] + + set efm=%EError\ %n,%Cline\ %l,%Ccolumn\ %c,%Z%m + cgetexpr lines + let l = getqflist() + call assert_equal(275, l[0].nr) + call assert_equal(42, l[0].lnum) + call assert_equal(3, l[0].col) + call assert_equal('E', l[0].type) + call assert_equal("\n' ' expected after '--'", l[0].text) + + " Test for %> + let lines =<< trim [DATA] + Error in line 147 of foo.c: + unknown variable 'i' + [DATA] + + set efm=unknown\ variable\ %m,%E%>Error\ in\ line\ %l\ of\ %f:,%Z%m + cgetexpr lines + let l = getqflist() + call assert_equal(147, l[0].lnum) + call assert_equal('E', l[0].type) + call assert_equal("\nunknown variable 'i'", l[0].text) + + " Test for %A, %C and other formats + let lines =<< trim [DATA] + ============================================================== + FAIL: testGetTypeIdCachesResult (dbfacadeTest.DjsDBFacadeTest) + -------------------------------------------------------------- + Traceback (most recent call last): + File "unittests/dbfacadeTest.py", line 89, in testFoo + self.assertEquals(34, dtid) + File "/usr/lib/python2.2/unittest.py", line 286, in + failUnlessEqual + raise self.failureException, \\ + W:AssertionError: 34 != 33 + + -------------------------------------------------------------- + Ran 27 tests in 0.063s + [DATA] + + set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%t:%m + cgetexpr lines + let l = getqflist() + call assert_equal(8, len(l)) + call assert_equal(89, l[4].lnum) + call assert_equal(1, l[4].valid) + call assert_equal('unittests/dbfacadeTest.py', bufname(l[4].bufnr)) + call assert_equal('W', l[4].type) + + " Test for %o + set efm=%f(%o):%l\ %m + cgetexpr ['Xotestfile(Language.PureScript.Types):20 Error'] + call writefile(['Line1'], 'Xotestfile') + let l = getqflist() + call assert_equal(1, len(l), string(l)) + call assert_equal('Language.PureScript.Types', l[0].module) + copen + call assert_equal('Language.PureScript.Types|20| Error', getline(1)) + call feedkeys("\<CR>", 'xn') + call assert_equal('Xotestfile', expand('%:t')) + cclose + bd + call delete("Xotestfile") + + " Test for a long module name + cexpr 'Xtest(' . repeat('m', 1026) . '):15 message' + let l = getqflist() + " call assert_equal(repeat('m', 1024), l[0].module) + call assert_equal(repeat('m', 1023), l[0].module) + call assert_equal(15, l[0].lnum) + call assert_equal('message', l[0].text) + + " The following sequence of commands used to crash Vim + set efm=%W%m + cgetexpr ['msg1'] + let l = getqflist() + call assert_equal(1, len(l), string(l)) + call assert_equal('msg1', l[0].text) + set efm=%C%m + lexpr 'msg2' + let l = getloclist(0) + call assert_equal(1, len(l), string(l)) + call assert_equal('msg2', l[0].text) + lopen + call setqflist([], 'r') + caddbuf + let l = getqflist() + call assert_equal(1, len(l), string(l)) + call assert_equal('|| msg2', l[0].text) + + " When matching error lines, case should be ignored. Test for this. + set noignorecase + let l=getqflist({'lines' : ['Xtest:FOO10:Line 20'], 'efm':'%f:foo%l:%m'}) + call assert_equal(10, l.items[0].lnum) + call assert_equal('Line 20', l.items[0].text) + set ignorecase& + + new | only + let &efm = save_efm +endfunc + +" Test for '%t' (error type) field in 'efm' +func Test_efm_error_type() + let save_efm = &efm + + " error type + set efm=%f:%l:%t:%m + let lines =<< trim END + Xfile1:10:E:msg1 + Xfile1:20:W:msg2 + Xfile1:30:I:msg3 + Xfile1:40:N:msg4 + Xfile1:50:R:msg5 + END + cexpr lines + let output = split(execute('clist'), "\n") + call assert_equal([ + \ ' 1 Xfile1:10 error: msg1', + \ ' 2 Xfile1:20 warning: msg2', + \ ' 3 Xfile1:30 info: msg3', + \ ' 4 Xfile1:40 note: msg4', + \ ' 5 Xfile1:50 R: msg5'], output) + + " error type and a error number + set efm=%f:%l:%t:%n:%m + let lines =<< trim END + Xfile1:10:E:2:msg1 + Xfile1:20:W:4:msg2 + Xfile1:30:I:6:msg3 + Xfile1:40:N:8:msg4 + Xfile1:50:R:3:msg5 + END + cexpr lines + let output = split(execute('clist'), "\n") + call assert_equal([ + \ ' 1 Xfile1:10 error 2: msg1', + \ ' 2 Xfile1:20 warning 4: msg2', + \ ' 3 Xfile1:30 info 6: msg3', + \ ' 4 Xfile1:40 note 8: msg4', + \ ' 5 Xfile1:50 R 3: msg5'], output) + let &efm = save_efm +endfunc + +" Test for end_lnum ('%e') and end_col ('%k') fields in 'efm' +func Test_efm_end_lnum_col() + let save_efm = &efm + + " single line + set efm=%f:%l-%e:%c-%k:%t:%m + cexpr ["Xfile1:10-20:1-2:E:msg1", "Xfile1:20-30:2-3:W:msg2",] + let output = split(execute('clist'), "\n") + call assert_equal([ + \ ' 1 Xfile1:10-20 col 1-2 error: msg1', + \ ' 2 Xfile1:20-30 col 2-3 warning: msg2'], output) + + " multiple lines + set efm=%A%n)%m,%Z%f:%l-%e:%c-%k + let lines =<< trim END + 1)msg1 + Xfile1:14-24:1-2 + 2)msg2 + Xfile1:24-34:3-4 + END + cexpr lines + let output = split(execute('clist'), "\n") + call assert_equal([ + \ ' 1 Xfile1:14-24 col 1-2 error 1: msg1', + \ ' 2 Xfile1:24-34 col 3-4 error 2: msg2'], output) + let &efm = save_efm +endfunc + +func XquickfixChangedByAutocmd(cchar) + call s:setup_commands(a:cchar) + if a:cchar == 'c' + let ErrorNr = 'E925' + func! ReadFunc() + colder + cgetexpr [] + endfunc + else + let ErrorNr = 'E926' + func! ReadFunc() + lolder + lgetexpr [] + endfunc + endif + + augroup QF_Test + au! + autocmd BufReadCmd test_changed.txt call ReadFunc() + augroup END + + new | only + let words = [ "a", "b" ] + let qflist = [] + for word in words + call add(qflist, {'filename': 'test_changed.txt'}) + call g:Xsetlist(qflist, ' ') + endfor + call assert_fails('Xrewind', ErrorNr . ':') + + augroup QF_Test + au! + augroup END + + if a:cchar == 'c' + cexpr ["Xtest1:1:Line"] + cwindow + only + augroup QF_Test + au! + autocmd WinEnter * call setqflist([], 'f') + augroup END + call assert_fails('exe "normal \<CR>"', 'E925:') + augroup QF_Test + au! + augroup END + endif + %bw! +endfunc + +func Test_quickfix_was_changed_by_autocmd() + call XquickfixChangedByAutocmd('c') + call XquickfixChangedByAutocmd('l') +endfunc + +func Test_setloclist_in_autocommand() + call writefile(['test1', 'test2'], 'Xfile') + edit Xfile + let s:bufnr = bufnr() + call setloclist(1, + \ [{'bufnr' : s:bufnr, 'lnum' : 1, 'text' : 'test1'}, + \ {'bufnr' : s:bufnr, 'lnum' : 2, 'text' : 'test2'}]) + + augroup Test_LocList + au! + autocmd BufEnter * call setloclist(1, + \ [{'bufnr' : s:bufnr, 'lnum' : 1, 'text' : 'test1'}, + \ {'bufnr' : s:bufnr, 'lnum' : 2, 'text' : 'test2'}], 'r') + augroup END + + lopen + call assert_fails('exe "normal j\<CR>"', 'E926:') + + augroup Test_LocList + au! + augroup END + call delete('Xfile') +endfunc + +func Test_caddbuffer_to_empty() + helpgr quickfix + call setqflist([], 'r') + cad + try + cn + catch + " number of matches is unknown + call assert_true(v:exception =~ 'E553:') + endtry + quit! +endfunc + +func Test_cgetexpr_works() + " this must not crash Vim + cgetexpr [$x] + lgetexpr [$x] +endfunc + +" Tests for the setqflist() and setloclist() functions +func SetXlistTests(cchar, bnum) + call s:setup_commands(a:cchar) + + call g:Xsetlist([{'bufnr': a:bnum, 'lnum': 1}, + \ {'bufnr': a:bnum, 'lnum': 2, 'end_lnum': 3, 'col': 4, 'end_col': 5, 'user_data': {'6': [7, 8]}}]) + let l = g:Xgetlist() + call assert_equal(2, len(l)) + call assert_equal(2, l[1].lnum) + call assert_equal(3, l[1].end_lnum) + call assert_equal(4, l[1].col) + call assert_equal(5, l[1].end_col) + call assert_equal({'6': [7, 8]}, l[1].user_data) + + " Test that user_data is garbage collected + call g:Xsetlist([{'user_data': ['high', 5]}, + \ {'user_data': {'this': [7, 'eight'], 'is': ['a', 'dictionary']}}]) + call test_garbagecollect_now() + let l = g:Xgetlist() + call assert_equal(2, len(l)) + call assert_equal(['high', 5], l[0].user_data) + call assert_equal({'this': [7, 'eight'], 'is': ['a', 'dictionary']}, l[1].user_data) + + Xnext + call g:Xsetlist([{'bufnr': a:bnum, 'lnum': 3}], 'a') + let l = g:Xgetlist() + call assert_equal(3, len(l)) + Xnext + call assert_equal(3, line('.')) + + " Appending entries to the list should not change the cursor position + " in the quickfix window + Xwindow + 1 + call g:Xsetlist([{'bufnr': a:bnum, 'lnum': 4}, + \ {'bufnr': a:bnum, 'lnum': 5}], 'a') + call assert_equal(1, line('.')) + close + + call g:Xsetlist([{'bufnr': a:bnum, 'lnum': 3}, + \ {'bufnr': a:bnum, 'lnum': 4}, + \ {'bufnr': a:bnum, 'lnum': 5}], 'r') + let l = g:Xgetlist() + call assert_equal(3, len(l)) + call assert_equal(5, l[2].lnum) + + call g:Xsetlist([]) + let l = g:Xgetlist() + call assert_equal(0, len(l)) + + " Tests for setting the 'valid' flag + call g:Xsetlist([{'bufnr':a:bnum, 'lnum':4, 'valid':0}]) + Xwindow + call assert_equal(1, winnr('$')) + let l = g:Xgetlist() + call g:Xsetlist(l) + call assert_equal(0, g:Xgetlist()[0].valid) + " Adding a non-valid entry should not mark the list as having valid entries + call g:Xsetlist([{'bufnr':a:bnum, 'lnum':5, 'valid':0}], 'a') + Xwindow + call assert_equal(1, winnr('$')) + + " :cnext/:cprev should still work even with invalid entries in the list + let l = [{'bufnr' : a:bnum, 'lnum' : 1, 'text' : '1', 'valid' : 0}, + \ {'bufnr' : a:bnum, 'lnum' : 2, 'text' : '2', 'valid' : 0}] + call g:Xsetlist(l) + Xnext + call assert_equal(2, g:Xgetlist({'idx' : 0}).idx) + Xprev + call assert_equal(1, g:Xgetlist({'idx' : 0}).idx) + " :cnext/:cprev should still work after appending invalid entries to an + " empty list + call g:Xsetlist([]) + call g:Xsetlist(l, 'a') + Xnext + call assert_equal(2, g:Xgetlist({'idx' : 0}).idx) + Xprev + call assert_equal(1, g:Xgetlist({'idx' : 0}).idx) + + call g:Xsetlist([{'text':'Text1', 'valid':1}]) + Xwindow + call assert_equal(2, winnr('$')) + Xclose + let save_efm = &efm + set efm=%m + Xgetexpr 'TestMessage' + let l = g:Xgetlist() + call g:Xsetlist(l) + call assert_equal(1, g:Xgetlist()[0].valid) + let &efm = save_efm + + " Error cases: + " Refer to a non-existing buffer and pass a non-dictionary type + call assert_fails("call g:Xsetlist([{'bufnr':998, 'lnum':4}," . + \ " {'bufnr':999, 'lnum':5}])", 'E92:') + call g:Xsetlist([[1, 2,3]]) + call assert_equal(0, len(g:Xgetlist())) + call assert_fails('call g:Xsetlist([], [])', 'E928:') + call g:Xsetlist([v:_null_dict]) + call assert_equal([], g:Xgetlist()) +endfunc + +func Test_setqflist() + new Xtestfile | only + let bnum = bufnr('%') + call setline(1, range(1,5)) + + call SetXlistTests('c', bnum) + call SetXlistTests('l', bnum) + + enew! + call delete('Xtestfile') +endfunc + +func Xlist_empty_middle(cchar) + call s:setup_commands(a:cchar) + + " create three quickfix lists + let @/ = 'Test_' + Xvimgrep // test_quickfix.vim + let testlen = len(g:Xgetlist()) + call assert_true(testlen > 0) + Xvimgrep empty test_quickfix.vim + call assert_true(len(g:Xgetlist()) > 0) + Xvimgrep matches test_quickfix.vim + let matchlen = len(g:Xgetlist()) + call assert_true(matchlen > 0) + Xolder + " make the middle list empty + call g:Xsetlist([], 'r') + call assert_true(len(g:Xgetlist()) == 0) + Xolder + call assert_equal(testlen, len(g:Xgetlist())) + Xnewer + Xnewer + call assert_equal(matchlen, len(g:Xgetlist())) +endfunc + +func Test_setqflist_empty_middle() + call Xlist_empty_middle('c') + call Xlist_empty_middle('l') +endfunc + +func Xlist_empty_older(cchar) + call s:setup_commands(a:cchar) + + " create three quickfix lists + Xvimgrep one test_quickfix.vim + let onelen = len(g:Xgetlist()) + call assert_true(onelen > 0) + Xvimgrep two test_quickfix.vim + let twolen = len(g:Xgetlist()) + call assert_true(twolen > 0) + Xvimgrep three test_quickfix.vim + let threelen = len(g:Xgetlist()) + call assert_true(threelen > 0) + Xolder 2 + " make the first list empty, check the others didn't change + call g:Xsetlist([], 'r') + call assert_true(len(g:Xgetlist()) == 0) + Xnewer + call assert_equal(twolen, len(g:Xgetlist())) + Xnewer + call assert_equal(threelen, len(g:Xgetlist())) +endfunc + +func Test_setqflist_empty_older() + call Xlist_empty_older('c') + call Xlist_empty_older('l') +endfunc + +func XquickfixSetListWithAct(cchar) + call s:setup_commands(a:cchar) + + let list1 = [{'filename': 'fnameA', 'text': 'A'}, + \ {'filename': 'fnameB', 'text': 'B'}] + let list2 = [{'filename': 'fnameC', 'text': 'C'}, + \ {'filename': 'fnameD', 'text': 'D'}, + \ {'filename': 'fnameE', 'text': 'E'}] + + " {action} is unspecified. Same as specifying ' '. + new | only + silent! Xnewer 99 + call g:Xsetlist(list1) + call g:Xsetlist(list2) + let li = g:Xgetlist() + call assert_equal(3, len(li)) + call assert_equal('C', li[0]['text']) + call assert_equal('D', li[1]['text']) + call assert_equal('E', li[2]['text']) + silent! Xolder + let li = g:Xgetlist() + call assert_equal(2, len(li)) + call assert_equal('A', li[0]['text']) + call assert_equal('B', li[1]['text']) + + " {action} is specified ' '. + new | only + silent! Xnewer 99 + call g:Xsetlist(list1) + call g:Xsetlist(list2, ' ') + let li = g:Xgetlist() + call assert_equal(3, len(li)) + call assert_equal('C', li[0]['text']) + call assert_equal('D', li[1]['text']) + call assert_equal('E', li[2]['text']) + silent! Xolder + let li = g:Xgetlist() + call assert_equal(2, len(li)) + call assert_equal('A', li[0]['text']) + call assert_equal('B', li[1]['text']) + + " {action} is specified 'a'. + new | only + silent! Xnewer 99 + call g:Xsetlist(list1) + call g:Xsetlist(list2, 'a') + let li = g:Xgetlist() + call assert_equal(5, len(li)) + call assert_equal('A', li[0]['text']) + call assert_equal('B', li[1]['text']) + call assert_equal('C', li[2]['text']) + call assert_equal('D', li[3]['text']) + call assert_equal('E', li[4]['text']) + + " {action} is specified 'r'. + new | only + silent! Xnewer 99 + call g:Xsetlist(list1) + call g:Xsetlist(list2, 'r') + let li = g:Xgetlist() + call assert_equal(3, len(li)) + call assert_equal('C', li[0]['text']) + call assert_equal('D', li[1]['text']) + call assert_equal('E', li[2]['text']) + + " Test for wrong value. + new | only + call assert_fails("call g:Xsetlist(0)", 'E714:') + call assert_fails("call g:Xsetlist(list1, '')", 'E927:') + call assert_fails("call g:Xsetlist(list1, 'aa')", 'E927:') + call assert_fails("call g:Xsetlist(list1, ' a')", 'E927:') + call assert_fails("call g:Xsetlist(list1, 0)", 'E928:') +endfunc + +func Test_setqflist_invalid_nr() + " The following command used to crash Vim + eval []->setqflist(' ', {'nr' : $XXX_DOES_NOT_EXIST}) +endfunc + +func Test_setqflist_user_sets_buftype() + call setqflist([{'text': 'foo'}, {'text': 'bar'}]) + set buftype=quickfix + call setqflist([], 'a') + enew +endfunc + +func Test_quickfix_set_list_with_act() + call XquickfixSetListWithAct('c') + call XquickfixSetListWithAct('l') +endfunc + +func XLongLinesTests(cchar) + let l = g:Xgetlist() + + call assert_equal(4, len(l)) + call assert_equal(1, l[0].lnum) + call assert_equal(1, l[0].col) + call assert_equal(1975, len(l[0].text)) + call assert_equal(2, l[1].lnum) + call assert_equal(1, l[1].col) + call assert_equal(4070, len(l[1].text)) + call assert_equal(3, l[2].lnum) + call assert_equal(1, l[2].col) + call assert_equal(4070, len(l[2].text)) + call assert_equal(4, l[3].lnum) + call assert_equal(1, l[3].col) + call assert_equal(10, len(l[3].text)) + + call g:Xsetlist([], 'r') +endfunc + +func s:long_lines_tests(cchar) + call s:setup_commands(a:cchar) + + let testfile = 'samples/quickfix.txt' + + " file + exe 'Xgetfile' testfile + call XLongLinesTests(a:cchar) + + " list + Xexpr readfile(testfile) + call XLongLinesTests(a:cchar) + + " string + Xexpr join(readfile(testfile), "\n") + call XLongLinesTests(a:cchar) + + " buffer + exe 'edit' testfile + exe 'Xbuffer' bufnr('%') + call XLongLinesTests(a:cchar) +endfunc + +func Test_long_lines() + call s:long_lines_tests('c') + call s:long_lines_tests('l') +endfunc + +func Test_cgetfile_on_long_lines() + " Problematic values if the line is longer than 4096 bytes. Then 1024 bytes + " are read at a time. + for len in [4078, 4079, 4080, 5102, 5103, 5104, 6126, 6127, 6128, 7150, 7151, 7152] + let lines =<< trim END + /tmp/file1:1:1:aaa + /tmp/file2:1:1:%s + /tmp/file3:1:1:bbb + /tmp/file4:1:1:ccc + END + let lines[1] = substitute(lines[1], '%s', repeat('x', len), '') + call writefile(lines, 'Xcqetfile.txt') + cgetfile Xcqetfile.txt + call assert_equal(4, getqflist(#{size: v:true}).size, 'with length ' .. len) + endfor + call delete('Xcqetfile.txt') +endfunc + +func s:create_test_file(filename) + let l = [] + for i in range(1, 20) + call add(l, 'Line' . i) + endfor + call writefile(l, a:filename) +endfunc + +func Test_switchbuf() + call s:create_test_file('Xqftestfile1') + call s:create_test_file('Xqftestfile2') + call s:create_test_file('Xqftestfile3') + + new | only + edit Xqftestfile1 + let file1_winid = win_getid() + new Xqftestfile2 + let file2_winid = win_getid() + let lines =<< trim END + Xqftestfile1:5:Line5 + Xqftestfile1:6:Line6 + Xqftestfile2:10:Line10 + Xqftestfile2:11:Line11 + Xqftestfile3:15:Line15 + Xqftestfile3:16:Line16 + END + cgetexpr lines + + new + let winid = win_getid() + cfirst | cnext + call assert_equal(winid, win_getid()) + 2cnext + call assert_equal(winid, win_getid()) + 2cnext + call assert_equal(winid, win_getid()) + + " Test for 'switchbuf' set to search for files in windows in the current + " tabpage and jump to an existing window (if present) + set switchbuf=useopen + enew + cfirst | cnext + call assert_equal(file1_winid, win_getid()) + 2cnext + call assert_equal(file2_winid, win_getid()) + 2cnext + call assert_equal(file2_winid, win_getid()) + + " Test for 'switchbuf' set to search for files in tabpages and jump to an + " existing tabpage (if present) + enew | only + set switchbuf=usetab + tabedit Xqftestfile1 + tabedit Xqftestfile2 + tabedit Xqftestfile3 + tabfirst + cfirst | cnext + call assert_equal(2, tabpagenr()) + 2cnext + call assert_equal(3, tabpagenr()) + 6cnext + call assert_equal(4, tabpagenr()) + 2cpfile + call assert_equal(2, tabpagenr()) + 2cnfile + call assert_equal(4, tabpagenr()) + tabfirst | tabonly | enew + + " Test for 'switchbuf' set to open a new window for every file + set switchbuf=split + cfirst | cnext + call assert_equal(1, winnr('$')) + cnext | cnext + call assert_equal(2, winnr('$')) + cnext | cnext + call assert_equal(3, winnr('$')) + + " Test for 'switchbuf' set to open a new tabpage for every file + set switchbuf=newtab + enew | only + cfirst | cnext + call assert_equal(1, tabpagenr('$')) + cnext | cnext + call assert_equal(2, tabpagenr('$')) + cnext | cnext + call assert_equal(3, tabpagenr('$')) + tabfirst | enew | tabonly | only + + set switchbuf=uselast + split + let last_winid = win_getid() + copen + exe "normal 1G\<CR>" + call assert_equal(last_winid, win_getid()) + enew | only + + " With an empty 'switchbuf', jumping to a quickfix entry should open the + " file in an existing window (if present) + set switchbuf= + edit Xqftestfile1 + let file1_winid = win_getid() + new Xqftestfile2 + let file2_winid = win_getid() + copen + exe "normal 1G\<CR>" + call assert_equal(file1_winid, win_getid()) + copen + exe "normal 3G\<CR>" + call assert_equal(file2_winid, win_getid()) + copen | only + exe "normal 5G\<CR>" + call assert_equal(2, winnr('$')) + call assert_equal(1, bufwinnr('Xqftestfile3')) + + " If only quickfix window is open in the current tabpage, jumping to an + " entry with 'switchbuf' set to 'usetab' should search in other tabpages. + enew | only + set switchbuf=usetab + tabedit Xqftestfile1 + tabedit Xqftestfile2 + tabedit Xqftestfile3 + tabfirst + copen | only + clast + call assert_equal(4, tabpagenr()) + tabfirst | tabonly | enew | only + + " Jumping to a file that is not present in any of the tabpages and the + " current tabpage doesn't have any usable windows, should open it in a new + " window in the current tabpage. + copen | only + cfirst + call assert_equal(1, tabpagenr()) + call assert_equal('Xqftestfile1', @%) + + " If opening a file changes 'switchbuf', then the new value should be + " retained. + set modeline&vim + call writefile(["vim: switchbuf=split"], 'Xqftestfile1') + enew | only + set switchbuf&vim + cexpr "Xqftestfile1:1:10" + call assert_equal('split', &switchbuf) + call writefile(["vim: switchbuf=usetab"], 'Xqftestfile1') + enew | only + set switchbuf=useopen + cexpr "Xqftestfile1:1:10" + call assert_equal('usetab', &switchbuf) + call writefile(["vim: switchbuf&vim"], 'Xqftestfile1') + enew | only + set switchbuf=useopen + cexpr "Xqftestfile1:1:10" + call assert_equal('uselast', &switchbuf) + + call delete('Xqftestfile1') + call delete('Xqftestfile2') + call delete('Xqftestfile3') + set switchbuf&vim + + enew | only +endfunc + +func Xadjust_qflnum(cchar) + call s:setup_commands(a:cchar) + + enew | only + + let fname = 'Xqftestfile' . a:cchar + call s:create_test_file(fname) + exe 'edit ' . fname + + Xgetexpr [fname . ':5:Line5', + \ fname . ':10:Line10', + \ fname . ':15:Line15', + \ fname . ':20:Line20'] + + 6,14delete + call append(6, ['Buffer', 'Window']) + + let l = g:Xgetlist() + call assert_equal(5, l[0].lnum) + call assert_equal(6, l[2].lnum) + call assert_equal(13, l[3].lnum) + + " If a file doesn't have any quickfix entries, then deleting lines in the + " file should not update the quickfix list + call g:Xsetlist([], 'f') + 1,2delete + call assert_equal([], g:Xgetlist()) + + enew! + call delete(fname) +endfunc + +func Test_adjust_lnum() + call setloclist(0, []) + call Xadjust_qflnum('c') + call setqflist([]) + call Xadjust_qflnum('l') +endfunc + +" Tests for the :grep/:lgrep and :grepadd/:lgrepadd commands +func s:test_xgrep(cchar) + call s:setup_commands(a:cchar) + + " The following lines are used for the grep test. Don't remove. + " Grep_Test_Text: Match 1 + " Grep_Test_Text: Match 2 + " GrepAdd_Test_Text: Match 1 + " GrepAdd_Test_Text: Match 2 + enew! | only + set makeef&vim + silent Xgrep Grep_Test_Text: test_quickfix.vim + call assert_true(len(g:Xgetlist()) == 5) + Xopen + call assert_true(w:quickfix_title =~ '^:grep') + Xclose + enew + set makeef=Temp_File_## + silent Xgrepadd GrepAdd_Test_Text: test_quickfix.vim + call assert_true(len(g:Xgetlist()) == 9) + + " Try with 'grepprg' set to 'internal' + set grepprg=internal + silent Xgrep Grep_Test_Text: test_quickfix.vim + silent Xgrepadd GrepAdd_Test_Text: test_quickfix.vim + call assert_true(len(g:Xgetlist()) == 9) + set grepprg&vim + + call writefile(['Vim'], 'XtestTempFile') + set makeef=XtestTempFile + silent Xgrep Grep_Test_Text: test_quickfix.vim + call assert_equal(5, len(g:Xgetlist())) + call assert_false(filereadable('XtestTempFile')) + set makeef&vim +endfunc + +func Test_grep() + if !has('unix') + " The grepprg may not be set on non-Unix systems + return + endif + + call s:test_xgrep('c') + call s:test_xgrep('l') +endfunc + +func Test_two_windows() + " Use one 'errorformat' for two windows. Add an expression to each of them, + " make sure they each keep their own state. + set efm=%DEntering\ dir\ '%f',%f:%l:%m,%XLeaving\ dir\ '%f' + call mkdir('Xone/a', 'p') + call mkdir('Xtwo/a', 'p') + let lines = ['1', '2', 'one one one', '4', 'two two two', '6', '7'] + call writefile(lines, 'Xone/a/one.txt') + call writefile(lines, 'Xtwo/a/two.txt') + + new one + let one_id = win_getid() + lexpr "" + new two + let two_id = win_getid() + lexpr "" + + laddexpr "Entering dir 'Xtwo/a'" + call win_gotoid(one_id) + laddexpr "Entering dir 'Xone/a'" + call win_gotoid(two_id) + laddexpr 'two.txt:5:two two two' + call win_gotoid(one_id) + laddexpr 'one.txt:3:one one one' + + let loc_one = getloclist(one_id) + call assert_equal('Xone/a/one.txt', bufname(loc_one[1].bufnr)) + call assert_equal(3, loc_one[1].lnum) + + let loc_two = getloclist(two_id) + call assert_equal('Xtwo/a/two.txt', bufname(loc_two[1].bufnr)) + call assert_equal(5, loc_two[1].lnum) + + call win_gotoid(one_id) + bwipe! + call win_gotoid(two_id) + bwipe! + call delete('Xone', 'rf') + call delete('Xtwo', 'rf') +endfunc + +func XbottomTests(cchar) + call s:setup_commands(a:cchar) + + " Calling lbottom without any errors should fail + if a:cchar == 'l' + call assert_fails('lbottom', 'E776:') + endif + + call g:Xsetlist([{'filename': 'foo', 'lnum': 42}]) + Xopen + let wid = win_getid() + call assert_equal(1, line('.')) + wincmd w + call g:Xsetlist([{'filename': 'var', 'lnum': 24}], 'a') + Xbottom + call win_gotoid(wid) + call assert_equal(2, line('.')) + Xclose +endfunc + +" Tests for the :cbottom and :lbottom commands +func Test_cbottom() + call XbottomTests('c') + call XbottomTests('l') +endfunc + +func HistoryTest(cchar) + call s:setup_commands(a:cchar) + + " clear all lists after the first one, then replace the first one. + call g:Xsetlist([]) + call assert_fails('Xolder 99', 'E380:') + let entry = {'filename': 'foo', 'lnum': 42} + call g:Xsetlist([entry], 'r') + call g:Xsetlist([entry, entry]) + call g:Xsetlist([entry, entry, entry]) + let res = split(execute(a:cchar . 'hist'), "\n") + call assert_equal(3, len(res)) + let common = 'errors :set' . (a:cchar == 'c' ? 'qf' : 'loc') . 'list()' + call assert_equal(' error list 1 of 3; 1 ' . common, res[0]) + call assert_equal(' error list 2 of 3; 2 ' . common, res[1]) + call assert_equal('> error list 3 of 3; 3 ' . common, res[2]) + + " Test for changing the quickfix lists + call assert_equal(3, g:Xgetlist({'nr' : 0}).nr) + exe '1' . a:cchar . 'hist' + call assert_equal(1, g:Xgetlist({'nr' : 0}).nr) + exe '3' . a:cchar . 'hist' + call assert_equal(3, g:Xgetlist({'nr' : 0}).nr) + call assert_fails('-2' . a:cchar . 'hist', 'E16:') + call assert_fails('4' . a:cchar . 'hist', 'E16:') + + call g:Xsetlist([], 'f') + let l = split(execute(a:cchar . 'hist'), "\n") + call assert_equal('No entries', l[0]) + if a:cchar == 'c' + call assert_fails('4chist', 'E16:') + else + call assert_fails('4lhist', 'E776:') + endif + + " An empty list should still show the stack history + call g:Xsetlist([]) + let res = split(execute(a:cchar . 'hist'), "\n") + call assert_equal('> error list 1 of 1; 0 ' . common, res[0]) + + call g:Xsetlist([], 'f') +endfunc + +func Test_history() + call HistoryTest('c') + call HistoryTest('l') +endfunc + +func Test_duplicate_buf() + " make sure we can get the highest buffer number + edit DoesNotExist + edit DoesNotExist2 + let last_buffer = bufnr("$") + + " make sure only one buffer is created + call writefile(['this one', 'that one'], 'Xgrepthis') + vimgrep one Xgrepthis + vimgrep one Xgrepthis + call assert_equal(last_buffer + 1, bufnr("$")) + + call delete('Xgrepthis') +endfunc + +" Quickfix/Location list set/get properties tests +func Xproperty_tests(cchar) + call s:setup_commands(a:cchar) + + " Error cases + call assert_fails('call g:Xgetlist(99)', 'E715:') + call assert_fails('call g:Xsetlist(99)', 'E714:') + call assert_fails('call g:Xsetlist([], "a", [])', 'E715:') + + " Set and get the title + call g:Xsetlist([]) + Xopen + wincmd p + call g:Xsetlist([{'filename':'foo', 'lnum':27}]) + let s = g:Xsetlist([], 'a', {'title' : 'Sample'}) + call assert_equal(0, s) + let d = g:Xgetlist({"title":1}) + call assert_equal('Sample', d.title) + " Try setting title to a non-string value + call assert_equal(-1, g:Xsetlist([], 'a', {'title' : ['Test']})) + call assert_equal('Sample', g:Xgetlist({"title":1}).title) + + Xopen + call assert_equal('Sample', w:quickfix_title) + Xclose + + " Tests for action argument + silent! Xolder 999 + let qfnr = g:Xgetlist({'all':1}).nr + call g:Xsetlist([], 'r', {'title' : 'N1'}) + call assert_equal('N1', g:Xgetlist({'all':1}).title) + call g:Xsetlist([], ' ', {'title' : 'N2'}) + call assert_equal(qfnr + 1, g:Xgetlist({'all':1}).nr) + + let res = g:Xgetlist({'nr': 0}) + call assert_equal(qfnr + 1, res.nr) + call assert_equal(['nr'], keys(res)) + + call g:Xsetlist([], ' ', {'title' : 'N3'}) + call assert_equal('N2', g:Xgetlist({'nr':2, 'title':1}).title) + + " Changing the title of an earlier quickfix list + call g:Xsetlist([], 'r', {'title' : 'NewTitle', 'nr' : 2}) + call assert_equal('NewTitle', g:Xgetlist({'nr':2, 'title':1}).title) + + " Changing the title of an invalid quickfix list + call assert_equal(-1, g:Xsetlist([], ' ', + \ {'title' : 'SomeTitle', 'nr' : 99})) + call assert_equal(-1, g:Xsetlist([], ' ', + \ {'title' : 'SomeTitle', 'nr' : 'abc'})) + + if a:cchar == 'c' + copen + call assert_equal({'winid':win_getid()}, getqflist({'winid':1})) + cclose + endif + + " Invalid arguments + call assert_fails('call g:Xgetlist([])', 'E715') + call assert_fails('call g:Xsetlist([], "a", [])', 'E715') + let s = g:Xsetlist([], 'a', {'abc':1}) + call assert_equal(-1, s) + + call assert_equal({}, g:Xgetlist({'abc':1})) + call assert_equal('', g:Xgetlist({'nr':99, 'title':1}).title) + call assert_equal('', g:Xgetlist({'nr':[], 'title':1}).title) + + if a:cchar == 'l' + call assert_equal({}, getloclist(99, {'title': 1})) + endif + + " Context related tests + let s = g:Xsetlist([], 'a', {'context':[1,2,3]}) + call assert_equal(0, s) + call test_garbagecollect_now() + let d = g:Xgetlist({'context':1}) + call assert_equal([1,2,3], d.context) + call g:Xsetlist([], 'a', {'context':{'color':'green'}}) + let d = g:Xgetlist({'context':1}) + call assert_equal({'color':'green'}, d.context) + call g:Xsetlist([], 'a', {'context':"Context info"}) + let d = g:Xgetlist({'context':1}) + call assert_equal("Context info", d.context) + call g:Xsetlist([], 'a', {'context':246}) + let d = g:Xgetlist({'context':1}) + call assert_equal(246, d.context) + " set other Vim data types as context + call g:Xsetlist([], 'a', {'context' : v:_null_blob}) + if has('channel') + call g:Xsetlist([], 'a', {'context' : test_null_channel()}) + endif + if has('job') + call g:Xsetlist([], 'a', {'context' : test_null_job()}) + endif + " Nvim doesn't have null functions + " call g:Xsetlist([], 'a', {'context' : test_null_function()}) + " Nvim doesn't have null partials + " call g:Xsetlist([], 'a', {'context' : test_null_partial()}) + call g:Xsetlist([], 'a', {'context' : ''}) + call test_garbagecollect_now() + if a:cchar == 'l' + " Test for copying context across two different location lists + new | only + let w1_id = win_getid() + let l = [1] + call setloclist(0, [], 'a', {'context':l}) + new + let w2_id = win_getid() + call add(l, 2) + call assert_equal([1, 2], getloclist(w1_id, {'context':1}).context) + call assert_equal([1, 2], getloclist(w2_id, {'context':1}).context) + unlet! l + call assert_equal([1, 2], getloclist(w2_id, {'context':1}).context) + only + call setloclist(0, [], 'f') + call assert_equal('', getloclist(0, {'context':1}).context) + endif + + " Test for changing the context of previous quickfix lists + call g:Xsetlist([], 'f') + Xexpr "One" + Xexpr "Two" + Xexpr "Three" + call g:Xsetlist([], 'r', {'context' : [1], 'nr' : 1}) + call g:Xsetlist([], 'a', {'context' : [2], 'nr' : 2}) + " Also, check for setting the context using quickfix list number zero. + call g:Xsetlist([], 'r', {'context' : [3], 'nr' : 0}) + call test_garbagecollect_now() + let l = g:Xgetlist({'nr' : 1, 'context' : 1}) + call assert_equal([1], l.context) + let l = g:Xgetlist({'nr' : 2, 'context' : 1}) + call assert_equal([2], l.context) + let l = g:Xgetlist({'nr' : 3, 'context' : 1}) + call assert_equal([3], l.context) + + " Test for changing the context through reference and for garbage + " collection of quickfix context + let l = ["red"] + call g:Xsetlist([], ' ', {'context' : l}) + call add(l, "blue") + let x = g:Xgetlist({'context' : 1}) + call add(x.context, "green") + call assert_equal(["red", "blue", "green"], l) + call assert_equal(["red", "blue", "green"], x.context) + unlet l + call test_garbagecollect_now() + let m = g:Xgetlist({'context' : 1}) + call assert_equal(["red", "blue", "green"], m.context) + + " Test for setting/getting items + Xexpr "" + let qfprev = g:Xgetlist({'nr':0}) + let s = g:Xsetlist([], ' ', {'title':'Green', + \ 'items' : [{'filename':'F1', 'lnum':10}]}) + call assert_equal(0, s) + let qfcur = g:Xgetlist({'nr':0}) + call assert_true(qfcur.nr == qfprev.nr + 1) + let l = g:Xgetlist({'items':1}) + call assert_equal('F1', bufname(l.items[0].bufnr)) + call assert_equal(10, l.items[0].lnum) + call g:Xsetlist([], 'a', {'items' : [{'filename':'F2', 'lnum':20}, + \ {'filename':'F2', 'lnum':30}]}) + let l = g:Xgetlist({'items':1}) + call assert_equal('F2', bufname(l.items[2].bufnr)) + call assert_equal(30, l.items[2].lnum) + call g:Xsetlist([], 'r', {'items' : [{'filename':'F3', 'lnum':40}]}) + let l = g:Xgetlist({'items':1}) + call assert_equal('F3', bufname(l.items[0].bufnr)) + call assert_equal(40, l.items[0].lnum) + call g:Xsetlist([], 'r', {'items' : []}) + let l = g:Xgetlist({'items':1}) + call assert_equal(0, len(l.items)) + + call g:Xsetlist([], 'r', {'title' : 'TestTitle'}) + call g:Xsetlist([], 'r', {'items' : [{'filename' : 'F1', 'lnum' : 10, 'text' : 'L10'}]}) + call g:Xsetlist([], 'r', {'items' : [{'filename' : 'F1', 'lnum' : 10, 'text' : 'L10'}]}) + call assert_equal('TestTitle', g:Xgetlist({'title' : 1}).title) + + " Test for getting id of window associated with a location list window + if a:cchar == 'l' + only + call assert_equal(0, g:Xgetlist({'all' : 1}).filewinid) + let wid = win_getid() + Xopen + call assert_equal(wid, g:Xgetlist({'filewinid' : 1}).filewinid) + wincmd w + call assert_equal(0, g:Xgetlist({'filewinid' : 1}).filewinid) + only + endif + + " The following used to crash Vim with address sanitizer + call g:Xsetlist([], 'f') + call g:Xsetlist([], 'a', {'items' : [{'filename':'F1', 'lnum':10}]}) + call assert_equal(10, g:Xgetlist({'items':1}).items[0].lnum) + + " Try setting the items using a string + call assert_equal(-1, g:Xsetlist([], ' ', {'items' : 'Test'})) + + " Save and restore the quickfix stack + call g:Xsetlist([], 'f') + call assert_equal(0, g:Xgetlist({'nr':'$'}).nr) + Xexpr "File1:10:Line1" + Xexpr "File2:20:Line2" + Xexpr "File3:30:Line3" + let last_qf = g:Xgetlist({'nr':'$'}).nr + call assert_equal(3, last_qf) + let qstack = [] + for i in range(1, last_qf) + let qstack = add(qstack, g:Xgetlist({'nr':i, 'all':1})) + endfor + call g:Xsetlist([], 'f') + for i in range(len(qstack)) + call g:Xsetlist([], ' ', qstack[i]) + endfor + call assert_equal(3, g:Xgetlist({'nr':'$'}).nr) + call assert_equal(10, g:Xgetlist({'nr':1, 'items':1}).items[0].lnum) + call assert_equal(20, g:Xgetlist({'nr':2, 'items':1}).items[0].lnum) + call assert_equal(30, g:Xgetlist({'nr':3, 'items':1}).items[0].lnum) + call g:Xsetlist([], 'f') + + " Swap two quickfix lists + Xexpr "File1:10:Line10" + Xexpr "File2:20:Line20" + Xexpr "File3:30:Line30" + call g:Xsetlist([], 'r', {'nr':1,'title':'Colors','context':['Colors']}) + call g:Xsetlist([], 'r', {'nr':2,'title':'Fruits','context':['Fruits']}) + let l1=g:Xgetlist({'nr':1,'all':1}) + let l2=g:Xgetlist({'nr':2,'all':1}) + let save_id = l1.id + let l1.id=l2.id + let l2.id=save_id + call g:Xsetlist([], 'r', l1) + call g:Xsetlist([], 'r', l2) + let newl1=g:Xgetlist({'nr':1,'all':1}) + let newl2=g:Xgetlist({'nr':2,'all':1}) + call assert_equal('Fruits', newl1.title) + call assert_equal(['Fruits'], newl1.context) + call assert_equal('Line20', newl1.items[0].text) + call assert_equal('Colors', newl2.title) + call assert_equal(['Colors'], newl2.context) + call assert_equal('Line10', newl2.items[0].text) + call g:Xsetlist([], 'f') + + " Cannot specify both a non-empty list argument and a dict argument + call assert_fails("call g:Xsetlist([{}], ' ', {})", 'E475:') +endfunc + +func Test_qf_property() + call Xproperty_tests('c') + call Xproperty_tests('l') +endfunc + +" Test for setting the current index in the location/quickfix list +func Xtest_setqfidx(cchar) + call s:setup_commands(a:cchar) + + Xgetexpr "F1:10:1:Line1\nF2:20:2:Line2\nF3:30:3:Line3" + Xgetexpr "F4:10:1:Line1\nF5:20:2:Line2\nF6:30:3:Line3" + Xgetexpr "F7:10:1:Line1\nF8:20:2:Line2\nF9:30:3:Line3" + + call g:Xsetlist([], 'a', {'nr' : 3, 'idx' : 2}) + call g:Xsetlist([], 'a', {'nr' : 2, 'idx' : 2}) + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 3}) + Xolder 2 + Xopen + call assert_equal(3, line('.')) + Xnewer + call assert_equal(2, line('.')) + Xnewer + call assert_equal(2, line('.')) + " Update the current index with the quickfix window open + wincmd w + call g:Xsetlist([], 'a', {'nr' : 3, 'idx' : 3}) + Xopen + call assert_equal(3, line('.')) + Xclose + + " Set the current index to the last entry + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : '$'}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + " A large value should set the index to the last index + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 1}) + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 999}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + " Invalid index values + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : -1}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 0}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 'xx'}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + call assert_fails("call g:Xsetlist([], 'a', {'nr':1, 'idx':[]})", 'E745:') + + call g:Xsetlist([], 'f') + new | only +endfunc + +func Test_setqfidx() + call Xtest_setqfidx('c') + call Xtest_setqfidx('l') +endfunc + +" Tests for the QuickFixCmdPre/QuickFixCmdPost autocommands +func QfAutoCmdHandler(loc, cmd) + call add(g:acmds, a:loc . a:cmd) +endfunc + +func Test_Autocmd() + autocmd QuickFixCmdPre * call QfAutoCmdHandler('pre', expand('<amatch>')) + autocmd QuickFixCmdPost * call QfAutoCmdHandler('post', expand('<amatch>')) + + let g:acmds = [] + cexpr "F1:10:Line 10" + caddexpr "F1:20:Line 20" + cgetexpr "F1:30:Line 30" + cexpr "" + caddexpr "" + cgetexpr "" + silent! cexpr non_existing_func() + silent! caddexpr non_existing_func() + silent! cgetexpr non_existing_func() + let l =<< trim END + precexpr + postcexpr + precaddexpr + postcaddexpr + precgetexpr + postcgetexpr + precexpr + postcexpr + precaddexpr + postcaddexpr + precgetexpr + postcgetexpr + precexpr + precaddexpr + precgetexpr + END + call assert_equal(l, g:acmds) + + let g:acmds = [] + enew! | call append(0, "F2:10:Line 10") + cbuffer! + enew! | call append(0, "F2:20:Line 20") + cgetbuffer + enew! | call append(0, "F2:30:Line 30") + caddbuffer + new + let bnum = bufnr('%') + bunload + exe 'silent! cbuffer! ' . bnum + exe 'silent! cgetbuffer ' . bnum + exe 'silent! caddbuffer ' . bnum + enew! + let l =<< trim END + precbuffer + postcbuffer + precgetbuffer + postcgetbuffer + precaddbuffer + postcaddbuffer + precbuffer + precgetbuffer + precaddbuffer + END + call assert_equal(l, g:acmds) + + call writefile(['Xtest:1:Line1'], 'Xtest') + call writefile([], 'Xempty') + let g:acmds = [] + cfile Xtest + caddfile Xtest + cgetfile Xtest + cfile Xempty + caddfile Xempty + cgetfile Xempty + silent! cfile do_not_exist + silent! caddfile do_not_exist + silent! cgetfile do_not_exist + let l =<< trim END + precfile + postcfile + precaddfile + postcaddfile + precgetfile + postcgetfile + precfile + postcfile + precaddfile + postcaddfile + precgetfile + postcgetfile + precfile + postcfile + precaddfile + postcaddfile + precgetfile + postcgetfile + END + call assert_equal(l, g:acmds) + + let g:acmds = [] + helpgrep quickfix + silent! helpgrep non_existing_help_topic + vimgrep test Xtest + vimgrepadd test Xtest + silent! vimgrep non_existing_test Xtest + silent! vimgrepadd non_existing_test Xtest + set makeprg= + silent! make + set makeprg& + let l =<< trim END + prehelpgrep + posthelpgrep + prehelpgrep + posthelpgrep + previmgrep + postvimgrep + previmgrepadd + postvimgrepadd + previmgrep + postvimgrep + previmgrepadd + postvimgrepadd + premake + postmake + END + call assert_equal(l, g:acmds) + + if has('unix') + " Run this test only on Unix-like systems. The grepprg may not be set on + " non-Unix systems. + " The following lines are used for the grep test. Don't remove. + " Grep_Autocmd_Text: Match 1 + " GrepAdd_Autocmd_Text: Match 2 + let g:acmds = [] + silent grep Grep_Autocmd_Text test_quickfix.vim + silent grepadd GrepAdd_Autocmd_Text test_quickfix.vim + silent grep abc123def Xtest + silent grepadd abc123def Xtest + set grepprg=internal + silent grep Grep_Autocmd_Text test_quickfix.vim + silent grepadd GrepAdd_Autocmd_Text test_quickfix.vim + silent lgrep Grep_Autocmd_Text test_quickfix.vim + silent lgrepadd GrepAdd_Autocmd_Text test_quickfix.vim + set grepprg&vim + let l =<< trim END + pregrep + postgrep + pregrepadd + postgrepadd + pregrep + postgrep + pregrepadd + postgrepadd + pregrep + postgrep + pregrepadd + postgrepadd + prelgrep + postlgrep + prelgrepadd + postlgrepadd + END + call assert_equal(l, g:acmds) + endif + + call delete('Xtest') + call delete('Xempty') + au! QuickFixCmdPre + au! QuickFixCmdPost +endfunc + +func Test_Autocmd_Exception() + set efm=%m + lgetexpr '?' + + try + call DoesNotExit() + catch + lgetexpr '1' + finally + lgetexpr '1' + endtry + + call assert_equal('1', getloclist(0)[0].text) + + set efm&vim +endfunc + +func Test_caddbuffer_wrong() + " This used to cause a memory access in freed memory. + let save_efm = &efm + set efm=%EEEE%m,%WWWW,%+CCCC%>%#,%GGGG%.# + cgetexpr ['WWWW', 'EEEE', 'CCCC'] + let &efm = save_efm + caddbuffer + bwipe! +endfunc + +func Test_caddexpr_wrong() + " This used to cause a memory access in freed memory. + cbuffer + cbuffer + copen + let save_efm = &efm + set efm=% + call assert_fails('caddexpr ""', 'E376:') + let &efm = save_efm +endfunc + +func Test_dirstack_cleanup() + " This used to cause a memory access in freed memory. + let save_efm = &efm + lexpr '0' + lopen + fun X(c) + let save_efm=&efm + set efm=%D%f + if a:c == 'c' + caddexpr '::' + else + laddexpr ':0:0' + endif + let &efm=save_efm + endfun + call X('c') + call X('l') + call setqflist([], 'r') + caddbuffer + let &efm = save_efm +endfunc + +" Tests for jumping to entries from the location list window and quickfix +" window +func Test_cwindow_jump() + set efm=%f%%%l%%%m + lgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"] + lopen | only + lfirst + call assert_true(winnr('$') == 2) + call assert_true(winnr() == 1) + " Location list for the new window should be set + call assert_true(getloclist(0)[2].text == 'Line 30') + + " Open a scratch buffer + " Open a new window and create a location list + " Open the location list window and close the other window + " Jump to an entry. + " Should create a new window and jump to the entry. The scratch buffer + " should not be used. + enew | only + set buftype=nofile + below new + lgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"] + lopen + 2wincmd c + lnext + call assert_true(winnr('$') == 3) + call assert_true(winnr() == 2) + + " Open two windows with two different location lists + " Open the location list window and close the previous window + " Jump to an entry in the location list window + " Should open the file in the first window and not set the location list. + enew | only + lgetexpr ["F1%5%Line 5"] + below new + lgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"] + lopen + 2wincmd c + lnext + call assert_true(winnr() == 1) + call assert_true(getloclist(0)[0].text == 'Line 5') + + enew | only + cgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"] + copen + cnext + call assert_true(winnr('$') == 2) + call assert_true(winnr() == 1) + + " open the quickfix buffer in two windows and jump to an entry. Should open + " the file in the first quickfix window. + enew | only + copen + let bnum = bufnr('') + exe 'sbuffer ' . bnum + wincmd b + cfirst + call assert_equal(2, winnr()) + call assert_equal('F1', @%) + enew | only + exe 'sb' bnum + exe 'botright sb' bnum + wincmd t + clast + call assert_equal(2, winnr()) + call assert_equal('quickfix', getwinvar(1, '&buftype')) + call assert_equal('quickfix', getwinvar(3, '&buftype')) + + " Jumping to a file from the location list window should find a usable + " window by wrapping around the window list. + enew | only + call setloclist(0, [], 'f') + new | new + lgetexpr ["F1%10%Line 10", "F2%20%Line 20", "F3%30%Line 30"] + lopen + 1close + call assert_equal(0, getloclist(3, {'id' : 0}).id) + lnext + call assert_equal(3, winnr()) + call assert_equal(getloclist(1, {'id' : 0}).id, getloclist(3, {'id' : 0}).id) + + enew | only + set efm&vim +endfunc + +func Test_cwindow_highlight() + CheckScreendump + + let lines =<< trim END + call setline(1, ['some', 'text', 'with', 'matches']) + write XCwindow + vimgrep e XCwindow + redraw + cwindow 4 + END + call writefile(lines, 'XtestCwindow') + let buf = RunVimInTerminal('-S XtestCwindow', #{rows: 12}) + call VerifyScreenDump(buf, 'Test_quickfix_cwindow_1', {}) + + call term_sendkeys(buf, ":cnext\<CR>") + call VerifyScreenDump(buf, 'Test_quickfix_cwindow_2', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XtestCwindow') + call delete('XCwindow') +endfunc + +func XvimgrepTests(cchar) + call s:setup_commands(a:cchar) + + let lines =<< trim END + Editor:VIM vim + Editor:Emacs EmAcS + Editor:Notepad NOTEPAD + END + call writefile(lines, 'Xtestfile1') + call writefile(['Linux', 'macOS', 'MS-Windows'], 'Xtestfile2') + + " Error cases + call assert_fails('Xvimgrep /abc *', 'E682:') + + let @/='' + call assert_fails('Xvimgrep // *', 'E35:') + + call assert_fails('Xvimgrep abc', 'E683:') + call assert_fails('Xvimgrep a1b2c3 Xtestfile1', 'E480:') + call assert_fails('Xvimgrep pat Xa1b2c3', 'E480:') + + Xexpr "" + Xvimgrepadd Notepad Xtestfile1 + Xvimgrepadd macOS Xtestfile2 + let l = g:Xgetlist() + call assert_equal(2, len(l)) + call assert_equal('Editor:Notepad NOTEPAD', l[0].text) + + 10Xvimgrep #\cvim#g Xtestfile? + let l = g:Xgetlist() + call assert_equal(2, len(l)) + call assert_equal(8, l[0].col) + call assert_equal(11, l[0].end_col) + call assert_equal(12, l[1].col) + call assert_equal(15, l[1].end_col) + + 1Xvimgrep ?Editor? Xtestfile* + let l = g:Xgetlist() + call assert_equal(1, len(l)) + call assert_equal('Editor:VIM vim', l[0].text) + + edit +3 Xtestfile2 + Xvimgrep +\cemacs+j Xtestfile1 + let l = g:Xgetlist() + call assert_equal('Xtestfile2', @%) + call assert_equal('Editor:Emacs EmAcS', l[0].text) + + " Test for unloading a buffer after vimgrep searched the buffer + %bwipe + Xvimgrep /Editor/j Xtestfile* + call assert_equal(0, getbufinfo('Xtestfile1')[0].loaded) + call assert_equal([], getbufinfo('Xtestfile2')) + + " Test for opening the dummy buffer used by vimgrep in a window. The new + " window should be closed + %bw! + augroup QF_Test + au! + autocmd BufReadPre * exe "sb " .. expand("<abuf>") + augroup END + call assert_fails("Xvimgrep /sublime/ Xtestfile1", 'E480:') + call assert_equal(1, winnr('$')) + augroup QF_Test + au! + augroup END + + call delete('Xtestfile1') + call delete('Xtestfile2') +endfunc + +" Tests for the :vimgrep command +func Test_vimgrep() + call XvimgrepTests('c') + call XvimgrepTests('l') +endfunc + +func Test_vimgrep_wildcards_expanded_once() + new X[id-01] file.txt + call setline(1, 'some text to search for') + vimgrep text % + bwipe! +endfunc + +" Test for incsearch highlighting of the :vimgrep pattern +" This test used to cause "E315: ml_get: invalid lnum" errors. +func Test_vimgrep_incsearch() + CheckFunction test_override + enew + set incsearch + call test_override("char_avail", 1) + + call feedkeys(":2vimgrep assert test_quickfix.vim test_cdo.vim\<CR>", "ntx") + let l = getqflist() + call assert_equal(2, len(l)) + + call test_override("ALL", 0) + set noincsearch +endfunc + +" Test vimgrep with the last search pattern not set +func Test_vimgrep_with_no_last_search_pat() + let lines =<< trim [SCRIPT] + call assert_fails('vimgrep // *', 'E35:') + 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 vimgrep without swap file +func Test_vimgrep_without_swap_file() + let lines =<< trim [SCRIPT] + vimgrep grep test_c* + call writefile(['done'], 'Xresult') + qall! + [SCRIPT] + call writefile(lines, 'Xscript') + if RunVim([], [], '--clean -n -S Xscript Xscript') + call assert_equal(['done'], readfile('Xresult')) + endif + call delete('Xscript') + call delete('Xresult') +endfunc + +func Test_vimgrep_existing_swapfile() + call writefile(['match apple with apple'], 'Xapple') + call writefile(['swapfile'], '.Xapple.swp') + let g:foundSwap = 0 + let g:ignoreSwapExists = 1 + augroup grep + au SwapExists * let foundSwap = 1 | let v:swapchoice = 'e' + augroup END + vimgrep apple Xapple + call assert_equal(1, g:foundSwap) + call assert_match('.Xapple.swo', swapname('')) + + call delete('Xapple') + call delete('Xapple.swp') + augroup grep + au! SwapExists + augroup END + unlet g:ignoreSwapExists +endfunc + +func XfreeTests(cchar) + call s:setup_commands(a:cchar) + + enew | only + + " Deleting the quickfix stack should work even When the current list is + " somewhere in the middle of the stack + Xexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15'] + Xexpr ['Xfile2:20:20:Line 20', 'Xfile2:25:25:Line 25'] + Xexpr ['Xfile3:30:30:Line 30', 'Xfile3:35:35:Line 35'] + Xolder + call g:Xsetlist([], 'f') + call assert_equal(0, len(g:Xgetlist())) + + " After deleting the stack, adding a new list should create a stack with a + " single list. + Xexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15'] + call assert_equal(1, g:Xgetlist({'all':1}).nr) + + " Deleting the stack from a quickfix window should update/clear the + " quickfix/location list window. + Xexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15'] + Xexpr ['Xfile2:20:20:Line 20', 'Xfile2:25:25:Line 25'] + Xexpr ['Xfile3:30:30:Line 30', 'Xfile3:35:35:Line 35'] + Xolder + Xwindow + call g:Xsetlist([], 'f') + call assert_equal(2, winnr('$')) + call assert_equal(1, line('$')) + Xclose + + " Deleting the stack from a non-quickfix window should update/clear the + " quickfix/location list window. + Xexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15'] + Xexpr ['Xfile2:20:20:Line 20', 'Xfile2:25:25:Line 25'] + Xexpr ['Xfile3:30:30:Line 30', 'Xfile3:35:35:Line 35'] + Xolder + Xwindow + wincmd p + call g:Xsetlist([], 'f') + call assert_equal(0, len(g:Xgetlist())) + wincmd p + call assert_equal(2, winnr('$')) + call assert_equal(1, line('$')) + + " After deleting the location list stack, if the location list window is + " opened, then a new location list should be created. So opening the + " location list window again should not create a new window. + if a:cchar == 'l' + lexpr ['Xfile1:10:10:Line 10', 'Xfile1:15:15:Line 15'] + wincmd p + lopen + call assert_equal(2, winnr('$')) + endif + Xclose +endfunc + +" Tests for the quickfix free functionality +func Test_qf_free() + call XfreeTests('c') + call XfreeTests('l') +endfunc + +" Test for buffer overflow when parsing lines and adding new entries to +" the quickfix list. +func Test_bufoverflow() + set efm=%f:%l:%m + cgetexpr ['File1:100:' . repeat('x', 1025)] + + set efm=%+GCompiler:\ %.%#,%f:%l:%m + cgetexpr ['Compiler: ' . repeat('a', 1015), 'File1:10:Hello World'] + + set efm=%DEntering\ directory\ %f,%f:%l:%m + cgetexpr ['Entering directory ' . repeat('a', 1006), + \ 'File1:10:Hello World'] + set efm&vim +endfunc + +" Tests for getting the quickfix stack size +func XsizeTests(cchar) + call s:setup_commands(a:cchar) + + call g:Xsetlist([], 'f') + call assert_equal(0, g:Xgetlist({'nr':'$'}).nr) + call assert_equal('', g:Xgetlist({'nr':'$', 'all':1}).title) + call assert_equal(0, g:Xgetlist({'nr':0}).nr) + + Xexpr "File1:10:Line1" + Xexpr "File2:20:Line2" + Xexpr "File3:30:Line3" + Xolder | Xolder + call assert_equal(3, g:Xgetlist({'nr':'$'}).nr) + call g:Xsetlist([], 'f') + + Xexpr "File1:10:Line1" + Xexpr "File2:20:Line2" + Xexpr "File3:30:Line3" + Xolder | Xolder + call g:Xsetlist([], 'a', {'nr':'$', 'title':'Compiler'}) + call assert_equal('Compiler', g:Xgetlist({'nr':3, 'all':1}).title) +endfunc + +func Test_Qf_Size() + call XsizeTests('c') + call XsizeTests('l') +endfunc + +func Test_cclose_from_copen() + augroup QF_Test + au! + au FileType qf :call assert_fails(':cclose', 'E788') + augroup END + copen + augroup QF_Test + au! + augroup END + augroup! QF_Test +endfunc + +func Test_cclose_in_autocmd() + " Problem is only triggered if "starting" is zero, so that the OptionSet + " event will be triggered. + " call test_override('starting', 1) + augroup QF_Test + au! + au FileType qf :call assert_fails(':cclose', 'E788') + augroup END + copen + augroup QF_Test + au! + augroup END + augroup! QF_Test + " call test_override('starting', 0) +endfunc + +" Check that ":file" without an argument is possible even when "curbuf->b_ro_locked" +" is set. +func Test_file_from_copen() + " Works without argument. + augroup QF_Test + au! + au FileType qf file + augroup END + copen + + augroup QF_Test + au! + augroup END + cclose + + " Fails with argument. + augroup QF_Test + au! + au FileType qf call assert_fails(':file foo', 'E788') + augroup END + copen + augroup QF_Test + au! + augroup END + cclose + + augroup! QF_Test +endfunc + +func Test_resize_from_copen() + augroup QF_Test + au! + au FileType qf resize 5 + augroup END + try + " This should succeed without any exception. No other buffers are + " involved in the autocmd. + copen + finally + augroup QF_Test + au! + augroup END + augroup! QF_Test + endtry +endfunc + +func Test_filetype_autocmd() + " this changes the location list while it is in use to fill a buffer + lexpr '' + lopen + augroup FT_loclist + au FileType * call setloclist(0, [], 'f') + augroup END + silent! lolder + lexpr '' + + augroup FT_loclist + au! FileType + augroup END +endfunc + +func Test_vimgrep_with_textlock() + new + + " Simple way to execute something with "textlock" set. + " Check that vimgrep without jumping can be executed. + au InsertCharPre * vimgrep /RunTheTest/j runtest.vim + normal ax + let qflist = getqflist() + call assert_true(len(qflist) > 0) + call assert_match('RunTheTest', qflist[0].text) + call setqflist([], 'r') + au! InsertCharPre + + " Check that vimgrepadd without jumping can be executed. + au InsertCharPre * vimgrepadd /RunTheTest/j runtest.vim + normal ax + let qflist = getqflist() + call assert_true(len(qflist) > 0) + call assert_match('RunTheTest', qflist[0].text) + call setqflist([], 'r') + au! InsertCharPre + + " Check that lvimgrep without jumping can be executed. + au InsertCharPre * lvimgrep /RunTheTest/j runtest.vim + normal ax + let qflist = getloclist(0) + call assert_true(len(qflist) > 0) + call assert_match('RunTheTest', qflist[0].text) + call setloclist(0, [], 'r') + au! InsertCharPre + + " Check that lvimgrepadd without jumping can be executed. + au InsertCharPre * lvimgrepadd /RunTheTest/j runtest.vim + normal ax + let qflist = getloclist(0) + call assert_true(len(qflist) > 0) + call assert_match('RunTheTest', qflist[0].text) + call setloclist(0, [], 'r') + au! InsertCharPre + + " trying to jump will give an error + au InsertCharPre * vimgrep /RunTheTest/ runtest.vim + call assert_fails('normal ax', 'E565:') + au! InsertCharPre + + au InsertCharPre * vimgrepadd /RunTheTest/ runtest.vim + call assert_fails('normal ax', 'E565:') + au! InsertCharPre + + au InsertCharPre * lvimgrep /RunTheTest/ runtest.vim + call assert_fails('normal ax', 'E565:') + au! InsertCharPre + + au InsertCharPre * lvimgrepadd /RunTheTest/ runtest.vim + call assert_fails('normal ax', 'E565:') + au! InsertCharPre + + bwipe! +endfunc + +" Tests for the quickfix buffer b:changedtick variable +func Xchangedtick_tests(cchar) + call s:setup_commands(a:cchar) + + new | only + + Xexpr "" | Xexpr "" | Xexpr "" + + Xopen + Xolder + Xolder + Xaddexpr "F1:10:Line10" + Xaddexpr "F2:20:Line20" + call g:Xsetlist([{"filename":"F3", "lnum":30, "text":"Line30"}], 'a') + call g:Xsetlist([], 'f') + call assert_equal(8, getbufvar('%', 'changedtick')) + Xclose +endfunc + +func Test_changedtick() + call Xchangedtick_tests('c') + call Xchangedtick_tests('l') +endfunc + +" Tests for parsing an expression using setqflist() +func Xsetexpr_tests(cchar) + call s:setup_commands(a:cchar) + + let t = ["File1:10:Line10", "File1:20:Line20"] + call g:Xsetlist([], ' ', {'lines' : t}) + call g:Xsetlist([], 'a', {'lines' : ["File1:30:Line30"]}) + + let l = g:Xgetlist() + call assert_equal(3, len(l)) + call assert_equal(20, l[1].lnum) + call assert_equal('Line30', l[2].text) + call g:Xsetlist([], 'r', {'lines' : ["File2:5:Line5"]}) + let l = g:Xgetlist() + call assert_equal(1, len(l)) + call assert_equal('Line5', l[0].text) + call assert_equal(-1, g:Xsetlist([], 'a', {'lines' : 10})) + call assert_equal(-1, g:Xsetlist([], 'a', {'lines' : "F1:10:L10"})) + + call g:Xsetlist([], 'f') + " Add entries to multiple lists + call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["File1:10:Line10"]}) + call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["File2:20:Line20"]}) + call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["File1:15:Line15"]}) + call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["File2:25:Line25"]}) + call assert_equal('Line15', g:Xgetlist({'nr':1, 'items':1}).items[1].text) + call assert_equal('Line25', g:Xgetlist({'nr':2, 'items':1}).items[1].text) + + " Adding entries using a custom efm + set efm& + call g:Xsetlist([], ' ', {'efm' : '%f#%l#%m', + \ 'lines' : ["F1#10#L10", "F2#20#L20"]}) + call assert_equal(20, g:Xgetlist({'items':1}).items[1].lnum) + call g:Xsetlist([], 'a', {'efm' : '%f#%l#%m', 'lines' : ["F3:30:L30"]}) + call assert_equal('F3:30:L30', g:Xgetlist({'items':1}).items[2].text) + call assert_equal(20, g:Xgetlist({'items':1}).items[1].lnum) + call assert_equal(-1, g:Xsetlist([], 'a', {'efm' : [], + \ 'lines' : ['F1:10:L10']})) +endfunc + +func Test_setexpr() + call Xsetexpr_tests('c') + call Xsetexpr_tests('l') +endfunc + +" Tests for per quickfix/location list directory stack +func Xmultidirstack_tests(cchar) + call s:setup_commands(a:cchar) + + call g:Xsetlist([], 'f') + Xexpr "" | Xexpr "" + + call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["Entering dir 'Xone/a'"]}) + call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["Entering dir 'Xtwo/a'"]}) + call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["one.txt:3:one one one"]}) + call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["two.txt:5:two two two"]}) + + let l1 = g:Xgetlist({'nr':1, 'items':1}) + let l2 = g:Xgetlist({'nr':2, 'items':1}) + call assert_equal('Xone/a/one.txt', bufname(l1.items[1].bufnr)) + call assert_equal(3, l1.items[1].lnum) + call assert_equal('Xtwo/a/two.txt', bufname(l2.items[1].bufnr)) + call assert_equal(5, l2.items[1].lnum) +endfunc + +func Test_multidirstack() + call mkdir('Xone/a', 'p') + call mkdir('Xtwo/a', 'p') + let lines = ['1', '2', 'one one one', '4', 'two two two', '6', '7'] + call writefile(lines, 'Xone/a/one.txt') + call writefile(lines, 'Xtwo/a/two.txt') + let save_efm = &efm + set efm=%DEntering\ dir\ '%f',%f:%l:%m,%XLeaving\ dir\ '%f' + + call Xmultidirstack_tests('c') + call Xmultidirstack_tests('l') + + let &efm = save_efm + call delete('Xone', 'rf') + call delete('Xtwo', 'rf') +endfunc + +" Tests for per quickfix/location list file stack +func Xmultifilestack_tests(cchar) + call s:setup_commands(a:cchar) + + call g:Xsetlist([], 'f') + Xexpr "" | Xexpr "" + + call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["[one.txt]"]}) + call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["[two.txt]"]}) + call g:Xsetlist([], 'a', {'nr' : 1, 'lines' : ["(3,5) one one one"]}) + call g:Xsetlist([], 'a', {'nr' : 2, 'lines' : ["(5,9) two two two"]}) + + let l1 = g:Xgetlist({'nr':1, 'items':1}) + let l2 = g:Xgetlist({'nr':2, 'items':1}) + call assert_equal('one.txt', bufname(l1.items[1].bufnr)) + call assert_equal(3, l1.items[1].lnum) + call assert_equal('two.txt', bufname(l2.items[1].bufnr)) + call assert_equal(5, l2.items[1].lnum) + + " Test for start of a new error line in the same line where a previous + " error line ends with a file stack. + let efm_val = 'Error\ l%l\ in\ %f,' + let efm_val .= '%-P%>(%f%r,Error\ l%l\ in\ %m,%-Q)%r' + let lines =<< trim END + (one.txt + Error l4 in one.txt + ) (two.txt + Error l6 in two.txt + ) + Error l8 in one.txt + END + let l = g:Xgetlist({'lines': lines, 'efm' : efm_val}) + call assert_equal(3, len(l.items)) + call assert_equal('one.txt', bufname(l.items[0].bufnr)) + call assert_equal(4, l.items[0].lnum) + call assert_equal('one.txt', l.items[0].text) + call assert_equal('two.txt', bufname(l.items[1].bufnr)) + call assert_equal(6, l.items[1].lnum) + call assert_equal('two.txt', l.items[1].text) + call assert_equal('one.txt', bufname(l.items[2].bufnr)) + call assert_equal(8, l.items[2].lnum) + call assert_equal('', l.items[2].text) +endfunc + +func Test_multifilestack() + let lines = ['1', '2', 'one one one', '4', 'two two two', '6', '7'] + call writefile(lines, 'one.txt') + call writefile(lines, 'two.txt') + let save_efm = &efm + set efm=%+P[%f],(%l\\,%c)\ %m,%-Q + + call Xmultifilestack_tests('c') + call Xmultifilestack_tests('l') + + let &efm = save_efm + call delete('one.txt') + call delete('two.txt') +endfunc + +" Tests for per buffer 'efm' setting +func Test_perbuf_efm() + call writefile(["File1-10-Line10"], 'one.txt') + call writefile(["File2#20#Line20"], 'two.txt') + set efm=%f#%l#%m + new | only + new + setlocal efm=%f-%l-%m + cfile one.txt + wincmd w + caddfile two.txt + + let l = getqflist() + call assert_equal(10, l[0].lnum) + call assert_equal('Line20', l[1].text) + + set efm& + new | only + call delete('one.txt') + call delete('two.txt') +endfunc + +" Open multiple help windows using ":lhelpgrep +" This test used to crash Vim +func Test_Multi_LL_Help() + new | only + lhelpgrep window + lopen + e# + lhelpgrep buffer + call assert_equal(3, winnr('$')) + call assert_true(len(getloclist(1)) != 0) + call assert_true(len(getloclist(2)) != 0) + new | only +endfunc + +" Tests for adding new quickfix lists using setqflist() +func XaddQf_tests(cchar) + call s:setup_commands(a:cchar) + + " Create a new list using ' ' for action + call g:Xsetlist([], 'f') + call g:Xsetlist([], ' ', {'title' : 'Test1'}) + let l = g:Xgetlist({'nr' : '$', 'all' : 1}) + call assert_equal(1, l.nr) + call assert_equal('Test1', l.title) + + " Create a new list using ' ' for action and '$' for 'nr' + call g:Xsetlist([], 'f') + call g:Xsetlist([], ' ', {'title' : 'Test2', 'nr' : '$'}) + let l = g:Xgetlist({'nr' : '$', 'all' : 1}) + call assert_equal(1, l.nr) + call assert_equal('Test2', l.title) + + " Create a new list using 'a' for action + call g:Xsetlist([], 'f') + call g:Xsetlist([], 'a', {'title' : 'Test3'}) + let l = g:Xgetlist({'nr' : '$', 'all' : 1}) + call assert_equal(1, l.nr) + call assert_equal('Test3', l.title) + + " Create a new list using 'a' for action and '$' for 'nr' + call g:Xsetlist([], 'f') + call g:Xsetlist([], 'a', {'title' : 'Test3', 'nr' : '$'}) + call g:Xsetlist([], 'a', {'title' : 'Test4'}) + let l = g:Xgetlist({'nr' : '$', 'all' : 1}) + call assert_equal(1, l.nr) + call assert_equal('Test4', l.title) + + " Adding a quickfix list should remove all the lists following the current + " list. + Xexpr "" | Xexpr "" | Xexpr "" + silent! 10Xolder + call g:Xsetlist([], ' ', {'title' : 'Test5'}) + let l = g:Xgetlist({'nr' : '$', 'all' : 1}) + call assert_equal(2, l.nr) + call assert_equal('Test5', l.title) + + " Add a quickfix list using '$' as the list number. + let lastqf = g:Xgetlist({'nr':'$'}).nr + silent! 99Xolder + call g:Xsetlist([], ' ', {'nr' : '$', 'title' : 'Test6'}) + let l = g:Xgetlist({'nr' : '$', 'all' : 1}) + call assert_equal(lastqf + 1, l.nr) + call assert_equal('Test6', l.title) + + " Add a quickfix list using 'nr' set to one more than the quickfix + " list size. + let lastqf = g:Xgetlist({'nr':'$'}).nr + silent! 99Xolder + call g:Xsetlist([], ' ', {'nr' : lastqf + 1, 'title' : 'Test7'}) + let l = g:Xgetlist({'nr' : '$', 'all' : 1}) + call assert_equal(lastqf + 1, l.nr) + call assert_equal('Test7', l.title) + + " Add a quickfix list to a stack with 10 lists using 'nr' set to '$' + exe repeat('Xexpr "" |', 9) . 'Xexpr ""' + silent! 99Xolder + call g:Xsetlist([], ' ', {'nr' : '$', 'title' : 'Test8'}) + let l = g:Xgetlist({'nr' : '$', 'all' : 1}) + call assert_equal(10, l.nr) + call assert_equal('Test8', l.title) + + " Add a quickfix list using 'nr' set to a value greater than 10 + call assert_equal(-1, g:Xsetlist([], ' ', {'nr' : 12, 'title' : 'Test9'})) + + " Try adding a quickfix list with 'nr' set to a value greater than the + " quickfix list size but less than 10. + call g:Xsetlist([], 'f') + Xexpr "" | Xexpr "" | Xexpr "" + silent! 99Xolder + call assert_equal(-1, g:Xsetlist([], ' ', {'nr' : 8, 'title' : 'Test10'})) + + " Add a quickfix list using 'nr' set to a some string or list + call assert_equal(-1, g:Xsetlist([], ' ', {'nr' : [1,2], 'title' : 'Test11'})) +endfunc + +func Test_add_qf() + call XaddQf_tests('c') + call XaddQf_tests('l') +endfunc + +" Test for getting the quickfix list items from some text without modifying +" the quickfix stack +func XgetListFromLines(cchar) + call s:setup_commands(a:cchar) + call g:Xsetlist([], 'f') + + let l = g:Xgetlist({'lines' : ["File2:20:Line20", "File2:30:Line30"]}).items + call assert_equal(2, len(l)) + call assert_equal(30, l[1].lnum) + + call assert_equal({}, g:Xgetlist({'lines' : 10})) + call assert_equal({}, g:Xgetlist({'lines' : 'File1:10:Line10'})) + call assert_equal([], g:Xgetlist({'lines' : []}).items) + call assert_equal([], g:Xgetlist({'lines' : [10, 20]}).items) + + " Parse text using a custom efm + set efm& + let l = g:Xgetlist({'lines':['File3#30#Line30'], 'efm' : '%f#%l#%m'}).items + call assert_equal('Line30', l[0].text) + let l = g:Xgetlist({'lines':['File3:30:Line30'], 'efm' : '%f-%l-%m'}).items + call assert_equal('File3:30:Line30', l[0].text) + let l = g:Xgetlist({'lines':['File3:30:Line30'], 'efm' : [1,2]}) + call assert_equal({}, l) + call assert_fails("call g:Xgetlist({'lines':['abc'], 'efm':'%2'})", 'E376:') + call assert_fails("call g:Xgetlist({'lines':['abc'], 'efm':''})", 'E378:') + + " Make sure that the quickfix stack is not modified + call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr) +endfunc + +func Test_get_list_from_lines() + call XgetListFromLines('c') + call XgetListFromLines('l') +endfunc + +" Tests for the quickfix list id +func Xqfid_tests(cchar) + call s:setup_commands(a:cchar) + + call g:Xsetlist([], 'f') + call assert_equal(0, g:Xgetlist({'id':0}).id) + Xexpr '' + let start_id = g:Xgetlist({'id' : 0}).id + Xexpr '' | Xexpr '' + Xolder + call assert_equal(start_id, g:Xgetlist({'id':0, 'nr':1}).id) + call assert_equal(start_id + 1, g:Xgetlist({'id':0, 'nr':0}).id) + call assert_equal(start_id + 2, g:Xgetlist({'id':0, 'nr':'$'}).id) + call assert_equal(0, g:Xgetlist({'id':0, 'nr':99}).id) + call assert_equal(2, g:Xgetlist({'id':start_id + 1, 'nr':0}).nr) + call assert_equal(0, g:Xgetlist({'id':99, 'nr':0}).id) + call assert_equal(0, g:Xgetlist({'id':"abc", 'nr':0}).id) + + call g:Xsetlist([], 'a', {'id':start_id, 'context':[1,2]}) + call assert_equal([1,2], g:Xgetlist({'nr':1, 'context':1}).context) + call g:Xsetlist([], 'a', {'id':start_id+1, 'lines':['F1:10:L10']}) + call assert_equal('L10', g:Xgetlist({'nr':2, 'items':1}).items[0].text) + call assert_equal(-1, g:Xsetlist([], 'a', {'id':999, 'title':'Vim'})) + call assert_equal(-1, g:Xsetlist([], 'a', {'id':'abc', 'title':'Vim'})) + + let qfid = g:Xgetlist({'id':0, 'nr':0}) + call g:Xsetlist([], 'f') + call assert_equal(0, g:Xgetlist({'id':qfid, 'nr':0}).id) +endfunc + +func Test_qf_id() + call Xqfid_tests('c') + call Xqfid_tests('l') +endfunc + +func Xqfjump_tests(cchar) + call s:setup_commands(a:cchar) + + call writefile(["Line1\tFoo", "Line2"], 'F1') + call writefile(["Line1\tBar", "Line2"], 'F2') + call writefile(["Line1\tBaz", "Line2"], 'F3') + + call g:Xsetlist([], 'f') + + " Tests for + " Jumping to a line using a pattern + " Jumping to a column greater than the last column in a line + " Jumping to a line greater than the last line in the file + let l = [] + for i in range(1, 7) + call add(l, {}) + endfor + let l[0].filename='F1' + let l[0].pattern='Line1' + let l[1].filename='F2' + let l[1].pattern='Line1' + let l[2].filename='F3' + let l[2].pattern='Line1' + let l[3].filename='F3' + let l[3].lnum=1 + let l[3].col=9 + let l[3].vcol=1 + let l[4].filename='F3' + let l[4].lnum=99 + let l[5].filename='F3' + let l[5].lnum=1 + let l[5].col=99 + let l[5].vcol=1 + let l[6].filename='F3' + let l[6].pattern='abcxyz' + + call g:Xsetlist([], ' ', {'items' : l}) + Xopen | only + 2Xnext + call assert_equal(3, g:Xgetlist({'idx' : 0}).idx) + call assert_equal('F3', @%) + Xnext + call assert_equal(7, col('.')) + Xnext + call assert_equal(2, line('.')) + Xnext + call assert_equal(9, col('.')) + 2 + Xnext + call assert_equal(2, line('.')) + + if a:cchar == 'l' + " When jumping to a location list entry in the location list window and + " no usable windows are available, then a new window should be opened. + enew! | new | only + call g:Xsetlist([], 'f') + setlocal buftype=nofile + new + let lines =<< trim END + F1:1:1:Line1 + F1:2:2:Line2 + F2:1:1:Line1 + F2:2:2:Line2 + F3:1:1:Line1 + F3:2:2:Line2 + END + call g:Xsetlist([], ' ', {'lines': lines}) + Xopen + let winid = win_getid() + wincmd p + close + call win_gotoid(winid) + Xnext + call assert_equal(3, winnr('$')) + call assert_equal(1, winnr()) + call assert_equal(2, line('.')) + + " When jumping to an entry in the location list window and the window + " associated with the location list is not present and a window containing + " the file is already present, then that window should be used. + close + belowright new + call g:Xsetlist([], 'f') + edit F3 + call win_gotoid(winid) + Xlast + call assert_equal(3, winnr()) + call assert_equal(6, g:Xgetlist({'size' : 1}).size) + call assert_equal(winid, g:Xgetlist({'winid' : 1}).winid) + endif + + " Cleanup + enew! + new | only + + call delete('F1') + call delete('F2') + call delete('F3') +endfunc + +func Test_qfjump() + call Xqfjump_tests('c') + call Xqfjump_tests('l') +endfunc + +" Tests for the getqflist() and getloclist() functions when the list is not +" present or is empty +func Xgetlist_empty_tests(cchar) + call s:setup_commands(a:cchar) + + " Empty quickfix stack + call g:Xsetlist([], 'f') + call assert_equal('', g:Xgetlist({'context' : 0}).context) + call assert_equal(0, g:Xgetlist({'id' : 0}).id) + call assert_equal(0, g:Xgetlist({'idx' : 0}).idx) + call assert_equal([], g:Xgetlist({'items' : 0}).items) + call assert_equal(0, g:Xgetlist({'nr' : 0}).nr) + call assert_equal(0, g:Xgetlist({'size' : 0}).size) + call assert_equal('', g:Xgetlist({'title' : 0}).title) + call assert_equal(0, g:Xgetlist({'winid' : 0}).winid) + call assert_equal(0, g:Xgetlist({'changedtick' : 0}).changedtick) + if a:cchar == 'c' + call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, + \ 'items' : [], 'nr' : 0, 'size' : 0, 'qfbufnr' : 0, + \ 'title' : '', 'winid' : 0, 'changedtick': 0, + \ 'quickfixtextfunc' : ''}, g:Xgetlist({'all' : 0})) + else + call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, + \ 'items' : [], 'nr' : 0, 'size' : 0, 'title' : '', + \ 'winid' : 0, 'changedtick': 0, 'filewinid' : 0, + \ 'qfbufnr' : 0, 'quickfixtextfunc' : ''}, + \ g:Xgetlist({'all' : 0})) + endif + + " Quickfix window with empty stack + silent! Xopen + let qfwinid = (a:cchar == 'c') ? win_getid() : 0 + let qfbufnr = (a:cchar == 'c') ? bufnr('') : 0 + call assert_equal(qfwinid, g:Xgetlist({'winid' : 0}).winid) + Xclose + + " Empty quickfix list + Xexpr "" + call assert_equal('', g:Xgetlist({'context' : 0}).context) + call assert_notequal(0, g:Xgetlist({'id' : 0}).id) + call assert_equal(0, g:Xgetlist({'idx' : 0}).idx) + call assert_equal([], g:Xgetlist({'items' : 0}).items) + call assert_notequal(0, g:Xgetlist({'nr' : 0}).nr) + call assert_equal(0, g:Xgetlist({'size' : 0}).size) + call assert_notequal('', g:Xgetlist({'title' : 0}).title) + call assert_equal(0, g:Xgetlist({'winid' : 0}).winid) + call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick) + + let qfid = g:Xgetlist({'id' : 0}).id + call g:Xsetlist([], 'f') + + " Non-existing quickfix identifier + call assert_equal('', g:Xgetlist({'id' : qfid, 'context' : 0}).context) + call assert_equal(0, g:Xgetlist({'id' : qfid}).id) + call assert_equal(0, g:Xgetlist({'id' : qfid, 'idx' : 0}).idx) + call assert_equal([], g:Xgetlist({'id' : qfid, 'items' : 0}).items) + call assert_equal(0, g:Xgetlist({'id' : qfid, 'nr' : 0}).nr) + call assert_equal(0, g:Xgetlist({'id' : qfid, 'size' : 0}).size) + call assert_equal('', g:Xgetlist({'id' : qfid, 'title' : 0}).title) + call assert_equal(0, g:Xgetlist({'id' : qfid, 'winid' : 0}).winid) + call assert_equal(0, g:Xgetlist({'id' : qfid, 'changedtick' : 0}).changedtick) + if a:cchar == 'c' + call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [], + \ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0, + \ 'qfbufnr' : qfbufnr, 'quickfixtextfunc' : '', + \ 'changedtick' : 0}, g:Xgetlist({'id' : qfid, 'all' : 0})) + else + call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [], + \ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0, + \ 'changedtick' : 0, 'filewinid' : 0, 'qfbufnr' : 0, + \ 'quickfixtextfunc' : ''}, + \ g:Xgetlist({'id' : qfid, 'all' : 0})) + endif + + " Non-existing quickfix list number + call assert_equal('', g:Xgetlist({'nr' : 5, 'context' : 0}).context) + call assert_equal(0, g:Xgetlist({'nr' : 5}).nr) + call assert_equal(0, g:Xgetlist({'nr' : 5, 'idx' : 0}).idx) + call assert_equal([], g:Xgetlist({'nr' : 5, 'items' : 0}).items) + call assert_equal(0, g:Xgetlist({'nr' : 5, 'id' : 0}).id) + call assert_equal(0, g:Xgetlist({'nr' : 5, 'size' : 0}).size) + call assert_equal('', g:Xgetlist({'nr' : 5, 'title' : 0}).title) + call assert_equal(0, g:Xgetlist({'nr' : 5, 'winid' : 0}).winid) + call assert_equal(0, g:Xgetlist({'nr' : 5, 'changedtick' : 0}).changedtick) + if a:cchar == 'c' + call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [], + \ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0, + \ 'changedtick' : 0, 'qfbufnr' : qfbufnr, + \ 'quickfixtextfunc' : ''}, g:Xgetlist({'nr' : 5, 'all' : 0})) + else + call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [], + \ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0, + \ 'changedtick' : 0, 'filewinid' : 0, 'qfbufnr' : 0, + \ 'quickfixtextfunc' : ''}, g:Xgetlist({'nr' : 5, 'all' : 0})) + endif +endfunc + +func Test_empty_list_quickfixtextfunc() + " This was crashing. Can only reproduce by running it in a separate Vim + " instance. + let lines =<< trim END + func s:Func(o) + cgetexpr '0' + endfunc + cope + let &quickfixtextfunc = 's:Func' + cgetfile [ex + END + call writefile(lines, 'Xquickfixtextfunc') + call RunVim([], [], '-e -s -S Xquickfixtextfunc -c qa') + call delete('Xquickfixtextfunc') +endfunc + +func Test_getqflist() + call Xgetlist_empty_tests('c') + call Xgetlist_empty_tests('l') +endfunc + +func Test_getqflist_invalid_nr() + " The following commands used to crash Vim + cexpr "" + call getqflist({'nr' : $XXX_DOES_NOT_EXIST_XXX}) + + " Cleanup + call setqflist([], 'r') +endfunc + +" Tests for the quickfix/location list changedtick +func Xqftick_tests(cchar) + call s:setup_commands(a:cchar) + + call g:Xsetlist([], 'f') + + Xexpr "F1:10:Line10" + let qfid = g:Xgetlist({'id' : 0}).id + call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick) + Xaddexpr "F2:20:Line20\nF2:21:Line21" + call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick) + call g:Xsetlist([], 'a', {'lines' : ["F3:30:Line30", "F3:31:Line31"]}) + call assert_equal(3, g:Xgetlist({'changedtick' : 0}).changedtick) + call g:Xsetlist([], 'r', {'lines' : ["F4:40:Line40"]}) + call assert_equal(4, g:Xgetlist({'changedtick' : 0}).changedtick) + call g:Xsetlist([], 'a', {'title' : 'New Title'}) + call assert_equal(5, g:Xgetlist({'changedtick' : 0}).changedtick) + + enew! + call append(0, ["F5:50:L50", "F6:60:L60"]) + Xaddbuffer + call assert_equal(6, g:Xgetlist({'changedtick' : 0}).changedtick) + enew! + + call g:Xsetlist([], 'a', {'context' : {'bus' : 'pci'}}) + call assert_equal(7, g:Xgetlist({'changedtick' : 0}).changedtick) + call g:Xsetlist([{'filename' : 'F7', 'lnum' : 10, 'text' : 'L7'}, + \ {'filename' : 'F7', 'lnum' : 11, 'text' : 'L11'}], 'a') + call assert_equal(8, g:Xgetlist({'changedtick' : 0}).changedtick) + call g:Xsetlist([{'filename' : 'F7', 'lnum' : 10, 'text' : 'L7'}, + \ {'filename' : 'F7', 'lnum' : 11, 'text' : 'L11'}], ' ') + call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick) + call g:Xsetlist([{'filename' : 'F7', 'lnum' : 10, 'text' : 'L7'}, + \ {'filename' : 'F7', 'lnum' : 11, 'text' : 'L11'}], 'r') + call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick) + + if isdirectory("Xone") + call delete("Xone", 'rf') + endif + call writefile(["F8:80:L80", "F8:81:L81"], "Xone") + Xfile Xone + call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick) + Xaddfile Xone + call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick) + + " Test case for updating a non-current quickfix list + call g:Xsetlist([], 'f') + Xexpr "F1:1:L1" + Xexpr "F2:2:L2" + call g:Xsetlist([], 'a', {'nr' : 1, "lines" : ["F10:10:L10"]}) + call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick) + call assert_equal(2, g:Xgetlist({'nr' : 1, 'changedtick' : 0}).changedtick) + + call delete("Xone") +endfunc + +func Test_qf_tick() + call Xqftick_tests('c') + call Xqftick_tests('l') +endfunc + +" Test helpgrep with lang specifier +func Xtest_helpgrep_with_lang_specifier(cchar) + call s:setup_commands(a:cchar) + Xhelpgrep Vim@en + call assert_equal('help', &filetype) + call assert_notequal(0, g:Xgetlist({'nr' : '$'}).nr) + new | only +endfunc + +func Test_helpgrep_with_lang_specifier() + call Xtest_helpgrep_with_lang_specifier('c') + call Xtest_helpgrep_with_lang_specifier('l') +endfunc + +" The following test used to crash Vim. +" Open the location list window and close the regular window associated with +" the location list. When the garbage collection runs now, it incorrectly +" marks the location list context as not in use and frees the context. +func Test_ll_window_ctx() + call setloclist(0, [], 'f') + call setloclist(0, [], 'a', {'context' : []}) + lopen | only + call test_garbagecollect_now() + echo getloclist(0, {'context' : 1}).context + enew | only +endfunc + +" The following test used to crash vim +func Test_lfile_crash() + sp Xtest + au QuickFixCmdPre * bw + call assert_fails('lfile', 'E40') + au! QuickFixCmdPre +endfunc + +" The following test used to crash vim +func Test_lbuffer_crash() + sv Xtest + augroup QF_Test + au! + au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * bw + augroup END + lbuffer + augroup QF_Test + au! + augroup END +endfunc + +" The following test used to crash vim +func Test_lexpr_crash() + augroup QF_Test + au! + au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * call setloclist(0, [], 'f') + augroup END + lexpr "" + augroup QF_Test + au! + augroup END + + enew | only + augroup QF_Test + au! + au BufNew * call setloclist(0, [], 'f') + augroup END + lexpr 'x:1:x' + augroup QF_Test + au! + augroup END + + enew | only + lexpr '' + lopen + augroup QF_Test + au! + au FileType * call setloclist(0, [], 'f') + augroup END + lexpr '' + augroup QF_Test + au! + augroup END +endfunc + +" The following test used to crash Vim +func Test_lvimgrep_crash() + sv Xtest + augroup QF_Test + au! + au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * call setloclist(0, [], 'f') + augroup END + lvimgrep quickfix test_quickfix.vim + augroup QF_Test + au! + augroup END + + new | only + augroup QF_Test + au! + au BufEnter * call setloclist(0, [], 'r') + augroup END + call assert_fails('lvimgrep Test_lvimgrep_crash *', 'E926:') + augroup QF_Test + au! + augroup END + + enew | only +endfunc + +func Test_lvimgrep_crash2() + au BufNewFile x sfind + call assert_fails('lvimgrep x x', 'E471:') + call assert_fails('lvimgrep x x x', 'E471:') + + au! BufNewFile +endfunc + +" Test for the position of the quickfix and location list window +func Test_qfwin_pos() + " Open two windows + new | only + new + cexpr ['F1:10:L10'] + copen + " Quickfix window should be the bottom most window + call assert_equal(3, winnr()) + close + " Open at the very top + wincmd t + topleft copen + call assert_equal(1, winnr()) + close + " open left of the current window + wincmd t + below new + leftabove copen + call assert_equal(2, winnr()) + close + " open right of the current window + rightbelow copen + call assert_equal(3, winnr()) + close +endfunc + +" Tests for quickfix/location lists changed by autocommands when +" :vimgrep/:lvimgrep commands are running. +func Test_vimgrep_autocmd() + call setqflist([], 'f') + call writefile(['stars'], 'Xtest1.txt') + call writefile(['stars'], 'Xtest2.txt') + + " Test 1: + " When searching for a pattern using :vimgrep, if the quickfix list is + " changed by an autocmd, the results should be added to the correct quickfix + " list. + autocmd BufRead Xtest2.txt cexpr '' | cexpr '' + silent vimgrep stars Xtest*.txt + call assert_equal(1, getqflist({'nr' : 0}).nr) + call assert_equal(3, getqflist({'nr' : '$'}).nr) + call assert_equal('Xtest2.txt', bufname(getqflist()[1].bufnr)) + au! BufRead Xtest2.txt + + " Test 2: + " When searching for a pattern using :vimgrep, if the quickfix list is + " freed, then a error should be given. + silent! %bwipe! + call setqflist([], 'f') + autocmd BufRead Xtest2.txt for i in range(10) | cexpr '' | endfor + call assert_fails('vimgrep stars Xtest*.txt', 'E925:') + au! BufRead Xtest2.txt + + " Test 3: + " When searching for a pattern using :lvimgrep, if the location list is + " freed, then the command should error out. + silent! %bwipe! + let g:save_winid = win_getid() + autocmd BufRead Xtest2.txt call setloclist(g:save_winid, [], 'f') + call assert_fails('lvimgrep stars Xtest*.txt', 'E926:') + au! BufRead Xtest2.txt + + call delete('Xtest1.txt') + call delete('Xtest2.txt') + call setqflist([], 'f') +endfunc + +" Test for an autocmd changing the current directory when running vimgrep +func Xvimgrep_autocmd_cd(cchar) + call s:setup_commands(a:cchar) + + %bwipe + let save_cwd = getcwd() + + augroup QF_Test + au! + autocmd BufRead * silent cd %:p:h + augroup END + + 10Xvimgrep /vim/ Xdir/** + let l = g:Xgetlist() + call assert_equal('f1.txt', bufname(l[0].bufnr)) + call assert_equal('f2.txt', fnamemodify(bufname(l[2].bufnr), ':t')) + + augroup QF_Test + au! + augroup END + + exe 'cd ' . save_cwd +endfunc + +func Test_vimgrep_autocmd_cd() + call mkdir('Xdir/a', 'p') + call mkdir('Xdir/b', 'p') + call writefile(['a_L1_vim', 'a_L2_vim'], 'Xdir/a/f1.txt') + call writefile(['b_L1_vim', 'b_L2_vim'], 'Xdir/b/f2.txt') + call Xvimgrep_autocmd_cd('c') + call Xvimgrep_autocmd_cd('l') + %bwipe + call delete('Xdir', 'rf') +endfunc + +" The following test used to crash Vim +func Test_lhelpgrep_autocmd() + lhelpgrep quickfix + augroup QF_Test + au! + autocmd QuickFixCmdPost * call setloclist(0, [], 'f') + augroup END + lhelpgrep buffer + call assert_equal('help', &filetype) + call assert_equal(0, getloclist(0, {'nr' : '$'}).nr) + lhelpgrep tabpage + call assert_equal('help', &filetype) + call assert_equal(1, getloclist(0, {'nr' : '$'}).nr) + augroup QF_Test + au! + augroup END + + new | only + augroup QF_Test + au! + au BufEnter * call setqflist([], 'f') + augroup END + call assert_fails('helpgrep quickfix', 'E925:') + " run the test with a help window already open + help + wincmd w + call assert_fails('helpgrep quickfix', 'E925:') + augroup QF_Test + au! + augroup END + + new | only + augroup QF_Test + au! + au BufEnter * call setqflist([], 'r') + augroup END + call assert_fails('helpgrep quickfix', 'E925:') + augroup QF_Test + au! + augroup END + + new | only + augroup QF_Test + au! + au BufEnter * call setloclist(0, [], 'r') + augroup END + call assert_fails('lhelpgrep quickfix', 'E926:') + augroup QF_Test + au! + augroup END + + " Replace the contents of a help window location list when it is still in + " use. + new | only + lhelpgrep quickfix + wincmd w + augroup QF_Test + au! + autocmd WinEnter * call setloclist(0, [], 'r') + augroup END + call assert_fails('lhelpgrep win_getid', 'E926:') + augroup QF_Test + au! + augroup END + + %bw! +endfunc + +" The following test used to crash Vim +func Test_lhelpgrep_autocmd_free_loclist() + %bw! + lhelpgrep quickfix + wincmd w + augroup QF_Test + au! + autocmd WinEnter * call setloclist(0, [], 'f') + augroup END + lhelpgrep win_getid + wincmd w + wincmd w + wincmd w + augroup QF_Test + au! + augroup END + %bw! +endfunc + +" Test for shortening/simplifying the file name when opening the +" quickfix window or when displaying the quickfix list +func Test_shorten_fname() + if !has('unix') + return + endif + %bwipe + " Create a quickfix list with a absolute path filename + let fname = getcwd() . '/test_quickfix.vim' + call setqflist([], ' ', {'lines':[fname . ":20:Line20"], 'efm':'%f:%l:%m'}) + call assert_equal(fname, bufname('test_quickfix.vim')) + " Opening the quickfix window should simplify the file path + cwindow + call assert_equal('test_quickfix.vim', bufname('test_quickfix.vim')) + cclose + %bwipe + " Create a quickfix list with a absolute path filename + call setqflist([], ' ', {'lines':[fname . ":20:Line20"], 'efm':'%f:%l:%m'}) + call assert_equal(fname, bufname('test_quickfix.vim')) + " Displaying the quickfix list should simplify the file path + silent! clist + call assert_equal('test_quickfix.vim', bufname('test_quickfix.vim')) + " Add a few entries for the same file with different paths and check whether + " the buffer name is shortened + %bwipe + call setqflist([], 'f') + call setqflist([{'filename' : 'test_quickfix.vim', 'lnum' : 10}, + \ {'filename' : '../testdir/test_quickfix.vim', 'lnum' : 20}, + \ {'filename' : fname, 'lnum' : 30}], ' ') + copen + call assert_equal(['test_quickfix.vim|10| ', + \ 'test_quickfix.vim|20| ', + \ 'test_quickfix.vim|30| '], getline(1, '$')) + cclose +endfunc + +" Quickfix title tests +" In the below tests, 'exe "cmd"' is used to invoke the quickfix commands. +" Otherwise due to indentation, the title is set with spaces at the beginning +" of the command. +func Test_qftitle() + call writefile(["F1:1:Line1"], 'Xerr') + + " :cexpr + exe "cexpr readfile('Xerr')" + call assert_equal(":cexpr readfile('Xerr')", getqflist({'title' : 1}).title) + + " :cgetexpr + exe "cgetexpr readfile('Xerr')" + call assert_equal(":cgetexpr readfile('Xerr')", + \ getqflist({'title' : 1}).title) + + " :caddexpr + call setqflist([], 'f') + exe "caddexpr readfile('Xerr')" + call assert_equal(":caddexpr readfile('Xerr')", + \ getqflist({'title' : 1}).title) + + " :cbuffer + new Xerr + exe "cbuffer" + call assert_equal(':cbuffer (Xerr)', getqflist({'title' : 1}).title) + + " :cgetbuffer + edit Xerr + exe "cgetbuffer" + call assert_equal(':cgetbuffer (Xerr)', getqflist({'title' : 1}).title) + + " :caddbuffer + call setqflist([], 'f') + edit Xerr + exe "caddbuffer" + call assert_equal(':caddbuffer (Xerr)', getqflist({'title' : 1}).title) + + " :cfile + exe "cfile Xerr" + call assert_equal(':cfile Xerr', getqflist({'title' : 1}).title) + + " :cgetfile + exe "cgetfile Xerr" + call assert_equal(':cgetfile Xerr', getqflist({'title' : 1}).title) + + " :caddfile + call setqflist([], 'f') + exe "caddfile Xerr" + call assert_equal(':caddfile Xerr', getqflist({'title' : 1}).title) + + " :grep + set grepprg=internal + exe "grep F1 Xerr" + call assert_equal(':grep F1 Xerr', getqflist({'title' : 1}).title) + + " :grepadd + call setqflist([], 'f') + exe "grepadd F1 Xerr" + call assert_equal(':grepadd F1 Xerr', getqflist({'title' : 1}).title) + set grepprg&vim + + " :vimgrep + exe "vimgrep F1 Xerr" + call assert_equal(':vimgrep F1 Xerr', getqflist({'title' : 1}).title) + + " :vimgrepadd + call setqflist([], 'f') + exe "vimgrepadd F1 Xerr" + call assert_equal(':vimgrepadd F1 Xerr', getqflist({'title' : 1}).title) + + call setqflist(['F1:10:L10'], ' ') + call assert_equal(':setqflist()', getqflist({'title' : 1}).title) + + call setqflist([], 'f') + call setqflist(['F1:10:L10'], 'a') + call assert_equal(':setqflist()', getqflist({'title' : 1}).title) + + call setqflist([], 'f') + call setqflist(['F1:10:L10'], 'r') + call assert_equal(':setqflist()', getqflist({'title' : 1}).title) + + close + call delete('Xerr') + + call setqflist([], ' ', {'title' : 'Errors'}) + copen + call assert_equal('Errors', w:quickfix_title) + call setqflist([], 'r', {'items' : [{'filename' : 'a.c', 'lnum' : 10}]}) + call assert_equal('Errors', w:quickfix_title) + cclose + + " Switching to another quickfix list in one tab page should update the + " quickfix window title and statusline in all the other tab pages also + call setqflist([], 'f') + %bw! + cgetexpr ['file_one:1:1: error in the first quickfix list'] + call setqflist([], 'a', {'title': 'first quickfix list'}) + cgetexpr ['file_two:2:1: error in the second quickfix list'] + call setqflist([], 'a', {'title': 'second quickfix list'}) + copen + wincmd t + tabnew two + copen + wincmd t + colder + call assert_equal('first quickfix list', gettabwinvar(1, 2, 'quickfix_title')) + call assert_equal('first quickfix list', gettabwinvar(2, 2, 'quickfix_title')) + call assert_equal(1, tabpagewinnr(1)) + call assert_equal(1, tabpagewinnr(2)) + tabnew + call setqflist([], 'a', {'title': 'new quickfix title'}) + call assert_equal('new quickfix title', gettabwinvar(1, 2, 'quickfix_title')) + call assert_equal('new quickfix title', gettabwinvar(2, 2, 'quickfix_title')) + %bw! +endfunc + +func Test_lbuffer_with_bwipe() + new + new + augroup nasty + au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * bwipe + augroup END + lbuffer + augroup nasty + au! + augroup END +endfunc + +" Test for an autocmd freeing the quickfix/location list when cexpr/lexpr is +" running +func Xexpr_acmd_freelist(cchar) + call s:setup_commands(a:cchar) + + " This was using freed memory (but with what events?) + augroup nasty + au QuickFixCmdPre,QuickFixCmdPost,BufEnter,BufLeave * call g:Xsetlist([], 'f') + augroup END + Xexpr "x" + augroup nasty + au! + augroup END +endfunc + +func Test_cexpr_acmd_freelist() + call Xexpr_acmd_freelist('c') + call Xexpr_acmd_freelist('l') +endfunc + +" Test for commands that create a new quickfix/location list and jump to the +" first error automatically. +func Xjumpto_first_error_test(cchar) + call s:setup_commands(a:cchar) + + call s:create_test_file('Xtestfile1') + call s:create_test_file('Xtestfile2') + let l = ['Xtestfile1:2:Line2', 'Xtestfile2:4:Line4'] + + " Test for cexpr/lexpr + enew + Xexpr l + call assert_equal('Xtestfile1', @%) + call assert_equal(2, line('.')) + + " Test for cfile/lfile + enew + call writefile(l, 'Xerr') + Xfile Xerr + call assert_equal('Xtestfile1', @%) + call assert_equal(2, line('.')) + + " Test for cbuffer/lbuffer + edit Xerr + Xbuffer + call assert_equal('Xtestfile1', @%) + call assert_equal(2, line('.')) + + call delete('Xerr') + call delete('Xtestfile1') + call delete('Xtestfile2') +endfunc + +func Test_jumpto_first_error() + call Xjumpto_first_error_test('c') + call Xjumpto_first_error_test('l') +endfunc + +" Test for a quickfix autocmd changing the quickfix/location list before +" jumping to the first error in the new list. +func Xautocmd_changelist(cchar) + call s:setup_commands(a:cchar) + + " Test for cfile/lfile + call s:create_test_file('Xtestfile1') + call s:create_test_file('Xtestfile2') + Xexpr 'Xtestfile1:2:Line2' + autocmd QuickFixCmdPost * Xolder + call writefile(['Xtestfile2:4:Line4'], 'Xerr') + Xfile Xerr + call assert_equal('Xtestfile2', @%) + call assert_equal(4, line('.')) + autocmd! QuickFixCmdPost + + " Test for cbuffer/lbuffer + call g:Xsetlist([], 'f') + Xexpr 'Xtestfile1:2:Line2' + autocmd QuickFixCmdPost * Xolder + call writefile(['Xtestfile2:4:Line4'], 'Xerr') + edit Xerr + Xbuffer + call assert_equal('Xtestfile2', @%) + call assert_equal(4, line('.')) + autocmd! QuickFixCmdPost + + " Test for cexpr/lexpr + call g:Xsetlist([], 'f') + Xexpr 'Xtestfile1:2:Line2' + autocmd QuickFixCmdPost * Xolder + Xexpr 'Xtestfile2:4:Line4' + call assert_equal('Xtestfile2', @%) + call assert_equal(4, line('.')) + autocmd! QuickFixCmdPost + + " The grepprg may not be set on non-Unix systems + if has('unix') + " Test for grep/lgrep + call g:Xsetlist([], 'f') + Xexpr 'Xtestfile1:2:Line2' + autocmd QuickFixCmdPost * Xolder + silent Xgrep Line5 Xtestfile2 + call assert_equal('Xtestfile2', @%) + call assert_equal(5, line('.')) + autocmd! QuickFixCmdPost + endif + + " Test for vimgrep/lvimgrep + call g:Xsetlist([], 'f') + Xexpr 'Xtestfile1:2:Line2' + autocmd QuickFixCmdPost * Xolder + silent Xvimgrep Line5 Xtestfile2 + call assert_equal('Xtestfile2', @%) + call assert_equal(5, line('.')) + autocmd! QuickFixCmdPost + + " Test for autocommands clearing the quickfix list before jumping to the + " first error. This should not result in an error + autocmd QuickFixCmdPost * call g:Xsetlist([], 'r') + let v:errmsg = '' + " Test for cfile/lfile + Xfile Xerr + call assert_true(v:errmsg !~# 'E42:') + " Test for cbuffer/lbuffer + edit Xerr + Xbuffer + call assert_true(v:errmsg !~# 'E42:') + " Test for cexpr/lexpr + Xexpr 'Xtestfile2:4:Line4' + call assert_true(v:errmsg !~# 'E42:') + " Test for grep/lgrep + " The grepprg may not be set on non-Unix systems + if has('unix') + silent Xgrep Line5 Xtestfile2 + call assert_true(v:errmsg !~# 'E42:') + endif + " Test for vimgrep/lvimgrep + call assert_fails('silent Xvimgrep Line5 Xtestfile2', 'E480:') + autocmd! QuickFixCmdPost + + call delete('Xerr') + call delete('Xtestfile1') + call delete('Xtestfile2') +endfunc + +func Test_autocmd_changelist() + call Xautocmd_changelist('c') + call Xautocmd_changelist('l') +endfunc + +" Tests for the ':filter /pat/ clist' command +func Test_filter_clist() + cexpr ['Xfile1:10:10:Line 10', 'Xfile2:15:15:Line 15'] + call assert_equal([' 2 Xfile2:15 col 15: Line 15'], + \ split(execute('filter /Line 15/ clist'), "\n")) + call assert_equal([' 1 Xfile1:10 col 10: Line 10'], + \ split(execute('filter /Xfile1/ clist'), "\n")) + call assert_equal([], split(execute('filter /abc/ clist'), "\n")) + + call setqflist([{'module' : 'abc', 'pattern' : 'pat1'}, + \ {'module' : 'pqr', 'pattern' : 'pat2'}], ' ') + call assert_equal([' 2 pqr:pat2: '], + \ split(execute('filter /pqr/ clist'), "\n")) + call assert_equal([' 1 abc:pat1: '], + \ split(execute('filter /pat1/ clist'), "\n")) +endfunc + +" Tests for the "CTRL-W <CR>" command. +func Xview_result_split_tests(cchar) + call s:setup_commands(a:cchar) + + " Test that "CTRL-W <CR>" in a qf/ll window fails with empty list. + call g:Xsetlist([]) + Xopen + let l:win_count = winnr('$') + call assert_fails('execute "normal! \<C-W>\<CR>"', 'E42') + call assert_equal(l:win_count, winnr('$')) + Xclose +endfunc + +func Test_view_result_split() + call Xview_result_split_tests('c') + call Xview_result_split_tests('l') +endfunc + +" Test that :cc sets curswant +func Test_curswant() + helpgrep quickfix + normal! llll + 1cc + call assert_equal(getcurpos()[4], virtcol('.')) + cclose | helpclose +endfunc + +" Test for opening a file from the quickfix window using CTRL-W <Enter> +" doesn't leave an empty buffer around. +func Test_splitview() + call s:create_test_file('Xtestfile1') + call s:create_test_file('Xtestfile2') + new | only + let last_bufnr = bufnr('Test_sv_1', 1) + let l = ['Xtestfile1:2:Line2', 'Xtestfile2:4:Line4'] + cgetexpr l + copen + let numbufs = len(getbufinfo()) + exe "normal \<C-W>\<CR>" + copen + exe "normal j\<C-W>\<CR>" + " Make sure new empty buffers are not created + call assert_equal(numbufs, len(getbufinfo())) + " Creating a new buffer should use the next available buffer number + call assert_equal(last_bufnr + 4, bufnr("Test_sv_2", 1)) + bwipe Test_sv_1 + bwipe Test_sv_2 + new | only + + " When split opening files from location list window, make sure that two + " windows doesn't refer to the same location list + lgetexpr l + let locid = getloclist(0, {'id' : 0}).id + lopen + exe "normal \<C-W>\<CR>" + call assert_notequal(locid, getloclist(0, {'id' : 0}).id) + call assert_equal(0, getloclist(0, {'winid' : 0}).winid) + new | only + + " When split opening files from a helpgrep location list window, a new help + " window should be opened with a copy of the location list. + lhelpgrep window + let locid = getloclist(0, {'id' : 0}).id + lwindow + exe "normal j\<C-W>\<CR>" + call assert_notequal(locid, getloclist(0, {'id' : 0}).id) + call assert_equal(0, getloclist(0, {'winid' : 0}).winid) + new | only + + " Using :split or :vsplit from a quickfix window should behave like a :new + " or a :vnew command + copen + split + call assert_equal(3, winnr('$')) + let l = getwininfo() + call assert_equal([0, 0, 1], [l[0].quickfix, l[1].quickfix, l[2].quickfix]) + close + copen + vsplit + let l = getwininfo() + call assert_equal([0, 0, 1], [l[0].quickfix, l[1].quickfix, l[2].quickfix]) + new | only + + call delete('Xtestfile1') + call delete('Xtestfile2') +endfunc + +" Test for parsing entries using visual screen column +func Test_viscol() + enew + call writefile(["Col1\tCol2\tCol3"], 'Xfile1') + edit Xfile1 + + " Use byte offset for column number + set efm& + cexpr "Xfile1:1:5:XX\nXfile1:1:9:YY\nXfile1:1:20:ZZ" + call assert_equal([5, 8], [col('.'), virtcol('.')]) + cnext + call assert_equal([9, 12], [col('.'), virtcol('.')]) + cnext + call assert_equal([14, 20], [col('.'), virtcol('.')]) + + " Use screen column offset for column number + set efm=%f:%l:%v:%m + cexpr "Xfile1:1:8:XX\nXfile1:1:12:YY\nXfile1:1:20:ZZ" + call assert_equal([5, 8], [col('.'), virtcol('.')]) + cnext + call assert_equal([9, 12], [col('.'), virtcol('.')]) + cnext + call assert_equal([14, 20], [col('.'), virtcol('.')]) + cexpr "Xfile1:1:6:XX\nXfile1:1:15:YY\nXfile1:1:24:ZZ" + call assert_equal([5, 8], [col('.'), virtcol('.')]) + cnext + call assert_equal([10, 16], [col('.'), virtcol('.')]) + cnext + call assert_equal([14, 20], [col('.'), virtcol('.')]) + + enew + call writefile(["Col1\täü\töß\tCol4"], 'Xfile1') + + " Use byte offset for column number + set efm& + cexpr "Xfile1:1:8:XX\nXfile1:1:11:YY\nXfile1:1:16:ZZ" + call assert_equal([8, 10], [col('.'), virtcol('.')]) + cnext + call assert_equal([11, 17], [col('.'), virtcol('.')]) + cnext + call assert_equal([16, 25], [col('.'), virtcol('.')]) + + " Use screen column offset for column number + set efm=%f:%l:%v:%m + cexpr "Xfile1:1:10:XX\nXfile1:1:17:YY\nXfile1:1:25:ZZ" + call assert_equal([8, 10], [col('.'), virtcol('.')]) + cnext + call assert_equal([11, 17], [col('.'), virtcol('.')]) + cnext + call assert_equal([16, 25], [col('.'), virtcol('.')]) + + " Use screen column number with a multi-line error message + enew + call writefile(["à test"], 'Xfile1') + set efm=%E===\ %f\ ===,%C%l:%v,%Z%m + cexpr ["=== Xfile1 ===", "1:3", "errormsg"] + call assert_equal('Xfile1', @%) + call assert_equal([0, 1, 4, 0], getpos('.')) + + " Repeat previous test with byte offset %c: ensure that fix to issue #7145 + " does not break this + set efm=%E===\ %f\ ===,%C%l:%c,%Z%m + cexpr ["=== Xfile1 ===", "1:3", "errormsg"] + call assert_equal('Xfile1', @%) + call assert_equal([0, 1, 3, 0], getpos('.')) + + enew | only + set efm& + call delete('Xfile1') +endfunc + +" Test for the quickfix window buffer +func Xqfbuf_test(cchar) + call s:setup_commands(a:cchar) + + " Quickfix buffer should be reused across closing and opening a quickfix + " window + Xexpr "F1:10:Line10" + Xopen + let qfbnum = bufnr('') + Xclose + " Even after the quickfix window is closed, the buffer should be loaded + call assert_true(bufloaded(qfbnum)) + call assert_true(qfbnum, g:Xgetlist({'qfbufnr' : 0}).qfbufnr) + Xopen + " Buffer should be reused when opening the window again + call assert_equal(qfbnum, bufnr('')) + Xclose + + " When quickfix buffer is wiped out, getqflist() should return 0 + %bw! + Xexpr "" + Xopen + bw! + call assert_equal(0, g:Xgetlist({'qfbufnr': 0}).qfbufnr) + + if a:cchar == 'l' + %bwipe + " For a location list, when both the file window and the location list + " window for the list are closed, then the buffer should be freed. + new | only + lexpr "F1:10:Line10" + let wid = win_getid() + lopen + let qfbnum = bufnr('') + call assert_match(qfbnum . ' %a- "\[Location List]"', execute('ls')) + close + " When the location list window is closed, the buffer name should not + " change to 'Quickfix List' + call assert_match(qfbnum . 'u h- "\[Location List]"', execute('ls!')) + call assert_true(bufloaded(qfbnum)) + + " After deleting a location list buffer using ":bdelete", opening the + " location list window should mark the buffer as a location list buffer. + exe "bdelete " . qfbnum + lopen + call assert_equal("quickfix", &buftype) + call assert_equal(1, getwininfo(win_getid(winnr()))[0].loclist) + call assert_equal(wid, getloclist(0, {'filewinid' : 0}).filewinid) + call assert_false(&swapfile) + lclose + + " When the location list is cleared for the window, the buffer should be + " removed + call setloclist(0, [], 'f') + call assert_false(bufexists(qfbnum)) + call assert_equal(0, getloclist(0, {'qfbufnr' : 0}).qfbufnr) + + " When the location list is freed with the location list window open, the + " location list buffer should not be lost. It should be reused when the + " location list is again populated. + lexpr "F1:10:Line10" + lopen + let wid = win_getid() + let qfbnum = bufnr('') + wincmd p + call setloclist(0, [], 'f') + lexpr "F1:10:Line10" + lopen + call assert_equal(wid, win_getid()) + call assert_equal(qfbnum, bufnr('')) + lclose + + " When the window with the location list is closed, the buffer should be + " removed + new | only + call assert_false(bufexists(qfbnum)) + endif +endfunc + +func Test_qfbuf() + call Xqfbuf_test('c') + call Xqfbuf_test('l') +endfunc + +" If there is an autocmd to use only one window, then opening the location +" list window used to crash Vim. +func Test_winonly_autocmd() + call s:create_test_file('Xtest1') + " Autocmd to show only one Vim window at a time + autocmd WinEnter * only + new + " Load the location list + lexpr "Xtest1:5:Line5\nXtest1:10:Line10\nXtest1:15:Line15" + let loclistid = getloclist(0, {'id' : 0}).id + " Open the location list window. Only this window will be shown and the file + " window is closed. + lopen + call assert_equal(loclistid, getloclist(0, {'id' : 0}).id) + " Jump to an entry in the location list and make sure that the cursor is + " positioned correctly. + ll 3 + call assert_equal(loclistid, getloclist(0, {'id' : 0}).id) + call assert_equal('Xtest1', @%) + call assert_equal(15, line('.')) + " Cleanup + autocmd! WinEnter + new | only + call delete('Xtest1') +endfunc + +" Test to make sure that an empty quickfix buffer is not reused for loading +" a normal buffer. +func Test_empty_qfbuf() + enew | only + call writefile(["Test"], 'Xfile1') + call setqflist([], 'f') + copen | only + let qfbuf = bufnr('') + edit Xfile1 + call assert_notequal(qfbuf, bufnr('')) + enew + call delete('Xfile1') +endfunc + +" Test for the :cbelow, :cabove, :lbelow and :labove commands. +" And for the :cafter, :cbefore, :lafter and :lbefore commands. +func Xtest_below(cchar) + call s:setup_commands(a:cchar) + + " No quickfix/location list + call assert_fails('Xbelow', 'E42:') + call assert_fails('Xabove', 'E42:') + call assert_fails('Xbefore', 'E42:') + call assert_fails('Xafter', 'E42:') + + " Empty quickfix/location list + call g:Xsetlist([]) + call assert_fails('Xbelow', 'E42:') + call assert_fails('Xabove', 'E42:') + call assert_fails('Xbefore', 'E42:') + call assert_fails('Xafter', 'E42:') + + call s:create_test_file('X1') + call s:create_test_file('X2') + call s:create_test_file('X3') + call s:create_test_file('X4') + + " Invalid entries + edit X1 + call g:Xsetlist(["E1", "E2"]) + call assert_fails('Xbelow', 'E42:') + call assert_fails('Xabove', 'E42:') + call assert_fails('3Xbelow', 'E42:') + call assert_fails('4Xabove', 'E42:') + call assert_fails('Xbefore', 'E42:') + call assert_fails('Xafter', 'E42:') + call assert_fails('3Xbefore', 'E42:') + call assert_fails('4Xafter', 'E42:') + + " Test the commands with various arguments + Xexpr ["X1:5:3:L5", "X2:5:2:L5", "X2:10:3:L10", "X2:15:4:L15", "X3:3:5:L3"] + edit +7 X2 + Xabove + call assert_equal(['X2', 5], [@%, line('.')]) + call assert_fails('Xabove', 'E553:') + normal 7G + Xbefore + call assert_equal(['X2', 5, 2], [@%, line('.'), col('.')]) + call assert_fails('Xbefore', 'E553:') + + normal 2j + Xbelow + call assert_equal(['X2', 10], [@%, line('.')]) + normal 7G + Xafter + call assert_equal(['X2', 10, 3], [@%, line('.'), col('.')]) + + " Last error in this file + Xbelow 99 + call assert_equal(['X2', 15], [@%, line('.')]) + call assert_fails('Xbelow', 'E553:') + normal gg + Xafter 99 + call assert_equal(['X2', 15, 4], [@%, line('.'), col('.')]) + call assert_fails('Xafter', 'E553:') + + " First error in this file + Xabove 99 + call assert_equal(['X2', 5], [@%, line('.')]) + call assert_fails('Xabove', 'E553:') + normal G + Xbefore 99 + call assert_equal(['X2', 5, 2], [@%, line('.'), col('.')]) + call assert_fails('Xbefore', 'E553:') + + normal gg + Xbelow 2 + call assert_equal(['X2', 10], [@%, line('.')]) + normal gg + Xafter 2 + call assert_equal(['X2', 10, 3], [@%, line('.'), col('.')]) + + normal G + Xabove 2 + call assert_equal(['X2', 10], [@%, line('.')]) + normal G + Xbefore 2 + call assert_equal(['X2', 10, 3], [@%, line('.'), col('.')]) + + edit X4 + call assert_fails('Xabove', 'E42:') + call assert_fails('Xbelow', 'E42:') + call assert_fails('Xbefore', 'E42:') + call assert_fails('Xafter', 'E42:') + if a:cchar == 'l' + " If a buffer has location list entries from some other window but not + " from the current window, then the commands should fail. + edit X1 | split | call setloclist(0, [], 'f') + call assert_fails('Xabove', 'E776:') + call assert_fails('Xbelow', 'E776:') + call assert_fails('Xbefore', 'E776:') + call assert_fails('Xafter', 'E776:') + close + endif + + " Test for lines with multiple quickfix entries + let lines =<< trim END + X1:5:L5 + X2:5:1:L5_1 + X2:5:2:L5_2 + X2:5:3:L5_3 + X2:10:1:L10_1 + X2:10:2:L10_2 + X2:10:3:L10_3 + X2:15:1:L15_1 + X2:15:2:L15_2 + X2:15:3:L15_3 + X3:3:L3 + END + Xexpr lines + edit +1 X2 + Xbelow 2 + call assert_equal(['X2', 10, 1], [@%, line('.'), col('.')]) + normal 1G + Xafter 2 + call assert_equal(['X2', 5, 2], [@%, line('.'), col('.')]) + + normal gg + Xbelow 99 + call assert_equal(['X2', 15, 1], [@%, line('.'), col('.')]) + normal gg + Xafter 99 + call assert_equal(['X2', 15, 3], [@%, line('.'), col('.')]) + + normal G + Xabove 2 + call assert_equal(['X2', 10, 1], [@%, line('.'), col('.')]) + normal G + Xbefore 2 + call assert_equal(['X2', 15, 2], [@%, line('.'), col('.')]) + + normal G + Xabove 99 + call assert_equal(['X2', 5, 1], [@%, line('.'), col('.')]) + normal G + Xbefore 99 + call assert_equal(['X2', 5, 1], [@%, line('.'), col('.')]) + + normal 10G + Xabove + call assert_equal(['X2', 5, 1], [@%, line('.'), col('.')]) + normal 10G$ + 2Xbefore + call assert_equal(['X2', 10, 2], [@%, line('.'), col('.')]) + + normal 10G + Xbelow + call assert_equal(['X2', 15, 1], [@%, line('.'), col('.')]) + normal 9G + 5Xafter + call assert_equal(['X2', 15, 2], [@%, line('.'), col('.')]) + + " Invalid range + if a:cchar == 'c' + call assert_fails('-2cbelow', 'E16:') + call assert_fails('-2cafter', 'E16:') + else + call assert_fails('-2lbelow', 'E16:') + call assert_fails('-2lafter', 'E16:') + endif + + call delete('X1') + call delete('X2') + call delete('X3') + call delete('X4') +endfunc + +func Test_cbelow() + call Xtest_below('c') + call Xtest_below('l') +endfunc + +func Test_quickfix_count() + let commands =<< trim END + cNext + cNfile + cabove + cbelow + cfirst + clast + cnewer + cnext + cnfile + colder + cprevious + crewind + lNext + lNfile + labove + lbelow + lfirst + llast + lnewer + lnext + lnfile + lolder + lprevious + lrewind + END + for cmd in commands + call assert_fails('-1' .. cmd, 'E16:') + call assert_fails('.' .. cmd, 'E16:') + call assert_fails('%' .. cmd, 'E16:') + call assert_fails('$' .. cmd, 'E16:') + endfor +endfunc + +" Test for aborting quickfix commands using QuickFixCmdPre +func Xtest_qfcmd_abort(cchar) + call s:setup_commands(a:cchar) + + call g:Xsetlist([], 'f') + + " cexpr/lexpr + let e = '' + try + Xexpr ["F1:10:Line10", "F2:20:Line20"] + catch /.*/ + let e = v:exception + endtry + call assert_equal('AbortCmd', e) + call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr) + + " cfile/lfile + call writefile(["F1:10:Line10", "F2:20:Line20"], 'Xfile1') + let e = '' + try + Xfile Xfile1 + catch /.*/ + let e = v:exception + endtry + call assert_equal('AbortCmd', e) + call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr) + call delete('Xfile1') + + " cgetbuffer/lgetbuffer + enew! + call append(0, ["F1:10:Line10", "F2:20:Line20"]) + let e = '' + try + Xgetbuffer + catch /.*/ + let e = v:exception + endtry + call assert_equal('AbortCmd', e) + call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr) + enew! + + " vimgrep/lvimgrep + let e = '' + try + Xvimgrep /func/ test_quickfix.vim + catch /.*/ + let e = v:exception + endtry + call assert_equal('AbortCmd', e) + call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr) + + " helpgrep/lhelpgrep + let e = '' + try + Xhelpgrep quickfix + catch /.*/ + let e = v:exception + endtry + call assert_equal('AbortCmd', e) + call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr) + + " grep/lgrep + if has('unix') + let e = '' + try + silent Xgrep func test_quickfix.vim + catch /.*/ + let e = v:exception + endtry + call assert_equal('AbortCmd', e) + call assert_equal(0, g:Xgetlist({'nr' : '$'}).nr) + endif +endfunc + +func Test_qfcmd_abort() + augroup QF_Test + au! + autocmd QuickFixCmdPre * throw "AbortCmd" + augroup END + + call Xtest_qfcmd_abort('c') + call Xtest_qfcmd_abort('l') + + augroup QF_Test + au! + augroup END +endfunc + +" Test for using a file in one of the parent directories. +func Test_search_in_dirstack() + call mkdir('Xtestdir/a/b/c', 'p') + let save_cwd = getcwd() + call writefile(["X1_L1", "X1_L2"], 'Xtestdir/Xfile1') + call writefile(["X2_L1", "X2_L2"], 'Xtestdir/a/Xfile2') + call writefile(["X3_L1", "X3_L2"], 'Xtestdir/a/b/Xfile3') + call writefile(["X4_L1", "X4_L2"], 'Xtestdir/a/b/c/Xfile4') + + let lines = "Entering dir Xtestdir\n" . + \ "Entering dir a\n" . + \ "Entering dir b\n" . + \ "Xfile2:2:X2_L2\n" . + \ "Leaving dir a\n" . + \ "Xfile1:2:X1_L2\n" . + \ "Xfile3:1:X3_L1\n" . + \ "Entering dir c\n" . + \ "Xfile4:2:X4_L2\n" . + \ "Leaving dir c\n" + set efm=%DEntering\ dir\ %f,%XLeaving\ dir\ %f,%f:%l:%m + cexpr lines .. "Leaving dir Xtestdir|\n" | let next = 1 + call assert_equal(11, getqflist({'size' : 0}).size) + call assert_equal(4, getqflist({'idx' : 0}).idx) + call assert_equal('X2_L2', getline('.')) + call assert_equal(1, next) + cnext + call assert_equal(6, getqflist({'idx' : 0}).idx) + call assert_equal('X1_L2', getline('.')) + cnext + call assert_equal(7, getqflist({'idx' : 0}).idx) + call assert_equal(1, line('$')) + call assert_equal('', getline(1)) + cnext + call assert_equal(9, getqflist({'idx' : 0}).idx) + call assert_equal(1, line('$')) + call assert_equal('', getline(1)) + + set efm& + exe 'cd ' . save_cwd + call delete('Xtestdir', 'rf') +endfunc + +" Test for :cquit +func Test_cquit() + " Exit Vim with a non-zero value + if RunVim([], ["cquit 7"], '') + call assert_equal(7, v:shell_error) + endif + + if RunVim([], ["50cquit"], '') + call assert_equal(50, v:shell_error) + endif + + " Exit Vim with default value + if RunVim([], ["cquit"], '') + call assert_equal(1, v:shell_error) + endif + + " Exit Vim with zero value + if RunVim([], ["cquit 0"], '') + call assert_equal(0, v:shell_error) + endif + + " Exit Vim with negative value + call assert_fails('-3cquit', 'E16:') +endfunc + +" Test for getting a specific item from a quickfix list +func Xtest_getqflist_by_idx(cchar) + call s:setup_commands(a:cchar) + " Empty list + call assert_equal([], g:Xgetlist({'idx' : 1, 'items' : 0}).items) + Xexpr ['F1:10:L10', 'F1:20:L20'] + let l = g:Xgetlist({'idx' : 2, 'items' : 0}).items + call assert_equal(bufnr('F1'), l[0].bufnr) + call assert_equal(20, l[0].lnum) + call assert_equal('L20', l[0].text) + call assert_equal([], g:Xgetlist({'idx' : -1, 'items' : 0}).items) + call assert_equal([], g:Xgetlist({'idx' : 3, 'items' : 0}).items) + call assert_equal({}, g:Xgetlist(#{idx: "abc"})) + %bwipe! +endfunc + +func Test_getqflist_by_idx() + call Xtest_getqflist_by_idx('c') + call Xtest_getqflist_by_idx('l') +endfunc + +" Test for the 'quickfixtextfunc' setting +func Tqfexpr(info) + if a:info.quickfix + let qfl = getqflist({'id' : a:info.id, 'items' : 1}).items + else + let qfl = getloclist(a:info.winid, {'id' : a:info.id, 'items' : 1}).items + endif + + let l = [] + for idx in range(a:info.start_idx - 1, a:info.end_idx - 1) + let e = qfl[idx] + let s = '' + if e.bufnr != 0 + let bname = bufname(e.bufnr) + let s ..= fnamemodify(bname, ':.') + endif + let s ..= '-' + let s ..= 'L' .. string(e.lnum) .. 'C' .. string(e.col) .. '-' + let s ..= e.text + call add(l, s) + endfor + + return l +endfunc + +func Xtest_qftextfunc(cchar) + call s:setup_commands(a:cchar) + + set efm=%f:%l:%c:%m + set quickfixtextfunc=Tqfexpr + call assert_equal('Tqfexpr', &quickfixtextfunc) + call assert_equal('', + \ g:Xgetlist({'quickfixtextfunc' : 1}).quickfixtextfunc) + call g:Xsetlist([ + \ { 'filename': 'F1', 'lnum': 10, 'col': 2, + \ 'end_col': 7, 'text': 'green'}, + \ { 'filename': 'F1', 'lnum': 20, 'end_lnum': 25, 'col': 4, + \ 'end_col': 8, 'text': 'blue'}, + \ ]) + + Xwindow + call assert_equal('F1-L10C2-green', getline(1)) + call assert_equal('F1-L20C4-blue', getline(2)) + Xclose + set quickfixtextfunc&vim + Xwindow + call assert_equal('F1|10 col 2-7| green', getline(1)) + call assert_equal('F1|20-25 col 4-8| blue', getline(2)) + Xclose + + set efm=%f:%l:%c:%m + set quickfixtextfunc=Tqfexpr + " Update the list with only the cwindow + Xwindow + only + call g:Xsetlist([ + \ { 'filename': 'F2', 'lnum': 20, 'col': 2, + \ 'end_col': 7, 'text': 'red'} + \ ]) + call assert_equal(['F2-L20C2-red'], getline(1, '$')) + new + Xclose + set efm& + set quickfixtextfunc& + + " Test for per list 'quickfixtextfunc' setting + func PerQfText(info) + if a:info.quickfix + let qfl = getqflist({'id' : a:info.id, 'items' : 1}).items + else + let qfl = getloclist(a:info.winid, {'id' : a:info.id, 'items' : 1}).items + endif + if empty(qfl) + return [] + endif + let l = [] + for idx in range(a:info.start_idx - 1, a:info.end_idx - 1) + call add(l, 'Line ' .. qfl[idx].lnum .. ', Col ' .. qfl[idx].col) + endfor + return l + endfunc + set quickfixtextfunc=Tqfexpr + call g:Xsetlist([], ' ', {'quickfixtextfunc' : "PerQfText"}) + Xaddexpr ['F1:10:2:green', 'F1:20:4:blue'] + Xwindow + call assert_equal('Line 10, Col 2', getline(1)) + call assert_equal('Line 20, Col 4', getline(2)) + Xclose + call assert_equal(function('PerQfText'), + \ g:Xgetlist({'quickfixtextfunc' : 1}).quickfixtextfunc) + " Add entries to the list when the quickfix buffer is hidden + Xaddexpr ['F1:30:6:red'] + Xwindow + call assert_equal('Line 30, Col 6', getline(3)) + Xclose + call g:Xsetlist([], 'r', {'quickfixtextfunc' : ''}) + call assert_equal('', g:Xgetlist({'quickfixtextfunc' : 1}).quickfixtextfunc) + set quickfixtextfunc& + delfunc PerQfText + + " Non-existing function + set quickfixtextfunc=Tabc + call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E117:') + call assert_fails("Xwindow", 'E117:') + Xclose + set quickfixtextfunc& + + " set option to a non-function + set quickfixtextfunc=[10,\ 20] + call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E117:') + call assert_fails("Xwindow", 'E117:') + Xclose + set quickfixtextfunc& + + " set option to a function with different set of arguments + func Xqftext(a, b, c) + return a:a .. a:b .. a:c + endfunc + set quickfixtextfunc=Xqftext + call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E119:') + call assert_fails("Xwindow", 'E119:') + Xclose + + " set option to a function that returns a list with non-strings + func Xqftext2(d) + return ['one', [], 'two'] + endfunc + set quickfixtextfunc=Xqftext2 + call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue', 'F1:30:6:red']", + \ 'E730:') + call assert_fails('Xwindow', 'E730:') + call assert_equal(['one', 'F1|20 col 4| blue', 'F1|30 col 6| red'], + \ getline(1, '$')) + Xclose + + set quickfixtextfunc& + delfunc Xqftext + delfunc Xqftext2 + + " set the global option to a lambda function + set quickfixtextfunc={d\ ->\ map(g:Xgetlist({'id'\ :\ d.id,\ 'items'\ :\ 1}).items[d.start_idx-1:d.end_idx-1],\ 'v:val.text')} + Xexpr ['F1:10:2:green', 'F1:20:4:blue'] + Xwindow + call assert_equal(['green', 'blue'], getline(1, '$')) + Xclose + call assert_equal("{d -> map(g:Xgetlist({'id' : d.id, 'items' : 1}).items[d.start_idx-1:d.end_idx-1], 'v:val.text')}", &quickfixtextfunc) + set quickfixtextfunc& + + " use a lambda function that returns an empty list + set quickfixtextfunc={d\ ->\ []} + Xexpr ['F1:10:2:green', 'F1:20:4:blue'] + Xwindow + call assert_equal(['F1|10 col 2| green', 'F1|20 col 4| blue'], + \ getline(1, '$')) + Xclose + set quickfixtextfunc& + + " use a lambda function that returns a list with empty strings + set quickfixtextfunc={d\ ->\ ['',\ '']} + Xexpr ['F1:10:2:green', 'F1:20:4:blue'] + Xwindow + call assert_equal(['F1|10 col 2| green', 'F1|20 col 4| blue'], + \ getline(1, '$')) + Xclose + set quickfixtextfunc& + + " set the per-quickfix list text function to a lambda function + call g:Xsetlist([], ' ', + \ {'quickfixtextfunc' : + \ {d -> map(g:Xgetlist({'id' : d.id, 'items' : 1}).items[d.start_idx-1:d.end_idx-1], + \ "'Line ' .. v:val.lnum .. ', Col ' .. v:val.col")}}) + Xaddexpr ['F1:10:2:green', 'F1:20:4:blue'] + Xwindow + call assert_equal('Line 10, Col 2', getline(1)) + call assert_equal('Line 20, Col 4', getline(2)) + Xclose + call assert_match("function('<lambda>\\d\\+')", string(g:Xgetlist({'quickfixtextfunc' : 1}).quickfixtextfunc)) + call g:Xsetlist([], 'f') +endfunc + +func Test_qftextfunc() + call Xtest_qftextfunc('c') + call Xtest_qftextfunc('l') +endfunc + +func Test_qftextfunc_callback() + let lines =<< trim END + set efm=%f:%l:%c:%m + + #" Test for using a function name + LET &qftf = 'g:Tqfexpr' + cexpr "F0:0:0:L0" + copen + call assert_equal('F0-L0C0-L0', getline(1)) + cclose + + #" Test for using a function() + set qftf=function('g:Tqfexpr') + cexpr "F1:1:1:L1" + copen + call assert_equal('F1-L1C1-L1', getline(1)) + cclose + + #" Using a funcref variable to set 'quickfixtextfunc' + VAR Fn = function('g:Tqfexpr') + LET &qftf = Fn + cexpr "F2:2:2:L2" + copen + call assert_equal('F2-L2C2-L2', getline(1)) + cclose + + #" Using string(funcref_variable) to set 'quickfixtextfunc' + LET Fn = function('g:Tqfexpr') + LET &qftf = string(Fn) + cexpr "F3:3:3:L3" + copen + call assert_equal('F3-L3C3-L3', getline(1)) + cclose + + #" Test for using a funcref() + set qftf=funcref('g:Tqfexpr') + cexpr "F4:4:4:L4" + copen + call assert_equal('F4-L4C4-L4', getline(1)) + cclose + + #" Using a funcref variable to set 'quickfixtextfunc' + LET Fn = funcref('g:Tqfexpr') + LET &qftf = Fn + cexpr "F5:5:5:L5" + copen + call assert_equal('F5-L5C5-L5', getline(1)) + cclose + + #" Using a string(funcref_variable) to set 'quickfixtextfunc' + LET Fn = funcref('g:Tqfexpr') + LET &qftf = string(Fn) + cexpr "F5:5:5:L5" + copen + call assert_equal('F5-L5C5-L5', getline(1)) + cclose + + #" Test for using a lambda function with set + VAR optval = "LSTART a LMIDDLE Tqfexpr(a) LEND" + LET optval = substitute(optval, ' ', '\\ ', 'g') + exe "set qftf=" .. optval + cexpr "F6:6:6:L6" + copen + call assert_equal('F6-L6C6-L6', getline(1)) + cclose + + #" Set 'quickfixtextfunc' to a lambda expression + LET &qftf = LSTART a LMIDDLE Tqfexpr(a) LEND + cexpr "F7:7:7:L7" + copen + call assert_equal('F7-L7C7-L7', getline(1)) + cclose + + #" Set 'quickfixtextfunc' to string(lambda_expression) + LET &qftf = "LSTART a LMIDDLE Tqfexpr(a) LEND" + cexpr "F8:8:8:L8" + copen + call assert_equal('F8-L8C8-L8', getline(1)) + cclose + + #" Set 'quickfixtextfunc' to a variable with a lambda expression + VAR Lambda = LSTART a LMIDDLE Tqfexpr(a) LEND + LET &qftf = Lambda + cexpr "F9:9:9:L9" + copen + call assert_equal('F9-L9C9-L9', getline(1)) + cclose + + #" Set 'quickfixtextfunc' to a string(variable with a lambda expression) + LET Lambda = LSTART a LMIDDLE Tqfexpr(a) LEND + LET &qftf = string(Lambda) + cexpr "F9:9:9:L9" + copen + call assert_equal('F9-L9C9-L9', getline(1)) + cclose + END + call CheckLegacyAndVim9Success(lines) + + " Test for using a script-local function name + func s:TqfFunc2(info) + let g:TqfFunc2Args = [a:info.start_idx, a:info.end_idx] + return '' + endfunc + let g:TqfFunc2Args = [] + set quickfixtextfunc=s:TqfFunc2 + cexpr "F10:10:10:L10" + cclose + call assert_equal([1, 1], g:TqfFunc2Args) + + let &quickfixtextfunc = 's:TqfFunc2' + cexpr "F11:11:11:L11" + cclose + call assert_equal([1, 1], g:TqfFunc2Args) + delfunc s:TqfFunc2 + + " set 'quickfixtextfunc' to a partial with dict. This used to cause a crash. + func SetQftfFunc() + let params = {'qftf': function('g:DictQftfFunc')} + let &quickfixtextfunc = params.qftf + endfunc + func g:DictQftfFunc(_) dict + endfunc + call SetQftfFunc() + new + call SetQftfFunc() + bw + call test_garbagecollect_now() + new + set qftf= + wincmd w + set qftf= + :%bw! + + " set per-quickfix list 'quickfixtextfunc' to a partial with dict. This used + " to cause a crash. + let &qftf = '' + func SetLocalQftfFunc() + let params = {'qftf': function('g:DictQftfFunc')} + call setqflist([], 'a', {'quickfixtextfunc' : params.qftf}) + endfunc + call SetLocalQftfFunc() + call test_garbagecollect_now() + call setqflist([], 'a', {'quickfixtextfunc' : ''}) + delfunc g:DictQftfFunc + delfunc SetQftfFunc + delfunc SetLocalQftfFunc + set efm& +endfunc + +" Test for updating a location list for some other window and check that +" 'qftextfunc' uses the correct location list. +func Test_qftextfunc_other_loclist() + %bw! + call setloclist(0, [], 'f') + + " create a window and a location list for it and open the location list + " window + lexpr ['F1:10:12:one', 'F1:20:14:two'] + let w1_id = win_getid() + call setloclist(0, [], ' ', + \ {'lines': ['F1:10:12:one', 'F1:20:14:two'], + \ 'quickfixtextfunc': + \ {d -> map(getloclist(d.winid, {'id' : d.id, + \ 'items' : 1}).items[d.start_idx-1:d.end_idx-1], + \ "'Line ' .. v:val.lnum .. ', Col ' .. v:val.col")}}) + lwindow + let w2_id = win_getid() + + " create another window and a location list for it and open the location + " list window + topleft new + let w3_id = win_getid() + call setloclist(0, [], ' ', + \ {'lines': ['F2:30:32:eleven', 'F2:40:34:twelve'], + \ 'quickfixtextfunc': + \ {d -> map(getloclist(d.winid, {'id' : d.id, + \ 'items' : 1}).items[d.start_idx-1:d.end_idx-1], + \ "'Ligne ' .. v:val.lnum .. ', Colonne ' .. v:val.col")}}) + lwindow + let w4_id = win_getid() + + topleft new + lexpr ['F3:50:52:green', 'F3:60:54:blue'] + let w5_id = win_getid() + + " change the location list for some other window + call setloclist(0, [], 'r', {'lines': ['F3:55:56:aaa', 'F3:57:58:bbb']}) + call setloclist(w1_id, [], 'r', {'lines': ['F1:62:63:bbb', 'F1:64:65:ccc']}) + call setloclist(w3_id, [], 'r', {'lines': ['F2:76:77:ddd', 'F2:78:79:eee']}) + call assert_equal(['Line 62, Col 63', 'Line 64, Col 65'], + \ getbufline(winbufnr(w2_id), 1, '$')) + call assert_equal(['Ligne 76, Colonne 77', 'Ligne 78, Colonne 79'], + \ getbufline(winbufnr(w4_id), 1, '$')) + call setloclist(w2_id, [], 'r', {'lines': ['F1:32:33:fff', 'F1:34:35:ggg']}) + call setloclist(w4_id, [], 'r', {'lines': ['F2:46:47:hhh', 'F2:48:49:jjj']}) + call assert_equal(['Line 32, Col 33', 'Line 34, Col 35'], + \ getbufline(winbufnr(w2_id), 1, '$')) + call assert_equal(['Ligne 46, Colonne 47', 'Ligne 48, Colonne 49'], + \ getbufline(winbufnr(w4_id), 1, '$')) + + call win_gotoid(w5_id) + lwindow + call assert_equal(['F3|55 col 56| aaa', 'F3|57 col 58| bbb'], + \ getline(1, '$')) + %bw! +endfunc + +" Running :lhelpgrep command more than once in a help window, doesn't jump to +" the help topic +func Test_lhelpgrep_from_help_window() + call mkdir('Xtestdir/doc', 'p') + call writefile(['window'], 'Xtestdir/doc/a.txt') + call writefile(['buffer'], 'Xtestdir/doc/b.txt') + let save_rtp = &rtp + let &rtp = 'Xtestdir' + lhelpgrep window + lhelpgrep buffer + call assert_equal('b.txt', fnamemodify(@%, ":p:t")) + lhelpgrep window + call assert_equal('a.txt', fnamemodify(@%, ":p:t")) + let &rtp = save_rtp + call delete('Xtestdir', 'rf') + new | only! +endfunc + +" Test for the crash fixed by 7.3.715 +func Test_setloclist_crash() + %bw! + let g:BufNum = bufnr() + augroup QF_Test + au! + au BufUnload * call setloclist(0, [{'bufnr':g:BufNum, 'lnum':1, 'col':1, 'text': 'tango down'}]) + augroup END + + try + lvimgrep /.*/ *.mak + catch /E926:/ + endtry + call assert_equal('tango down', getloclist(0, {'items' : 0}).items[0].text) + call assert_equal(1, getloclist(0, {'size' : 0}).size) + + augroup QF_Test + au! + augroup END + unlet g:BufNum + %bw! +endfunc + +" Test for adding an invalid entry with the quickfix window open and making +" sure that the window contents are not changed +func Test_add_invalid_entry_with_qf_window() + call setqflist([], 'f') + cexpr "Xfile1:10:aa" + copen + call setqflist(['bb'], 'a') + call assert_equal(1, line('$')) + call assert_equal(['Xfile1|10| aa'], getline(1, '$')) + call assert_equal([{'lnum': 10 , 'end_lnum': 0 , 'bufnr': bufnr('Xfile1') , 'col': 0 , 'end_col': 0 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist()) + + call setqflist([{'lnum': 10 , 'bufnr': bufnr('Xfile1') , 'col': 0 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r') + call assert_equal(1 , line('$')) + call assert_equal(['Xfile1|10| aa'] , getline(1 , '$')) + call assert_equal([{'lnum': 10 , 'end_lnum': 0 , 'bufnr': bufnr('Xfile1') , 'col': 0 , 'end_col': 0 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist()) + + call setqflist([{'lnum': 10 , 'end_lnum': 0 , 'bufnr': bufnr('Xfile1') , 'col': 0 , 'end_col': 0 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r') + call assert_equal(1 , line('$')) + call assert_equal(['Xfile1|10| aa'] , getline(1 , '$')) + call assert_equal([{'lnum': 10 , 'end_lnum': 0 , 'bufnr': bufnr('Xfile1') , 'col': 0 , 'end_col': 0 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist()) + + call setqflist([{'lnum': 10 , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 0 , 'end_col': -456 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r') + call assert_equal(1 , line('$')) + call assert_equal(['Xfile1|10| aa'] , getline(1 , '$')) + call assert_equal([{'lnum': 10 , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 0 , 'end_col': -456 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist()) + + call setqflist([{'lnum': 10 , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 0 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r') + call assert_equal(1 , line('$')) + call assert_equal(['Xfile1|10 col 666| aa'] , getline(1 , '$')) + call assert_equal([{'lnum': 10 , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 0 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist()) + + call setqflist([{'lnum': 10 , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': -456 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r') + call assert_equal(1 , line('$')) + call assert_equal(['Xfile1|10 col 666| aa'] , getline(1 , '$')) + call assert_equal([{'lnum': 10 , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': -456 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist()) + + call setqflist([{'lnum': 10 , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 222 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r') + call assert_equal(1 , line('$')) + call assert_equal(['Xfile1|10 col 666-222| aa'] , getline(1 , '$')) + call assert_equal([{'lnum': 10 , 'end_lnum': -123 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 222 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist()) + + call setqflist([{'lnum': 10 , 'end_lnum': 6 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 222 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , 'r') + call assert_equal(1 , line('$')) + call assert_equal(['Xfile1|10-6 col 666-222| aa'] , getline(1 , '$')) + call assert_equal([{'lnum': 10 , 'end_lnum': 6 , 'bufnr': bufnr('Xfile1') , 'col': 666 , 'end_col': 222 , 'pattern': '' , 'valid': 1 , 'vcol': 0 , 'nr': -1 , 'type': '' , 'module': '' , 'text': 'aa'}] , getqflist()) + cclose +endfunc + +" Test for very weird problem: autocommand causes a failure, resulting opening +" the quickfix window to fail. This still splits the window, but otherwise +" should not mess up buffers. +func Test_quickfix_window_fails_to_open() + CheckScreendump + + let lines =<< trim END + anything + try + anything + endtry + END + call writefile(lines, 'XquickfixFails') + + let lines =<< trim END + split XquickfixFails + silent vimgrep anything % + normal o + au BufLeave * ++once source XquickfixFails + " This will trigger the autocommand, which causes an error, what follows + " is aborted but the window was already split. + silent! cwindow + END + call writefile(lines, 'XtestWinFails') + let buf = RunVimInTerminal('-S XtestWinFails', #{rows: 13}) + call VerifyScreenDump(buf, 'Test_quickfix_window_fails', {}) + + " clean up + call term_sendkeys(buf, ":bwipe!\<CR>") + call term_wait(buf) + call StopVimInTerminal(buf) + call delete('XtestWinFails') + call delete('XquickfixFails') +endfunc + +" Test for updating the quickfix buffer whenever the associated quickfix list +" is changed. +func Xqfbuf_update(cchar) + call s:setup_commands(a:cchar) + + Xexpr "F1:1:line1" + Xopen + call assert_equal(['F1|1| line1'], getline(1, '$')) + call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick) + + " Test setqflist() using the 'lines' key in 'what' + " add a new entry + call g:Xsetlist([], 'a', {'lines' : ['F2:2: line2']}) + call assert_equal(['F1|1| line1', 'F2|2| line2'], getline(1, '$')) + call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick) + " replace all the entries with a single entry + call g:Xsetlist([], 'r', {'lines' : ['F3:3: line3']}) + call assert_equal(['F3|3| line3'], getline(1, '$')) + call assert_equal(3, g:Xgetlist({'changedtick' : 0}).changedtick) + " remove all the entries + call g:Xsetlist([], 'r', {'lines' : []}) + call assert_equal([''], getline(1, '$')) + call assert_equal(4, g:Xgetlist({'changedtick' : 0}).changedtick) + " add a new list + call g:Xsetlist([], ' ', {'lines' : ['F4:4: line4']}) + call assert_equal(['F4|4| line4'], getline(1, '$')) + call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick) + + " Test setqflist() using the 'items' key in 'what' + " add a new entry + call g:Xsetlist([], 'a', {'items' : [{'filename' : 'F5', 'lnum' : 5, 'text' : 'line5'}]}) + call assert_equal(['F4|4| line4', 'F5|5| line5'], getline(1, '$')) + call assert_equal(2, g:Xgetlist({'changedtick' : 0}).changedtick) + " replace all the entries with a single entry + call g:Xsetlist([], 'r', {'items' : [{'filename' : 'F6', 'lnum' : 6, 'text' : 'line6'}]}) + call assert_equal(['F6|6| line6'], getline(1, '$')) + call assert_equal(3, g:Xgetlist({'changedtick' : 0}).changedtick) + " remove all the entries + call g:Xsetlist([], 'r', {'items' : []}) + call assert_equal([''], getline(1, '$')) + call assert_equal(4, g:Xgetlist({'changedtick' : 0}).changedtick) + " add a new list + call g:Xsetlist([], ' ', {'items' : [{'filename' : 'F7', 'lnum' : 7, 'text' : 'line7'}]}) + call assert_equal(['F7|7| line7'], getline(1, '$')) + call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick) + + call g:Xsetlist([], ' ', {}) + call assert_equal([''], getline(1, '$')) + call assert_equal(1, g:Xgetlist({'changedtick' : 0}).changedtick) + + Xclose +endfunc + +func Test_qfbuf_update() + call Xqfbuf_update('c') + call Xqfbuf_update('l') +endfunc + +" Test for the :vimgrep 'f' flag (fuzzy match) +func Xvimgrep_fuzzy_match(cchar) + call s:setup_commands(a:cchar) + + Xvimgrep /three one/f Xfile* + let l = g:Xgetlist() + call assert_equal(2, len(l)) + call assert_equal(['Xfile1', 1, 9, 'one two three'], + \ [bufname(l[0].bufnr), l[0].lnum, l[0].col, l[0].text]) + call assert_equal(['Xfile2', 2, 1, 'three one two'], + \ [bufname(l[1].bufnr), l[1].lnum, l[1].col, l[1].text]) + + Xvimgrep /the/f Xfile* + let l = g:Xgetlist() + call assert_equal(3, len(l)) + call assert_equal(['Xfile1', 1, 9, 'one two three'], + \ [bufname(l[0].bufnr), l[0].lnum, l[0].col, l[0].text]) + call assert_equal(['Xfile2', 2, 1, 'three one two'], + \ [bufname(l[1].bufnr), l[1].lnum, l[1].col, l[1].text]) + call assert_equal(['Xfile2', 4, 4, 'aaathreeaaa'], + \ [bufname(l[2].bufnr), l[2].lnum, l[2].col, l[2].text]) + + Xvimgrep /aaa/fg Xfile* + let l = g:Xgetlist() + call assert_equal(4, len(l)) + call assert_equal(['Xfile1', 2, 1, 'aaaaaa'], + \ [bufname(l[0].bufnr), l[0].lnum, l[0].col, l[0].text]) + call assert_equal(['Xfile1', 2, 4, 'aaaaaa'], + \ [bufname(l[1].bufnr), l[1].lnum, l[1].col, l[1].text]) + call assert_equal(['Xfile2', 4, 1, 'aaathreeaaa'], + \ [bufname(l[2].bufnr), l[2].lnum, l[2].col, l[2].text]) + call assert_equal(['Xfile2', 4, 9, 'aaathreeaaa'], + \ [bufname(l[3].bufnr), l[3].lnum, l[3].col, l[3].text]) + + call assert_fails('Xvimgrep /xyz/fg Xfile*', 'E480:') +endfunc + +func Test_vimgrep_fuzzy_match() + call writefile(['one two three', 'aaaaaa'], 'Xfile1') + call writefile(['one', 'three one two', 'two', 'aaathreeaaa'], 'Xfile2') + call Xvimgrep_fuzzy_match('c') + call Xvimgrep_fuzzy_match('l') + call delete('Xfile1') + call delete('Xfile2') +endfunc + +func Test_locationlist_open_in_newtab() + call s:create_test_file('Xqftestfile1') + call s:create_test_file('Xqftestfile2') + call s:create_test_file('Xqftestfile3') + + %bwipe! + + let lines =<< trim END + Xqftestfile1:5:Line5 + Xqftestfile2:10:Line10 + Xqftestfile3:16:Line16 + END + lgetexpr lines + + silent! llast + call assert_equal(1, tabpagenr('$')) + call assert_equal('Xqftestfile3', bufname()) + + set switchbuf=newtab + + silent! lfirst + call assert_equal(2, tabpagenr('$')) + call assert_equal('Xqftestfile1', bufname()) + + silent! lnext + call assert_equal(3, tabpagenr('$')) + call assert_equal('Xqftestfile2', bufname()) + + call delete('Xqftestfile1') + call delete('Xqftestfile2') + call delete('Xqftestfile3') + set switchbuf&vim + + %bwipe! +endfunc + +" Test for win_gettype() in quickfix and location list windows +func Test_win_gettype() + copen + call assert_equal("quickfix", win_gettype()) + let wid = win_getid() + wincmd p + call assert_equal("quickfix", win_gettype(wid)) + cclose + lexpr '' + lopen + call assert_equal("loclist", win_gettype()) + let wid = win_getid() + wincmd p + call assert_equal("loclist", win_gettype(wid)) + lclose +endfunc + +fun Test_vimgrep_nomatch() + call XexprTests('c') + call g:Xsetlist([{'lnum':10,'text':'Line1'}]) + copen + if has("win32") + call assert_fails('vimgrep foo *.zzz', 'E479:') + let expected = [{'lnum': 10, 'bufnr': 0, 'end_lnum': 0, 'pattern': '', 'valid': 0, 'vcol': 0, 'nr': 0, 'module': '', 'type': '', 'end_col': 0, 'col': 0, 'text': 'Line1'}] + else + call assert_fails('vimgrep foo *.zzz', 'E480:') + let expected = [] + endif + call assert_equal(expected, getqflist()) + cclose +endfunc + +" Test for opening the quickfix window in two tab pages and then closing one +" of the quickfix windows. This should not make the quickfix buffer unlisted. +" (github issue #9300). +func Test_two_qf_windows() + cexpr "F1:1:line1" + copen + tabnew + copen + call assert_true(&buflisted) + cclose + tabfirst + call assert_true(&buflisted) + let bnum = bufnr() + cclose + " if all the quickfix windows are closed, then buffer should be unlisted. + call assert_false(buflisted(bnum)) + %bw! + + " Repeat the test for a location list + lexpr "F2:2:line2" + lopen + let bnum = bufnr() + tabnew + exe "buffer" bnum + tabfirst + lclose + tablast + call assert_true(buflisted(bnum)) + tabclose + lopen + call assert_true(buflisted(bnum)) + lclose + call assert_false(buflisted(bnum)) + %bw! +endfunc + +" Weird sequence of commands that caused entering a wiped-out buffer +func Test_lopen_bwipe() + func R() + silent! tab lopen + e x + silent! lfile + endfunc + + cal R() + cal R() + cal R() + bw! + delfunc R +endfunc + +" Another sequence of commands that caused all buffers to be wiped out +func Test_lopen_bwipe_all() + let lines =<< trim END + func R() + silent! tab lopen + e foo + silent! lfile + endfunc + cal R() + exe "norm \<C-W>\<C-V>0" + cal R() + bwipe + + call writefile(['done'], 'Xresult') + qall! + END + call writefile(lines, 'Xscript') + if RunVim([], [], '-u NONE -n -X -Z -e -m -s -S Xscript') + call assert_equal(['done'], readfile('Xresult')) + endif + + call delete('Xscript') + call delete('Xresult') +endfunc + +" Test for calling setqflist() function recursively +func Test_recursive_setqflist() + augroup QF_Test + au! + autocmd BufWinEnter quickfix call setqflist([], 'r') + augroup END + + copen + call assert_fails("call setqflist([], 'a')", 'E952:') + + augroup QF_Test + au! + augroup END + %bw! +endfunc + +" Test for failure to create a new window when selecting a file from the +" quickfix window +func Test_cwindow_newwin_fails() + cgetexpr ["Xfile1:10:L10", "Xfile1:20:L20"] + cwindow + only + let qf_wid = win_getid() + " create the maximum number of scratch windows + let hor_win_count = (&lines - 1)/2 + let hor_split_count = hor_win_count - 1 + for s in range(1, hor_split_count) | new | set buftype=nofile | endfor + call win_gotoid(qf_wid) + call assert_fails('exe "normal \<CR>"', 'E36:') + %bw! +endfunc + +" Test for updating the location list when only the location list window is +" present and the corresponding file window is closed. +func Test_loclist_update_with_llwin_only() + %bw! + new + wincmd w + lexpr ["Xfile1:1:Line1"] + lopen + wincmd p + close + call setloclist(2, [], 'r', {'lines': ["Xtest2:2:Line2"]}) + call assert_equal(['Xtest2|2| Line2'], getbufline(winbufnr(2), 1, '$')) + %bw! +endfunc + +" Test for getting the quickfix list after a buffer with an error is wiped out +func Test_getqflist_wiped_out_buffer() + %bw! + cexpr ["Xtest1:34:Wiped out"] + let bnum = bufnr('Xtest1') + call assert_equal(bnum, getqflist()[0].bufnr) + bw Xtest1 + call assert_equal(0, getqflist()[0].bufnr) + %bw! +endfunc + +" Test for the status message that is displayed when opening a new quickfix +" list +func Test_qflist_statusmsg() + cexpr "1\n2" + cexpr "1\n2\n3\ntest_quickfix.vim:1:msg" + call assert_equal('(4 of 4): msg', v:statusmsg) + call setqflist([], 'f') + %bw! + + " When creating a new quickfix list, if an autocmd changes the quickfix list + " in the stack, then an error message should be displayed. + augroup QF_Test + au! + au BufEnter test_quickfix.vim colder + augroup END + cexpr "1\n2" + call assert_fails('cexpr "1\n2\n3\ntest_quickfix.vim:1:msg"', 'E925:') + call setqflist([], 'f') + augroup QF_Test + au! + augroup END + %bw! + + augroup QF_Test + au! + au BufEnter test_quickfix.vim caddexpr "4" + augroup END + call assert_fails('cexpr "1\n2\n3\ntest_quickfix.vim:1:msg"', 'E925:') + call setqflist([], 'f') + augroup QF_Test + au! + augroup END + %bw! +endfunc + +func Test_quickfixtextfunc_recursive() + func s:QFTfunc(o) + cgete '0' + endfunc + copen + let &quickfixtextfunc = 's:QFTfunc' + cex "" + + let &quickfixtextfunc = '' + cclose +endfunc + +" Test for replacing the location list from an autocmd. This used to cause a +" read from freed memory. +func Test_loclist_replace_autocmd() + %bw! + call setloclist(0, [], 'f') + let s:bufnr = bufnr() + cal setloclist(0, [{'0': 0, '': ''}]) + au BufEnter * cal setloclist(1, [{'t': ''}, {'bufnr': s:bufnr}], 'r') + lopen + try + exe "norm j\<CR>" + catch + endtry + lnext + %bw! + call setloclist(0, [], 'f') +endfunc + +" Test for a very long error line and a very long information line +func Test_very_long_error_line() + let msg = repeat('abcdefghijklmn', 146) + let emsg = 'Xlonglines.c:1:' . msg + call writefile([msg, emsg], 'Xerror', 'D') + cfile Xerror + cwindow + call assert_equal($'|| {msg}', getline(1)) + call assert_equal($'Xlonglines.c|1| {msg}', getline(2)) + cclose + + let l = execute('clist!')->split("\n") + call assert_equal([$' 1: {msg}', $' 2 Xlonglines.c:1: {msg}'], l) + + let l = execute('cc')->split("\n") + call assert_equal([$'(2 of 2): {msg}'], l) + + call setqflist([], 'f') +endfunc + +" In the quickfix window, spaces at the beginning of an informational line +" should not be removed but should be removed from an error line. +func Test_info_line_with_space() + cexpr ["a.c:20:12: error: expected ';' before ':' token", + \ ' 20 | Afunc():', '', ' | ^'] + copen + call assert_equal(["a.c|20 col 12| error: expected ';' before ':' token", + \ '|| 20 | Afunc():', '|| ', + \ '|| | ^'], getline(1, '$')) + cclose + + let l = execute('clist!')->split("\n") + call assert_equal([" 1 a.c:20 col 12: error: expected ';' before ':' token", + \ ' 2: 20 | Afunc():', ' 3: ', ' 4: | ^'], l) + + call setqflist([], 'f') +endfunc + +func s:QfTf(_) +endfunc + +func Test_setqflist_cb_arg() + " This was changing the callback name in the dictionary. + let d = #{quickfixtextfunc: 's:QfTf'} + call setqflist([], 'a', d) + call assert_equal('s:QfTf', d.quickfixtextfunc) + + call setqflist([], 'f') +endfunc + +" Test that setqflist() should not prevent :stopinsert from working +func Test_setqflist_stopinsert() + new + call setqflist([], 'f') + copen + cclose + func StopInsert() + stopinsert + call setqflist([{'text': 'foo'}]) + return '' + endfunc + + call setline(1, 'abc') + call cursor(1, 1) + call feedkeys("i\<C-R>=StopInsert()\<CR>$", 'tnix') + call assert_equal('foo', getqflist()[0].text) + call assert_equal([0, 1, 3, 0, v:maxcol], getcurpos()) + call assert_equal(['abc'], getline(1, '$')) + + delfunc StopInsert + call setqflist([], 'f') + bwipe! +endfunc + +func Test_quickfix_buffer_contents() + call setqflist([{'filename':'filename', 'pattern':'pattern', 'text':'text'}]) + copen + call assert_equal(['filename|pattern| text'], getline(1, '$')) " The assert failed with Vim v9.0.0736; '| text' did not appear after the pattern. + call setqflist([], 'f') +endfunc + +" Test for "%b" in "errorformat" +func Test_efm_format_b() + call setqflist([], 'f') + new + call setline(1, ['1: abc', '1: def', '1: ghi']) + let b1 = bufnr() + new + call setline(1, ['2: abc', '2: def', '2: ghi']) + let b2 = bufnr() + new + call setline(1, ['3: abc', '3: def', '3: ghi']) + let b3 = bufnr() + new + let lines =<< trim eval END + {b1}:1:1 + {b2}:2:2 + {b3}:3:3 + END + call setqflist([], ' ', #{lines: lines, efm: '%b:%l:%c'}) + cfirst + call assert_equal([b1, 1, 1], [bufnr(), line('.'), col('.')]) + cnext + call assert_equal([b2, 2, 2], [bufnr(), line('.'), col('.')]) + cnext + call assert_equal([b3, 3, 3], [bufnr(), line('.'), col('.')]) + enew! + + " Use a non-existing buffer + let lines =<< trim eval END + 9991:1:1:m1 + 9992:2:2:m2 + {b3}:3:3:m3 + END + call setqflist([], ' ', #{lines: lines, efm: '%b:%l:%c:%m'}) + cfirst | cnext + call assert_equal([b3, 3, 3], [bufnr(), line('.'), col('.')]) + " Lines with non-existing buffer numbers should be used as non-error lines + call assert_equal([ + \ #{lnum: 0, bufnr: 0, end_lnum: 0, pattern: '', valid: 0, vcol: 0, nr: -1, + \ module: '', type: '', end_col: 0, col: 0, text: '9991:1:1:m1'}, + \ #{lnum: 0, bufnr: 0, end_lnum: 0, pattern: '', valid: 0, vcol: 0, nr: -1, + \ module: '', type: '', end_col: 0, col: 0, text: '9992:2:2:m2'}, + \ #{lnum: 3, bufnr: b3, end_lnum: 0, pattern: '', valid: 1, vcol: 0, + \ nr: -1, module: '', type: '', end_col: 0, col: 3, text: 'm3'}], + \ getqflist()) + %bw! + call setqflist([], 'f') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_quotestar.vim b/test/old/testdir/test_quotestar.vim new file mode 100644 index 0000000000..93b0d928ce --- /dev/null +++ b/test/old/testdir/test_quotestar.vim @@ -0,0 +1,156 @@ +" *-register (quotestar) tests + +source shared.vim +source check.vim + +CheckFeature clipboard_working + +func Do_test_quotestar_for_macunix() + if empty(exepath('pbcopy')) || empty(exepath('pbpaste')) + return 'Test requires pbcopy(1) and pbpaste(1)' + endif + + let @* = '' + + " Test #1: Pasteboard to Vim + let test_msg = "text from pasteboard to vim via quotestar" + " Write a piece of text to the pasteboard. + call system('/bin/echo -n "' . test_msg . '" | pbcopy') + " See if the *-register is changed as expected. + call assert_equal(test_msg, @*) + + " Test #2: Vim to Pasteboard + let test_msg = "text from vim to pasteboard via quotestar" + " Write a piece of text to the *-register. + let @* = test_msg + " See if the pasteboard is changed as expected. + call assert_equal(test_msg, system('pbpaste')) + + return '' +endfunc + +func Do_test_quotestar_for_x11() + if !has('clientserver') || !has('job') + return 'Test requires the client-server and job features' + endif + + let cmd = GetVimCommand() + if cmd == '' + return 'GetVimCommand() failed' + endif + try + call remote_send('xxx', '') + catch + if v:exception =~ 'E240:' + " No connection to the X server, give up. + return + endif + " ignore other errors + endtry + + let name = 'XVIMCLIPBOARD' + + " Make sure a previous server has exited + try + call remote_send(name, ":qa!\<CR>") + catch /E241:/ + endtry + call WaitForAssert({-> assert_notmatch(name, serverlist())}) + + 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. + call WaitForAssert({-> assert_match(name, serverlist())}) + + " Wait for the server to be up and answering requests. One second is not + " always sufficient. + call WaitForAssert({-> assert_notequal('', remote_expr(name, "v:version", "", 2))}) + + " Clear the *-register of this vim instance and wait for it to be picked up + " by the server. + let @* = 'no' + call remote_foreground(name) + call WaitForAssert({-> assert_equal("no", remote_expr(name, "@*", "", 1))}) + + " Set the * register on the server. + call remote_send(name, ":let @* = 'yes'\<CR>") + call WaitForAssert({-> assert_equal("yes", remote_expr(name, "@*", "", 1))}) + + " Check that the *-register of this vim instance is changed as expected. + call WaitForAssert({-> assert_equal("yes", @*)}) + + " Handle the large selection over 262040 byte. + let length = 262044 + let sample = 'a' . repeat('b', length - 2) . 'c' + let @* = sample + call WaitFor('remote_expr("' . name . '", "len(@*) >= ' . length . '", "", 1)') + let res = remote_expr(name, "@*", "", 2) + call assert_equal(length, len(res)) + " Check length to prevent a large amount of output at assertion failure. + if length == len(res) + call assert_equal(sample, res) + endif + + if has('unix') && has('gui') && !has('gui_running') + let @* = '' + + " Running in a terminal and the GUI is available: Tell the server to open + " the GUI and check that the remote command still works. + if has('gui_motif') + " For those GUIs, 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 in the GUI to be up and answering requests. + " First need to wait for the GUI to start up, otherwise the send hangs in + " trying to send to the terminal window. + " On some systems and with valgrind this can be very slow. + sleep 1 + call WaitForAssert({-> assert_match("1", remote_expr(name, "has('gui_running')", "", 1))}, 10000) + + call remote_send(name, ":let @* = 'maybe'\<CR>") + call WaitForAssert({-> assert_equal("maybe", remote_expr(name, "@*", "", 2))}) + + call assert_equal('maybe', @*) + endif + + call remote_send(name, ":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 + + return '' +endfunc + +func Test_quotestar() + let g:test_is_flaky = 1 + let skipped = '' + + let quotestar_saved = @* + + if has('macunix') + let skipped = Do_test_quotestar_for_macunix() + elseif has('x11') + if empty($DISPLAY) + let skipped = "Test can only run when $DISPLAY is set." + else + let skipped = Do_test_quotestar_for_x11() + endif + else + let skipped = "Test is not implemented yet for this platform." + endif + + let @* = quotestar_saved + + if !empty(skipped) + throw 'Skipped: ' . skipped + endif +endfunc diff --git a/test/old/testdir/test_random.vim b/test/old/testdir/test_random.vim new file mode 100644 index 0000000000..5fdbfe9cd8 --- /dev/null +++ b/test/old/testdir/test_random.vim @@ -0,0 +1,59 @@ +" Tests for srand() and rand() + +source check.vim +source shared.vim + +func Test_Rand() + let r = srand(123456789) + call assert_equal([1573771921, 319883699, 2742014374, 1324369493], r) + call assert_equal(4284103975, rand(r)) + call assert_equal(1001954530, rand(r)) + call assert_equal(2701803082, rand(r)) + call assert_equal(2658065534, rand(r)) + call assert_equal(3104308804, rand(r)) + + let s = srand() + " using /dev/urandom or used time, result is different each time + call assert_notequal(s, srand()) + + " Nvim does not support test_srand_seed + " call test_srand_seed(123456789) + " call assert_equal(4284103975, rand()) + " call assert_equal(1001954530, rand()) + " call test_srand_seed() + + if has('float') + call assert_fails('echo srand(1.2)', 'E805:') + endif + call assert_fails('echo srand([1])', 'E745:') + call assert_fails('echo rand("burp")', 'E475:') + call assert_fails('echo rand([1, 2, 3])', 'E730:') + call assert_fails('echo rand([[1], 2, 3, 4])', 'E730:') + call assert_fails('echo rand([1, [2], 3, 4])', 'E730:') + call assert_fails('echo rand([1, 2, [3], 4])', 'E730:') + call assert_fails('echo rand([1, 2, 3, [4]])', 'E730:') +endfunc + +func Test_issue_5587() + call rand() + call garbagecollect() + call rand() +endfunc + +func Test_srand() + CheckNotGui + + let cmd = GetVimCommand() .. ' -V -es -c "echo rand()" -c qa!' + let bad = 0 + for _ in range(10) + echo cmd + let result1 = system(cmd) + let result2 = system(cmd) + if result1 ==# result2 + let bad += 1 + endif + endfor + call assert_inrange(0, 4, bad) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_recover.vim b/test/old/testdir/test_recover.vim new file mode 100644 index 0000000000..fa8cc1abaf --- /dev/null +++ b/test/old/testdir/test_recover.vim @@ -0,0 +1,481 @@ +" Test :recover + +source check.vim + +func Test_recover_root_dir() + " This used to access invalid memory. + split Xtest + set dir=/ + call assert_fails('recover', 'E305:') + close! + + if has('win32') + " can write in / directory on MS-Windows + let &directory = 'F:\\' + elseif filewritable('/') == 2 + set dir=/notexist/ + endif + call assert_fails('split Xtest', 'E303:') + + " No error with empty 'directory' setting. + set directory= + split XtestOK + close! + + set dir& +endfunc + +" Make a copy of the current swap file to "Xswap". +" Return the name of the swap file. +func CopySwapfile() + preserve + " get the name of the swap file + let swname = split(execute("swapname"))[0] + let swname = substitute(swname, '[[:blank:][:cntrl:]]*\(.\{-}\)[[:blank:][:cntrl:]]*$', '\1', '') + " make a copy of the swap file in Xswap + set binary + exe 'sp ' . swname + w! Xswap + set nobinary + return swname +endfunc + +" Inserts 10000 lines with text to fill the swap file with two levels of pointer +" blocks. Then recovers from the swap file and checks all text is restored. +" +" We need about 10000 lines of 100 characters to get two levels of pointer +" blocks. +func Test_swap_file() + set directory=. + set fileformat=unix undolevels=-1 + edit! Xtest + let text = "\tabcdefghijklmnoparstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnoparstuvwxyz0123456789" + let i = 1 + let linecount = 10000 + while i <= linecount + call append(i - 1, i . text) + let i += 1 + endwhile + $delete + + let swname = CopySwapfile() + + new + only! + bwipe! Xtest + call rename('Xswap', swname) + recover Xtest + call delete(swname) + let linedollar = line('$') + call assert_equal(linecount, linedollar) + if linedollar < linecount + let linecount = linedollar + endif + let i = 1 + while i <= linecount + call assert_equal(i . text, getline(i)) + let i += 1 + endwhile + + set undolevels& + enew! | only +endfunc + +func Test_nocatch_process_still_running() + let g:skipped_reason = 'test_override() is N/A' + return + " sysinfo.uptime probably only works on Linux + if !has('linux') + let g:skipped_reason = 'only works on Linux' + return + endif + " the GUI dialog can't be handled + if has('gui_running') + let g:skipped_reason = 'only works in the terminal' + return + endif + + " don't intercept existing swap file here + au! SwapExists + + " Edit a file and grab its swapfile. + edit Xswaptest + call setline(1, ['a', 'b', 'c']) + let swname = CopySwapfile() + + " Forget we edited this file + new + only! + bwipe! Xswaptest + + call rename('Xswap', swname) + call feedkeys('e', 'tL') + redir => editOutput + edit Xswaptest + redir END + call assert_match('E325: ATTENTION', editOutput) + call assert_match('file name: .*Xswaptest', editOutput) + call assert_match('process ID: \d* (STILL RUNNING)', editOutput) + + " Forget we edited this file + new + only! + bwipe! Xswaptest + + " pretend we rebooted + call test_override("uptime", 0) + sleep 1 + + call feedkeys('e', 'tL') + redir => editOutput + edit Xswaptest + redir END + call assert_match('E325: ATTENTION', editOutput) + call assert_notmatch('(STILL RUNNING)', editOutput) + + call test_override("ALL", 0) + call delete(swname) +endfunc + +" Test for :recover with multiple swap files +func Test_recover_multiple_swap_files() + CheckUnix + new Xfile1 + call setline(1, ['a', 'b', 'c']) + preserve + let b = readblob(swapname('')) + call writefile(b, '.Xfile1.swm', 'D') + call writefile(b, '.Xfile1.swn', 'D') + call writefile(b, '.Xfile1.swo', 'D') + %bw! + call feedkeys(":recover Xfile1\<CR>3\<CR>q", 'xt') + call assert_equal(['a', 'b', 'c'], getline(1, '$')) + " try using out-of-range number to select a swap file + bw! + call feedkeys(":recover Xfile1\<CR>4\<CR>q", 'xt') + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! + call feedkeys(":recover Xfile1\<CR>0\<CR>q", 'xt') + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! +endfunc + +" Test for :recover using an empty swap file +func Test_recover_empty_swap_file() + CheckUnix + call writefile([], '.Xfile1.swp', 'D') + set dir=. + let msg = execute('recover Xfile1') + call assert_match('Unable to read block 0 from .Xfile1.swp', msg) + call assert_equal('Xfile1', @%) + bw! + + " make sure there are no old swap files laying around + for f in glob('.sw?', 0, 1) + call delete(f) + endfor + + " :recover from an empty buffer + call assert_fails('recover', 'E305:') + set dir&vim +endfunc + +" Test for :recover using a corrupted swap file +" Refer to the comments in the memline.c file for the swap file headers +" definition. +func Test_recover_corrupted_swap_file() + CheckUnix + + " recover using a partial swap file + call writefile(0z1234, '.Xfile1.swp') + call assert_fails('recover Xfile1', 'E295:') + bw! + + " recover using invalid content in the swap file + call writefile([repeat('1', 2*1024)], '.Xfile1.swp') + call assert_fails('recover Xfile1', 'E307:') + call delete('.Xfile1.swp') + + " :recover using a swap file with a corrupted header + edit Xfile1 + preserve + let sn = swapname('') + let b = readblob(sn) + let save_b = copy(b) + bw! + + " Not all fields are written in a system-independent manner. Detect whether + " the test is running on a little or big-endian system, so the correct + " corruption values can be set. + " The B0_MAGIC_LONG field may be 32-bit or 64-bit, depending on the system, + " even though the value stored is only 32-bits. Therefore, need to check + " both the high and low 32-bits to compute these values. + let little_endian = (b[1008:1011] == 0z33323130) || (b[1012:1015] == 0z33323130) + let system_64bit = little_endian ? (b[1012:1015] == 0z00000000) : (b[1008:1011] == 0z00000000) + + " clear the B0_MAGIC_LONG field + if system_64bit + let b[1008:1015] = 0z00000000.00000000 + else + let b[1008:1011] = 0z00000000 + endif + call writefile(b, sn) + let msg = execute('recover Xfile1') + call assert_match('the file has been damaged', msg) + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! + + " reduce the page size + let b = copy(save_b) + let b[12:15] = 0z00010000 + call writefile(b, sn) + let msg = execute('recover Xfile1') + call assert_match('page size is smaller than minimum value', msg) + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! + + " clear the pointer ID + let b = copy(save_b) + let b[4096:4097] = 0z0000 + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E310:') + call assert_equal('Xfile1', @%) + call assert_equal([''], getline(1, '$')) + bw! + + " set the number of pointers in a pointer block to zero + let b = copy(save_b) + let b[4098:4099] = 0z0000 + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???EMPTY BLOCK'], getline(1, '$')) + bw! + + " set the number of pointers in a pointer block to a large value + let b = copy(save_b) + let b[4098:4099] = 0zFFFF + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E1364:') + call assert_equal('Xfile1', @%) + bw! + + " set the block number in a pointer entry to a negative number + let b = copy(save_b) + if v:true " Nvim changed this field from a long to an int64_t + let b[4104:4111] = little_endian ? 0z00000000.00000080 : 0z80000000.00000000 + else + let b[4104:4107] = little_endian ? 0z00000080 : 0z80000000 + endif + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???LINES MISSING'], getline(1, '$')) + bw! + + " clear the data block ID + let b = copy(save_b) + let b[8192:8193] = 0z0000 + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???BLOCK MISSING'], getline(1, '$')) + bw! + + " set the number of lines in the data block to zero + let b = copy(save_b) + if system_64bit + let b[8208:8215] = 0z00000000.00000000 + else + let b[8208:8211] = 0z00000000 + endif + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['??? from here until ???END lines may have been inserted/deleted', + \ '???END'], getline(1, '$')) + bw! + + " set the number of lines in the data block to a large value + let b = copy(save_b) + if system_64bit + let b[8208:8215] = 0z00FFFFFF.FFFFFF00 + else + let b[8208:8211] = 0z00FFFF00 + endif + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['??? from here until ???END lines may have been inserted/deleted', + \ '', '???', '??? lines may be missing', + \ '???END'], getline(1, '$')) + bw! + + " use an invalid text start for the lines in a data block + let b = copy(save_b) + if system_64bit + let b[8216:8219] = 0z00000000 + else + let b[8212:8215] = 0z00000000 + endif + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???'], getline(1, '$')) + bw! + + " use an incorrect text end (db_txt_end) for the data block + let b = copy(save_b) + let b[8204:8207] = little_endian ? 0z80000000 : 0z00000080 + call writefile(b, sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['??? from here until ???END lines may be messed up', '', + \ '???END'], getline(1, '$')) + bw! + + " remove the data block + let b = copy(save_b) + call writefile(b[:8191], sn) + call assert_fails('recover Xfile1', 'E312:') + call assert_equal('Xfile1', @%) + call assert_equal(['???MANY LINES MISSING'], getline(1, '$')) + + bw! + call delete(sn) +endfunc + +" Test for :recover using an encrypted swap file +func Test_recover_encrypted_swap_file() + CheckFeature cryptv + CheckUnix + + " Recover an encrypted file from the swap file without the original file + new Xfile1 + call feedkeys(":X\<CR>vim\<CR>vim\<CR>", 'xt') + call setline(1, ['aaa', 'bbb', 'ccc']) + preserve + let b = readblob('.Xfile1.swp') + call writefile(b, '.Xfile1.swm') + bw! + call feedkeys(":recover Xfile1\<CR>vim\<CR>\<CR>", 'xt') + call assert_equal(['aaa', 'bbb', 'ccc'], getline(1, '$')) + bw! + call delete('.Xfile1.swm') + + " Recover an encrypted file from the swap file with the original file + new Xfile1 + call feedkeys(":X\<CR>vim\<CR>vim\<CR>", 'xt') + call setline(1, ['aaa', 'bbb', 'ccc']) + update + call setline(1, ['111', '222', '333']) + preserve + let b = readblob('.Xfile1.swp') + call writefile(b, '.Xfile1.swm') + bw! + call feedkeys(":recover Xfile1\<CR>vim\<CR>\<CR>", 'xt') + call assert_equal(['111', '222', '333'], getline(1, '$')) + call assert_true(&modified) + bw! + call delete('.Xfile1.swm') + call delete('Xfile1') +endfunc + +" Test for :recover using a unreadable swap file +func Test_recover_unreadable_swap_file() + CheckUnix + CheckNotRoot + new Xfile1 + let b = readblob('.Xfile1.swp') + call writefile(b, '.Xfile1.swm', 'D') + bw! + call setfperm('.Xfile1.swm', '-w-------') + call assert_fails('recover Xfile1', 'E306:') +endfunc + +" Test for using :recover when the original file and the swap file have the +" same contents. +func Test_recover_unmodified_file() + CheckUnix + call writefile(['aaa', 'bbb', 'ccc'], 'Xfile1') + edit Xfile1 + preserve + let b = readblob('.Xfile1.swp') + %bw! + call writefile(b, '.Xfile1.swz', 'D') + let msg = execute('recover Xfile1') + call assert_equal(['aaa', 'bbb', 'ccc'], getline(1, '$')) + call assert_false(&modified) + call assert_match('Buffer contents equals file contents', msg) + bw! + call delete('Xfile1') +endfunc + +" Test for recovering a file when editing a symbolically linked file +func Test_recover_symbolic_link() + CheckUnix + call writefile(['aaa', 'bbb', 'ccc'], 'Xfile1', 'D') + silent !ln -s Xfile1 Xfile2 + edit Xfile2 + call assert_equal('.Xfile1.swp', fnamemodify(swapname(''), ':t')) + preserve + let b = readblob('.Xfile1.swp') + %bw! + call writefile([], 'Xfile1') + call writefile(b, '.Xfile1.swp') + silent! recover Xfile2 + call assert_equal(['aaa', 'bbb', 'ccc'], getline(1, '$')) + call assert_true(&modified) + update + %bw! + call assert_equal(['aaa', 'bbb', 'ccc'], readfile('Xfile1')) + call delete('Xfile2') + call delete('.Xfile1.swp') +endfunc + +" Test for recovering a file when an autocmd moves the cursor to an invalid +" line. This used to result in an internal error (E315) which is fixed +" by 8.2.2966. +func Test_recover_invalid_cursor_pos() + call writefile([], 'Xfile1', 'D') + edit Xfile1 + preserve + let b = readblob('.Xfile1.swp') + bw! + augroup Test + au! + au BufReadPost Xfile1 normal! 3G + augroup END + call writefile(range(1, 3), 'Xfile1') + call writefile(b, '.Xfile1.swp', 'D') + try + recover Xfile1 + catch /E308:/ + " this test is for the :E315 internal error. + " ignore the 'E308: Original file may have been changed' error + endtry + redraw! + augroup Test + au! + augroup END + augroup! Test +endfunc + +" Test for recovering a buffer without a name +func Test_noname_buffer() + new + call setline(1, ['one', 'two']) + preserve + let sn = swapname('') + let b = readblob(sn) + bw! + call writefile(b, sn, 'D') + exe "recover " .. sn + call assert_equal(['one', 'two'], getline(1, '$')) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_regex_char_classes.vim b/test/old/testdir/test_regex_char_classes.vim new file mode 100644 index 0000000000..db16f057c8 --- /dev/null +++ b/test/old/testdir/test_regex_char_classes.vim @@ -0,0 +1,297 @@ +" Tests for regexp with backslash and other special characters inside [] +" Also test backslash for hex/octal numbered character. +" + +scriptencoding utf-8 + +function RunSTest(value, calls, expected) + new + call feedkeys("i" . a:value, "mx") + exec a:calls + call assert_equal(a:expected, getline(1), printf("wrong result for %s", a:calls)) + quit! +endfunction + +function RunXTest(value, search_exp, expected) + new + call feedkeys("i" . a:value, "mx") + call feedkeys("gg" . a:search_exp . "\nx", "mx") + call assert_equal(a:expected, getline(1), printf("wrong result for %s", a:search_exp)) + quit! +endfunction + + +function Test_x_search() + let res = "test text test text" + call RunXTest("test \\text test text", "/[\\x]", res) + call RunXTest("test \ttext test text", "/[\\t\\]]", res) + call RunXTest("test text ]test text", "/[]y]", res) + call RunXTest("test ]text test text", "/[\\]]", res) + call RunXTest("test text te^st text", "/[y^]", res) + call RunXTest("test te$xt test text", "/[$y]", res) + call RunXTest("test taext test text", "/[\\x61]", res) + call RunXTest("test tbext test text","/[\\x60-\\x64]", res) + call RunXTest("test 5text test text","/[\\x785]", res) + call RunXTest("testc text test text","/[\\o143]", res) + call RunXTest("tesdt text test text","/[\\o140-\\o144]", res) + call RunXTest("test7 text test text", "/[\\o417]", res) + call RunXTest("test text tBest text", "/\\%x42", res) + call RunXTest("test text teCst text", "/\\%o103", res) + call RunXTest("test text \<C-V>x00test text", "/[\\x00]", res) +endfunction + +function Test_s_search() + let res = "test text test text" + call RunSTest("test te\<C-V>x00xt t\<C-V>x04est t\<C-V>x10ext", "s/[\\x00-\\x10]//g", res) + call RunSTest("test \\xyztext test text", "s/[\\x-z]\\+//", res) + call RunSTest("test text tev\\uyst text", "s/[\\u-z]\\{2,}//", res) + call RunSTest("xx aaaaa xx a", "s/\\(a\\)\\+//", "xx xx a") + call RunSTest("xx aaaaa xx a", "s/\\(a*\\)\\+//", "xx aaaaa xx a") + call RunSTest("xx aaaaa xx a", "s/\\(a*\\)*//", "xx aaaaa xx a") + call RunSTest("xx aaaaa xx", "s/\\(a\\)\\{2,3}/A/", "xx Aaa xx") + call RunSTest("xx aaaaa xx", "s/\\(a\\)\\{-2,3}/A/", "xx Aaaa xx") + call RunSTest("xx aaa12aa xx", "s/\\(a\\)*\\(12\\)\\@>/A/", "xx Aaa xx") + call RunSTest("xx foobar xbar xx", "s/\\(foo\\)\\@<!bar/A/", "xx foobar xA xx") + call RunSTest("xx an file xx", "s/\\(an\\_s\\+\\)\\@<=file/A/", "xx an A xx") + call RunSTest("x= 9;", "s/^\\(\\h\\w*\\%(->\\|\\.\\)\\=\\)\\+=/XX/", "XX 9;") + call RunSTest("hh= 77;", "s/^\\(\\h\\w*\\%(->\\|\\.\\)\\=\\)\\+=/YY/", "YY 77;") + call RunSTest(" aaa ", "s/aaa/xyz/", " xyz ") + call RunSTest(" xyz", "s/~/bcd/", " bcd") + call RunSTest(" bcdbcdbcd", "s/~\\+/BB/", " BB") +endfunction + +" Test character classes in regexp using regexpengine 0, 1, 2. +func Test_regex_char_classes() + new + let save_enc = &encoding + set encoding=utf-8 + + let input = "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b" + + " Format is [cmd_to_run, expected_output] + let tests = [ + \ [':s/\%#=0\d//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1\d//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2\d//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[0-9]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1[0-9]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2[0-9]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0\D//g', + \ "0123456789"], + \ [':s/\%#=1\D//g', + \ "0123456789"], + \ [':s/\%#=2\D//g', + \ "0123456789"], + \ [':s/\%#=0[^0-9]//g', + \ "0123456789"], + \ [':s/\%#=1[^0-9]//g', + \ "0123456789"], + \ [':s/\%#=2[^0-9]//g', + \ "0123456789"], + \ [':s/\%#=0\o//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./89:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1\o//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./89:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2\o//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./89:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[0-7]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./89:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1[0-7]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./89:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2[0-7]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./89:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0\O//g', + \ "01234567"], + \ [':s/\%#=1\O//g', + \ "01234567"], + \ [':s/\%#=2\O//g', + \ "01234567"], + \ [':s/\%#=0[^0-7]//g', + \ "01234567"], + \ [':s/\%#=1[^0-7]//g', + \ "01234567"], + \ [':s/\%#=2[^0-7]//g', + \ "01234567"], + \ [':s/\%#=0\x//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@GHIXYZ[\]^_`ghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1\x//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@GHIXYZ[\]^_`ghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2\x//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@GHIXYZ[\]^_`ghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[0-9A-Fa-f]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@GHIXYZ[\]^_`ghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1[0-9A-Fa-f]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@GHIXYZ[\]^_`ghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2[0-9A-Fa-f]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@GHIXYZ[\]^_`ghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0\X//g', + \ "0123456789ABCDEFabcdef"], + \ [':s/\%#=1\X//g', + \ "0123456789ABCDEFabcdef"], + \ [':s/\%#=2\X//g', + \ "0123456789ABCDEFabcdef"], + \ [':s/\%#=0[^0-9A-Fa-f]//g', + \ "0123456789ABCDEFabcdef"], + \ [':s/\%#=1[^0-9A-Fa-f]//g', + \ "0123456789ABCDEFabcdef"], + \ [':s/\%#=2[^0-9A-Fa-f]//g', + \ "0123456789ABCDEFabcdef"], + \ [':s/\%#=0\w//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1\w//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2\w//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[0-9A-Za-z_]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1[0-9A-Za-z_]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2[0-9A-Za-z_]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0\W//g', + \ "0123456789ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=1\W//g', + \ "0123456789ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=2\W//g', + \ "0123456789ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=0[^0-9A-Za-z_]//g', + \ "0123456789ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=1[^0-9A-Za-z_]//g', + \ "0123456789ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=2[^0-9A-Za-z_]//g', + \ "0123456789ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=0\h//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1\h//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2\h//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[A-Za-z_]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1[A-Za-z_]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2[A-Za-z_]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0\H//g', + \ "ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=1\H//g', + \ "ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=2\H//g', + \ "ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=0[^A-Za-z_]//g', + \ "ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=1[^A-Za-z_]//g', + \ "ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=2[^A-Za-z_]//g', + \ "ABCDEFGHIXYZ_abcdefghiwxyz"], + \ [':s/\%#=0\a//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1\a//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2\a//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[A-Za-z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1[A-Za-z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2[A-Za-z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0\A//g', + \ "ABCDEFGHIXYZabcdefghiwxyz"], + \ [':s/\%#=1\A//g', + \ "ABCDEFGHIXYZabcdefghiwxyz"], + \ [':s/\%#=2\A//g', + \ "ABCDEFGHIXYZabcdefghiwxyz"], + \ [':s/\%#=0[^A-Za-z]//g', + \ "ABCDEFGHIXYZabcdefghiwxyz"], + \ [':s/\%#=1[^A-Za-z]//g', + \ "ABCDEFGHIXYZabcdefghiwxyz"], + \ [':s/\%#=2[^A-Za-z]//g', + \ "ABCDEFGHIXYZabcdefghiwxyz"], + \ [':s/\%#=0\l//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1\l//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2\l//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[a-z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1[a-z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2[a-z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0\L//g', + \ "abcdefghiwxyz"], + \ [':s/\%#=1\L//g', + \ "abcdefghiwxyz"], + \ [':s/\%#=2\L//g', + \ "abcdefghiwxyz"], + \ [':s/\%#=0[^a-z]//g', + \ "abcdefghiwxyz"], + \ [':s/\%#=1[^a-z]//g', + \ "abcdefghiwxyz"], + \ [':s/\%#=2[^a-z]//g', + \ "abcdefghiwxyz"], + \ [':s/\%#=0\u//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1\u//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2\u//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[A-Z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1[A-Z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2[A-Z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./0123456789:;<=>?@[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0\U//g', + \ "ABCDEFGHIXYZ"], + \ [':s/\%#=1\U//g', + \ "ABCDEFGHIXYZ"], + \ [':s/\%#=2\U//g', + \ "ABCDEFGHIXYZ"], + \ [':s/\%#=0[^A-Z]//g', + \ "ABCDEFGHIXYZ"], + \ [':s/\%#=1[^A-Z]//g', + \ "ABCDEFGHIXYZ"], + \ [':s/\%#=2[^A-Z]//g', + \ "ABCDEFGHIXYZ"], + \ [':s/\%#=0\%' . line('.') . 'l^\t...//g', + \ "!\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1\%' . line('.') . 'l^\t...//g', + \ "!\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2\%' . line('.') . 'l^\t...//g', + \ "!\"#$%&'()#+'-./0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[0-z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=1[0-z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=2[0-z]//g', + \ "\t\<C-L>\<C-M> !\"#$%&'()#+'-./{|}~\<C-?>\u0080\u0082\u0090\u009b"], + \ [':s/\%#=0[^0-z]//g', + \ "0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz"], + \ [':s/\%#=1[^0-z]//g', + \ "0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz"], + \ [':s/\%#=2[^0-z]//g', + \ "0123456789:;<=>?@ABCDEFGHIXYZ[\]^_`abcdefghiwxyz"] + \] + + for [cmd, expected] in tests + call append(0, input) + call cursor(1, 1) + exe cmd + call assert_equal(expected, getline(1), cmd) + endfor + + let &encoding = save_enc + enew! + close +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_regexp_latin.vim b/test/old/testdir/test_regexp_latin.vim new file mode 100644 index 0000000000..ece6ae518e --- /dev/null +++ b/test/old/testdir/test_regexp_latin.vim @@ -0,0 +1,1094 @@ +" Tests for regexp in latin1 encoding + +" set encoding=latin1 +scriptencoding latin1 + +source check.vim + +func s:equivalence_test() + let str = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ' + \ .. 'a b c d e f g h i j k l m n o p q r s t u v w x y z ' + \ .. "0 1 2 3 4 5 6 7 8 9 " + \ .. "` ~ ! ? ; : . , / \\ ' \" | < > [ ] { } ( ) @ # $ % ^ & * _ - + \b \e \f \n \r \t" + let groups = split(str) + for group1 in groups + for c in split(group1, '\zs') + " next statement confirms that equivalence class matches every + " character in group + call assert_match('^[[=' . c . '=]]*$', group1) + for group2 in groups + if group2 != group1 + " next statement converts that equivalence class doesn't match + " a character in any other group + call assert_equal(-1, match(group2, '[[=' . c . '=]]')) + endif + endfor + endfor + endfor +endfunc + +func Test_equivalence_re1() + throw 'skipped: Nvim does not support enc=latin1' + set re=1 + call s:equivalence_test() +endfunc + +func Test_equivalence_re2() + throw 'skipped: Nvim does not support enc=latin1' + set re=2 + call s:equivalence_test() +endfunc + +func Test_range_with_newline() + new + call setline(1, "a") + call assert_equal(0, search("[ -*\\n- ]")) + call assert_equal(0, search("[ -*\\t-\\n]")) + bwipe! +endfunc + +func Test_pattern_compile_speed() + CheckOption spellcapcheck + CheckFunction reltimefloat + + let start = reltime() + " this used to be very slow, not it should be about a second + set spc=\\v(((((Nxxxxxxx&&xxxx){179})+)+)+){179} + call assert_inrange(0.01, 10.0, reltimefloat(reltime(start))) + set spc= +endfunc + +func Test_get_equi_class() + new + " Incomplete equivalence class caused invalid memory access + s/^/[[= + call assert_equal(1, search(getline(1))) + s/.*/[[. + call assert_equal(1, search(getline(1))) +endfunc + +func Test_rex_init() + set noincsearch + set re=1 + new + setlocal iskeyword=a-z + call setline(1, ['abc', 'ABC']) + call assert_equal(1, search('[[:keyword:]]')) + new + setlocal iskeyword=A-Z + call setline(1, ['abc', 'ABC']) + call assert_equal(2, search('[[:keyword:]]')) + bwipe! + bwipe! + set re=0 +endfunc + +func Test_backref() + new + call setline(1, ['one', 'two', 'three', 'four', 'five']) + call assert_equal(3, search('\%#=1\(e\)\1')) + call assert_equal(3, search('\%#=2\(e\)\1')) + call assert_fails('call search("\\%#=1\\(e\\1\\)")', 'E65:') + call assert_fails('call search("\\%#=2\\(e\\1\\)")', 'E65:') + bwipe! +endfunc + +func Test_multi_failure() + set re=1 + call assert_fails('/a**', 'E61:') + call assert_fails('/a*\+', 'E62:') + call assert_fails('/a\{a}', 'E554:') + set re=2 + call assert_fails('/a**', 'E871:') + call assert_fails('/a*\+', 'E871:') + call assert_fails('/a\{a}', 'E554:') + set re=0 +endfunc + +func Test_column_success_failure() + new + call setline(1, 'xbar') + + set re=1 + %s/\%>0v./A/ + call assert_equal('Abar', getline(1)) + call assert_fails('/\%v', 'E71:') + call assert_fails('/\%>v', 'E71:') + call assert_fails('/\%c', 'E71:') + call assert_fails('/\%<c', 'E71:') + call assert_fails('/\%l', 'E71:') + set re=2 + %s/\%>0v./B/ + call assert_equal('Bbar', getline(1)) + call assert_fails('/\%v', 'E1273:') + call assert_fails('/\%>v', 'E1273:') + call assert_fails('/\%c', 'E1273:') + call assert_fails('/\%<c', 'E1273:') + call assert_fails('/\%l', 'E1273:') + + set re=0 + bwipe! +endfunc + +func Test_recursive_addstate() + throw 'skipped: TODO: ' + " This will call addstate() recursively until it runs into the limit. + let lnum = search('\v((){328}){389}') + call assert_equal(0, lnum) +endfunc + +func Test_out_of_memory() + new + s/^/,n + " This will be slow... + call assert_fails('call search("\\v((n||<)+);")', 'E363:') +endfunc + +" Tests for regexp patterns without multi-byte support. +func Test_regexp_single_line_pat() + " tl is a List of Lists with: + " regexp engines to test + " 0 - test with 'regexpengine' values 0 and 1 + " 1 - test with 'regexpengine' values 0 and 2 + " 2 - test with 'regexpengine' values 0, 1 and 2 + " regexp pattern + " text to test the pattern on + " expected match (optional) + " expected submatch 1 (optional) + " expected submatch 2 (optional) + " etc. + " When there is no match use only the first two items. + let tl = [] + + call add(tl, [2, 'ab', 'aab', 'ab']) + call add(tl, [2, 'b', 'abcdef', 'b']) + call add(tl, [2, 'bc*', 'abccccdef', 'bcccc']) + call add(tl, [2, 'bc\{-}', 'abccccdef', 'b']) + call add(tl, [2, 'bc\{-}\(d\)', 'abccccdef', 'bccccd', 'd']) + call add(tl, [2, 'bc*', 'abbdef', 'b']) + call add(tl, [2, 'c*', 'ccc', 'ccc']) + call add(tl, [2, 'bc*', 'abdef', 'b']) + call add(tl, [2, 'c*', 'abdef', '']) + call add(tl, [2, 'bc\+', 'abccccdef', 'bcccc']) + call add(tl, [2, 'bc\+', 'abdef']) " no match + " match escape character in a string + call add(tl, [2, '.\e.', "one\<Esc>two", "e\<Esc>t"]) + " match backspace character in a string + call add(tl, [2, '.\b.', "one\<C-H>two", "e\<C-H>t"]) + " match newline character in a string + call add(tl, [2, 'o\nb', "foo\nbar", "o\nb"]) + + " operator \| + call add(tl, [2, 'a\|ab', 'cabd', 'a']) " alternation is ordered + + call add(tl, [2, 'c\?', 'ccb', 'c']) + call add(tl, [2, 'bc\?', 'abd', 'b']) + call add(tl, [2, 'bc\?', 'abccd', 'bc']) + + call add(tl, [2, '\va{1}', 'ab', 'a']) + + call add(tl, [2, '\va{2}', 'aa', 'aa']) + call add(tl, [2, '\va{2}', 'caad', 'aa']) + call add(tl, [2, '\va{2}', 'aba']) + call add(tl, [2, '\va{2}', 'ab']) + call add(tl, [2, '\va{2}', 'abaa', 'aa']) + call add(tl, [2, '\va{2}', 'aaa', 'aa']) + + call add(tl, [2, '\vb{1}', 'abca', 'b']) + call add(tl, [2, '\vba{2}', 'abaa', 'baa']) + call add(tl, [2, '\vba{3}', 'aabaac']) + + call add(tl, [2, '\v(ab){1}', 'ab', 'ab', 'ab']) + call add(tl, [2, '\v(ab){1}', 'dabc', 'ab', 'ab']) + call add(tl, [2, '\v(ab){1}', 'acb']) + + call add(tl, [2, '\v(ab){0,2}', 'acb', "", ""]) + call add(tl, [2, '\v(ab){0,2}', 'ab', 'ab', 'ab']) + call add(tl, [2, '\v(ab){1,2}', 'ab', 'ab', 'ab']) + call add(tl, [2, '\v(ab){1,2}', 'ababc', 'abab', 'ab']) + call add(tl, [2, '\v(ab){2,4}', 'ababcab', 'abab', 'ab']) + call add(tl, [2, '\v(ab){2,4}', 'abcababa', 'abab', 'ab']) + + call add(tl, [2, '\v(ab){2}', 'abab', 'abab', 'ab']) + call add(tl, [2, '\v(ab){2}', 'cdababe', 'abab', 'ab']) + call add(tl, [2, '\v(ab){2}', 'abac']) + call add(tl, [2, '\v(ab){2}', 'abacabab', 'abab', 'ab']) + call add(tl, [2, '\v((ab){2}){2}', 'abababab', 'abababab', 'abab', 'ab']) + call add(tl, [2, '\v((ab){2}){2}', 'abacabababab', 'abababab', 'abab', 'ab']) + + call add(tl, [2, '\v(a{1}){1}', 'a', 'a', 'a']) + call add(tl, [2, '\v(a{2}){1}', 'aa', 'aa', 'aa']) + call add(tl, [2, '\v(a{2}){1}', 'aaac', 'aa', 'aa']) + call add(tl, [2, '\v(a{2}){1}', 'daaac', 'aa', 'aa']) + call add(tl, [2, '\v(a{1}){2}', 'daaac', 'aa', 'a']) + call add(tl, [2, '\v(a{1}){2}', 'aaa', 'aa', 'a']) + call add(tl, [2, '\v(a{2})+', 'adaac', 'aa', 'aa']) + call add(tl, [2, '\v(a{2})+', 'aa', 'aa', 'aa']) + call add(tl, [2, '\v(a{2}){1}', 'aa', 'aa', 'aa']) + call add(tl, [2, '\v(a{1}){2}', 'aa', 'aa', 'a']) + call add(tl, [2, '\v(a{1}){1}', 'a', 'a', 'a']) + call add(tl, [2, '\v(a{2}){2}', 'aaaa', 'aaaa', 'aa']) + call add(tl, [2, '\v(a{2}){2}', 'aaabaaaa', 'aaaa', 'aa']) + + call add(tl, [2, '\v(a+){2}', 'dadaac', 'aa', 'a']) + call add(tl, [2, '\v(a{3}){2}', 'aaaaaaa', 'aaaaaa', 'aaa']) + + call add(tl, [2, '\v(a{1,2}){2}', 'daaac', 'aaa', 'a']) + call add(tl, [2, '\v(a{1,3}){2}', 'daaaac', 'aaaa', 'a']) + call add(tl, [2, '\v(a{1,3}){2}', 'daaaaac', 'aaaaa', 'aa']) + call add(tl, [2, '\v(a{1,3}){3}', 'daac']) + call add(tl, [2, '\v(a{1,2}){2}', 'dac']) + call add(tl, [2, '\v(a+)+', 'daac', 'aa', 'aa']) + call add(tl, [2, '\v(a+)+', 'aaa', 'aaa', 'aaa']) + call add(tl, [2, '\v(a+){1,2}', 'aaa', 'aaa', 'aaa']) + call add(tl, [2, '\v(a+)(a+)', 'aaa', 'aaa', 'aa', 'a']) + call add(tl, [2, '\v(a{3})+', 'daaaac', 'aaa', 'aaa']) + call add(tl, [2, '\v(a|b|c)+', 'aacb', 'aacb', 'b']) + call add(tl, [2, '\v(a|b|c){2}', 'abcb', 'ab', 'b']) + call add(tl, [2, '\v(abc){2}', 'abcabd', ]) + call add(tl, [2, '\v(abc){2}', 'abdabcabc','abcabc', 'abc']) + + call add(tl, [2, 'a*', 'cc', '']) + call add(tl, [2, '\v(a*)+', 'cc', '']) + call add(tl, [2, '\v((ab)+)+', 'ab', 'ab', 'ab', 'ab']) + call add(tl, [2, '\v(((ab)+)+)+', 'ab', 'ab', 'ab', 'ab', 'ab']) + call add(tl, [2, '\v(((ab)+)+)+', 'dababc', 'abab', 'abab', 'abab', 'ab']) + call add(tl, [2, '\v(a{0,2})+', 'cc', '']) + call add(tl, [2, '\v(a*)+', '', '']) + call add(tl, [2, '\v((a*)+)+', '', '']) + call add(tl, [2, '\v((ab)*)+', '', '']) + call add(tl, [2, '\va{1,3}', 'aab', 'aa']) + call add(tl, [2, '\va{2,3}', 'abaa', 'aa']) + + call add(tl, [2, '\v((ab)+|c*)+', 'abcccaba', 'abcccab', '', 'ab']) + call add(tl, [2, '\v(a{2})|(b{3})', 'bbabbbb', 'bbb', '', 'bbb']) + call add(tl, [2, '\va{2}|b{2}', 'abab']) + call add(tl, [2, '\v(a)+|(c)+', 'bbacbaacbbb', 'a', 'a']) + call add(tl, [2, '\vab{2,3}c', 'aabbccccccccccccc', 'abbc']) + call add(tl, [2, '\vab{2,3}c', 'aabbbccccccccccccc', 'abbbc']) + call add(tl, [2, '\vab{2,3}cd{2,3}e', 'aabbbcddee', 'abbbcdde']) + call add(tl, [2, '\va(bc){2}d', 'aabcbfbc' ]) + call add(tl, [2, '\va*a{2}', 'a', ]) + call add(tl, [2, '\va*a{2}', 'aa', 'aa' ]) + call add(tl, [2, '\va*a{2}', 'aaa', 'aaa' ]) + call add(tl, [2, '\va*a{2}', 'bbbabcc', ]) + call add(tl, [2, '\va*b*|a*c*', 'a', 'a']) + call add(tl, [2, '\va{1}b{1}|a{1}b{1}', '']) + + " submatches + call add(tl, [2, '\v(a)', 'ab', 'a', 'a']) + call add(tl, [2, '\v(a)(b)', 'ab', 'ab', 'a', 'b']) + call add(tl, [2, '\v(ab)(b)(c)', 'abbc', 'abbc', 'ab', 'b', 'c']) + call add(tl, [2, '\v((a)(b))', 'ab', 'ab', 'ab', 'a', 'b']) + call add(tl, [2, '\v(a)|(b)', 'ab', 'a', 'a']) + + call add(tl, [2, '\v(a*)+', 'aaaa', 'aaaa', '']) + call add(tl, [2, 'x', 'abcdef']) + + " + " Simple tests + " + + " Search single groups + call add(tl, [2, 'ab', 'aab', 'ab']) + call add(tl, [2, 'ab', 'baced']) + call add(tl, [2, 'ab', ' ab ', 'ab']) + + " Search multi-modifiers + call add(tl, [2, 'x*', 'xcd', 'x']) + call add(tl, [2, 'x*', 'xxxxxxxxxxxxxxxxsofijiojgf', 'xxxxxxxxxxxxxxxx']) + " empty match is good + call add(tl, [2, 'x*', 'abcdoij', '']) + " no match here + call add(tl, [2, 'x\+', 'abcdoin']) + call add(tl, [2, 'x\+', 'abcdeoijdfxxiuhfij', 'xx']) + call add(tl, [2, 'x\+', 'xxxxx', 'xxxxx']) + call add(tl, [2, 'x\+', 'abc x siufhiush xxxxxxxxx', 'x']) + call add(tl, [2, 'x\=', 'x sdfoij', 'x']) + call add(tl, [2, 'x\=', 'abc sfoij', '']) " empty match is good + call add(tl, [2, 'x\=', 'xxxxxxxxx c', 'x']) + call add(tl, [2, 'x\?', 'x sdfoij', 'x']) + " empty match is good + call add(tl, [2, 'x\?', 'abc sfoij', '']) + call add(tl, [2, 'x\?', 'xxxxxxxxxx c', 'x']) + + call add(tl, [2, 'a\{0,0}', 'abcdfdoij', '']) + " same thing as 'a?' + call add(tl, [2, 'a\{0,1}', 'asiubid axxxaaa', 'a']) + " same thing as 'a\{0,1}' + call add(tl, [2, 'a\{1,0}', 'asiubid axxxaaa', 'a']) + call add(tl, [2, 'a\{3,6}', 'aa siofuh']) + call add(tl, [2, 'a\{3,6}', 'aaaaa asfoij afaa', 'aaaaa']) + call add(tl, [2, 'a\{3,6}', 'aaaaaaaa', 'aaaaaa']) + call add(tl, [2, 'a\{0}', 'asoiuj', '']) + call add(tl, [2, 'a\{2}', 'aaaa', 'aa']) + call add(tl, [2, 'a\{2}', 'iuash fiusahfliusah fiushfilushfi uhsaifuh askfj nasfvius afg aaaa sfiuhuhiushf', 'aa']) + call add(tl, [2, 'a\{2}', 'abcdefghijklmnopqrestuvwxyz1234567890']) + " same thing as 'a*' + call add(tl, [2, 'a\{0,}', 'oij sdigfusnf', '']) + call add(tl, [2, 'a\{0,}', 'aaaaa aa', 'aaaaa']) + call add(tl, [2, 'a\{2,}', 'sdfiougjdsafg']) + call add(tl, [2, 'a\{2,}', 'aaaaasfoij ', 'aaaaa']) + call add(tl, [2, 'a\{5,}', 'xxaaaaxxx ']) + call add(tl, [2, 'a\{5,}', 'xxaaaaaxxx ', 'aaaaa']) + call add(tl, [2, 'a\{,0}', 'oidfguih iuhi hiu aaaa', '']) + call add(tl, [2, 'a\{,5}', 'abcd', 'a']) + call add(tl, [2, 'a\{,5}', 'aaaaaaaaaa', 'aaaaa']) + " leading star as normal char when \{} follows + call add(tl, [2, '^*\{4,}$', '***']) + call add(tl, [2, '^*\{4,}$', '****', '****']) + call add(tl, [2, '^*\{4,}$', '*****', '*****']) + " same thing as 'a*' + call add(tl, [2, 'a\{}', 'bbbcddiuhfcd', '']) + call add(tl, [2, 'a\{}', 'aaaaioudfh coisf jda', 'aaaa']) + + call add(tl, [2, 'a\{-0,0}', 'abcdfdoij', '']) + " anti-greedy version of 'a?' + call add(tl, [2, 'a\{-0,1}', 'asiubid axxxaaa', '']) + call add(tl, [2, 'a\{-3,6}', 'aa siofuh']) + call add(tl, [2, 'a\{-3,6}', 'aaaaa asfoij afaa', 'aaa']) + call add(tl, [2, 'a\{-3,6}', 'aaaaaaaa', 'aaa']) + call add(tl, [2, 'a\{-0}', 'asoiuj', '']) + call add(tl, [2, 'a\{-2}', 'aaaa', 'aa']) + call add(tl, [2, 'a\{-2}', 'abcdefghijklmnopqrestuvwxyz1234567890']) + call add(tl, [2, 'a\{-0,}', 'oij sdigfusnf', '']) + call add(tl, [2, 'a\{-0,}', 'aaaaa aa', '']) + call add(tl, [2, 'a\{-2,}', 'sdfiougjdsafg']) + call add(tl, [2, 'a\{-2,}', 'aaaaasfoij ', 'aa']) + call add(tl, [2, 'a\{-,0}', 'oidfguih iuhi hiu aaaa', '']) + call add(tl, [2, 'a\{-,5}', 'abcd', '']) + call add(tl, [2, 'a\{-,5}', 'aaaaaaaaaa', '']) + " anti-greedy version of 'a*' + call add(tl, [2, 'a\{-}', 'bbbcddiuhfcd', '']) + call add(tl, [2, 'a\{-}', 'aaaaioudfh coisf jda', '']) + + " Test groups of characters and submatches + call add(tl, [2, '\(abc\)*', 'abcabcabc', 'abcabcabc', 'abc']) + call add(tl, [2, '\(ab\)\+', 'abababaaaaa', 'ababab', 'ab']) + call add(tl, [2, '\(abaaaaa\)*cd', 'cd', 'cd', '']) + call add(tl, [2, '\(test1\)\? \(test2\)\?', 'test1 test3', 'test1 ', 'test1', '']) + call add(tl, [2, '\(test1\)\= \(test2\) \(test4443\)\=', ' test2 test4443 yupiiiiiiiiiii', ' test2 test4443', '', 'test2', 'test4443']) + call add(tl, [2, '\(\(sub1\) hello \(sub 2\)\)', 'asterix sub1 hello sub 2 obelix', 'sub1 hello sub 2', 'sub1 hello sub 2', 'sub1', 'sub 2']) + call add(tl, [2, '\(\(\(yyxxzz\)\)\)', 'abcdddsfiusfyyzzxxyyxxzz', 'yyxxzz', 'yyxxzz', 'yyxxzz', 'yyxxzz']) + call add(tl, [2, '\v((ab)+|c+)+', 'abcccaba', 'abcccab', 'ab', 'ab']) + call add(tl, [2, '\v((ab)|c*)+', 'abcccaba', 'abcccab', '', 'ab']) + call add(tl, [2, '\v(a(c*)+b)+', 'acbababaaa', 'acbabab', 'ab', '']) + call add(tl, [2, '\v(a|b*)+', 'aaaa', 'aaaa', '']) + call add(tl, [2, '\p*', 'a ', 'a ']) + + " Test greedy-ness and lazy-ness + call add(tl, [2, 'a\{-2,7}','aaaaaaaaaaaaa', 'aa']) + call add(tl, [2, 'a\{-2,7}x','aaaaaaaaax', 'aaaaaaax']) + call add(tl, [2, 'a\{2,7}','aaaaaaaaaaaaaaaaaaaa', 'aaaaaaa']) + call add(tl, [2, 'a\{2,7}x','aaaaaaaaax', 'aaaaaaax']) + call add(tl, [2, '\vx(.{-,8})yz(.*)','xayxayzxayzxayz','xayxayzxayzxayz','ayxa','xayzxayz']) + call add(tl, [2, '\vx(.*)yz(.*)','xayxayzxayzxayz','xayxayzxayzxayz', 'ayxayzxayzxa','']) + call add(tl, [2, '\v(a{1,2}){-2,3}','aaaaaaa','aaaa','aa']) + call add(tl, [2, '\v(a{-1,3})+', 'aa', 'aa', 'a']) + call add(tl, [2, '^\s\{-}\zs\( x\|x$\)', ' x', ' x', ' x']) + call add(tl, [2, '^\s\{-}\zs\(x\| x$\)', ' x', ' x', ' x']) + call add(tl, [2, '^\s\{-}\ze\(x\| x$\)', ' x', '', ' x']) + call add(tl, [2, '^\(\s\{-}\)\(x\| x$\)', ' x', ' x', '', ' x']) + + " Test Character classes + call add(tl, [2, '\d\+e\d\d','test 10e23 fd','10e23']) + + " Test collections and character range [] + call add(tl, [2, '\v[a]', 'abcd', 'a']) + call add(tl, [2, 'a[bcd]', 'abcd', 'ab']) + call add(tl, [2, 'a[b-d]', 'acbd', 'ac']) + call add(tl, [2, '[a-d][e-f][x-x]d', 'cexdxx', 'cexd']) + call add(tl, [2, '\v[[:alpha:]]+', 'abcdefghijklmnopqrstuvwxyz6','abcdefghijklmnopqrstuvwxyz']) + call add(tl, [2, '[[:alpha:]\+]', '6x8','x']) + call add(tl, [2, '[^abc]\+','abcabcabc']) + call add(tl, [2, '[^abc]','defghiasijvoinasoiunbvb','d']) + call add(tl, [2, '[^abc]\+','ddddddda','ddddddd']) + call add(tl, [2, '[^a-d]\+','aaaAAAZIHFNCddd','AAAZIHFNC']) + call add(tl, [2, '[a-f]*','iiiiiiii','']) + call add(tl, [2, '[a-f]*','abcdefgh','abcdef']) + call add(tl, [2, '[^a-f]\+','abcdefgh','gh']) + call add(tl, [2, '[a-c]\{-3,6}','abcabc','abc']) + call add(tl, [2, '[^[:alpha:]]\+','abcccadfoij7787ysf287yrnccdu','7787']) + call add(tl, [2, '[-a]', '-', '-']) + call add(tl, [2, '[a-]', '-', '-']) + call add(tl, [2, '[a-f]*\c','ABCDEFGH','ABCDEF']) + call add(tl, [2, '[abc][xyz]\c','-af-AF-BY--','BY']) + " filename regexp + call add(tl, [2, '[-./[:alnum:]_~]\+', 'log13.file', 'log13.file']) + " special chars + call add(tl, [2, '[\]\^\-\\]\+', '\^\\\-\---^', '\^\\\-\---^']) + " collation elem + call add(tl, [2, '[[.a.]]\+', 'aa', 'aa']) + " middle of regexp + call add(tl, [2, 'abc[0-9]*ddd', 'siuhabc ii']) + call add(tl, [2, 'abc[0-9]*ddd', 'adf abc44482ddd oijs', 'abc44482ddd']) + call add(tl, [2, '\_[0-9]\+', 'asfi9888u', '9888']) + call add(tl, [2, '[0-9\n]\+', 'asfi9888u', '9888']) + call add(tl, [2, '\_[0-9]\+', "asfi\n9888u", "\n9888"]) + call add(tl, [2, '\_f', " \na ", "\n"]) + call add(tl, [2, '\_f\+', " \na ", "\na"]) + call add(tl, [2, '[0-9A-Za-z-_.]\+', " @0_a.A-{ ", "0_a.A-"]) + + " Test start/end of line, start/end of file + call add(tl, [2, '^a.', "a_\nb ", "a_"]) + call add(tl, [2, '^a.', "b a \na_"]) + call add(tl, [2, '.a$', " a\n "]) + call add(tl, [2, '.a$', " a b\n_a", "_a"]) + call add(tl, [2, '\%^a.', "a a\na", "a "]) + call add(tl, [2, '\%^a', " a \na "]) + call add(tl, [2, '.a\%$', " a\n "]) + call add(tl, [2, '.a\%$', " a\n_a", "_a"]) + + " Test recognition of character classes + call add(tl, [2, '[0-7]\+', 'x0123456789x', '01234567']) + call add(tl, [2, '[^0-7]\+', '0a;X+% 897', 'a;X+% 89']) + call add(tl, [2, '[0-9]\+', 'x0123456789x', '0123456789']) + call add(tl, [2, '[^0-9]\+', '0a;X+% 9', 'a;X+% ']) + call add(tl, [2, '[0-9a-fA-F]\+', 'x0189abcdefg', '0189abcdef']) + call add(tl, [2, '[^0-9A-Fa-f]\+', '0189g;X+% ab', 'g;X+% ']) + call add(tl, [2, '[a-z_A-Z0-9]\+', ';+aso_SfOij ', 'aso_SfOij']) + call add(tl, [2, '[^a-z_A-Z0-9]\+', 'aSo_;+% sfOij', ';+% ']) + call add(tl, [2, '[a-z_A-Z]\+', '0abyz_ABYZ;', 'abyz_ABYZ']) + call add(tl, [2, '[^a-z_A-Z]\+', 'abAB_09;+% yzYZ', '09;+% ']) + call add(tl, [2, '[a-z]\+', '0abcxyz1', 'abcxyz']) + call add(tl, [2, '[a-z]\+', 'AabxyzZ', 'abxyz']) + call add(tl, [2, '[^a-z]\+', 'a;X09+% x', ';X09+% ']) + call add(tl, [2, '[^a-z]\+', 'abX0;%yz', 'X0;%']) + call add(tl, [2, '[a-zA-Z]\+', '0abABxzXZ9', 'abABxzXZ']) + call add(tl, [2, '[^a-zA-Z]\+', 'ab09_;+ XZ', '09_;+ ']) + call add(tl, [2, '[A-Z]\+', 'aABXYZz', 'ABXYZ']) + call add(tl, [2, '[^A-Z]\+', 'ABx0;%YZ', 'x0;%']) + call add(tl, [2, '[a-z]\+\c', '0abxyzABXYZ;', 'abxyzABXYZ']) + call add(tl, [2, '[A-Z]\+\c', '0abABxzXZ9', 'abABxzXZ']) + call add(tl, [2, '\c[^a-z]\+', 'ab09_;+ XZ', '09_;+ ']) + call add(tl, [2, '\c[^A-Z]\+', 'ab09_;+ XZ', '09_;+ ']) + call add(tl, [2, '\C[^A-Z]\+', 'ABCOIJDEOIFNSD jsfoij sa', ' jsfoij sa']) + + " Tests for \z features + " match ends at \ze + call add(tl, [2, 'xx \ze test', 'xx ']) + call add(tl, [2, 'abc\zeend', 'oij abcend', 'abc']) + call add(tl, [2, 'aa\zebb\|aaxx', ' aabb ', 'aa']) + call add(tl, [2, 'aa\zebb\|aaxx', ' aaxx ', 'aaxx']) + call add(tl, [2, 'aabb\|aa\zebb', ' aabb ', 'aabb']) + call add(tl, [2, 'aa\zebb\|aaebb', ' aabb ', 'aa']) + " match starts at \zs + call add(tl, [2, 'abc\zsdd', 'ddabcddxyzt', 'dd']) + call add(tl, [2, 'aa \zsax', ' ax']) + call add(tl, [2, 'abc \zsmatch\ze abc', 'abc abc abc match abc abc', 'match']) + call add(tl, [2, '\v(a \zsif .*){2}', 'a if then a if last', 'if last', 'a if last']) + call add(tl, [2, '\>\zs.', 'aword. ', '.']) + call add(tl, [2, '\s\+\ze\[/\|\s\zs\s\+', 'is [a t', ' ']) + + " Tests for \@= and \& features + call add(tl, [2, 'abc\@=', 'abc', 'ab']) + call add(tl, [2, 'abc\@=cd', 'abcd', 'abcd']) + call add(tl, [2, 'abc\@=', 'ababc', 'ab']) + " will never match, no matter the input text + call add(tl, [2, 'abcd\@=e', 'abcd']) + " will never match + call add(tl, [2, 'abcd\@=e', 'any text in here ... ']) + call add(tl, [2, '\v(abc)@=..', 'xabcd', 'ab', 'abc']) + call add(tl, [2, '\(.*John\)\@=.*Bob', 'here is John, and here is B']) + call add(tl, [2, '\(John.*\)\@=.*Bob', 'John is Bobs friend', 'John is Bob', 'John is Bobs friend']) + call add(tl, [2, '\<\S\+\())\)\@=', '$((i=i+1))', 'i=i+1', '))']) + call add(tl, [2, '.*John\&.*Bob', 'here is John, and here is B']) + call add(tl, [2, '.*John\&.*Bob', 'John is Bobs friend', 'John is Bob']) + call add(tl, [2, '\v(test1)@=.*yep', 'this is a test1, yep it is', 'test1, yep', 'test1']) + call add(tl, [2, 'foo\(bar\)\@!', 'foobar']) + call add(tl, [2, 'foo\(bar\)\@!', 'foo bar', 'foo']) + call add(tl, [2, 'if \(\(then\)\@!.\)*$', ' if then else']) + call add(tl, [2, 'if \(\(then\)\@!.\)*$', ' if else ', 'if else ', ' ']) + call add(tl, [2, '\(foo\)\@!bar', 'foobar', 'bar']) + call add(tl, [2, '\(foo\)\@!...bar', 'foobar']) + call add(tl, [2, '^\%(.*bar\)\@!.*\zsfoo', ' bar foo ']) + call add(tl, [2, '^\%(.*bar\)\@!.*\zsfoo', ' foo bar ']) + call add(tl, [2, '^\%(.*bar\)\@!.*\zsfoo', ' foo xxx ', 'foo']) + call add(tl, [2, '[ ]\@!\p\%([ ]\@!\p\)*:', 'implicit mappings:', 'mappings:']) + call add(tl, [2, '[ ]\@!\p\([ ]\@!\p\)*:', 'implicit mappings:', 'mappings:', 's']) + call add(tl, [2, 'm\k\+_\@=\%(_\@!\k\)\@<=\k\+e', 'mx__xe', 'mx__xe']) + call add(tl, [2, '\%(\U\@<=S\k*\|S\l\)R', 'SuR', 'SuR']) + + " Combining different tests and features + call add(tl, [2, '[[:alpha:]]\{-2,6}', '787abcdiuhsasiuhb4', 'ab']) + call add(tl, [2, '', 'abcd', '']) + call add(tl, [2, '\v(())', 'any possible text', '']) + call add(tl, [2, '\v%(ab(xyz)c)', ' abxyzc ', 'abxyzc', 'xyz']) + call add(tl, [2, '\v(test|)empty', 'tesempty', 'empty', '']) + call add(tl, [2, '\v(a|aa)(a|aa)', 'aaa', 'aa', 'a', 'a']) + + " \%u and friends + call add(tl, [2, '\%d32', 'yes no', ' ']) + call add(tl, [2, '\%o40', 'yes no', ' ']) + call add(tl, [2, '\%x20', 'yes no', ' ']) + call add(tl, [2, '\%u0020', 'yes no', ' ']) + call add(tl, [2, '\%U00000020', 'yes no', ' ']) + call add(tl, [2, '\%d0', "yes\x0ano", "\x0a"]) + + "" \%[abc] + call add(tl, [2, 'foo\%[bar]', 'fobar']) + call add(tl, [2, 'foo\%[bar]', 'foobar', 'foobar']) + call add(tl, [2, 'foo\%[bar]', 'fooxx', 'foo']) + call add(tl, [2, 'foo\%[bar]', 'foobxx', 'foob']) + call add(tl, [2, 'foo\%[bar]', 'foobaxx', 'fooba']) + call add(tl, [2, 'foo\%[bar]', 'foobarxx', 'foobar']) + call add(tl, [2, 'foo\%[bar]x', 'foobxx', 'foobx']) + call add(tl, [2, 'foo\%[bar]x', 'foobarxx', 'foobarx']) + call add(tl, [2, '\%[bar]x', 'barxx', 'barx']) + call add(tl, [2, '\%[bar]x', 'bxx', 'bx']) + call add(tl, [2, '\%[bar]x', 'xxx', 'x']) + call add(tl, [2, 'b\%[[ao]r]', 'bar bor', 'bar']) + call add(tl, [2, 'b\%[[]]r]', 'b]r bor', 'b]r']) + call add(tl, [2, '@\%[\w\-]*', '<http://john.net/pandoc/>[@pandoc]', '@pandoc']) + + " Alternatives, must use first longest match + call add(tl, [2, 'goo\|go', 'google', 'goo']) + call add(tl, [2, '\<goo\|\<go', 'google', 'goo']) + call add(tl, [2, '\<goo\|go', 'google', 'goo']) + + " Back references + call add(tl, [2, '\(\i\+\) \1', ' abc abc', 'abc abc', 'abc']) + call add(tl, [2, '\(\i\+\) \1', 'xgoo goox', 'goo goo', 'goo']) + call add(tl, [2, '\(a\)\(b\)\(c\)\(dd\)\(e\)\(f\)\(g\)\(h\)\(i\)\1\2\3\4\5\6\7\8\9', 'xabcddefghiabcddefghix', 'abcddefghiabcddefghi', 'a', 'b', 'c', 'dd', 'e', 'f', 'g', 'h', 'i']) + call add(tl, [2, '\(\d*\)a \1b', ' a b ', 'a b', '']) + call add(tl, [2, '^.\(.\).\_..\1.', "aaa\naaa\nb", "aaa\naaa", 'a']) + call add(tl, [2, '^.*\.\(.*\)/.\+\(\1\)\@<!$', 'foo.bat/foo.com', 'foo.bat/foo.com', 'bat']) + call add(tl, [2, '^.*\.\(.*\)/.\+\(\1\)\@<!$', 'foo.bat/foo.bat']) + call add(tl, [2, '^.*\.\(.*\)/.\+\(\1\)\@<=$', 'foo.bat/foo.bat', 'foo.bat/foo.bat', 'bat', 'bat']) + call add(tl, [2, '\\\@<!\${\(\d\+\%(:.\{-}\)\?\\\@<!\)}', '2013-06-27${0}', '${0}', '0']) + call add(tl, [2, '^\(a*\)\1$', 'aaaaaaaa', 'aaaaaaaa', 'aaaa']) + call add(tl, [2, '^\(a\{-2,}\)\1\+$', 'aaaaaaaaa', 'aaaaaaaaa', 'aaa']) + + " Look-behind with limit + call add(tl, [2, '<\@<=span.', 'xxspanxx<spanyyy', 'spany']) + call add(tl, [2, '<\@1<=span.', 'xxspanxx<spanyyy', 'spany']) + call add(tl, [2, '<\@2<=span.', 'xxspanxx<spanyyy', 'spany']) + call add(tl, [2, '\(<<\)\@<=span.', 'xxspanxxxx<spanxx<<spanyyy', 'spany', '<<']) + call add(tl, [2, '\(<<\)\@1<=span.', 'xxspanxxxx<spanxx<<spanyyy']) + call add(tl, [2, '\(<<\)\@2<=span.', 'xxspanxxxx<spanxx<<spanyyy', 'spany', '<<']) + call add(tl, [2, '\(foo\)\@<!bar.', 'xx foobar1 xbar2 xx', 'bar2']) + + " look-behind match in front of a zero-width item + call add(tl, [2, '\v\C%(<Last Changed:\s+)@<=.*$', '" test header']) + call add(tl, [2, '\v\C%(<Last Changed:\s+)@<=.*$', '" Last Changed: 1970', '1970']) + call add(tl, [2, '\(foo\)\@<=\>', 'foobar']) + call add(tl, [2, '\(foo\)\@<=\>', 'barfoo', '', 'foo']) + call add(tl, [2, '\(foo\)\@<=.*', 'foobar', 'bar', 'foo']) + + " complicated look-behind match + call add(tl, [2, '\(r\@<=\|\w\@<!\)\/', 'x = /word/;', '/']) + call add(tl, [2, '^[a-z]\+\ze \&\(asdf\)\@<!', 'foo bar', 'foo']) + + "" \@> + call add(tl, [2, '\(a*\)\@>a', 'aaaa']) + call add(tl, [2, '\(a*\)\@>b', 'aaab', 'aaab', 'aaa']) + call add(tl, [2, '^\(.\{-}b\)\@>.', ' abcbd', ' abc', ' ab']) + call add(tl, [2, '\(.\{-}\)\(\)\@>$', 'abc', 'abc', 'abc', '']) + " TODO: BT engine does not restore submatch after failure + call add(tl, [1, '\(a*\)\@>a\|a\+', 'aaaa', 'aaaa']) + + " "\_" prepended negated collection matches EOL + call add(tl, [2, '\_[^8-9]\+', "asfi\n9888", "asfi\n"]) + call add(tl, [2, '\_[^a]\+', "asfi\n9888", "sfi\n9888"]) + + " Requiring lots of states. + call add(tl, [2, '[0-9a-zA-Z]\{8}-\([0-9a-zA-Z]\{4}-\)\{3}[0-9a-zA-Z]\{12}', " 12345678-1234-1234-1234-123456789012 ", "12345678-1234-1234-1234-123456789012", "1234-"]) + + " Skip adding state twice + call add(tl, [2, '^\%(\%(^\s*#\s*if\>\|#\s*if\)\)\(\%>1c.*$\)\@=', "#if FOO", "#if", ' FOO']) + + " Test \%V atom + call add(tl, [2, '\%>70vGesamt', 'Jean-Michel Charlier & Victor Hubinon\Gesamtausgabe [Salleck] Buck Danny {Jean-Michel Charlier & Victor Hubinon}\Gesamtausgabe', 'Gesamt']) + + " Test for ignoring case and matching repeated characters + call add(tl, [2, '\cb\+', 'aAbBbBcC', 'bBbB']) + + " Run the tests + for t in tl + let re = t[0] + let pat = t[1] + let text = t[2] + let matchidx = 3 + for engine in [0, 1, 2] + if engine == 2 && re == 0 || engine == 1 && re == 1 + continue + endif + let ®expengine = engine + try + let l = matchlist(text, pat) + catch + call assert_report('Error ' . engine . ': pat: \"' . pat + \ . '\", text: \"' . text . '\", caused an exception: \"' + \ . v:exception . '\"') + endtry + " check the match itself + if len(l) == 0 && len(t) > matchidx + call assert_report('Error ' . engine . ': pat: \"' . pat + \ . '\", text: \"' . text . '\", did not match, expected: \"' + \ . t[matchidx] . '\"') + elseif len(l) > 0 && len(t) == matchidx + call assert_report('Error ' . engine . ': pat: \"' . pat + \ . '\", text: \"' . text . '\", match: \"' . l[0] + \ . '\", expected no match') + elseif len(t) > matchidx && l[0] != t[matchidx] + call assert_report('Error ' . engine . ': pat: \"' . pat + \ . '\", text: \"' . text . '\", match: \"' . l[0] + \ . '\", expected: \"' . t[matchidx] . '\"') + else + " Test passed + endif + + " check all the nine submatches + if len(l) > 0 + for i in range(1, 9) + if len(t) <= matchidx + i + let e = '' + else + let e = t[matchidx + i] + endif + if l[i] != e + call assert_report('Error ' . engine . ': pat: \"' . pat + \ . '\", text: \"' . text . '\", submatch ' . i . ': \"' + \ . l[i] . '\", expected: \"' . e . '\"') + endif + endfor + unlet i + endif + endfor + endfor + + unlet t tl e l +endfunc + +" Tests for multi-line regexp patterns without multi-byte support. +func Test_regexp_multiline_pat() + " tl is a List of Lists with: + " regexp engines to test + " 0 - test with 'regexpengine' values 0 and 1 + " 1 - test with 'regexpengine' values 0 and 2 + " 2 - test with 'regexpengine' values 0, 1 and 2 + " regexp pattern + " List with text to test the pattern on + " List with the expected match + let tl = [] + + " back references + call add(tl, [2, '^.\(.\).\_..\1.', ['aaa', 'aaa', 'b'], ['XX', 'b']]) + call add(tl, [2, '\v.*\/(.*)\n.*\/\1$', ['./Dir1/Dir2/zyxwvuts.txt', './Dir1/Dir2/abcdefgh.bat', '', './Dir1/Dir2/file1.txt', './OtherDir1/OtherDir2/file1.txt'], ['./Dir1/Dir2/zyxwvuts.txt', './Dir1/Dir2/abcdefgh.bat', '', 'XX']]) + + " line breaks + call add(tl, [2, '\S.*\nx', ['abc', 'def', 'ghi', 'xjk', 'lmn'], ['abc', 'def', 'XXjk', 'lmn']]) + + " Any single character or end-of-line + call add(tl, [2, '\_.\+', ['a', 'b', 'c'], ['XX']]) + " Any identifier or end-of-line + call add(tl, [2, '\_i\+', ['a', 'b', ';', '2'], ['XX;XX']]) + " Any identifier but excluding digits or end-of-line + call add(tl, [2, '\_I\+', ['a', 'b', ';', '2'], ['XX;XX2XX']]) + " Any keyword or end-of-line + call add(tl, [2, '\_k\+', ['a', 'b', '=', '2'], ['XX=XX']]) + " Any keyword but excluding digits or end-of-line + call add(tl, [2, '\_K\+', ['a', 'b', '=', '2'], ['XX=XX2XX']]) + " Any filename character or end-of-line + call add(tl, [2, '\_f\+', ['a', 'b', '.', '5'], ['XX']]) + " Any filename character but excluding digits or end-of-line + call add(tl, [2, '\_F\+', ['a', 'b', '.', '5'], ['XX5XX']]) + " Any printable character or end-of-line + call add(tl, [2, '\_p\+', ['a', 'b', '=', '4'], ['XX']]) + " Any printable character excluding digits or end-of-line + call add(tl, [2, '\_P\+', ['a', 'b', '=', '4'], ['XX4XX']]) + " Any whitespace character or end-of-line + call add(tl, [2, '\_s\+', [' ', ' ', 'a', 'b'], ['XXaXXbXX']]) + " Any non-whitespace character or end-of-line + call add(tl, [2, '\_S\+', [' ', ' ', 'a', 'b'], [' XX XX']]) + " Any decimal digit or end-of-line + call add(tl, [2, '\_d\+', ['1', 'a', '2', 'b', '3'], ['XXaXXbXX']]) + " Any non-decimal digit or end-of-line + call add(tl, [2, '\_D\+', ['1', 'a', '2', 'b', '3'], ['1XX2XX3XX']]) + " Any hexadecimal digit or end-of-line + call add(tl, [2, '\_x\+', ['1', 'a', 'g', '9', '8'], ['XXgXX']]) + " Any non-hexadecimal digit or end-of-line + call add(tl, [2, '\_X\+', ['1', 'a', 'g', '9', '8'], ['1XXaXX9XX8XX']]) + " Any octal digit or end-of-line + call add(tl, [2, '\_o\+', ['0', '7', '8', '9', '0'], ['XX8XX9XX']]) + " Any non-octal digit or end-of-line + call add(tl, [2, '\_O\+', ['0', '7', '8', '9', '0'], ['0XX7XX0XX']]) + " Any word character or end-of-line + call add(tl, [2, '\_w\+', ['A', 'B', '=', 'C', 'D'], ['XX=XX']]) + " Any non-word character or end-of-line + call add(tl, [2, '\_W\+', ['A', 'B', '=', 'C', 'D'], ['AXXBXXCXXDXX']]) + " Any head-of-word character or end-of-line + call add(tl, [2, '\_h\+', ['a', '1', 'b', '2', 'c'], ['XX1XX2XX']]) + " Any non-head-of-word character or end-of-line + call add(tl, [2, '\_H\+', ['a', '1', 'b', '2', 'c'], ['aXXbXXcXX']]) + " Any alphabetic character or end-of-line + call add(tl, [2, '\_a\+', ['a', '1', 'b', '2', 'c'], ['XX1XX2XX']]) + " Any non-alphabetic character or end-of-line + call add(tl, [2, '\_A\+', ['a', '1', 'b', '2', 'c'], ['aXXbXXcXX']]) + " Any lowercase character or end-of-line + call add(tl, [2, '\_l\+', ['a', 'A', 'b', 'B'], ['XXAXXBXX']]) + " Any non-lowercase character or end-of-line + call add(tl, [2, '\_L\+', ['a', 'A', 'b', 'B'], ['aXXbXX']]) + " Any uppercase character or end-of-line + call add(tl, [2, '\_u\+', ['a', 'A', 'b', 'B'], ['aXXbXX']]) + " Any non-uppercase character or end-of-line + call add(tl, [2, '\_U\+', ['a', 'A', 'b', 'B'], ['XXAXXBXX']]) + " Collection or end-of-line + call add(tl, [2, '\_[a-z]\+', ['a', 'A', 'b', 'B'], ['XXAXXBXX']]) + " start of line anywhere in the text + call add(tl, [2, 'one\zs\_s*\_^\zetwo', + \ ['', 'one', ' two', 'one', '', 'two'], + \ ['', 'one', ' two', 'oneXXtwo']]) + " end of line anywhere in the text + call add(tl, [2, 'one\zs\_$\_s*two', + \ ['', 'one', ' two', 'one', '', 'two'], ['', 'oneXX', 'oneXX']]) + + " Check that \_[0-9] matching EOL does not break a following \> + call add(tl, [2, '\<\(\(25\_[0-5]\|2\_[0-4]\_[0-9]\|\_[01]\?\_[0-9]\_[0-9]\?\)\.\)\{3\}\(25\_[0-5]\|2\_[0-4]\_[0-9]\|\_[01]\?\_[0-9]\_[0-9]\?\)\>', ['', 'localnet/192.168.0.1', ''], ['', 'localnet/XX', '']]) + + " Check a pattern with a line break and ^ and $ + call add(tl, [2, 'a\n^b$\n^c', ['a', 'b', 'c'], ['XX']]) + + call add(tl, [2, '\(^.\+\n\)\1', [' dog', ' dog', 'asdf'], ['XXasdf']]) + + " Run the multi-line tests + for t in tl + let re = t[0] + let pat = t[1] + let before = t[2] + let after = t[3] + for engine in [0, 1, 2] + if engine == 2 && re == 0 || engine == 1 && re == 1 + continue + endif + let ®expengine = engine + new + call setline(1, before) + exe '%s/' . pat . '/XX/' + let result = getline(1, '$') + q! + if result != after + call assert_report('Error: pat: \"' . pat . '\", text: \"' + \ . string(before) . '\", expected: \"' . string(after) + \ . '\", got: \"' . string(result) . '\"') + else + " Test passed + endif + endfor + endfor + unlet t tl +endfunc + +" Check that using a pattern on two lines doesn't get messed up by using +" matchstr() with \ze in between. +func Test_matchstr_with_ze() + new + call append(0, ['Substitute here:', '<T="">Ta 5</Title>', + \ '<T="">Ac 7</Title>']) + call cursor(1, 1) + set re=0 + + .+1,.+2s/""/\='"' . matchstr(getline("."), '\d\+\ze<') . '"' + call assert_equal(['Substitute here:', '<T="5">Ta 5</Title>', + \ '<T="7">Ac 7</Title>', ''], getline(1, '$')) + + bwipe! +endfunc + +" Check a pattern with a look behind crossing a line boundary +func Test_lookbehind_across_line() + new + call append(0, ['Behind:', 'asdfasd<yyy', 'xxstart1', 'asdfasd<yy', + \ 'xxxstart2', 'asdfasd<yy', 'xxstart3']) + call cursor(1, 1) + call search('\(<\_[xy]\+\)\@3<=start') + call assert_equal([0, 7, 3, 0], getpos('.')) + bwipe! +endfunc + +" Test for the \%V atom (match inside the visual area) +func Regex_Match_Visual_Area() + call append(0, ['Visual:', 'thexe the thexethe', 'andaxand andaxand', + \ 'oooxofor foroxooo', 'oooxofor foroxooo']) + call cursor(1, 1) + exe "normal jfxvfx:s/\\%Ve/E/g\<CR>" + exe "normal jV:s/\\%Va/A/g\<CR>" + exe "normal jfx\<C-V>fxj:s/\\%Vo/O/g\<CR>" + call assert_equal(['Visual:', 'thexE thE thExethe', 'AndAxAnd AndAxAnd', + \ 'oooxOfOr fOrOxooo', 'oooxOfOr fOrOxooo', ''], getline(1, '$')) + %d +endfunc + +" Check matching Visual area +func Test_matching_visual_area() + new + set regexpengine=1 + call Regex_Match_Visual_Area() + set regexpengine=2 + call Regex_Match_Visual_Area() + set regexpengine& + bwipe! +endfunc + +" Check matching marks +func Regex_Mark() + call append(0, ['', '', '', 'Marks:', 'asdfSasdfsadfEasdf', 'asdfSas', + \ 'dfsadfEasdf', '', '', '', '', '']) + call cursor(4, 1) + exe "normal jfSmsfEme:.-4,.+6s/.\\%>'s.*\\%<'e../here/\<CR>" + exe "normal jfSmsj0fEme:.-4,.+6s/.\\%>'s\\_.*\\%<'e../again/\<CR>" + call assert_equal(['', '', '', 'Marks:', 'asdfhereasdf', 'asdfagainasdf', + \ '', '', '', '', '', ''], getline(1, '$')) + %d +endfunc + +func Test_matching_marks() + new + set regexpengine=1 + call Regex_Mark() + set regexpengine=2 + call Regex_Mark() + bwipe! +endfunc + +" Check patterns matching cursor position. +func s:curpos_test() + new + call setline(1, ['ffooooo', 'boboooo', 'zoooooo', 'koooooo', 'moooooo', + \ "\t\t\tfoo", 'abababababababfoo', 'bababababababafoo', '********_', + \ ' xxxxxxxxxxxx xxxx xxxxxx xxxxxxx x xxxxxxxxx xx xxxxxx xxxxxx xxxxx xxxxxxx xx xxxx xxxxxxxx xxxx xxxxxxxxxxx xxx xxxxxxx xxxxxxxxx xx xxxxxx xx xxxxxxx xxxxxxxxxxxxxxxx xxxxxxxxx xxx xxxxxxxx xxxxxxxxx xxxx xxx xxxx xxx xxx xxxxx xxxxxxxxxxxx xxxx xxxxxxxxx xxxxxxxxxxx xx xxxxx xxx xxxxxxxx xxxxxx xxx xxx xxxxxxxxx xxxxxxx x xxxxxxxxx xx xxxxxx xxxxxxx xxxxxxxxxxxxxxxxxx xxxxxxx xxxxxxx xxx xxx xxxxxxxx xxxxxxx xxxx xxx xxxxxx xxxxx xxxxx xx xxxxxx xxxxxxx xxx xxxxxxxxxxxx xxxx xxxxxxxxx xxxxxx xxxxxx xxxxx xxx xxxxxxx xxxxxxxxxxxxxxxx xxxxxxxxx xxxxxxxxxx xxxx xx xxxxxxxx xxx xxxxxxxxxxx xxxxx']) + call setpos('.', [0, 1, 0, 0]) + s/\%>3c.//g + call setpos('.', [0, 2, 4, 0]) + s/\%#.*$//g + call setpos('.', [0, 3, 0, 0]) + s/\%<3c./_/g + %s/\%4l\%>5c./_/g + %s/\%6l\%>25v./_/g + %s/\%>6l\%3c./!/g + %s/\%>7l\%12c./?/g + %s/\%>7l\%<9l\%>5v\%<8v./#/g + $s/\%(|\u.*\)\@<=[^|\t]\+$//ge + call assert_equal(['ffo', 'bob', '__ooooo', 'koooo__', 'moooooo', + \ ' f__', 'ab!babababababfoo', + \ 'ba!ab##abab?bafoo', '**!*****_', + \ ' ! xxx?xxxxxxxx xxxx xxxxxx xxxxxxx x xxxxxxxxx xx xxxxxx xxxxxx xxxxx xxxxxxx xx xxxx xxxxxxxx xxxx xxxxxxxxxxx xxx xxxxxxx xxxxxxxxx xx xxxxxx xx xxxxxxx xxxxxxxxxxxxxxxx xxxxxxxxx xxx xxxxxxxx xxxxxxxxx xxxx xxx xxxx xxx xxx xxxxx xxxxxxxxxxxx xxxx xxxxxxxxx xxxxxxxxxxx xx xxxxx xxx xxxxxxxx xxxxxx xxx xxx xxxxxxxxx xxxxxxx x xxxxxxxxx xx xxxxxx xxxxxxx xxxxxxxxxxxxxxxxxx xxxxxxx xxxxxxx xxx xxx xxxxxxxx xxxxxxx xxxx xxx xxxxxx xxxxx xxxxx xx xxxxxx xxxxxxx xxx xxxxxxxxxxxx xxxx xxxxxxxxx xxxxxx xxxxxx xxxxx xxx xxxxxxx xxxxxxxxxxxxxxxx xxxxxxxxx xxxxxxxxxx xxxx xx xxxxxxxx xxx xxxxxxxxxxx xxxxx'], + \ getline(1, '$')) + bwipe! +endfunc + +func Test_matching_curpos() + set re=0 + call s:curpos_test() + set re=1 + call s:curpos_test() + set re=2 + call s:curpos_test() + set re& +endfunc + +" Test for matching the start and end of a buffer +func Regex_start_end_buffer() + call setline(1, repeat(['vim edit'], 20)) + /\%^ + call assert_equal([0, 1, 1, 0], getpos('.')) + exe "normal 50%/\\%^..\<CR>" + call assert_equal([0, 1, 1, 0], getpos('.')) + exe "normal 50%/\\%$\<CR>" + call assert_equal([0, 20, 8, 0], getpos('.')) + exe "normal 6gg/..\\%$\<CR>" + call assert_equal([0, 20, 7, 0], getpos('.')) + %d +endfunc + +func Test_start_end_of_buffer_match() + new + set regexpengine=1 + call Regex_start_end_buffer() + set regexpengine=2 + call Regex_start_end_buffer() + bwipe! +endfunc + +func Test_ze_before_zs() + call assert_equal('', matchstr(' ', '\%#=1\ze \zs')) + call assert_equal('', matchstr(' ', '\%#=2\ze \zs')) + call assert_equal(repeat([''], 10), matchlist(' ', '\%#=1\ze \zs')) + call assert_equal(repeat([''], 10), matchlist(' ', '\%#=2\ze \zs')) +endfunc + +" Check for detecting error +func Test_regexp_error() + call assert_fails("call matchlist('x x', '\\%#=1 \\zs*')", 'E888:') + call assert_fails("call matchlist('x x', '\\%#=1 \\ze*')", 'E888:') + call assert_fails("call matchlist('x x', '\\%#=2 \\zs*')", 'E888:') + call assert_fails("call matchlist('x x', '\\%#=2 \\ze*')", 'E888:') + call assert_fails('exe "normal /\\%#=1\\%[x\\%[x]]\<CR>"', 'E369:') + call assert_fails("call matchstr('abcd', '\\%o841\\%o142')", 'E678:') + call assert_equal('', matchstr('abcd', '\%o181\%o142')) +endfunc + +" Test for using the last substitute string pattern (~) +func Test_regexp_last_subst_string() + new + s/bar/baz/e + call assert_equal(matchstr("foo\nbaz\nbar", "\\%#=1\~"), "baz") + call assert_equal(matchstr("foo\nbaz\nbar", "\\%#=2\~"), "baz") + close! +endfunc + +" Check patterns matching cursor position. +func s:curpos_test2() + new + call setline(1, ['1', '2 foobar eins zwei drei vier fnf sechse', + \ '3 foobar eins zwei drei vier fnf sechse', + \ '4 foobar eins zwei drei vier fnf sechse', + \ '5 foobar eins zwei drei vier fnf sechse', + \ '6 foobar eins zwei drei vier fnf sechse', + \ '7 foobar eins zwei drei vier fnf sechse']) + call setpos('.', [0, 2, 10, 0]) + s/\%.c.*//g + call setpos('.', [0, 3, 15, 0]) + s/\%.l.*//g + call setpos('.', [0, 5, 3, 0]) + s/\%.v.*/_/g + call assert_equal(['1', + \ '2 foobar ', + \ '', + \ '4 foobar eins zwei drei vier fnf sechse', + \ '5 _', + \ '6 foobar eins zwei drei vier fnf sechse', + \ '7 foobar eins zwei drei vier fnf sechse'], + \ getline(1, '$')) + call assert_fails('call search("\\%.1l")', 'E1204:') + call assert_fails('call search("\\%.1c")', 'E1204:') + call assert_fails('call search("\\%.1v")', 'E1204:') + bwipe! +endfunc + +" Check patterns matching before or after cursor position. +func s:curpos_test3() + new + call setline(1, ['1', '2 foobar eins zwei drei vier fnf sechse', + \ '3 foobar eins zwei drei vier fnf sechse', + \ '4 foobar eins zwei drei vier fnf sechse', + \ '5 foobar eins zwei drei vier fnf sechse', + \ '6 foobar eins zwei drei vier fnf sechse', + \ '7 foobar eins zwei drei vier fnf sechse']) + call setpos('.', [0, 2, 10, 0]) + " Note: This removes all columns, except for the column directly in front of + " the cursor. Bug???? + :s/^.*\%<.c// + call setpos('.', [0, 3, 10, 0]) + :s/\%>.c.*$// + call setpos('.', [0, 5, 4, 0]) + " Note: This removes all columns, except for the column directly in front of + " the cursor. Bug???? + :s/^.*\%<.v/_/ + call setpos('.', [0, 6, 4, 0]) + :s/\%>.v.*$/_/ + call assert_equal(['1', + \ ' eins zwei drei vier fnf sechse', + \ '3 foobar e', + \ '4 foobar eins zwei drei vier fnf sechse', + \ '_foobar eins zwei drei vier fnf sechse', + \ '6 fo_', + \ '7 foobar eins zwei drei vier fnf sechse'], + \ getline(1, '$')) + sil %d + call setline(1, ['1', '2 foobar eins zwei drei vier fnf sechse', + \ '3 foobar eins zwei drei vier fnf sechse', + \ '4 foobar eins zwei drei vier fnf sechse', + \ '5 foobar eins zwei drei vier fnf sechse', + \ '6 foobar eins zwei drei vier fnf sechse', + \ '7 foobar eins zwei drei vier fnf sechse']) + call setpos('.', [0, 4, 4, 0]) + %s/\%<.l.*// + call setpos('.', [0, 5, 4, 0]) + %s/\%>.l.*// + call assert_equal(['', '', '', + \ '4 foobar eins zwei drei vier fnf sechse', + \ '5 foobar eins zwei drei vier fnf sechse', + \ '', ''], + \ getline(1, '$')) + bwipe! +endfunc + +" Test that matching below, at or after the +" cursor position work +func Test_matching_pos() + for val in range(3) + exe "set re=" .. val + " Match at cursor position + call s:curpos_test2() + " Match before or after cursor position + call s:curpos_test3() + endfor + set re& +endfunc + +func Test_using_mark_position() + " this was using freed memory + " new engine + new + norm O0 + call assert_fails("s/\\%')", 'E486:') + bwipe! + + " old engine + new + norm O0 + call assert_fails("s/\\%#=1\\%')", 'E486:') + bwipe! +endfunc + +func Test_using_visual_position() + " this was using freed memory + new + exe "norm 0o\<Esc>\<C-V>k\<C-X>o0" + /\%V + bwipe! +endfunc + +func Test_using_invalid_visual_position() + " this was going beyond the end of the line + new + exe "norm 0o000\<Esc>0\<C-V>$s0" + /\%V + bwipe! +endfunc + +func Test_using_two_engines_pattern() + new + call setline(1, ['foobar=0', 'foobar=1', 'foobar=2']) + " \%#= at the end of the pattern + for i in range(0, 2) + for j in range(0, 2) + exe "set re=" .. i + call cursor(j + 1, 7) + call assert_fails("%s/foobar\\%#=" .. j, 'E1281:') + endfor + endfor + set re=0 + + " \%#= at the start of the pattern + for i in range(0, 2) + call cursor(i + 1, 7) + exe ":%s/\\%#=" .. i .. "foobar=" .. i .. "/xx" + endfor + call assert_equal(['xx', 'xx', 'xx'], getline(1, '$')) + bwipe! +endfunc + +func Test_recursive_substitute_expr() + new + func Repl() + s + endfunc + silent! s/\%')/~\=Repl() + + bwipe! + delfunc Repl +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_regexp_utf8.vim b/test/old/testdir/test_regexp_utf8.vim new file mode 100644 index 0000000000..2253242a7c --- /dev/null +++ b/test/old/testdir/test_regexp_utf8.vim @@ -0,0 +1,603 @@ +" Tests for regexp in utf8 encoding + +func s:equivalence_test() + let str = "AÀÁÂÃÄÅĀĂĄǍǞǠǺȂȦȺḀẠẢẤẦẨẪẬẮẰẲẴẶ BƁɃḂḄḆ CÇĆĈĊČƇȻḈꞒ DĎĐƊḊḌḎḐḒ EÈÉÊËĒĔĖĘĚȄȆȨɆḔḖḘḚḜẸẺẼẾỀỂỄỆ FƑḞꞘ GĜĞĠĢƓǤǦǴḠꞠ HĤĦȞḢḤḦḨḪⱧ IÌÍÎÏĨĪĬĮİƗǏȈȊḬḮỈỊ JĴɈ KĶƘǨḰḲḴⱩꝀ LĹĻĽĿŁȽḶḸḺḼⱠ MḾṀṂ NÑŃŅŇǸṄṆṈṊꞤ OÒÓÔÕÖØŌŎŐƟƠǑǪǬǾȌȎȪȬȮȰṌṎṐṒỌỎỐỒỔỖỘỚỜỞỠỢ PƤṔṖⱣ QɊ RŔŖŘȐȒɌṘṚṜṞⱤꞦ SŚŜŞŠȘṠṢṤṦṨⱾꞨ TŢŤŦƬƮȚȾṪṬṮṰ UÙÚÛÜŨŪŬŮŰƯǕǙǛǓǗȔȖɄṲṴṶṸṺỤỦỨỪỬỮỰ VƲṼṾ WŴẀẂẄẆẈ XẊẌ YÝŶŸƳȲɎẎỲỴỶỸ ZŹŻŽƵẐẒẔⱫ aàáâãäåāăąǎǟǡǻȃȧᶏḁẚạảấầẩẫậắằẳẵặⱥ bƀɓᵬᶀḃḅḇ cçćĉċčƈȼḉꞓꞔ dďđɗᵭᶁᶑḋḍḏḑḓ eèéêëēĕėęěȅȇȩɇᶒḕḗḙḛḝẹẻẽếềểễệ fƒᵮᶂḟꞙ gĝğġģǥǧǵɠᶃḡꞡ hĥħȟḣḥḧḩḫẖⱨꞕ iìíîïĩīĭįǐȉȋɨᶖḭḯỉị jĵǰɉ kķƙǩᶄḱḳḵⱪꝁ lĺļľŀłƚḷḹḻḽⱡ mᵯḿṁṃ nñńņňʼnǹᵰᶇṅṇṉṋꞥ oòóôõöøōŏőơǒǫǭǿȍȏȫȭȯȱɵṍṏṑṓọỏốồổỗộớờởỡợ pƥᵱᵽᶈṕṗ qɋʠ rŕŗřȑȓɍɽᵲᵳᶉṛṝṟꞧ sśŝşšșȿᵴᶊṡṣṥṧṩꞩ tţťŧƫƭțʈᵵṫṭṯṱẗⱦ uùúûüũūŭůűųǚǖưǔǘǜȕȗʉᵾᶙṳṵṷṹṻụủứừửữự vʋᶌṽṿ wŵẁẃẅẇẉẘ xẋẍ yýÿŷƴȳɏẏẙỳỵỷỹ zźżžƶᵶᶎẑẓẕⱬ" + let groups = split(str) + for group1 in groups + for c in split(group1, '\zs') + " next statement confirms that equivalence class matches every + " character in group + call assert_match('^[[=' .. c .. '=]]*$', group1) + for group2 in groups + if group2 != group1 + " next statement converts that equivalence class doesn't match + " character in any other group + call assert_equal(-1, match(group2, '[[=' .. c .. '=]]'), c) + endif + endfor + endfor + endfor +endfunc + +func Test_equivalence_re1() + set re=1 + call s:equivalence_test() + set re=0 +endfunc + +func Test_equivalence_re2() + set re=2 + call s:equivalence_test() + set re=0 +endfunc + +func s:classes_test() + if has('win32') + set iskeyword=@,48-57,_,192-255 + endif + set isprint=@,161-255 + call assert_equal('Motörhead', matchstr('Motörhead', '[[:print:]]\+')) + + let alnumchars = '' + let alphachars = '' + let backspacechar = '' + let blankchars = '' + let cntrlchars = '' + let digitchars = '' + let escapechar = '' + let graphchars = '' + let lowerchars = '' + let printchars = '' + let punctchars = '' + let returnchar = '' + let spacechars = '' + let tabchar = '' + let upperchars = '' + let xdigitchars = '' + let identchars = '' + let identchars1 = '' + let kwordchars = '' + let kwordchars1 = '' + let fnamechars = '' + let fnamechars1 = '' + let i = 1 + while i <= 255 + let c = nr2char(i) + if c =~ '[[:alpha:]]' + let alphachars .= c + endif + if c =~ '[[:alnum:]]' + let alnumchars .= c + endif + if c =~ '[[:backspace:]]' + let backspacechar .= c + endif + if c =~ '[[:blank:]]' + let blankchars .= c + endif + if c =~ '[[:cntrl:]]' + let cntrlchars .= c + endif + if c =~ '[[:digit:]]' + let digitchars .= c + endif + if c =~ '[[:escape:]]' + let escapechar .= c + endif + if c =~ '[[:graph:]]' + let graphchars .= c + endif + if c =~ '[[:lower:]]' + let lowerchars .= c + endif + if c =~ '[[:print:]]' + let printchars .= c + endif + if c =~ '[[:punct:]]' + let punctchars .= c + endif + if c =~ '[[:return:]]' + let returnchar .= c + endif + if c =~ '[[:space:]]' + let spacechars .= c + endif + if c =~ '[[:tab:]]' + let tabchar .= c + endif + if c =~ '[[:upper:]]' + let upperchars .= c + endif + if c =~ '[[:xdigit:]]' + let xdigitchars .= c + endif + if c =~ '[[:ident:]]' + let identchars .= c + endif + if c =~ '\i' + let identchars1 .= c + endif + if c =~ '[[:keyword:]]' + let kwordchars .= c + endif + if c =~ '\k' + let kwordchars1 .= c + endif + if c =~ '[[:fname:]]' + let fnamechars .= c + endif + if c =~ '\f' + let fnamechars1 .= c + endif + let i += 1 + endwhile + + call assert_equal('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', alphachars) + call assert_equal('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', alnumchars) + call assert_equal("\b", backspacechar) + call assert_equal("\t ", blankchars) + call assert_equal("\x01\x02\x03\x04\x05\x06\x07\b\t\n\x0b\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\e\x1c\x1d\x1e\x1f\x7f", cntrlchars) + call assert_equal("0123456789", digitchars) + call assert_equal("\<Esc>", escapechar) + call assert_equal('!"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~', graphchars) + call assert_equal('abcdefghijklmnopqrstuvwxyzµßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ', lowerchars) + call assert_equal(' !"#$%&''()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ', printchars) + call assert_equal('!"#$%&''()*+,-./:;<=>?@[\]^_`{|}~', punctchars) + call assert_equal('ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ', upperchars) + call assert_equal("\r", returnchar) + call assert_equal("\t\n\x0b\f\r ", spacechars) + call assert_equal("\t", tabchar) + call assert_equal('0123456789ABCDEFabcdef', xdigitchars) + + if has('win32') + let identchars_ok = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz
¡¢£¤¥¦§µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ' + let kwordchars_ok = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyzµÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ' + else + let identchars_ok = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyzµÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ' + let kwordchars_ok = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyzµÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ' + endif + + if has('win32') + let fnamechars_ok = '!#$%+,-./0123456789:=@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]_abcdefghijklmnopqrstuvwxyz{}~ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ' + elseif has('amiga') + let fnamechars_ok = '$+,-./0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ' + elseif has('vms') + let fnamechars_ok = '#$%+,-./0123456789:;<>ABCDEFGHIJKLMNOPQRSTUVWXYZ[]_abcdefghijklmnopqrstuvwxyz~ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ' + else + let fnamechars_ok = '#$%+,-./0123456789=ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ' + endif + + call assert_equal(identchars_ok, identchars) + call assert_equal(kwordchars_ok, kwordchars) + call assert_equal(fnamechars_ok, fnamechars) + + call assert_equal(identchars1, identchars) + call assert_equal(kwordchars1, kwordchars) + call assert_equal(fnamechars1, fnamechars) +endfunc + +func Test_classes_re1() + set re=1 + call s:classes_test() + set re=0 +endfunc + +func Test_classes_re2() + set re=2 + call s:classes_test() + set re=0 +endfunc + +func Test_recursive_substitute() + new + s/^/\=execute("s#^##gn") + " check we are now not in the sandbox + call setwinvar(1, 'myvar', 1) + bwipe! +endfunc + +func Test_nested_backrefs() + " Check example in change.txt. + new + for re in range(0, 2) + exe 'set re=' . re + call setline(1, 'aa ab x') + 1s/\(\(a[a-d] \)*\)\(x\)/-\1- -\2- -\3-/ + call assert_equal('-aa ab - -ab - -x-', getline(1)) + + call assert_equal('-aa ab - -ab - -x-', substitute('aa ab x', '\(\(a[a-d] \)*\)\(x\)', '-\1- -\2- -\3-', '')) + endfor + bwipe! + set re=0 +endfunc + +func Test_eow_with_optional() + let expected = ['abc def', 'abc', 'def', '', '', '', '', '', '', ''] + for re in range(0, 2) + exe 'set re=' . re + let actual = matchlist('abc def', '\(abc\>\)\?\s*\(def\)') + call assert_equal(expected, actual) + endfor +endfunc + +func Test_reversed_range() + for re in range(0, 2) + exe 'set re=' . re + call assert_fails('call match("abc def", "[c-a]")', 'E944:', re) + endfor + set re=0 +endfunc + +func Test_large_class() + set re=1 + call assert_fails('call match("abc def", "[\u3000-\u4000]")', 'E945:') + set re=2 + call assert_equal(0, 'abc def' =~# '[\u3000-\u4000]') + call assert_equal(1, "\u3042" =~# '[\u3000-\u4000]') + set re=0 +endfunc + +func Test_optmatch_toolong() + set re=1 + " Can only handle about 8000 characters. + let pat = '\\%[' .. repeat('x', 9000) .. ']' + call assert_fails('call match("abc def", "' .. pat .. '")', 'E339:') + set re=0 +endfunc + +" Test for regexp patterns with multi-byte support, using utf-8. +func Test_multibyte_chars() + " tl is a List of Lists with: + " 2: test auto/old/new 0: test auto/old 1: test auto/new + " regexp pattern + " text to test the pattern on + " expected match (optional) + " expected submatch 1 (optional) + " expected submatch 2 (optional) + " etc. + " When there is no match use only the first two items. + let tl = [] + + " Multi-byte character tests. + call add(tl, [2, '[[:alpha:][=a=]]\+', '879 aiaãâaiuvna ', 'aiaãâaiuvna']) + call add(tl, [2, '[[=a=]]\+', 'ddaãâbcd', 'aãâ']) " equivalence classes + call add(tl, [2, '[^ม ]\+', 'มม oijasoifjos ifjoisj f osij j มมมมม abcd', 'oijasoifjos']) + call add(tl, [2, ' [^ ]\+', 'start มabcdม ', ' มabcdม']) + call add(tl, [2, '[ม[:alpha:][=a=]]\+', '879 aiaãมâมaiuvna ', 'aiaãมâมaiuvna']) + + " this is not a normal "i" but 0xec + call add(tl, [2, '\p\+', 'ìa', 'ìa']) + call add(tl, [2, '\p*', 'aあ', 'aあ']) + + " Test recognition of some character classes + call add(tl, [2, '\i\+', '&*¨xx ', 'xx']) + call add(tl, [2, '\f\+', '&*fname ', 'fname']) + + " Test composing character matching + call add(tl, [2, '.ม', 'xม่x yมy', 'yม']) + call add(tl, [2, '.ม่', 'xม่x yมy', 'xม่']) + call add(tl, [2, "\u05b9", " x\u05b9 ", "x\u05b9"]) + call add(tl, [2, ".\u05b9", " x\u05b9 ", "x\u05b9"]) + call add(tl, [2, "\u05b9\u05bb", " x\u05b9\u05bb ", "x\u05b9\u05bb"]) + call add(tl, [2, ".\u05b9\u05bb", " x\u05b9\u05bb ", "x\u05b9\u05bb"]) + call add(tl, [2, "\u05bb\u05b9", " x\u05b9\u05bb ", "x\u05b9\u05bb"]) + call add(tl, [2, ".\u05bb\u05b9", " x\u05b9\u05bb ", "x\u05b9\u05bb"]) + call add(tl, [2, "\u05b9", " y\u05bb x\u05b9 ", "x\u05b9"]) + call add(tl, [2, ".\u05b9", " y\u05bb x\u05b9 ", "x\u05b9"]) + call add(tl, [2, "\u05b9", " y\u05bb\u05b9 x\u05b9 ", "y\u05bb\u05b9"]) + call add(tl, [2, ".\u05b9", " y\u05bb\u05b9 x\u05b9 ", "y\u05bb\u05b9"]) + call add(tl, [1, "\u05b9\u05bb", " y\u05b9 x\u05b9\u05bb ", "x\u05b9\u05bb"]) + call add(tl, [2, ".\u05b9\u05bb", " y\u05bb x\u05b9\u05bb ", "x\u05b9\u05bb"]) + call add(tl, [2, "a", "ca\u0300t"]) + call add(tl, [2, "ca", "ca\u0300t"]) + call add(tl, [2, "a\u0300", "ca\u0300t", "a\u0300"]) + call add(tl, [2, 'a\%C', "ca\u0300t", "a\u0300"]) + call add(tl, [2, 'ca\%C', "ca\u0300t", "ca\u0300"]) + call add(tl, [2, 'ca\%Ct', "ca\u0300t", "ca\u0300t"]) + + " Test \Z + call add(tl, [2, 'ú\Z', 'x']) + call add(tl, [2, 'יהוה\Z', 'יהוה', 'יהוה']) + call add(tl, [2, 'יְהוָה\Z', 'יהוה', 'יהוה']) + call add(tl, [2, 'יהוה\Z', 'יְהוָה', 'יְהוָה']) + call add(tl, [2, 'יְהוָה\Z', 'יְהוָה', 'יְהוָה']) + call add(tl, [2, 'יְ\Z', 'וְיַ', 'יַ']) + call add(tl, [2, "ק\u200d\u05b9x\\Z", "xק\u200d\u05b9xy", "ק\u200d\u05b9x"]) + call add(tl, [2, "ק\u200d\u05b9x\\Z", "xק\u200dxy", "ק\u200dx"]) + call add(tl, [2, "ק\u200dx\\Z", "xק\u200d\u05b9xy", "ק\u200d\u05b9x"]) + call add(tl, [2, "ק\u200dx\\Z", "xק\u200dxy", "ק\u200dx"]) + call add(tl, [2, "\u05b9\\Z", "xyz"]) + call add(tl, [2, "\\Z\u05b9", "xyz"]) + call add(tl, [2, "\u05b9\\Z", "xy\u05b9z", "y\u05b9"]) + call add(tl, [2, "\\Z\u05b9", "xy\u05b9z", "y\u05b9"]) + call add(tl, [1, "\u05b9\\+\\Z", "xy\u05b9z\u05b9 ", "y\u05b9z\u05b9"]) + call add(tl, [1, "\\Z\u05b9\\+", "xy\u05b9z\u05b9 ", "y\u05b9z\u05b9"]) + + " Combining different tests and features + call add(tl, [2, '[^[=a=]]\+', 'ddaãâbcd', 'dd']) + + " Run the tests + for t in tl + let re = t[0] + let pat = t[1] + let text = t[2] + let matchidx = 3 + for engine in [0, 1, 2] + if engine == 2 && re == 0 || engine == 1 && re == 1 + continue + endif + let ®expengine = engine + try + let l = matchlist(text, pat) + catch + call assert_report('Error ' . engine . ': pat: \"' . pat . + \ '\", text: \"' . text . + \ '\", caused an exception: \"' . v:exception . '\"') + endtry + " check the match itself + if len(l) == 0 && len(t) > matchidx + call assert_report('Error ' . engine . ': pat: \"' . pat . + \ '\", text: \"' . text . + \ '\", did not match, expected: \"' . t[matchidx] . '\"') + elseif len(l) > 0 && len(t) == matchidx + call assert_report('Error ' . engine . ': pat: \"' . pat . + \ '\", text: \"' . text . '\", match: \"' . l[0] . + \ '\", expected no match') + elseif len(t) > matchidx && l[0] != t[matchidx] + call assert_report('Error ' . engine . ': pat: \"' . pat . + \ '\", text: \"' . text . '\", match: \"' . l[0] . + \ '\", expected: \"' . t[matchidx] . '\"') + else + " Test passed + endif + if len(l) > 0 + " check all the nine submatches + for i in range(1, 9) + if len(t) <= matchidx + i + let e = '' + else + let e = t[matchidx + i] + endif + if l[i] != e + call assert_report('Error ' . engine . ': pat: \"' . pat . + \ '\", text: \"' . text . '\", submatch ' . i . + \ ': \"' . l[i] . '\", expected: \"' . e . '\"') + endif + endfor + unlet i + endif + endfor + endfor + set regexpengine& +endfunc + +" check that 'ambiwidth' does not change the meaning of \p +func Test_ambiwidth() + set regexpengine=1 ambiwidth=single + call assert_equal(0, match("\u00EC", '\p')) + set regexpengine=1 ambiwidth=double + call assert_equal(0, match("\u00EC", '\p')) + set regexpengine=2 ambiwidth=single + call assert_equal(0, match("\u00EC", '\p')) + set regexpengine=2 ambiwidth=double + call assert_equal(0, match("\u00EC", '\p')) + set regexpengine& ambiwidth& +endfunc + +func Run_regexp_ignore_case() + call assert_equal('iIİ', substitute('iIİ', '\([iIİ]\)', '\1', 'g')) + + call assert_equal('iIx', substitute('iIİ', '\c\([İ]\)', 'x', 'g')) + call assert_equal('xxİ', substitute('iIİ', '\(i\c\)', 'x', 'g')) + call assert_equal('iIx', substitute('iIİ', '\(İ\c\)', 'x', 'g')) + call assert_equal('iIx', substitute('iIİ', '\c\(\%u0130\)', 'x', 'g')) + call assert_equal('iIx', substitute('iIİ', '\c\([\u0130]\)', 'x', 'g')) + call assert_equal('iIx', substitute('iIİ', '\c\([\u012f-\u0131]\)', 'x', 'g')) +endfunc + +func Test_regexp_ignore_case() + set regexpengine=1 + call Run_regexp_ignore_case() + set regexpengine=2 + call Run_regexp_ignore_case() + set regexpengine& +endfunc + +" Tests for regexp with multi-byte encoding and various magic settings +func Run_regexp_multibyte_magic() + let text =<< trim END + 1 a aa abb abbccc + 2 d dd dee deefff + 3 g gg ghh ghhiii + 4 j jj jkk jkklll + 5 m mm mnn mnnooo + 6 x ^aa$ x + 7 (a)(b) abbaa + 8 axx [ab]xx + 9 หม่x อมx + a อมx หม่x + b ちカヨは + c x ¬€x + d 天使x + e y + f z + g a啷bb + j 0123❤x + k combinations + l äö üᾱ̆́ + END + + new + call setline(1, text) + exe 'normal /a*b\{2}c\+/e' .. "\<CR>x" + call assert_equal('1 a aa abb abbcc', getline('.')) + exe 'normal /\Md\*e\{2}f\+/e' .. "\<CR>x" + call assert_equal('2 d dd dee deeff', getline('.')) + set nomagic + exe 'normal /g\*h\{2}i\+/e' .. "\<CR>x" + call assert_equal('3 g gg ghh ghhii', getline('.')) + exe 'normal /\mj*k\{2}l\+/e' .. "\<CR>x" + call assert_equal('4 j jj jkk jkkll', getline('.')) + exe 'normal /\vm*n{2}o+/e' .. "\<CR>x" + call assert_equal('5 m mm mnn mnnoo', getline('.')) + exe 'normal /\V^aa$/' .. "\<CR>x" + call assert_equal('6 x aa$ x', getline('.')) + set magic + exe 'normal /\v(a)(b)\2\1\1/e' .. "\<CR>x" + call assert_equal('7 (a)(b) abba', getline('.')) + exe 'normal /\V[ab]\(\[xy]\)\1' .. "\<CR>x" + call assert_equal('8 axx ab]xx', getline('.')) + + " search for multi-byte without composing char + exe 'normal /ม' .. "\<CR>x" + call assert_equal('9 หม่x อx', getline('.')) + + " search for multi-byte with composing char + exe 'normal /ม่' .. "\<CR>x" + call assert_equal('a อมx หx', getline('.')) + + " find word by change of word class + exe 'normal /ち\<カヨ\>は' .. "\<CR>x" + call assert_equal('b カヨは', getline('.')) + + " Test \%u, [\u] and friends + " c + exe 'normal /\%u20ac' .. "\<CR>x" + call assert_equal('c x ¬x', getline('.')) + " d + exe 'normal /[\u4f7f\u5929]\+' .. "\<CR>x" + call assert_equal('d 使x', getline('.')) + " e + exe 'normal /\%U12345678' .. "\<CR>x" + call assert_equal('e y', getline('.')) + " f + exe 'normal /[\U1234abcd\u1234\uabcd]' .. "\<CR>x" + call assert_equal('f z', getline('.')) + " g + exe 'normal /\%d21879b' .. "\<CR>x" + call assert_equal('g abb', getline('.')) + + " j Test backwards search from a multi-byte char + exe "normal /x\<CR>x?.\<CR>x" + call assert_equal('j 012❤', getline('.')) + " k + let @w=':%s#comb[i]nations#œ̄ṣ́m̥̄ᾱ̆́#g' + @w + call assert_equal('k œ̄ṣ́m̥̄ᾱ̆́', getline(18)) + + close! +endfunc + +func Test_regexp_multibyte_magic() + set regexpengine=1 + call Run_regexp_multibyte_magic() + set regexpengine=2 + call Run_regexp_multibyte_magic() + set regexpengine& +endfunc + +" Test for 7.3.192 +" command ":s/ \?/ /g" splits multi-byte characters into bytes +func Test_split_multibyte_to_bytes() + new + call setline(1, 'l äö üᾱ̆́') + s/ \?/ /g + call assert_equal(' l ä ö ü ᾱ̆́', getline(1)) + close! +endfunc + +" Test for matchstr() with multibyte characters +func Test_matchstr_multibyte() + new + call assert_equal('ב', matchstr("אבגד", ".", 0, 2)) + call assert_equal('בג', matchstr("אבגד", "..", 0, 2)) + call assert_equal('א', matchstr("אבגד", ".", 0, 0)) + call assert_equal('ג', matchstr("אבגד", ".", 4, -1)) + close! +endfunc + +" Test for 7.4.636 +" A search with end offset gets stuck at end of file. +func Test_search_with_end_offset() + new + call setline(1, ['', 'dog(a', 'cat(']) + exe "normal /(/e+\<CR>" + normal n"ayn + call assert_equal("a\ncat(", @a) + close! +endfunc + +" Check that "^" matches even when the line starts with a combining char +func Test_match_start_of_line_combining() + new + call setline(1, ['', "\u05ae", '']) + exe "normal gg/^\<CR>" + call assert_equal(2, getcurpos()[1]) + bwipe! +endfunc + +" Check that [[:upper:]] matches for automatic engine +func Test_match_char_class_upper() + new + + " Test 1: [[:upper:]]\{2,\} + set regexpengine=0 + call setline(1, ['05. ПЕСНЯ О ГЕРОЯХ муз. А. Давиденко, М. Коваля и Б. Шехтера ...', '05. PJESNJA O GJEROJAKH mus. A. Davidjenko, M. Kovalja i B. Shjekhtjera ...']) + call cursor(1,1) + let search_cmd='norm /\<[[:upper:]]\{2,\}\>' .. "\<CR>" + exe search_cmd + call assert_equal(4, searchcount().total, 'TEST 1') + set regexpengine=1 + exe search_cmd + call assert_equal(2, searchcount().total, 'TEST 1') + set regexpengine=2 + exe search_cmd + call assert_equal(4, searchcount().total, 'TEST 1') + + " Test 2: [[:upper:]].\+ + let search_cmd='norm /\<[[:upper:]].\+\>' .. "\<CR>" + set regexpengine=0 + exe search_cmd + call assert_equal(2, searchcount().total, 'TEST 2') + set regexpengine=1 + exe search_cmd + call assert_equal(1, searchcount().total, 'TEST 2') + set regexpengine=2 + exe search_cmd + call assert_equal(2, searchcount().total, 'TEST 2') + + " Test 3: [[:lower:]]\+ + let search_cmd='norm /\<[[:lower:]]\+\>' .. "\<CR>" + set regexpengine=0 + exe search_cmd + call assert_equal(4, searchcount().total, 'TEST 3 lower') + set regexpengine=1 + exe search_cmd + call assert_equal(2, searchcount().total, 'TEST 3 lower') + set regexpengine=2 + exe search_cmd + call assert_equal(4, searchcount().total, 'TEST 3 lower') + + " clean up + set regexpengine=0 + bwipe! +endfunc + +func Test_match_invalid_byte() + call writefile(0z630a.765d30aa0a.2e0a.790a.4030, 'Xinvalid') + new + source Xinvalid + bwipe! + call delete('Xinvalid') +endfunc + +func Test_match_too_complicated() + set regexpengine=1 + exe "noswapfile vsplit \xeb\xdb\x99" + silent! buf \&\zs*\zs*0 + bwipe! + set regexpengine=0 +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_registers.vim b/test/old/testdir/test_registers.vim new file mode 100644 index 0000000000..01f9507916 --- /dev/null +++ b/test/old/testdir/test_registers.vim @@ -0,0 +1,825 @@ +" Tests for register operations + +source check.vim +source view_util.vim + +" This test must be executed first to check for empty and unset registers. +func Test_aaa_empty_reg_test() + call assert_fails('normal @@', 'E748:') + call assert_fails('normal @%', 'E354:') + call assert_fails('normal @#', 'E354:') + call assert_fails('normal @!', 'E354:') + call assert_fails('normal @:', 'E30:') + call assert_fails('normal @.', 'E29:') + call assert_fails('put /', 'E35:') + call assert_fails('put .', 'E29:') +endfunc + +func Test_yank_shows_register() + enew + set report=0 + call setline(1, ['foo', 'bar']) + " Line-wise + exe 'norm! yy' + call assert_equal('1 line yanked', v:statusmsg) + exe 'norm! "zyy' + call assert_equal('1 line yanked into "z', v:statusmsg) + exe 'norm! yj' + call assert_equal('2 lines yanked', v:statusmsg) + exe 'norm! "zyj' + call assert_equal('2 lines yanked into "z', v:statusmsg) + + " Block-wise + exe "norm! \<C-V>y" + call assert_equal('block of 1 line yanked', v:statusmsg) + exe "norm! \<C-V>\"zy" + call assert_equal('block of 1 line yanked into "z', v:statusmsg) + exe "norm! \<C-V>jy" + call assert_equal('block of 2 lines yanked', v:statusmsg) + exe "norm! \<C-V>j\"zy" + call assert_equal('block of 2 lines yanked into "z', v:statusmsg) + + bwipe! +endfunc + +func Test_display_registers() + " Disable clipboard + let save_clipboard = get(g:, 'clipboard', {}) + let g:clipboard = {} + + e file1 + e file2 + call setline(1, ['foo', 'bar']) + /bar + exe 'norm! y2l"axx' + call feedkeys("i\<C-R>=2*4\n\<esc>") + call feedkeys(":ls\n", 'xt') + + " these commands work in the sandbox + let a = execute('sandbox display') + let b = execute('sandbox registers') + + call assert_equal(a, b) + call assert_match('^\nType Name Content\n' + \ . ' c "" a\n' + \ . ' c "0 ba\n' + \ . ' c "a b\n' + \ . '.*' + \ . ' c "- a\n' + \ . '.*' + \ . ' c ": ls\n' + \ . ' c "% file2\n' + \ . ' c "# file1\n' + \ . ' c "/ bar\n' + \ . ' c "= 2\*4', a) + + let a = execute('registers a') + call assert_match('^\nType Name Content\n' + \ . ' c "a b', a) + + let a = execute('registers :') + call assert_match('^\nType Name Content\n' + \ . ' c ": ls', a) + + bwipe! + let g:clipboard = save_clipboard +endfunc + +func Test_register_one() + " delete a line goes into register one + new + call setline(1, "one") + normal dd + call assert_equal("one\n", @1) + + " delete a word does not change register one, does change "- + call setline(1, "two") + normal de + call assert_equal("one\n", @1) + call assert_equal("two", @-) + + " delete a word with a register does not change register one + call setline(1, "three") + normal "ade + call assert_equal("three", @a) + call assert_equal("one\n", @1) + + " delete a word with register DOES change register one with one of a list of + " operators + " % + call setline(1, ["(12)3"]) + normal "ad% + call assert_equal("(12)", @a) + call assert_equal("(12)", @1) + + " ( + call setline(1, ["first second"]) + normal $"ad( + call assert_equal("first secon", @a) + call assert_equal("first secon", @1) + + " ) + call setline(1, ["First Second."]) + normal gg0"ad) + call assert_equal("First Second.", @a) + call assert_equal("First Second.", @1) + + " ` + call setline(1, ["start here."]) + normal gg0fhmx0"ad`x + call assert_equal("start ", @a) + call assert_equal("start ", @1) + + " / + call setline(1, ["searchX"]) + exe "normal gg0\"ad/X\<CR>" + call assert_equal("search", @a) + call assert_equal("search", @1) + + " ? + call setline(1, ["Ysearch"]) + exe "normal gg$\"ad?Y\<CR>" + call assert_equal("Ysearc", @a) + call assert_equal("Ysearc", @1) + + " n + call setline(1, ["Ynext"]) + normal gg$"adn + call assert_equal("Ynex", @a) + call assert_equal("Ynex", @1) + + " N + call setline(1, ["prevY"]) + normal gg0"adN + call assert_equal("prev", @a) + call assert_equal("prev", @1) + + " } + call setline(1, ["one", ""]) + normal gg0"ad} + call assert_equal("one\n", @a) + call assert_equal("one\n", @1) + + " { + call setline(1, ["", "two"]) + normal 2G$"ad{ + call assert_equal("\ntw", @a) + call assert_equal("\ntw", @1) + + bwipe! +endfunc + +func Test_recording_status_in_ex_line() + norm qx + redraw! + call assert_equal('recording @x', Screenline(&lines)) + set shortmess=q + redraw! + call assert_equal('recording', Screenline(&lines)) + set shortmess& + norm q + redraw! + call assert_equal('', Screenline(&lines)) +endfunc + +" Check that replaying a typed sequence does not use an Esc and following +" characters as an escape sequence. +func Test_recording_esc_sequence() + new + try + let save_F2 = &t_F2 + catch + endtry + let t_F2 = "\<Esc>OQ" + call feedkeys("qqiTest\<Esc>", "xt") + call feedkeys("OQuirk\<Esc>q", "xt") + call feedkeys("Go\<Esc>@q", "xt") + call assert_equal(['Quirk', 'Test', 'Quirk', 'Test'], getline(1, 4)) + bwipe! + if exists('save_F2') + let &t_F2 = save_F2 + else + set t_F2= + endif +endfunc + +func Test_recording_with_select_mode() + new + call feedkeys("qacc12345\<Esc>gH98765\<Esc>q", "tx") + call assert_equal("98765", getline(1)) + call assert_equal("cc12345\<Esc>gH98765\<Esc>", @a) + call setline(1, 'asdf') + normal! @a + call assert_equal("98765", getline(1)) + bwipe! +endfunc + +" Test for executing the last used register (@) +func Test_last_used_exec_reg() + " Test for the @: command + let a = '' + call feedkeys(":let a ..= 'Vim'\<CR>", 'xt') + normal @: + call assert_equal('VimVim', a) + + " Test for the @= command + let x = '' + let a = ":let x ..= 'Vim'\<CR>" + exe "normal @=a\<CR>" + normal @@ + call assert_equal('VimVim', x) + + " Test for the @. command + let a = '' + call feedkeys("i:let a ..= 'Edit'\<CR>", 'xt') + normal @. + normal @@ + call assert_equal('EditEdit', a) + + " Test for repeating the last command-line in visual mode + call append(0, 'register') + normal gg + let @r = '' + call feedkeys("v:yank R\<CR>", 'xt') + call feedkeys("v@:", 'xt') + call assert_equal("\nregister\nregister\n", @r) + + enew! +endfunc + +func Test_get_register() + enew + edit Xfile1 + edit Xfile2 + call assert_equal('Xfile2', getreg('%')) + call assert_equal('Xfile1', getreg('#')) + + call feedkeys("iTwo\<Esc>", 'xt') + call assert_equal('Two', getreg('.')) + call assert_equal('', getreg('_')) + call assert_beeps('normal ":yy') + call assert_beeps('normal "%yy') + call assert_beeps('normal ".yy') + + call assert_equal('', getreg("\<C-F>")) + call assert_equal('', getreg("\<C-W>")) + call assert_equal('', getreg("\<C-L>")) + " Change the last used register to '"' for the next test + normal! ""yy + let @" = 'happy' + call assert_equal('happy', getreg()) + call assert_equal('happy', getreg('')) + + call assert_equal('', getregtype('!')) + call assert_fails('echo getregtype([])', 'E730:') + call assert_equal('v', getregtype()) + call assert_equal('v', getregtype('')) + + " Test for inserting an invalid register content + call assert_beeps('exe "normal i\<C-R>!"') + + " Test for inserting a register with multiple lines + call deletebufline('', 1, '$') + call setreg('r', ['a', 'b']) + exe "normal i\<C-R>r" + call assert_equal(['a', 'b', ''], getline(1, '$')) + + " Test for inserting a multi-line register in the command line + call feedkeys(":\<C-R>r\<Esc>", 'xt') + " Nvim: no trailing CR because of #6137 + " call assert_equal("a\rb\r", histget(':', -1)) + call assert_equal("a\rb", histget(':', -1)) + + call assert_fails('let r = getreg("=", [])', 'E745:') + call assert_fails('let r = getreg("=", 1, [])', 'E745:') + enew! + + " Using a register in operator-pending mode should fail + call assert_beeps('norm! c"') +endfunc + +func Test_set_register() + call assert_fails("call setreg('#', 200)", 'E86:') + " call assert_fails("call setreg('a', test_unknown())", 'E908:') + + edit Xfile_alt_1 + let b1 = bufnr('') + edit Xfile_alt_2 + let b2 = bufnr('') + edit Xfile_alt_3 + let b3 = bufnr('') + call setreg('#', 'alt_1') + call assert_equal('Xfile_alt_1', getreg('#')) + call setreg('#', b2) + call assert_equal('Xfile_alt_2', getreg('#')) + + let ab = 'regwrite' + call setreg('=', '') + call setreg('=', 'a', 'a') + call setreg('=', 'b', 'a') + call assert_equal('regwrite', getreg('=')) + + " Test for setting a list of lines to special registers + call setreg('/', []) + call assert_equal('', @/) + call setreg('=', []) + call assert_equal('', @=) + call assert_fails("call setreg('/', ['a', 'b'])", 'E883:') + call assert_fails("call setreg('=', ['a', 'b'])", 'E883:') + call assert_equal(0, setreg('_', ['a', 'b'])) + + " Test for recording to a invalid register + call assert_beeps('normal q$') + + " Appending to a register when recording + call append(0, "text for clipboard test") + normal gg + call feedkeys('qrllq', 'xt') + call feedkeys('qRhhq', 'xt') + call assert_equal('llhh', getreg('r')) + + " Appending a list of characters to a register from different lines + let @r = '' + call append(0, ['abcdef', '123456']) + normal gg"ry3l + call cursor(2, 4) + normal "Ry3l + call assert_equal('abc456', @r) + + " Test for gP with multiple lines selected using characterwise motion + %delete + call append(0, ['vim editor', 'vim editor']) + let @r = '' + exe "normal ggwy/vim /e\<CR>gP" + call assert_equal(['vim editor', 'vim editor', 'vim editor'], getline(1, 3)) + + " Test for gP with . register + %delete + normal iabc + normal ".gp + call assert_equal('abcabc', getline(1)) + normal 0".gP + call assert_equal('abcabcabc', getline(1)) + + let @"='' + call setreg('', '1') + call assert_equal('1', @") + call setreg('@', '2') + call assert_equal('2', @") + + enew! +endfunc + +" Test for clipboard registers (* and +) +func Test_clipboard_regs() + throw 'skipped: needs clipboard=autoselect,autoselectplus' + + CheckNotGui + CheckFeature clipboard_working + + new + call append(0, "text for clipboard test") + normal gg"*yiw + call assert_equal('text', getreg('*')) + normal gg2w"+yiw + call assert_equal('clipboard', getreg('+')) + + " Test for replacing the clipboard register contents + set clipboard=unnamed + let @* = 'food' + normal ggviw"*p + call assert_equal('text', getreg('*')) + call assert_equal('food for clipboard test', getline(1)) + normal ggviw"*p + call assert_equal('food', getreg('*')) + call assert_equal('text for clipboard test', getline(1)) + + " Test for replacing the selection register contents + set clipboard=unnamedplus + let @+ = 'food' + normal ggviw"+p + call assert_equal('text', getreg('+')) + call assert_equal('food for clipboard test', getline(1)) + normal ggviw"+p + call assert_equal('food', getreg('+')) + call assert_equal('text for clipboard test', getline(1)) + + " Test for auto copying visually selected text to clipboard register + call setline(1, "text for clipboard test") + let @* = '' + set clipboard=autoselect + normal ggwwviwy + call assert_equal('clipboard', @*) + + " Test for auto copying visually selected text to selection register + let @+ = '' + set clipboard=autoselectplus + normal ggwviwy + call assert_equal('for', @+) + + set clipboard&vim + bwipe! +endfunc + +" Test for restarting the current mode (insert or virtual replace) after +" executing the contents of a register +func Test_put_reg_restart_mode() + new + call append(0, 'editor') + normal gg + let @r = "ivim \<Esc>" + call feedkeys("i\<C-O>@r\<C-R>=mode()\<CR>", 'xt') + call assert_equal('vimi editor', getline(1)) + + call setline(1, 'editor') + normal gg + call feedkeys("gR\<C-O>@r\<C-R>=mode()\<CR>", 'xt') + call assert_equal('vimReditor', getline(1)) + + bwipe! +endfunc + +" Test for executing a register using :@ command +func Test_execute_register() + call setreg('r', []) + call assert_beeps('@r') + let i = 1 + let @q = 'let i+= 1' + @q + @ + call assert_equal(3, i) + + " try to execute expression register and use a backspace to cancel it + new + call feedkeys("@=\<BS>ax\<CR>y", 'xt') + call assert_equal(['x', 'y'], getline(1, '$')) + close! + + " cannot execute a register in operator pending mode + call assert_beeps('normal! c@r') +endfunc + +" Test for getting register info +func Test_get_reginfo() + enew + call setline(1, ['foo', 'bar']) + + exe 'norm! "zyy' + let info = getreginfo('"') + call assert_equal('z', info.points_to) + call setreg('y', 'baz') + call assert_equal('z', getreginfo('').points_to) + call setreg('y', { 'isunnamed': v:true }) + call assert_equal('y', getreginfo('"').points_to) + + exe '$put' + call assert_equal(getreg('y'), getline(3)) + call setreg('', 'qux') + call assert_equal('0', getreginfo('').points_to) + call setreg('x', 'quux') + call assert_equal('0', getreginfo('').points_to) + + let info = getreginfo('') + call assert_equal(getreg('', 1, 1), info.regcontents) + call assert_equal(getregtype(''), info.regtype) + + exe "norm! 0\<c-v>e" .. '"zy' + let info = getreginfo('z') + call assert_equal(getreg('z', 1, 1), info.regcontents) + call assert_equal(getregtype('z'), info.regtype) + call assert_equal(1, +info.isunnamed) + + let info = getreginfo('"') + call assert_equal('z', info.points_to) + + let @a="a1b2" + nnoremap <F2> <Cmd>let g:RegInfo = getreginfo()<CR> + exe "normal \"a\<F2>" + call assert_equal({'regcontents': ['a1b2'], 'isunnamed': v:false, + \ 'regtype': 'v'}, g:RegInfo) + nunmap <F2> + unlet g:RegInfo + + " The type of "isunnamed" was VAR_SPECIAL but should be VAR_BOOL. Can only + " be noticed when using json_encod(). + call setreg('a', 'foo') + let reginfo = getreginfo('a') + let expected = #{regcontents: ['foo'], isunnamed: v:false, regtype: 'v'} + call assert_equal(json_encode(expected), json_encode(reginfo)) + + bwipe! +endfunc + +" Test for restoring register with dict from getreginfo +func Test_set_register_dict() + enew! + + call setreg('"', #{ regcontents: ['one', 'two'], + \ regtype: 'V', points_to: 'z' }) + call assert_equal(['one', 'two'], getreg('"', 1, 1)) + let info = getreginfo('"') + call assert_equal('z', info.points_to) + call assert_equal('V', info.regtype) + call assert_equal(1, +getreginfo('z').isunnamed) + + call setreg('x', #{ regcontents: ['three', 'four'], + \ regtype: 'v', isunnamed: v:true }) + call assert_equal(['three', 'four'], getreg('"', 1, 1)) + let info = getreginfo('"') + call assert_equal('x', info.points_to) + call assert_equal('v', info.regtype) + call assert_equal(1, +getreginfo('x').isunnamed) + + call setreg('y', #{ regcontents: 'five', + \ regtype: "\<c-v>", isunnamed: v:false }) + call assert_equal("\<c-v>4", getreginfo('y').regtype) + call assert_equal(0, +getreginfo('y').isunnamed) + call assert_equal(['three', 'four'], getreg('"', 1, 1)) + call assert_equal('x', getreginfo('"').points_to) + + call setreg('"', #{ regcontents: 'six' }) + call assert_equal('0', getreginfo('"').points_to) + call assert_equal(1, +getreginfo('0').isunnamed) + call assert_equal(['six'], getreginfo('0').regcontents) + call assert_equal(['six'], getreginfo('"').regcontents) + + let @x = 'one' + call setreg('x', {}) + call assert_equal(1, len(split(execute('reg x'), '\n'))) + + call assert_fails("call setreg('0', #{regtype: 'V'}, 'v')", 'E118:') + call assert_fails("call setreg('0', #{regtype: 'X'})", 'E475:') + call assert_fails("call setreg('0', #{regtype: 'vy'})", 'E475:') + + bwipe! +endfunc + +func Test_v_register() + enew + call setline(1, 'nothing') + + func s:Put() + let s:register = v:register + exec 'normal! "' .. v:register .. 'P' + endfunc + nnoremap <buffer> <plug>(test) :<c-u>call s:Put()<cr> + nmap <buffer> S <plug>(test) + + let @z = "testz\n" + let @" = "test@\n" + + let s:register = '' + call feedkeys('"_ddS', 'mx') + call assert_equal('test@', getline('.')) " fails before 8.2.0929 + call assert_equal('"', s:register) " fails before 8.2.0929 + + let s:register = '' + call feedkeys('"zS', 'mx') + call assert_equal('z', s:register) + + let s:register = '' + call feedkeys('"zSS', 'mx') + call assert_equal('"', s:register) + + let s:register = '' + call feedkeys('"_S', 'mx') + call assert_equal('_', s:register) + + let s:register = '' + normal "_ddS + call assert_equal('"', s:register) " fails before 8.2.0929 + call assert_equal('test@', getline('.')) " fails before 8.2.0929 + + let s:register = '' + execute 'normal "z:call' "s:Put()\n" + call assert_equal('z', s:register) + call assert_equal('testz', getline('.')) + + " Test operator and omap + let @b = 'testb' + func s:OpFunc(...) + let s:register2 = v:register + endfunc + set opfunc=s:OpFunc + + normal "bg@l + normal S + call assert_equal('"', s:register) " fails before 8.2.0929 + call assert_equal('b', s:register2) + + func s:Motion() + let s:register1 = v:register + normal! l + endfunc + onoremap <buffer> Q :<c-u>call s:Motion()<cr> + + normal "bg@Q + normal S + call assert_equal('"', s:register) + call assert_equal('b', s:register1) + call assert_equal('"', s:register2) + + set opfunc& + bwipe! +endfunc + +" Test for executing the contents of a register as an Ex command with line +" continuation. +func Test_execute_reg_as_ex_cmd() + " Line continuation with just two lines + let code =<< trim END + let l = [ + \ 1] + END + let @r = code->join("\n") + let l = [] + @r + call assert_equal([1], l) + + " Line continuation with more than two lines + let code =<< trim END + let l = [ + \ 1, + \ 2, + \ 3] + END + let @r = code->join("\n") + let l = [] + @r + call assert_equal([1, 2, 3], l) + + " use comments interspersed with code + let code =<< trim END + let l = [ + "\ one + \ 1, + "\ two + \ 2, + "\ three + \ 3] + END + let @r = code->join("\n") + let l = [] + @r + call assert_equal([1, 2, 3], l) + + " use line continuation in the middle + let code =<< trim END + let a = "one" + let l = [ + \ 1, + \ 2] + let b = "two" + END + let @r = code->join("\n") + let l = [] + @r + call assert_equal([1, 2], l) + call assert_equal("one", a) + call assert_equal("two", b) + + " only one line with a \ + let @r = "\\let l = 1" + call assert_fails('@r', 'E10:') + + " only one line with a "\ + let @r = ' "\ let i = 1' + @r + call assert_false(exists('i')) + + " first line also begins with a \ + let @r = "\\let l = [\n\\ 1]" + call assert_fails('@r', 'E10:') + + " Test with a large number of lines + let @r = "let str = \n" + let @r ..= repeat(" \\ 'abcdefghijklmnopqrstuvwxyz' ..\n", 312) + let @r ..= ' \ ""' + @r + call assert_equal(repeat('abcdefghijklmnopqrstuvwxyz', 312), str) +endfunc + +func Test_ve_blockpaste() + new + set ve=all + 0put =['QWERTZ','ASDFGH'] + call cursor(1,1) + exe ":norm! \<C-V>3ljdP" + call assert_equal(1, col('.')) + call assert_equal(getline(1, 2), ['QWERTZ', 'ASDFGH']) + call cursor(1,1) + exe ":norm! \<C-V>3ljd" + call cursor(1,1) + norm! $3lP + call assert_equal(5, col('.')) + call assert_equal(getline(1, 2), ['TZ QWER', 'GH ASDF']) + set ve&vim + bwipe! +endfunc + +func Test_insert_small_delete() + new + call setline(1, ['foo foobar bar']) + call cursor(1,1) + exe ":norm! ciw'\<C-R>-'" + call assert_equal("'foo' foobar bar", getline(1)) + exe ":norm! w.w." + call assert_equal("'foo' 'foobar' 'bar'", getline(1)) + bwipe! +endfunc + +" Record in insert mode using CTRL-O +func Test_record_in_insert_mode() + new + let @r = '' + call setline(1, ['foo']) + call feedkeys("i\<C-O>qrbaz\<C-O>q", 'xt') + call assert_equal('baz', @r) + bwipe! +endfunc + +func Test_record_in_select_mode() + new + call setline(1, 'text') + sil norm q00 + sil norm q + call assert_equal('0ext', getline(1)) + + %delete + let @r = '' + call setline(1, ['abc', 'abc', 'abc']) + smap <F2> <Right><Right>, + call feedkeys("qrgh\<F2>Dk\<Esc>q", 'xt') + call assert_equal("gh\<F2>Dk\<Esc>", @r) + norm j0@rj0@@ + call assert_equal([',Dk', ',Dk', ',Dk'], getline(1, 3)) + sunmap <F2> + + bwipe! +endfunc + +" A mapping that ends recording should be removed from the recorded register. +func Test_end_record_using_mapping() + new + call setline(1, 'aaa') + nnoremap s q + call feedkeys('safas', 'tx') + call assert_equal('fa', @a) + nunmap s + + nnoremap xx q + call feedkeys('0xxafaxx', 'tx') + call assert_equal('fa', @a) + nunmap xx + + nnoremap xsx q + call feedkeys('0qafaxsx', 'tx') + call assert_equal('fa', @a) + nunmap xsx + + bwipe! +endfunc + +" Starting a new recording should work immediately after replaying a recording +" that ends with a <Nop> mapping or a character search. +func Test_end_reg_executing() + new + nnoremap s <Nop> + let @a = 's' + call feedkeys("@aqaq\<Esc>", 'tx') + call assert_equal('', @a) + call assert_equal('', getline(1)) + + call setline(1, 'aaa') + nnoremap s qa + let @a = 'fa' + call feedkeys("@asq\<Esc>", 'tx') + call assert_equal('', @a) + call assert_equal('aaa', getline(1)) + + nunmap s + bwipe! +endfunc + +" An operator-pending mode mapping shouldn't be applied to keys typed in +" Insert mode immediately after a character search when replaying. +func Test_replay_charsearch_omap() + CheckFeature timers + + new + call setline(1, 'foo[blah]') + onoremap , k + call timer_start(10, {-> feedkeys(",bar\<Esc>q", 't')}) + call feedkeys('qrct[', 'xt!') + call assert_equal(',bar[blah]', getline(1)) + undo + call assert_equal('foo[blah]', getline(1)) + call feedkeys('@r', 'xt!') + call assert_equal(',bar[blah]', getline(1)) + + ounmap , + bwipe! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_reltime.vim b/test/old/testdir/test_reltime.vim new file mode 100644 index 0000000000..8ed09dd10f --- /dev/null +++ b/test/old/testdir/test_reltime.vim @@ -0,0 +1,32 @@ +" Tests for reltime() + +source check.vim +CheckFeature reltime +CheckFeature float + +func Test_reltime() + let g:test_is_flaky = 1 + let now = reltime() + sleep 10m + let later = reltime() + let elapsed = now->reltime() + call assert_true(reltimestr(elapsed) =~ '0\.0') + call assert_true(elapsed->reltimestr() != '0.0') + call assert_true(reltimefloat(elapsed) < 0.1) + call assert_true(elapsed->reltimefloat() > 0.0) + + let same = reltime(now, now) + call assert_equal('0.000', split(reltimestr(same))[0][:4]) + call assert_equal(0.0, reltimefloat(same)) + + let differs = reltime(now, later) + call assert_true(reltimestr(differs) =~ '0\.0') + call assert_true(reltimestr(differs) != '0.0') + call assert_true(reltimefloat(differs) < 0.1) + call assert_true(reltimefloat(differs) > 0.0) + + call assert_equal(0, reltime({})) + call assert_equal(0, reltime({}, {})) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_rename.vim b/test/old/testdir/test_rename.vim new file mode 100644 index 0000000000..5359b84923 --- /dev/null +++ b/test/old/testdir/test_rename.vim @@ -0,0 +1,120 @@ +" Test rename() + +source shared.vim + +func Test_rename_file_to_file() + call writefile(['foo'], 'Xrename1') + + call assert_equal(0, rename('Xrename1', 'Xrename2')) + + call assert_equal('', glob('Xrename1')) + call assert_equal(['foo'], readfile('Xrename2')) + + " When the destination file already exists, it should be overwritten. + call writefile(['foo'], 'Xrename1') + call writefile(['bar'], 'Xrename2') + + call assert_equal(0, rename('Xrename1', 'Xrename2')) + call assert_equal('', glob('Xrename1')) + call assert_equal(['foo'], readfile('Xrename2')) + + call delete('Xrename2') +endfunc + +func Test_rename_file_ignore_case() + " With 'fileignorecase', renaming file will go through a temp file + " when the source and destination file only differ by case. + set fileignorecase + call writefile(['foo'], 'Xrename') + + call assert_equal(0, 'Xrename'->rename('XRENAME')) + + call assert_equal(['foo'], readfile('XRENAME')) + + set fileignorecase& + call delete('XRENAME') +endfunc + +func Test_rename_same_file() + call writefile(['foo'], 'Xrename') + + " When the source and destination are the same file, nothing + " should be done. The source file should not be deleted. + call assert_equal(0, rename('Xrename', 'Xrename')) + call assert_equal(['foo'], readfile('Xrename')) + + call assert_equal(0, rename('./Xrename', 'Xrename')) + call assert_equal(['foo'], readfile('Xrename')) + + call delete('Xrename') +endfunc + +func Test_rename_dir_to_dir() + call mkdir('Xrenamedir1') + call writefile(['foo'], 'Xrenamedir1/Xrenamefile') + + call assert_equal(0, rename('Xrenamedir1', 'Xrenamedir2')) + + call assert_equal('', glob('Xrenamedir1')) + call assert_equal(['foo'], readfile('Xrenamedir2/Xrenamefile')) + + call delete('Xrenamedir2/Xrenamefile') + call delete('Xrenamedir2', 'd') +endfunc + +func Test_rename_same_dir() + call mkdir('Xrenamedir') + call writefile(['foo'], 'Xrenamedir/Xrenamefile') + + call assert_equal(0, rename('Xrenamedir', 'Xrenamedir')) + + call assert_equal(['foo'], readfile('Xrenamedir/Xrenamefile')) + + call delete('Xrenamedir/Xrenamefile') + call delete('Xrenamedir', 'd') +endfunc + +func Test_rename_copy() + " Check that when original file can't be deleted, rename() + " still succeeds but copies the file. + call mkdir('Xrenamedir') + call writefile(['foo'], 'Xrenamedir/Xrenamefile') + call setfperm('Xrenamedir', 'r-xr-xr-x') + + call assert_equal(0, rename('Xrenamedir/Xrenamefile', 'Xrenamefile')) + + if !has('win32') && !IsRoot() + " On Windows, the source file is removed despite + " its directory being made not writable. + call assert_equal(['foo'], readfile('Xrenamedir/Xrenamefile')) + endif + call assert_equal(['foo'], readfile('Xrenamefile')) + + call setfperm('Xrenamedir', 'rwxrwxrwx') + call delete('Xrenamedir/Xrenamefile') + call delete('Xrenamedir', 'd') + call delete('Xrenamefile') +endfunc + +func Test_rename_fails() + call writefile(['foo'], 'Xrenamefile') + + " Can't rename into a non-existing directory. + call assert_notequal(0, rename('Xrenamefile', 'Xdoesnotexist/Xrenamefile')) + + " Can't rename a non-existing file. + call assert_notequal(0, rename('Xdoesnotexist', 'Xrenamefile2')) + call assert_equal('', glob('Xrenamefile2')) + + " When rename() fails, the destination file should not be deleted. + call assert_notequal(0, rename('Xdoesnotexist', 'Xrenamefile')) + call assert_equal(['foo'], readfile('Xrenamefile')) + + " Can't rename to en empty file name. + call assert_notequal(0, rename('Xrenamefile', '')) + + call assert_fails('call rename("Xrenamefile", [])', 'E730') + call assert_fails('call rename(0z, "Xrenamefile")', 'E976') + + call delete('Xrenamefile') +endfunc diff --git a/test/old/testdir/test_retab.vim b/test/old/testdir/test_retab.vim new file mode 100644 index 0000000000..a4f95053c0 --- /dev/null +++ b/test/old/testdir/test_retab.vim @@ -0,0 +1,117 @@ +" Test :retab + +source check.vim + +func SetUp() + new + call setline(1, "\ta \t b c ") +endfunc + +func TearDown() + bwipe! +endfunc + +func Retab(bang, n) + let l:old_tabstop = &tabstop + let l:old_line = getline(1) + exe "retab" . a:bang . a:n + let l:line = getline(1) + call setline(1, l:old_line) + if a:n > 0 + " :retab changes 'tabstop' to n with argument n > 0. + call assert_equal(a:n, &tabstop) + exe 'set tabstop=' . l:old_tabstop + else + " :retab does not change 'tabstop' with empty or n <= 0. + call assert_equal(l:old_tabstop, &tabstop) + endif + return l:line +endfunc + +func Test_retab() + set tabstop=8 noexpandtab + call assert_equal("\ta\t b c ", Retab('', '')) + call assert_equal("\ta\t b c ", Retab('', 0)) + call assert_equal("\ta\t b c ", Retab('', 8)) + call assert_equal("\ta\t b\t c\t ", Retab('!', '')) + call assert_equal("\ta\t b\t c\t ", Retab('!', 0)) + call assert_equal("\ta\t b\t c\t ", Retab('!', 8)) + + call assert_equal("\t\ta\t\t\tb c ", Retab('', 4)) + call assert_equal("\t\ta\t\t\tb\t\t c\t ", Retab('!', 4)) + + call assert_equal(" a\t\tb c ", Retab('', 10)) + call assert_equal(" a\t\tb c ", Retab('!', 10)) + + set tabstop=8 expandtab + call assert_equal(" a b c ", Retab('', '')) + call assert_equal(" a b c ", Retab('', 0)) + call assert_equal(" a b c ", Retab('', 8)) + call assert_equal(" a b c ", Retab('!', '')) + call assert_equal(" a b c ", Retab('!', 0)) + call assert_equal(" a b c ", Retab('!', 8)) + + call assert_equal(" a b c ", Retab(' ', 4)) + call assert_equal(" a b c ", Retab('!', 4)) + + call assert_equal(" a b c ", Retab(' ', 10)) + call assert_equal(" a b c ", Retab('!', 10)) + + set tabstop=4 noexpandtab + call assert_equal("\ta\t\tb c ", Retab('', '')) + call assert_equal("\ta\t\tb\t\t c\t ", Retab('!', '')) + call assert_equal("\t a\t\t\tb c ", Retab('', 3)) + call assert_equal("\t a\t\t\tb\t\t\tc\t ", Retab('!', 3)) + call assert_equal(" a\t b c ", Retab('', 5)) + call assert_equal(" a\t b\t\t c\t ", Retab('!', 5)) + + set tabstop=4 expandtab + call assert_equal(" a b c ", Retab('', '')) + call assert_equal(" a b c ", Retab('!', '')) + call assert_equal(" a b c ", Retab('', 3)) + call assert_equal(" a b c ", Retab('!', 3)) + call assert_equal(" a b c ", Retab('', 5)) + call assert_equal(" a b c ", Retab('!', 5)) + + set tabstop& expandtab& +endfunc + +func Test_retab_error() + call assert_fails('retab -1', 'E487:') + call assert_fails('retab! -1', 'E487:') + call assert_fails('ret -1000', 'E487:') + call assert_fails('ret 10000', 'E475:') + call assert_fails('ret 80000000000000000000', 'E475:') +endfunc + +func RetabLoop() + while 1 + set ts=4000 + retab 4 + endwhile +endfunc + +func Test_retab_endless() + " inside try/catch we can catch the error message + call setline(1, "\t0\t") + let caught = 'no' + try + call RetabLoop() + catch /E1240:/ + let caught = v:exception + endtry + call assert_match('E1240:', caught) + + set tabstop& +endfunc + +func Test_nocatch_retab_endless() + " when not inside try/catch an interrupt is generated to get out of loops + call setline(1, "\t0\t") + call assert_fails('call RetabLoop()', ['E1240:', 'Interrupted']) + + set tabstop& +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_ruby.vim b/test/old/testdir/test_ruby.vim new file mode 100644 index 0000000000..4929496086 --- /dev/null +++ b/test/old/testdir/test_ruby.vim @@ -0,0 +1,437 @@ +" Tests for ruby interface + +source check.vim +CheckFeature ruby + +func Test_ruby_change_buffer() + call setline(line('$'), ['1 line 1']) + ruby Vim.command("normal /^1\n") + ruby $curbuf.line = "1 changed line 1" + call assert_equal('1 changed line 1', getline('$')) +endfunc + +func Test_rubydo() + throw 'skipped: TODO: ' + " Check deleting lines does not trigger ml_get error. + new + call setline(1, ['one', 'two', 'three']) + rubydo Vim.command("%d_") + bwipe! + + " Check switching to another buffer does not trigger ml_get error. + new + let wincount = winnr('$') + call setline(1, ['one', 'two', 'three']) + rubydo Vim.command("new") + call assert_equal(wincount + 1, winnr('$')) + %bwipe! +endfunc + +func Test_rubydo_dollar_underscore() + throw 'skipped: TODO: ' + new + call setline(1, ['one', 'two', 'three', 'four']) + 2,3rubydo $_ = '[' + $_ + ']' + call assert_equal(['one', '[two]', '[three]', 'four'], getline(1, '$')) + bwipe! + + call assert_fails('rubydo $_ = 0', 'E265:') + call assert_fails('rubydo (') + bwipe! +endfunc + +func Test_rubyfile() + " Check :rubyfile does not SEGV with Ruby level exception but just fails + let tempfile = tempname() . '.rb' + call writefile(['raise "vim!"'], tempfile) + call assert_fails('rubyfile ' . tempfile) + call delete(tempfile) +endfunc + +func Test_ruby_set_cursor() + " Check that setting the cursor position works. + new + call setline(1, ['first line', 'second line']) + normal gg + rubydo $curwin.cursor = [1, 5] + call assert_equal([1, 6], [line('.'), col('.')]) + call assert_equal([1, 5], rubyeval('$curwin.cursor')) + + " Check that movement after setting cursor position keeps current column. + normal j + call assert_equal([2, 6], [line('.'), col('.')]) + call assert_equal([2, 5], '$curwin.cursor'->rubyeval()) + + " call assert_fails('ruby $curwin.cursor = [1]', + " \ 'ArgumentError: array length must be 2') + bwipe! +endfunc + +" Test buffer.count and buffer.length (number of lines in buffer) +func Test_ruby_buffer_count() + new + call setline(1, ['one', 'two', 'three']) + call assert_equal(3, rubyeval('$curbuf.count')) + call assert_equal(3, rubyeval('$curbuf.length')) + bwipe! +endfunc + +" Test buffer.name (buffer name) +func Test_ruby_buffer_name() + new Xfoo + call assert_equal(expand('%:p'), rubyeval('$curbuf.name')) + bwipe + call assert_equal('', rubyeval('$curbuf.name')) +endfunc + +" Test buffer.number (number of the buffer). +func Test_ruby_buffer_number() + new + call assert_equal(bufnr('%'), rubyeval('$curbuf.number')) + new + call assert_equal(bufnr('%'), rubyeval('$curbuf.number')) + + %bwipe +endfunc + +" Test buffer.delete({n}) (delete line {n}) +func Test_ruby_buffer_delete() + new + call setline(1, ['one', 'two', 'three']) + ruby $curbuf.delete(2) + call assert_equal(['one', 'three'], getline(1, '$')) + + " call assert_fails('ruby $curbuf.delete(0)', 'IndexError: line number 0 out of range') + " call assert_fails('ruby $curbuf.delete(3)', 'IndexError: line number 3 out of range') + call assert_fails('ruby $curbuf.delete(3)', 'RuntimeError: Index out of bounds') + + bwipe! +endfunc + +" Test buffer.append({str}, str) (append line {str} after line {n}) +func Test_ruby_buffer_append() + new + ruby $curbuf.append(0, 'one') + ruby $curbuf.append(1, 'three') + ruby $curbuf.append(1, 'two') + ruby $curbuf.append(4, 'four') + + call assert_equal(['one', 'two', 'three', '', 'four'], getline(1, '$')) + + " call assert_fails('ruby $curbuf.append(-1, "x")', + " \ 'IndexError: line number -1 out of range') + call assert_fails('ruby $curbuf.append(-1, "x")', + \ 'ArgumentError: Index out of bounds') + call assert_fails('ruby $curbuf.append(6, "x")', + \ 'RuntimeError: Index out of bounds') + + bwipe! +endfunc + +" Test buffer.line (get or set the current line) +func Test_ruby_buffer_line() + new + call setline(1, ['one', 'two', 'three']) + 2 + call assert_equal('two', rubyeval('$curbuf.line')) + + ruby $curbuf.line = 'TWO' + call assert_equal(['one', 'TWO', 'three'], getline(1, '$')) + + bwipe! +endfunc + +" Test buffer.line_number (get current line number) +func Test_ruby_buffer_line_number() + new + call setline(1, ['one', 'two', 'three']) + 2 + call assert_equal(2, rubyeval('$curbuf.line_number')) + + bwipe! +endfunc + +func Test_ruby_buffer_get() + new + call setline(1, ['one', 'two']) + call assert_equal('one', rubyeval('$curbuf[1]')) + call assert_equal('two', rubyeval('$curbuf[2]')) + + " call assert_fails('ruby $curbuf[0]', + " \ 'IndexError: line number 0 out of range') + call assert_fails('ruby $curbuf[3]', + \ 'RuntimeError: Index out of bounds') + + bwipe! +endfunc + +func Test_ruby_buffer_set() + new + call setline(1, ['one', 'two']) + ruby $curbuf[2] = 'TWO' + ruby $curbuf[1] = 'ONE' + + " call assert_fails('ruby $curbuf[0] = "ZERO"', + " \ 'IndexError: line number 0 out of range') + " call assert_fails('ruby $curbuf[3] = "THREE"', + " \ 'IndexError: line number 3 out of range') + call assert_fails('ruby $curbuf[3] = "THREE"', + \ 'RuntimeError: Index out of bounds') + bwipe! +endfunc + +" Test window.width (get or set window height). +func Test_ruby_window_height() + new + + " Test setting window height + ruby $curwin.height = 2 + call assert_equal(2, winheight(0)) + + " Test getting window height + call assert_equal(2, rubyeval('$curwin.height')) + + bwipe +endfunc + +" Test window.width (get or set window width). +func Test_ruby_window_width() + vnew + + " Test setting window width + ruby $curwin.width = 2 + call assert_equal(2, winwidth(0)) + + " Test getting window width + call assert_equal(2, rubyeval('$curwin.width')) + + bwipe +endfunc + +" Test window.buffer (get buffer object of a window object). +func Test_ruby_window_buffer() + new Xfoo1 + new Xfoo2 + ruby $b2 = $curwin.buffer + ruby $w2 = $curwin + wincmd j + ruby $b1 = $curwin.buffer + ruby $w1 = $curwin + + " call assert_equal(rubyeval('$b1'), rubyeval('$w1.buffer')) + " call assert_equal(rubyeval('$b2'), rubyeval('$w2.buffer')) + call assert_equal(bufnr('Xfoo1'), rubyeval('$w1.buffer.number')) + call assert_equal(bufnr('Xfoo2'), rubyeval('$w2.buffer.number')) + + ruby $b1, $w1, $b2, $w2 = nil + %bwipe +endfunc + +" Test Vim::Window.current (get current window object) +func Test_ruby_Vim_window_current() + let cw = rubyeval('$curwin.to_s') + " call assert_equal(cw, rubyeval('Vim::Window.current')) + call assert_match('^#<Neovim::Window:0x\x\+>$', cw) +endfunc + +" Test Vim::Window.count (number of windows) +func Test_ruby_Vim_window_count() + new Xfoo1 + new Xfoo2 + split + call assert_equal(4, rubyeval('Vim::Window.count')) + %bwipe + call assert_equal(1, rubyeval('Vim::Window.count')) +endfunc + +" Test Vim::Window[n] (get window object of window n) +func Test_ruby_Vim_window_get() + new Xfoo1 + new Xfoo2 + call assert_match('Xfoo2$', rubyeval('Vim::Window[0].buffer.name')) + wincmd j + call assert_match('Xfoo1$', rubyeval('Vim::Window[1].buffer.name')) + wincmd j + call assert_equal('', rubyeval('Vim::Window[2].buffer.name')) + %bwipe +endfunc + +" Test Vim::Buffer.current (return the buffer object of current buffer) +func Test_ruby_Vim_buffer_current() + let cb = rubyeval('$curbuf.to_s') + " call assert_equal(cb, rubyeval('Vim::Buffer.current')) + call assert_match('^#<Neovim::Buffer:0x\x\+>$', cb) +endfunc + +" Test Vim::Buffer:.count (return the number of buffers) +func Test_ruby_Vim_buffer_count() + new Xfoo1 + new Xfoo2 + call assert_equal(3, rubyeval('Vim::Buffer.count')) + %bwipe + call assert_equal(1, rubyeval('Vim::Buffer.count')) +endfunc + +" Test Vim::buffer[n] (return the buffer object of buffer number n) +func Test_ruby_Vim_buffer_get() + new Xfoo1 + new Xfoo2 + + " Index of Vim::Buffer[n] goes from 0 to the number of buffers. + call assert_equal('', rubyeval('Vim::Buffer[0].name')) + call assert_match('Xfoo1$', rubyeval('Vim::Buffer[1].name')) + call assert_match('Xfoo2$', rubyeval('Vim::Buffer[2].name')) + call assert_fails('ruby print Vim::Buffer[3].name', + \ "NoMethodError: undefined method `name' for nil:NilClass") + %bwipe +endfunc + +" Test Vim::command({cmd}) (execute a Ex command)) +" Test Vim::command({cmd}) +func Test_ruby_Vim_command() + new + call setline(1, ['one', 'two', 'three', 'four']) + ruby Vim::command('2,3d') + call assert_equal(['one', 'four'], getline(1, '$')) + bwipe! +endfunc + +" Test Vim::set_option (set a vim option) +func Test_ruby_Vim_set_option() + call assert_equal(0, &number) + ruby Vim::set_option('number') + call assert_equal(1, &number) + ruby Vim::set_option('nonumber') + call assert_equal(0, &number) +endfunc + +func Test_ruby_Vim_evaluate() + call assert_equal(123, rubyeval('Vim::evaluate("123")')) + " Vim::evaluate("123").class gives Integer or Fixnum depending + " on versions of Ruby. + call assert_match('^Integer\|Fixnum$', rubyeval('Vim::evaluate("123").class')) + + if has('float') + call assert_equal(1.23, rubyeval('Vim::evaluate("1.23")')) + call assert_equal('Float', rubyeval('Vim::evaluate("1.23").class')) + endif + + call assert_equal('foo', rubyeval('Vim::evaluate("\"foo\"")')) + call assert_equal('String', rubyeval('Vim::evaluate("\"foo\"").class')) + + call assert_equal([1, 2], rubyeval('Vim::evaluate("[1, 2]")')) + call assert_equal('Array', rubyeval('Vim::evaluate("[1, 2]").class')) + + call assert_equal({'1': 2}, rubyeval('Vim::evaluate("{1:2}")')) + call assert_equal('Hash', rubyeval('Vim::evaluate("{1:2}").class')) + + call assert_equal(v:null, rubyeval('Vim::evaluate("v:null")')) + call assert_equal('NilClass', rubyeval('Vim::evaluate("v:null").class')) + + " call assert_equal(v:null, rubyeval('Vim::evaluate("v:none")')) + " call assert_equal('NilClass', rubyeval('Vim::evaluate("v:none").class')) + + call assert_equal(v:true, rubyeval('Vim::evaluate("v:true")')) + call assert_equal('TrueClass', rubyeval('Vim::evaluate("v:true").class')) + call assert_equal(v:false, rubyeval('Vim::evaluate("v:false")')) + call assert_equal('FalseClass',rubyeval('Vim::evaluate("v:false").class')) +endfunc + +func Test_ruby_Vim_evaluate_list() + call setline(line('$'), ['2 line 2']) + ruby Vim.command("normal /^2\n") + let l = ["abc", "def"] + ruby << trim EOF + curline = $curbuf.line_number + l = Vim.evaluate("l"); + $curbuf.append(curline, l.join("|")) + EOF + normal j + .rubydo $_ = $_.gsub(/\|/, '/') + call assert_equal('abc/def', getline('$')) +endfunc + +func Test_ruby_Vim_evaluate_dict() + let d = {'a': 'foo', 'b': 123} + redir => l:out + ruby d = Vim.evaluate("d"); print d + redir END + call assert_equal(['{"a"=>"foo", "b"=>123}'], split(l:out, "\n")) +endfunc + +" Test Vim::message({msg}) (display message {msg}) +func Test_ruby_Vim_message() + throw 'skipped: TODO: ' + ruby Vim::message('A message') + let messages = split(execute('message'), "\n") + call assert_equal('A message', messages[-1]) +endfunc + +func Test_ruby_print() + func RubyPrint(expr) + return trim(execute('ruby print ' . a:expr)) + endfunc + + call assert_equal('123', RubyPrint('123')) + call assert_equal('1.23', RubyPrint('1.23')) + call assert_equal('Hello World!', RubyPrint('"Hello World!"')) + call assert_equal('[1, 2]', RubyPrint('[1, 2]')) + call assert_equal('{"k1"=>"v1", "k2"=>"v2"}', RubyPrint('({"k1" => "v1", "k2" => "v2"})')) + call assert_equal('true', RubyPrint('true')) + call assert_equal('false', RubyPrint('false')) + call assert_equal('', RubyPrint('nil')) + call assert_match('Vim', RubyPrint('Vim')) + call assert_match('Module', RubyPrint('Vim.class')) + + delfunc RubyPrint +endfunc + +func Test_ruby_p() + ruby p 'Just a test' + let messages = GetMessages() + call assert_equal('"Just a test"', messages[-1]) + + " Check return values of p method + + call assert_equal(123, rubyeval('p(123)')) + call assert_equal([1, 2, 3], rubyeval('p(1, 2, 3)')) + + " Avoid the "message maintainer" line. + let $LANG = '' + messages clear + call assert_equal(v:true, rubyeval('p() == nil')) + + let messages = GetMessages() + call assert_equal(0, len(messages)) +endfunc + +func Test_rubyeval_error() + " On Linux or Windows the error matches: + " "syntax error, unexpected end-of-input" + " whereas on macOS in CI, the error message makes less sense: + " "SyntaxError: array length must be 2" + " Unclear why. The test does not check the error message. + call assert_fails('call rubyeval("(")') +endfunc + +" Test for various heredoc syntax +func Test_ruby_heredoc() + ruby << END +Vim.command('let s = "A"') +END + ruby << +Vim.command('let s ..= "B"') +. + ruby << trim END + Vim.command('let s ..= "C"') + END + ruby << trim + Vim.command('let s ..= "D"') + . + ruby << trim eof + Vim.command('let s ..= "E"') + eof + call assert_equal('ABCDE', s) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_scriptnames.vim b/test/old/testdir/test_scriptnames.vim new file mode 100644 index 0000000000..69e5e526fd --- /dev/null +++ b/test/old/testdir/test_scriptnames.vim @@ -0,0 +1,110 @@ + +" Test for the :scriptnames command +func Test_scriptnames() + call writefile(['let did_load_script = 123'], 'Xscripting') + source Xscripting + call assert_equal(123, g:did_load_script) + + let scripts = split(execute('scriptnames'), "\n") + let last = scripts[-1] + call assert_match('\<Xscripting\>', last) + let lastnr = substitute(last, '\D*\(\d\+\):.*', '\1', '') + exe 'script ' . lastnr + call assert_equal('Xscripting', expand('%:t')) + + call assert_fails('script ' . (lastnr + 1), 'E474:') + call assert_fails('script 0', 'E939:') + + new + call setline(1, 'nothing') + call assert_fails('script ' . lastnr, 'E37:') + exe 'script! ' . lastnr + call assert_equal('Xscripting', expand('%:t')) + + bwipe + call delete('Xscripting') + + let msgs = execute('messages') + scriptnames + call assert_equal(msgs, execute('messages')) +endfunc + +" Test for the getscriptinfo() function +func Test_getscriptinfo() + let lines =<< trim END + " scriptversion 3 + let g:loaded_script_id = expand("<SID>") + let s:XscriptVar = [1, #{v: 2}] + func s:XgetScriptVar() + return s:XscriptVar + endfunc + func s:Xscript_legacy_func1() + endfunc + " def s:Xscript_def_func1() + " enddef + func Xscript_legacy_func2() + endfunc + " def Xscript_def_func2() + " enddef + END + call writefile(lines, 'X22script91') + source X22script91 + let l = getscriptinfo() + call assert_match('X22script91$', l[-1].name) + call assert_equal(g:loaded_script_id, $"<SNR>{l[-1].sid}_") + " call assert_equal(3, l[-1].version) + call assert_equal(1, l[-1].version) + call assert_equal(0, has_key(l[-1], 'variables')) + call assert_equal(0, has_key(l[-1], 'functions')) + + " Get script information using script name + let l = getscriptinfo(#{name: '22script91'}) + call assert_equal(1, len(l)) + call assert_match('22script91$', l[0].name) + let sid = l[0].sid + + " Get script information using script-ID + let l = getscriptinfo({'sid': sid}) + call assert_equal(#{XscriptVar: [1, {'v': 2}]}, l[0].variables) + let funcs = ['Xscript_legacy_func2', + \ $"<SNR>{sid}_Xscript_legacy_func1", + "\ $"<SNR>{sid}_Xscript_def_func1", + "\ 'Xscript_def_func2', + \ $"<SNR>{sid}_XgetScriptVar"] + for f in funcs + call assert_true(index(l[0].functions, f) != -1) + endfor + + " Verify that a script-local variable cannot be modified using the dict + " returned by getscriptinfo() + let l[0].variables.XscriptVar = ['n'] + let funcname = $"<SNR>{sid}_XgetScriptVar" + call assert_equal([1, {'v': 2}], call(funcname, [])) + + let l = getscriptinfo({'name': 'foobar'}) + call assert_equal(0, len(l)) + let l = getscriptinfo({'name': ''}) + call assert_true(len(l) > 1) + + call assert_fails("echo getscriptinfo({'name': []})", 'E730:') + call assert_fails("echo getscriptinfo({'name': '\\@'})", 'E866:') + let l = getscriptinfo({'name': v:_null_string}) + call assert_true(len(l) > 1) + call assert_fails("echo getscriptinfo('foobar')", 'E1206:') + + call assert_fails("echo getscriptinfo({'sid': []})", 'E745:') + call assert_fails("echo getscriptinfo({'sid': {}})", 'E728:') + call assert_fails("echo getscriptinfo({'sid': 0})", 'E475:') + call assert_fails("echo getscriptinfo({'sid': -1})", 'E475:') + call assert_fails("echo getscriptinfo({'sid': -999})", 'E475:') + + echo getscriptinfo({'sid': '1'}) + " call assert_fails("vim9cmd echo getscriptinfo({'sid': '1'})", 'E1030:') + + let max_sid = max(map(getscriptinfo(), { k, v -> v.sid })) + call assert_equal([], getscriptinfo({'sid': max_sid + 1})) + + call delete('X22script91') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_scroll_opt.vim b/test/old/testdir/test_scroll_opt.vim new file mode 100644 index 0000000000..f2e7bc6b56 --- /dev/null +++ b/test/old/testdir/test_scroll_opt.vim @@ -0,0 +1,951 @@ +" Test for 'scroll', 'scrolloff', 'smoothscroll', etc. + +source check.vim +source screendump.vim +source mouse.vim + +func Test_reset_scroll() + let scr = &l:scroll + + setlocal scroll=1 + setlocal scroll& + call assert_equal(scr, &l:scroll) + + setlocal scroll=1 + setlocal scroll=0 + call assert_equal(scr, &l:scroll) + + try + execute 'setlocal scroll=' . (winheight(0) + 1) + " not reached + call assert_false(1) + catch + call assert_exception('E49:') + endtry + + split + + let scr = &l:scroll + + setlocal scroll=1 + setlocal scroll& + call assert_equal(scr, &l:scroll) + + setlocal scroll=1 + setlocal scroll=0 + call assert_equal(scr, &l:scroll) + + quit! +endfunc + +func Test_scolloff_even_line_count() + new + resize 6 + setlocal scrolloff=3 + call setline(1, range(20)) + normal 2j + call assert_equal(1, getwininfo(win_getid())[0].topline) + normal j + call assert_equal(1, getwininfo(win_getid())[0].topline) + normal j + call assert_equal(2, getwininfo(win_getid())[0].topline) + normal j + call assert_equal(3, getwininfo(win_getid())[0].topline) + + bwipe! +endfunc + +func Test_mouse_scroll_inactive_with_cursorbind() + for scb in [0, 1] + for so in [0, 1, 2] + let msg = $'scb={scb} so={so}' + + new | only + let w1 = win_getid() + setlocal cursorbind + let &l:scb = scb + let &l:so = so + call setline(1, range(101, 109)) + rightbelow vnew + let w2 = win_getid() + setlocal cursorbind + let &l:scb = scb + let &l:so = so + call setline(1, range(101, 109)) + + normal! $ + call assert_equal(3, col('.', w1), msg) + call assert_equal(3, col('.', w2), msg) + call Ntest_setmouse(1, 1) + call feedkeys("\<ScrollWheelDown>", 'xt') + call assert_equal(4, line('w0', w1), msg) + call assert_equal(4 + so, line('.', w1), msg) + call assert_equal(1, line('w0', w2), msg) + call assert_equal(1, line('.', w2), msg) + call feedkeys("\<ScrollWheelDown>", 'xt') + call assert_equal(7, line('w0', w1), msg) + call assert_equal(7 + so, line('.', w1), msg) + call assert_equal(1, line('w0', w2), msg) + call assert_equal(1, line('.', w2), msg) + call feedkeys("\<ScrollWheelUp>", 'xt') + call assert_equal(4, line('w0', w1), msg) + call assert_equal(7 + so, line('.', w1), msg) + call assert_equal(1, line('w0', w2), msg) + call assert_equal(1, line('.', w2), msg) + call feedkeys("\<ScrollWheelUp>", 'xt') + call assert_equal(1, line('w0', w1), msg) + call assert_equal(7 + so, line('.', w1), msg) + call assert_equal(1, line('w0', w2), msg) + call assert_equal(1, line('.', w2), msg) + normal! 0 + call assert_equal(1, line('.', w1), msg) + call assert_equal(1, col('.', w1), msg) + call assert_equal(1, line('.', w2), msg) + call assert_equal(1, col('.', w2), msg) + + bwipe! + bwipe! + endfor + endfor +endfunc + +func Test_CtrlE_CtrlY_stop_at_end() + enew + call setline(1, ['one', 'two']) + set number + exe "normal \<C-Y>" + call assert_equal([" 1 one "], ScreenLines(1, 10)) + exe "normal \<C-E>\<C-E>\<C-E>" + call assert_equal([" 2 two "], ScreenLines(1, 10)) + + bwipe! + set nonumber +endfunc + +func Test_smoothscroll_CtrlE_CtrlY() + CheckScreendump + + let lines =<< trim END + vim9script + setline(1, [ + 'line one', + 'word '->repeat(20), + 'line three', + 'long word '->repeat(7), + 'line', + 'line', + 'line', + ]) + set smoothscroll + :5 + END + call writefile(lines, 'XSmoothScroll', 'D') + let buf = RunVimInTerminal('-S XSmoothScroll', #{rows: 12, cols: 40}) + + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smoothscroll_1', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smoothscroll_2', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smoothscroll_3', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smoothscroll_4', {}) + + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smoothscroll_5', {}) + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smoothscroll_6', {}) + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smoothscroll_7', {}) + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smoothscroll_8', {}) + + if has('folding') + call term_sendkeys(buf, ":set foldmethod=indent\<CR>") + " move the cursor so we can reuse the same dumps + call term_sendkeys(buf, "5G") + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smoothscroll_1', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smoothscroll_2', {}) + call term_sendkeys(buf, "7G") + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smoothscroll_7', {}) + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smoothscroll_8', {}) + endif + + call StopVimInTerminal(buf) +endfunc + +func Test_smoothscroll_multibyte() + CheckScreendump + + let lines =<< trim END + set scrolloff=0 smoothscroll + call setline(1, [repeat('ϛ', 45), repeat('2', 36)]) + exe "normal G35l\<C-E>k" + END + call writefile(lines, 'XSmoothMultibyte', 'D') + let buf = RunVimInTerminal('-S XSmoothMultibyte', #{rows: 6, cols: 40}) + call VerifyScreenDump(buf, 'Test_smoothscroll_multi_1', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_smoothscroll_number() + CheckScreendump + + let lines =<< trim END + vim9script + setline(1, [ + 'one ' .. 'word '->repeat(20), + 'two ' .. 'long word '->repeat(7), + 'line', + 'line', + 'line', + ]) + set smoothscroll + set splitkeep=topline + set number cpo+=n + :3 + + def g:DoRel() + set number relativenumber scrolloff=0 + :%del + setline(1, [ + 'one', + 'very long text '->repeat(12), + 'three', + ]) + exe "normal 2Gzt\<C-E>" + enddef + END + call writefile(lines, 'XSmoothNumber', 'D') + let buf = RunVimInTerminal('-S XSmoothNumber', #{rows: 12, cols: 40}) + + call VerifyScreenDump(buf, 'Test_smooth_number_1', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_number_2', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_number_3', {}) + + call term_sendkeys(buf, ":set cpo-=n\<CR>") + call VerifyScreenDump(buf, 'Test_smooth_number_4', {}) + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smooth_number_5', {}) + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smooth_number_6', {}) + + call term_sendkeys(buf, ":botright split\<CR>gg") + call VerifyScreenDump(buf, 'Test_smooth_number_7', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_number_8', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_number_9', {}) + call term_sendkeys(buf, ":close\<CR>") + + call term_sendkeys(buf, ":call DoRel()\<CR>") + call VerifyScreenDump(buf, 'Test_smooth_number_10', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_smoothscroll_list() + CheckScreendump + + let lines =<< trim END + vim9script + set smoothscroll scrolloff=0 + set list + setline(1, [ + 'one', + 'very long text '->repeat(12), + 'three', + ]) + exe "normal 2Gzt\<C-E>" + END + call writefile(lines, 'XSmoothList', 'D') + let buf = RunVimInTerminal('-S XSmoothList', #{rows: 8, cols: 40}) + + call VerifyScreenDump(buf, 'Test_smooth_list_1', {}) + + call term_sendkeys(buf, ":set listchars+=precedes:#\<CR>") + call VerifyScreenDump(buf, 'Test_smooth_list_2', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_smoothscroll_diff_mode() + CheckScreendump + + let lines =<< trim END + vim9script + var text = 'just some text here' + setline(1, text) + set smoothscroll + diffthis + new + setline(1, text) + set smoothscroll + diffthis + END + call writefile(lines, 'XSmoothDiff', 'D') + let buf = RunVimInTerminal('-S XSmoothDiff', #{rows: 8}) + + call VerifyScreenDump(buf, 'Test_smooth_diff_1', {}) + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smooth_diff_1', {}) + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_diff_1', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_smoothscroll_wrap_scrolloff_zero() + CheckScreendump + + let lines =<< trim END + vim9script + setline(1, ['Line' .. (' with some text'->repeat(7))]->repeat(7)) + set smoothscroll scrolloff=0 + :3 + END + call writefile(lines, 'XSmoothWrap', 'D') + let buf = RunVimInTerminal('-S XSmoothWrap', #{rows: 8, cols: 40}) + + call VerifyScreenDump(buf, 'Test_smooth_wrap_1', {}) + + " moving cursor down - whole bottom line shows + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_smooth_wrap_2', {}) + + call term_sendkeys(buf, "\<C-E>j") + call VerifyScreenDump(buf, 'Test_smooth_wrap_3', {}) + + call term_sendkeys(buf, "G") + call VerifyScreenDump(buf, 'Test_smooth_wrap_4', {}) + + call term_sendkeys(buf, "4\<C-Y>G") + call VerifyScreenDump(buf, 'Test_smooth_wrap_4', {}) + + " moving cursor up right after the <<< marker - no need to show whole line + call term_sendkeys(buf, "2gj3l2k") + call VerifyScreenDump(buf, 'Test_smooth_wrap_5', {}) + + " moving cursor up where the <<< marker is - whole top line shows + call term_sendkeys(buf, "2j02k") + call VerifyScreenDump(buf, 'Test_smooth_wrap_6', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_smoothscroll_wrap_long_line() + CheckScreendump + + let lines =<< trim END + vim9script + setline(1, ['one', 'two', 'Line' .. (' with lots of text'->repeat(30)) .. ' end', 'four']) + set smoothscroll scrolloff=0 + normal 3G10|zt + END + call writefile(lines, 'XSmoothWrap', 'D') + let buf = RunVimInTerminal('-S XSmoothWrap', #{rows: 6, cols: 40}) + call VerifyScreenDump(buf, 'Test_smooth_long_1', {}) + + " scrolling up, cursor moves screen line down + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_long_2', {}) + call term_sendkeys(buf, "5\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_long_3', {}) + + " scrolling down, cursor moves screen line up + call term_sendkeys(buf, "5\<C-Y>") + call VerifyScreenDump(buf, 'Test_smooth_long_4', {}) + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smooth_long_5', {}) + + " 'scrolloff' set to 1, scrolling up, cursor moves screen line down + call term_sendkeys(buf, ":set scrolloff=1\<CR>") + call term_sendkeys(buf, "10|\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_long_6', {}) + + " 'scrolloff' set to 1, scrolling down, cursor moves screen line up + call term_sendkeys(buf, "\<C-E>") + call term_sendkeys(buf, "gjgj") + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smooth_long_7', {}) + + " 'scrolloff' set to 2, scrolling up, cursor moves screen line down + call term_sendkeys(buf, ":set scrolloff=2\<CR>") + call term_sendkeys(buf, "10|\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_long_8', {}) + + " 'scrolloff' set to 2, scrolling down, cursor moves screen line up + call term_sendkeys(buf, "\<C-E>") + call term_sendkeys(buf, "gj") + call term_sendkeys(buf, "\<C-Y>") + call VerifyScreenDump(buf, 'Test_smooth_long_9', {}) + + " 'scrolloff' set to 0, move cursor down one line. + " Cursor should move properly, and since this is a really long line, it will + " be put on top of the screen. + call term_sendkeys(buf, ":set scrolloff=0\<CR>") + call term_sendkeys(buf, "0j") + call VerifyScreenDump(buf, 'Test_smooth_long_10', {}) + + " Test zt/zz/zb that they work properly when a long line is above it + call term_sendkeys(buf, "zt") + call VerifyScreenDump(buf, 'Test_smooth_long_11', {}) + call term_sendkeys(buf, "zz") + call VerifyScreenDump(buf, 'Test_smooth_long_12', {}) + call term_sendkeys(buf, "zb") + call VerifyScreenDump(buf, 'Test_smooth_long_13', {}) + + " Repeat the step and move the cursor down again. + " This time, use a shorter long line that is barely long enough to span more + " than one window. Note that the cursor is at the bottom this time because + " Vim prefers to do so if we are scrolling a few lines only. + call term_sendkeys(buf, ":call setline(1, ['one', 'two', 'Line' .. (' with lots of text'->repeat(10)) .. ' end', 'four'])\<CR>") + " Currently visible lines were replaced, test that the lines and cursor + " are correctly displayed. + call VerifyScreenDump(buf, 'Test_smooth_long_14', {}) + call term_sendkeys(buf, "3Gzt") + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_smooth_long_15', {}) + + " Repeat the step but this time start it when the line is smooth-scrolled by + " one line. This tests that the offset calculation is still correct and + " still end up scrolling down to the next line with cursor at bottom of + " screen. + call term_sendkeys(buf, "3Gzt") + call term_sendkeys(buf, "\<C-E>j") + call VerifyScreenDump(buf, 'Test_smooth_long_16', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_smoothscroll_one_long_line() + CheckScreendump + + let lines =<< trim END + vim9script + setline(1, 'with lots of text '->repeat(7)) + set smoothscroll scrolloff=0 + END + call writefile(lines, 'XSmoothOneLong', 'D') + let buf = RunVimInTerminal('-S XSmoothOneLong', #{rows: 6, cols: 40}) + call VerifyScreenDump(buf, 'Test_smooth_one_long_1', {}) + + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_one_long_2', {}) + + call term_sendkeys(buf, "0") + call VerifyScreenDump(buf, 'Test_smooth_one_long_1', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_smoothscroll_long_line_showbreak() + CheckScreendump + + let lines =<< trim END + vim9script + # a line that spans four screen lines + setline(1, 'with lots of text in one line '->repeat(6)) + set smoothscroll scrolloff=0 showbreak=+++\ + END + call writefile(lines, 'XSmoothLongShowbreak', 'D') + let buf = RunVimInTerminal('-S XSmoothLongShowbreak', #{rows: 6, cols: 40}) + call VerifyScreenDump(buf, 'Test_smooth_long_showbreak_1', {}) + + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_long_showbreak_2', {}) + + call term_sendkeys(buf, "0") + call VerifyScreenDump(buf, 'Test_smooth_long_showbreak_1', {}) + + call StopVimInTerminal(buf) +endfunc + +" Check that 'smoothscroll' marker is drawn over double-width char correctly. +" Run with multiple encodings. +func Test_smoothscroll_marker_over_double_width() + " Run this in a separate Vim instance to avoid messing up. + let after =<< trim [CODE] + scriptencoding utf-8 + call setline(1, 'a'->repeat(&columns) .. '口'->repeat(10)) + setlocal smoothscroll + redraw + exe "norm \<C-E>" + redraw + " Check the chars one by one. Don't check the whole line concatenated. + call assert_equal('<', screenstring(1, 1)) + call assert_equal('<', screenstring(1, 2)) + call assert_equal('<', screenstring(1, 3)) + call assert_equal(' ', screenstring(1, 4)) + call assert_equal('口', screenstring(1, 5)) + call assert_equal('口', screenstring(1, 7)) + call assert_equal('口', screenstring(1, 9)) + call assert_equal('口', screenstring(1, 11)) + call assert_equal('口', screenstring(1, 13)) + call assert_equal('口', screenstring(1, 15)) + call writefile(v:errors, 'Xresult') + qall! + [CODE] + + let encodings = ['utf-8', 'cp932', 'cp936', 'cp949', 'cp950'] + if !has('win32') + let encodings += ['euc-jp'] + endif + if has('nvim') + let encodings = ['utf-8'] + endif + for enc in encodings + let msg = 'enc=' .. enc + if RunVim([], after, $'--clean --cmd "set encoding={enc}"') + call assert_equal([], readfile('Xresult'), msg) + endif + call delete('Xresult') + endfor +endfunc + +" Same as the test above, but check the text actually shown on screen. +" Only run with UTF-8 encoding. +func Test_smoothscroll_marker_over_double_width_dump() + CheckScreendump + + let lines =<< trim END + call setline(1, 'a'->repeat(&columns) .. '口'->repeat(10)) + setlocal smoothscroll + END + call writefile(lines, 'XSmoothMarkerOverDoubleWidth', 'D') + let buf = RunVimInTerminal('-S XSmoothMarkerOverDoubleWidth', #{rows: 6, cols: 40}) + call VerifyScreenDump(buf, 'Test_smooth_marker_over_double_width_1', {}) + + call term_sendkeys(buf, "\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_marker_over_double_width_2', {}) + + call StopVimInTerminal(buf) +endfunc + +func s:check_col_calc(win_col, win_line, buf_col) + call assert_equal(a:win_col, wincol()) + call assert_equal(a:win_line, winline()) + call assert_equal(a:buf_col, col('.')) +endfunc + +" Test that if the current cursor is on a smooth scrolled line, we correctly +" reposition it. Also check that we don't miscalculate the values by checking +" the consistency between wincol() and col('.') as they are calculated +" separately in code. +func Test_smoothscroll_cursor_position() + call NewWindow(10, 20) + setl smoothscroll wrap + call setline(1, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + + call s:check_col_calc(1, 1, 1) + exe "normal \<C-E>" + + " Move down another line to avoid blocking the <<< display + call s:check_col_calc(1, 2, 41) + exe "normal \<C-Y>" + call s:check_col_calc(1, 3, 41) + + " Test "g0/g<Home>" + exe "normal gg\<C-E>" + norm $gkg0 + call s:check_col_calc(1, 2, 21) + + " Test moving the cursor behind the <<< display with 'virtualedit' + set virtualedit=all + exe "normal \<C-E>3lgkh" + call s:check_col_calc(3, 2, 23) + set virtualedit& + + normal gg3l + exe "normal \<C-E>" + + " Move down only 1 line when we are out of the range of the <<< display + call s:check_col_calc(4, 1, 24) + exe "normal \<C-Y>" + call s:check_col_calc(4, 2, 24) + normal ggg$ + exe "normal \<C-E>" + call s:check_col_calc(20, 1, 40) + exe "normal \<C-Y>" + call s:check_col_calc(20, 2, 40) + normal gg + + " Test number, where we have indented lines + setl number + call s:check_col_calc(5, 1, 1) + exe "normal \<C-E>" + + " Move down only 1 line when the <<< display is on the number column + call s:check_col_calc(5, 1, 17) + exe "normal \<C-Y>" + call s:check_col_calc(5, 2, 17) + normal ggg$ + exe "normal \<C-E>" + call s:check_col_calc(20, 1, 32) + exe "normal \<C-Y>" + call s:check_col_calc(20, 2, 32) + normal gg + + setl numberwidth=1 + + " Move down another line when numberwidth is too short to cover the whole + " <<< display + call s:check_col_calc(3, 1, 1) + exe "normal \<C-E>" + call s:check_col_calc(3, 2, 37) + exe "normal \<C-Y>" + call s:check_col_calc(3, 3, 37) + normal ggl + + " Only move 1 line down when we are just past the <<< display + call s:check_col_calc(4, 1, 2) + exe "normal \<C-E>" + call s:check_col_calc(4, 1, 20) + exe "normal \<C-Y>" + call s:check_col_calc(4, 2, 20) + normal gg + setl numberwidth& + + " Test number + showbreak, so test that the additional indentation works + setl number showbreak=+++ + call s:check_col_calc(5, 1, 1) + exe "normal \<C-E>" + call s:check_col_calc(8, 1, 17) + exe "normal \<C-Y>" + call s:check_col_calc(8, 2, 17) + normal gg + + " Test number + cpo+=n mode, where wrapped lines aren't indented + setl number cpo+=n showbreak= + call s:check_col_calc(5, 1, 1) + exe "normal \<C-E>" + call s:check_col_calc(1, 2, 37) + exe "normal \<C-Y>" + call s:check_col_calc(1, 3, 37) + normal gg + + " Test list + listchars "precedes", where there is always 1 overlap + " regardless of number and cpo-=n. + setl number list listchars=precedes:< cpo-=n + call s:check_col_calc(5, 1, 1) + exe "normal 3|\<C-E>h" + call s:check_col_calc(6, 1, 18) + norm h + call s:check_col_calc(5, 2, 17) + normal gg + + bwipe! +endfunc + +func Test_smoothscroll_cursor_scrolloff() + call NewWindow(10, 20) + setl smoothscroll wrap + setl scrolloff=3 + + " 120 chars are 6 screen lines + call setline(1, "abcdefghijklmnopqrstABCDEFGHIJKLMNOPQRSTabcdefghijklmnopqrstABCDEFGHIJKLMNOPQRSTabcdefghijklmnopqrstABCDEFGHIJKLMNOPQRST") + call setline(2, "below") + + call s:check_col_calc(1, 1, 1) + + " CTRL-E shows "<<<DEFG...", cursor move four lines down + exe "normal \<C-E>" + call s:check_col_calc(1, 4, 81) + + " cursor on start of second line, "gk" moves into first line, skipcol doesn't + " change + exe "normal G0gk" + call s:check_col_calc(1, 5, 101) + + " move cursor left one window width worth, scrolls one screen line + exe "normal 20h" + call s:check_col_calc(1, 5, 81) + + " move cursor left one window width worth, scrolls one screen line + exe "normal 20h" + call s:check_col_calc(1, 4, 61) + + " cursor on last line, "gk" should not cause a scroll + set scrolloff=0 + normal G0 + call s:check_col_calc(1, 7, 1) + normal gk + call s:check_col_calc(1, 6, 101) + + bwipe! +endfunc + + +" Test that mouse picking is still accurate when we have smooth scrolled lines +func Test_smoothscroll_mouse_pos() + CheckNotGui + CheckUnix + + let save_mouse = &mouse + "let save_term = &term + "let save_ttymouse = &ttymouse + set mouse=a "term=xterm ttymouse=xterm2 + + call NewWindow(10, 20) + setl smoothscroll wrap + " First line will wrap to 3 physical lines. 2nd/3rd lines are short lines. + call setline(1, ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "line 2", "line 3"]) + + func s:check_mouse_click(row, col, buf_row, buf_col) + call MouseLeftClick(a:row, a:col) + + call assert_equal(a:col, wincol()) + call assert_equal(a:row, winline()) + call assert_equal(a:buf_row, line('.')) + call assert_equal(a:buf_col, col('.')) + endfunc + + " Check that clicking without scroll works first. + call s:check_mouse_click(3, 5, 1, 45) + call s:check_mouse_click(4, 1, 2, 1) + call s:check_mouse_click(4, 6, 2, 6) + call s:check_mouse_click(5, 1, 3, 1) + call s:check_mouse_click(5, 6, 3, 6) + + " Smooth scroll, and checks that this didn't mess up mouse clicking + exe "normal \<C-E>" + call s:check_mouse_click(2, 5, 1, 45) + call s:check_mouse_click(3, 1, 2, 1) + call s:check_mouse_click(3, 6, 2, 6) + call s:check_mouse_click(4, 1, 3, 1) + call s:check_mouse_click(4, 6, 3, 6) + + exe "normal \<C-E>" + call s:check_mouse_click(1, 5, 1, 45) + call s:check_mouse_click(2, 1, 2, 1) + call s:check_mouse_click(2, 6, 2, 6) + call s:check_mouse_click(3, 1, 3, 1) + call s:check_mouse_click(3, 6, 3, 6) + + " Make a new first line 11 physical lines tall so it's taller than window + " height, to test overflow calculations with really long lines wrapping. + normal gg + call setline(1, "12345678901234567890"->repeat(11)) + exe "normal 6\<C-E>" + call s:check_mouse_click(5, 1, 1, 201) + call s:check_mouse_click(6, 1, 2, 1) + call s:check_mouse_click(7, 1, 3, 1) + + let &mouse = save_mouse + "let &term = save_term + "let &ttymouse = save_ttymouse +endfunc + +" this was dividing by zero +func Test_smoothscroll_zero_width() + CheckScreendump + + let lines =<< trim END + winsize 0 0 + vsplit + vsplit + vsplit + vsplit + vsplit + sil norm H + set wrap + set smoothscroll + set number + END + call writefile(lines, 'XSmoothScrollZero', 'D') + let buf = RunVimInTerminal('-u NONE -i NONE -n -m -X -Z -e -s -S XSmoothScrollZero', #{rows: 6, cols: 60, wait_for_ruler: 0}) + call VerifyScreenDump(buf, 'Test_smoothscroll_zero_1', {}) + + call term_sendkeys(buf, ":sil norm \<C-V>\<C-W>\<C-V>\<C-N>\<CR>") + call VerifyScreenDump(buf, 'Test_smoothscroll_zero_2', {}) + + call StopVimInTerminal(buf) +endfunc + +" this was unnecessarily inserting lines +func Test_smoothscroll_ins_lines() + CheckScreendump + + let lines =<< trim END + set wrap + set smoothscroll + set scrolloff=0 + set conceallevel=2 + call setline(1, [ + \'line one' .. 'with lots of text in one line '->repeat(2), + \'line two', + \'line three', + \'line four', + \'line five' + \]) + END + call writefile(lines, 'XSmoothScrollInsLines', 'D') + let buf = RunVimInTerminal('-S XSmoothScrollInsLines', #{rows: 6, cols: 40}) + + call term_sendkeys(buf, "\<C-E>gjgk") + call VerifyScreenDump(buf, 'Test_smooth_ins_lines', {}) + + call StopVimInTerminal(buf) +endfunc + +" this placed the cursor in the command line +func Test_smoothscroll_cursormoved_line() + CheckScreendump + + let lines =<< trim END + set smoothscroll + call setline(1, [ + \'', + \'_'->repeat(&lines * &columns), + \(('_')->repeat(&columns - 2) .. 'xxx')->repeat(2) + \]) + autocmd CursorMoved * eval [line('w0'), line('w$')] + call search('xxx') + END + call writefile(lines, 'XSmoothCursorMovedLine', 'D') + let buf = RunVimInTerminal('-S XSmoothCursorMovedLine', #{rows: 6}) + + call VerifyScreenDump(buf, 'Test_smooth_cursormoved_line', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_smoothscroll_eob() + CheckScreendump + + let lines =<< trim END + set smoothscroll + call setline(1, ['']->repeat(100)) + norm G + END + call writefile(lines, 'XSmoothEob', 'D') + let buf = RunVimInTerminal('-S XSmoothEob', #{rows: 10}) + + " does not scroll halfway when scrolling to end of buffer + call VerifyScreenDump(buf, 'Test_smooth_eob_1', {}) + + " cursor is not placed below window + call term_sendkeys(buf, ":call setline(92, 'a'->repeat(100))\<CR>\<C-B>G") + call VerifyScreenDump(buf, 'Test_smooth_eob_2', {}) + + call StopVimInTerminal(buf) +endfunc + +" skipcol should not reset when doing incremental search on the same word +func Test_smoothscroll_incsearch() + CheckScreendump + + let lines =<< trim END + set smoothscroll number scrolloff=0 incsearch + call setline(1, repeat([''], 20)) + call setline(11, repeat('a', 100)) + call setline(14, 'bbbb') + END + call writefile(lines, 'XSmoothIncsearch', 'D') + let buf = RunVimInTerminal('-S XSmoothIncsearch', #{rows: 8, cols: 40}) + + call term_sendkeys(buf, "/b") + call VerifyScreenDump(buf, 'Test_smooth_incsearch_1', {}) + call term_sendkeys(buf, "b") + call VerifyScreenDump(buf, 'Test_smooth_incsearch_2', {}) + call term_sendkeys(buf, "b") + call VerifyScreenDump(buf, 'Test_smooth_incsearch_3', {}) + call term_sendkeys(buf, "b") + call VerifyScreenDump(buf, 'Test_smooth_incsearch_4', {}) + call term_sendkeys(buf, "\<CR>") + + call StopVimInTerminal(buf) +endfunc + +" Test scrolling multiple lines and stopping at non-zero skipcol. +func Test_smoothscroll_multi_skipcol() + CheckScreendump + + let lines =<< trim END + setlocal cursorline scrolloff=0 smoothscroll + call setline(1, repeat([''], 8)) + call setline(3, repeat('a', 50)) + call setline(4, repeat('a', 50)) + call setline(7, 'bbb') + call setline(8, 'ccc') + redraw + END + call writefile(lines, 'XSmoothMultiSkipcol', 'D') + let buf = RunVimInTerminal('-S XSmoothMultiSkipcol', #{rows: 10, cols: 40}) + call VerifyScreenDump(buf, 'Test_smooth_multi_skipcol_1', {}) + + call term_sendkeys(buf, "3\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_multi_skipcol_2', {}) + + call term_sendkeys(buf, "2\<C-E>") + call VerifyScreenDump(buf, 'Test_smooth_multi_skipcol_3', {}) + + call StopVimInTerminal(buf) +endfunc + +" this was dividing by zero bug in scroll_cursor_bot +func Test_smoothscroll_zero_width_scroll_cursor_bot() + CheckScreendump + + let lines =<< trim END + silent normal yy + silent normal 19p + set cpoptions+=n + vsplit + vertical resize 0 + set foldcolumn=1 + set number + set smoothscroll + silent normal 20G + END + call writefile(lines, 'XSmoothScrollZeroBot', 'D') + let buf = RunVimInTerminal('-u NONE -S XSmoothScrollZeroBot', #{rows: 19}) + call VerifyScreenDump(buf, 'Test_smoothscroll_zero_bot', {}) + + call StopVimInTerminal(buf) +endfunc + +" scroll_cursor_top() should reset skipcol when it changes topline +func Test_smoothscroll_cursor_top() + CheckScreendump + + let lines =<< trim END + set smoothscroll scrolloff=2 + new | 11resize | wincmd j + call setline(1, ['line1', 'line2', 'line3'->repeat(20), 'line4']) + exe "norm G3\<C-E>k" + END + call writefile(lines, 'XSmoothScrollCursorTop', 'D') + let buf = RunVimInTerminal('-u NONE -S XSmoothScrollCursorTop', #{rows: 12, cols:40}) + call VerifyScreenDump(buf, 'Test_smoothscroll_cursor_top', {}) + + call StopVimInTerminal(buf) +endfunc + +" Division by zero, shouldn't crash +func Test_smoothscroll_crash() + CheckScreendump + + let lines =<< trim END + 20 new + vsp + put =repeat('aaaa', 20) + set nu fdc=1 smoothscroll cpo+=n + vert resize 0 + exe "norm! 0\<c-e>" + END + call writefile(lines, 'XSmoothScrollCrash', 'D') + let buf = RunVimInTerminal('-u NONE -S XSmoothScrollCrash', #{rows: 12, cols:40}) + call term_sendkeys(buf, "2\<C-E>\<C-L>") + + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_scrollbind.vim b/test/old/testdir/test_scrollbind.vim new file mode 100644 index 0000000000..f67a559c60 --- /dev/null +++ b/test/old/testdir/test_scrollbind.vim @@ -0,0 +1,272 @@ +" Test for 'scrollbind' causing an unexpected scroll of one of the windows. +func Test_scrollbind() + " We don't want the status line to cause problems: + set laststatus=0 + let totalLines = &lines * 20 + let middle = totalLines / 2 + new | only + for i in range(1, totalLines) + call setline(i, 'LINE ' . i) + endfor + exe string(middle) + normal zt + normal M + aboveleft vert new + for i in range(1, totalLines) + call setline(i, 'line ' . i) + endfor + exe string(middle) + normal zt + normal M + " Execute the following two commands at once to reproduce the problem. + setl scb | wincmd p + setl scb + wincmd w + let topLineLeft = line('w0') + wincmd p + let topLineRight = line('w0') + setl noscrollbind + wincmd p + setl noscrollbind + call assert_equal(0, topLineLeft - topLineRight) +endfunc + +" Test for 'scrollbind' +func Test_scrollbind_opt() + new | only + set noscrollbind + set scrollopt=ver,jump scrolloff=2 nowrap noequalalways splitbelow + + " Insert the text used for the test + append + + +start of window 1 +. line 01 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 01 +. line 02 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 02 +. line 03 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 03 +. line 04 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 04 +. line 05 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 05 +. line 06 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 06 +. line 07 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 07 +. line 08 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 08 +. line 09 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 09 +. line 10 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 10 +. line 11 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 11 +. line 12 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 12 +. line 13 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 13 +. line 14 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 14 +. line 15 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 15 +end of window 1 + + +start of window 2 +. line 01 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 01 +. line 02 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 02 +. line 03 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 03 +. line 04 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 04 +. line 05 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 05 +. line 06 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 06 +. line 07 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 07 +. line 08 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 08 +. line 09 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 09 +. line 10 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 10 +. line 11 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 11 +. line 12 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 12 +. line 13 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 13 +. line 14 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 14 +. line 15 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 15 +. line 16 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 16 +end of window 2 + +. + + " Test using two windows open to one buffer, one extra empty window + split + new + wincmd t + resize 8 + call search('^start of window 1$') + normal zt + set scrollbind + wincmd j + resize 7 + call search('^start of window 2$') + normal zt + set scrollbind + + " -- start of tests -- + " Test scrolling down + normal L5jHyy + wincmd b | normal pr0 + wincmd t | normal Hyy + wincmd b | normal pr1 + wincmd t | normal L6jHyy + wincmd b | normal pr2 + wincmd k | normal Hyy + wincmd b | normal pr3 + + " Test scrolling up + wincmd t | normal H4k + wincmd j | normal H + wincmd t | normal Hyy + wincmd b | normal pr4 + wincmd k | normal Hyy + wincmd b | normal pr5 + wincmd k | normal 3k + wincmd t | normal H + wincmd j | normal Hyy + wincmd b | normal pr6 + wincmd t | normal Hyy + wincmd b | normal pr7 + + " Test horizontal scrolling + set scrollopt+=hor + normal gg"zyyG"zpG + wincmd t | normal 015zly$ + wincmd b | normal p"zpG + wincmd k | normal y$ + wincmd b | normal p"zpG + wincmd k | normal 10jH7zhg0y$ + wincmd b | normal p"zpG + wincmd t | normal Hg0y$ + wincmd b | normal p"zpG + set scrollopt-=hor + + wincmd b + call assert_equal([ + \ '', + \ '0 line 05 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 05', + \ '1 line 05 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 05', + \ '2 line 11 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 11', + \ '3 line 11 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 11', + \ '4 line 06 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 06', + \ '5 line 06 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 06', + \ '6 line 02 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 02', + \ '7 line 02 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 02', + \ '56789ABCDEFGHIJKLMNOPQRSTUVWXYZ 02', + \ 'UTSRQPONMLKJIHGREDCBA9876543210 02', + \ '. line 11 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 11', + \ '. line 11 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 11', + \ ''], getline(1, '$')) + enew! + + " ****** tests using two different buffers ***** + wincmd t | wincmd j | close + wincmd t | set noscrollbind + /start of window 2$/,/^end of window 2$/y + new + wincmd t | wincmd j | normal 4"zpGp + wincmd t + call search('^start of window 1$') + normal zt + set scrollbind + wincmd j + call search('^start of window 2$') + normal zt + set scrollbind + + " -- start of tests -- + " Test scrolling down + normal L5jHyy + wincmd b | normal pr0 + wincmd t | normal Hyy + wincmd b | normal pr1 + wincmd t | normal L6jHyy + wincmd b | normal pr2 + wincmd k | normal Hyy + wincmd b | normal pr3 + + " Test scrolling up + wincmd t | normal H4k + wincmd j | normal H + wincmd t | normal Hyy + wincmd b | normal pr4 + wincmd k | normal Hyy + wincmd b | normal pr5 + wincmd k | normal 3k + wincmd t | normal H + wincmd j | normal Hyy + wincmd b | normal pr6 + wincmd t | normal Hyy + wincmd b | normal pr7 + + " Test horizontal scrolling + set scrollopt+=hor + normal gg"zyyG"zpG + wincmd t | normal 015zly$ + wincmd b | normal p"zpG + wincmd k | normal y$ + wincmd b | normal p"zpG + wincmd k | normal 10jH7zhg0y$ + wincmd b | normal p"zpG + wincmd t | normal Hg0y$ + wincmd b | normal p"zpG + set scrollopt-=hor + + wincmd b + call assert_equal([ + \ '', + \ '0 line 05 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 05', + \ '1 line 05 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 05', + \ '2 line 11 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 11', + \ '3 line 11 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 11', + \ '4 line 06 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 06', + \ '5 line 06 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 06', + \ '6 line 02 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 02', + \ '7 line 02 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 02', + \ '56789ABCDEFGHIJKLMNOPQRSTUVWXYZ 02', + \ 'UTSRQPONMLKJIHGREDCBA9876543210 02', + \ '. line 10 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 10', + \ '. line 10 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 10', + \ ''], getline(1, '$')) + enew! + + " Test 'syncbind' + wincmd t | set noscrollbind | normal ggL + wincmd j | set noscrollbind | normal ggL + set scrollbind + wincmd t | set scrollbind | normal G + wincmd j | normal G + syncbind + normal Hk + wincmd t | normal H + wincmd j | normal Hyy + wincmd b | normal p + wincmd t | normal yy + wincmd b | normal p + wincmd t | set noscrollbind | normal ggL + wincmd j | set noscrollbind + normal ggL + set scrollbind + wincmd t | set scrollbind + wincmd t | normal G + wincmd j | normal G + wincmd t | syncbind | normal Hk + wincmd j | normal H + wincmd t | normal Hyy + wincmd b | normal p + wincmd t | wincmd j | normal yy + wincmd b | normal p + wincmd t | normal H3k + wincmd j | normal H + wincmd t | normal Hyy + wincmd b | normal p + wincmd t | wincmd j | normal yy + wincmd b | normal p + + wincmd b + call assert_equal([ + \ '', + \ '. line 16 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 16', + \ 'start of window 2', + \ 'start of window 2', + \ '. line 16 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 16', + \ '. line 15 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ 15', + \ '. line 12 ZYXWVUTSRQPONMLKJIHGREDCBA9876543210 12', + \ ], getline(1, '$')) + enew! + + new | only! + set scrollbind& scrollopt& scrolloff& wrap& equalalways& splitbelow& +endfunc diff --git a/test/old/testdir/test_search.vim b/test/old/testdir/test_search.vim new file mode 100644 index 0000000000..018ee7ad5a --- /dev/null +++ b/test/old/testdir/test_search.vim @@ -0,0 +1,2134 @@ +" Test for the search command + +source shared.vim +source screendump.vim +source check.vim + +" See test/functional/legacy/search_spec.lua +func Test_search_cmdline() + CheckFunction test_override + CheckOption incsearch + + " need to disable char_avail, + " so that expansion of commandline works + call test_override("char_avail", 1) + new + call setline(1, [' 1', ' 2 these', ' 3 the', ' 4 their', ' 5 there', ' 6 their', ' 7 the', ' 8 them', ' 9 these', ' 10 foobar']) + " Test 1 + " CTRL-N / CTRL-P skips through the previous search history + set noincsearch + :1 + call feedkeys("/foobar\<cr>", 'tx') + call feedkeys("/the\<cr>", 'tx') + call assert_equal('the', @/) + call feedkeys("/thes\<C-P>\<C-P>\<cr>", 'tx') + call assert_equal('foobar', @/) + + " Test 2 + " Ctrl-G goes from one match to the next + " until the end of the buffer + set incsearch nowrapscan + :1 + " first match + call feedkeys("/the\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + :1 + " second match + call feedkeys("/the\<C-G>\<cr>", 'tx') + call assert_equal(' 3 the', getline('.')) + call assert_equal([0, 0, 0, 0], getpos('"')) + :1 + " third match + call feedkeys("/the".repeat("\<C-G>", 2)."\<cr>", 'tx') + call assert_equal(' 4 their', getline('.')) + :1 + " fourth match + call feedkeys("/the".repeat("\<C-G>", 3)."\<cr>", 'tx') + call assert_equal(' 5 there', getline('.')) + :1 + " fifth match + call feedkeys("/the".repeat("\<C-G>", 4)."\<cr>", 'tx') + call assert_equal(' 6 their', getline('.')) + :1 + " sixth match + call feedkeys("/the".repeat("\<C-G>", 5)."\<cr>", 'tx') + call assert_equal(' 7 the', getline('.')) + :1 + " seventh match + call feedkeys("/the".repeat("\<C-G>", 6)."\<cr>", 'tx') + call assert_equal(' 8 them', getline('.')) + :1 + " eighth match + call feedkeys("/the".repeat("\<C-G>", 7)."\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + :1 + " no further match + call feedkeys("/the".repeat("\<C-G>", 8)."\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + call assert_equal([0, 0, 0, 0], getpos('"')) + + " Test 3 + " Ctrl-G goes from one match to the next + " and continues back at the top + set incsearch wrapscan + :1 + " first match + call feedkeys("/the\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + :1 + " second match + call feedkeys("/the\<C-G>\<cr>", 'tx') + call assert_equal(' 3 the', getline('.')) + :1 + " third match + call feedkeys("/the".repeat("\<C-G>", 2)."\<cr>", 'tx') + call assert_equal(' 4 their', getline('.')) + :1 + " fourth match + call feedkeys("/the".repeat("\<C-G>", 3)."\<cr>", 'tx') + call assert_equal(' 5 there', getline('.')) + :1 + " fifth match + call feedkeys("/the".repeat("\<C-G>", 4)."\<cr>", 'tx') + call assert_equal(' 6 their', getline('.')) + :1 + " sixth match + call feedkeys("/the".repeat("\<C-G>", 5)."\<cr>", 'tx') + call assert_equal(' 7 the', getline('.')) + :1 + " seventh match + call feedkeys("/the".repeat("\<C-G>", 6)."\<cr>", 'tx') + call assert_equal(' 8 them', getline('.')) + :1 + " eighth match + call feedkeys("/the".repeat("\<C-G>", 7)."\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + :1 + " back at first match + call feedkeys("/the".repeat("\<C-G>", 8)."\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + + " Test 4 + " CTRL-T goes to the previous match + set incsearch nowrapscan + $ + " first match + call feedkeys("?the\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + $ + " first match + call feedkeys("?the\<C-G>\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + $ + " second match + call feedkeys("?the".repeat("\<C-T>", 1)."\<cr>", 'tx') + call assert_equal(' 8 them', getline('.')) + $ + " last match + call feedkeys("?the".repeat("\<C-T>", 7)."\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + $ + " last match + call feedkeys("?the".repeat("\<C-T>", 8)."\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + + " Test 5 + " CTRL-T goes to the previous match + set incsearch wrapscan + $ + " first match + call feedkeys("?the\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + $ + " first match at the top + call feedkeys("?the\<C-G>\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + $ + " second match + call feedkeys("?the".repeat("\<C-T>", 1)."\<cr>", 'tx') + call assert_equal(' 8 them', getline('.')) + $ + " last match + call feedkeys("?the".repeat("\<C-T>", 7)."\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + $ + " back at the bottom of the buffer + call feedkeys("?the".repeat("\<C-T>", 8)."\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + + " Test 6 + " CTRL-L adds to the search pattern + set incsearch wrapscan + 1 + " first match + call feedkeys("/the\<c-l>\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + 1 + " go to next match of 'thes' + call feedkeys("/the\<c-l>\<C-G>\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + 1 + " wrap around + call feedkeys("/the\<c-l>\<C-G>\<C-G>\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + 1 + " wrap around + set nowrapscan + call feedkeys("/the\<c-l>\<C-G>\<C-G>\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + + " Test 7 + " <bs> remove from match, but stay at current match + set incsearch wrapscan + 1 + " first match + call feedkeys("/thei\<cr>", 'tx') + call assert_equal(' 4 their', getline('.')) + 1 + " delete one char, add another + call feedkeys("/thei\<bs>s\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + 1 + " delete one char, add another, go to previous match, add one char + call feedkeys("/thei\<bs>s\<bs>\<C-T>\<c-l>\<cr>", 'tx') + call assert_equal(' 9 these', getline('.')) + 1 + " delete all chars, start from the beginning again + call feedkeys("/them". repeat("\<bs>",4).'the\>'."\<cr>", 'tx') + call assert_equal(' 3 the', getline('.')) + + " clean up + call test_override("char_avail", 0) + bw! +endfunc + +" See test/functional/legacy/search_spec.lua +func Test_search_cmdline2() + CheckFunction test_override + CheckOption incsearch + + " need to disable char_avail, + " so that expansion of commandline works + call test_override("char_avail", 1) + new + call setline(1, [' 1', ' 2 these', ' 3 the theother']) + " Test 1 + " Ctrl-T goes correctly back and forth + set incsearch + 1 + " first match + call feedkeys("/the\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + 1 + " go to next match (on next line) + call feedkeys("/the\<C-G>\<cr>", 'tx') + call assert_equal(' 3 the theother', getline('.')) + 1 + " go to next match (still on line 3) + call feedkeys("/the\<C-G>\<C-G>\<cr>", 'tx') + call assert_equal(' 3 the theother', getline('.')) + 1 + " go to next match (still on line 3) + call feedkeys("/the\<C-G>\<C-G>\<C-G>\<cr>", 'tx') + call assert_equal(' 3 the theother', getline('.')) + 1 + " go to previous match (on line 3) + call feedkeys("/the\<C-G>\<C-G>\<C-G>\<C-T>\<cr>", 'tx') + call assert_equal(' 3 the theother', getline('.')) + 1 + " go to previous match (on line 3) + call feedkeys("/the\<C-G>\<C-G>\<C-G>\<C-T>\<C-T>\<cr>", 'tx') + call assert_equal(' 3 the theother', getline('.')) + 1 + " go to previous match (on line 2) + call feedkeys("/the\<C-G>\<C-G>\<C-G>\<C-T>\<C-T>\<C-T>\<cr>", 'tx') + call assert_equal(' 2 these', getline('.')) + 1 + " go to previous match (on line 2) + call feedkeys("/the\<C-G>\<C-R>\<C-W>\<cr>", 'tx') + call assert_equal('theother', @/) + + " Test 2: keep the view, + " after deleting a character from the search cmd + call setline(1, [' 1', ' 2 these', ' 3 the', ' 4 their', ' 5 there', ' 6 their', ' 7 the', ' 8 them', ' 9 these', ' 10 foobar']) + resize 5 + 1 + call feedkeys("/foo\<bs>\<cr>", 'tx') + redraw + call assert_equal({'lnum': 10, 'leftcol': 0, 'col': 4, 'topfill': 0, 'topline': 6, 'coladd': 0, 'skipcol': 0, 'curswant': 4}, winsaveview()) + + " remove all history entries + for i in range(11) + call histdel('/') + endfor + + " Test 3: reset the view, + " after deleting all characters from the search cmd + norm! 1gg0 + " unfortunately, neither "/foo\<c-w>\<cr>", nor "/foo\<bs>\<bs>\<bs>\<cr>", + " nor "/foo\<c-u>\<cr>" works to delete the commandline. + " In that case Vim should return "E35 no previous regular expression", + " but it looks like Vim still sees /foo and therefore the test fails. + " Therefore, disabling this test + "call assert_fails(feedkeys("/foo\<c-w>\<cr>", 'tx'), 'E35') + "call assert_equal({'lnum': 1, 'leftcol': 0, 'col': 0, 'topfill': 0, 'topline': 1, 'coladd': 0, 'skipcol': 0, 'curswant': 0}, winsaveview()) + + " clean up + set noincsearch + call test_override("char_avail", 0) + bw! +endfunc + +func Test_use_sub_pat() + split + let @/ = '' + func X() + s/^/a/ + / + endfunc + call X() + bwipe! +endfunc + +func Test_searchpair() + new + call setline(1, ['other code', 'here [', ' [', ' " cursor here', ' ]]']) + + " should not give an error for using "42" + call assert_equal(0, searchpair('a', 'b', 'c', '', 42)) + + 4 + call assert_equal(3, searchpair('\[', '', ']', 'bW')) + call assert_equal([0, 3, 2, 0], getpos('.')) + 4 + call assert_equal(2, searchpair('\[', '', ']', 'bWr')) + call assert_equal([0, 2, 6, 0], getpos('.')) + 4 + call assert_equal(1, searchpair('\[', '', ']', 'bWm')) + call assert_equal([0, 3, 2, 0], getpos('.')) + 4|norm ^ + call assert_equal(5, searchpair('\[', '', ']', 'Wn')) + call assert_equal([0, 4, 2, 0], getpos('.')) + 4 + call assert_equal(2, searchpair('\[', '', ']', 'bW', + \ 'getline(".") =~ "^\\s*\["')) + call assert_equal([0, 2, 6, 0], getpos('.')) + set nomagic + 4 + call assert_equal(3, searchpair('\[', '', ']', 'bW')) + call assert_equal([0, 3, 2, 0], getpos('.')) + set magic + 4|norm ^ + call assert_equal(0, searchpair('{', '', '}', 'bW')) + call assert_equal([0, 4, 2, 0], getpos('.')) + + %d + call setline(1, ['if 1', ' if 2', ' else', ' endif 2', 'endif 1']) + + /\<if 1 + call assert_equal(5, searchpair('\<if\>', '\<else\>', '\<endif\>', 'W')) + call assert_equal([0, 5, 1, 0], getpos('.')) + /\<if 2 + call assert_equal(3, searchpair('\<if\>', '\<else\>', '\<endif\>', 'W')) + call assert_equal([0, 3, 3, 0], getpos('.')) + + q! +endfunc + +func Test_searchpairpos() + new + call setline(1, ['other code', 'here [', ' [', ' " cursor here', ' ]]']) + + 4 + call assert_equal([3, 2], searchpairpos('\[', '', ']', 'bW')) + call assert_equal([0, 3, 2, 0], getpos('.')) + 4 + call assert_equal([2, 6], searchpairpos('\[', '', ']', 'bWr')) + call assert_equal([0, 2, 6, 0], getpos('.')) + 4|norm ^ + call assert_equal([5, 2], searchpairpos('\[', '', ']', 'Wn')) + call assert_equal([0, 4, 2, 0], getpos('.')) + 4 + call assert_equal([2, 6], searchpairpos('\[', '', ']', 'bW', + \ 'getline(".") =~ "^\\s*\["')) + call assert_equal([0, 2, 6, 0], getpos('.')) + 4 + call assert_equal([2, 6], searchpairpos('\[', '', ']', 'bWr')) + call assert_equal([0, 2, 6, 0], getpos('.')) + set nomagic + 4 + call assert_equal([3, 2], searchpairpos('\[', '', ']', 'bW')) + call assert_equal([0, 3, 2, 0], getpos('.')) + set magic + 4|norm ^ + call assert_equal([0, 0], searchpairpos('{', '', '}', 'bW')) + call assert_equal([0, 4, 2, 0], getpos('.')) + + %d + call setline(1, ['if 1', ' if 2', ' else', ' endif 2', 'endif 1']) + /\<if 1 + call assert_equal([5, 1], searchpairpos('\<if\>', '\<else\>', '\<endif\>', 'W')) + call assert_equal([0, 5, 1, 0], getpos('.')) + /\<if 2 + call assert_equal([3, 3], searchpairpos('\<if\>', '\<else\>', '\<endif\>', 'W')) + call assert_equal([0, 3, 3, 0], getpos('.')) + + q! +endfunc + +func Test_searchpair_errors() + call assert_fails("call searchpair([0], 'middle', 'end', 'bW', 'skip', 99, 100)", 'E730: Using a List as a String') + call assert_fails("call searchpair('start', {-> 0}, 'end', 'bW', 'skip', 99, 100)", 'E729: Using a Funcref as a String') + call assert_fails("call searchpair('start', 'middle', {'one': 1}, 'bW', 'skip', 99, 100)", 'E731: Using a Dictionary as a String') + call assert_fails("call searchpair('start', 'middle', 'end', 'flags', 'skip', 99, 100)", 'E475: Invalid argument: flags') + call assert_fails("call searchpair('start', 'middle', 'end', 'bW', 'func', -99, 100)", 'E475: Invalid argument: -99') + call assert_fails("call searchpair('start', 'middle', 'end', 'bW', 'func', 99, -100)", 'E475: Invalid argument: -100') + call assert_fails("call searchpair('start', 'middle', 'end', 'e')", 'E475: Invalid argument: e') + call assert_fails("call searchpair('start', 'middle', 'end', 'sn')", 'E475: Invalid argument: sn') +endfunc + +func Test_searchpairpos_errors() + call assert_fails("call searchpairpos([0], 'middle', 'end', 'bW', 'skip', 99, 100)", 'E730: Using a List as a String') + call assert_fails("call searchpairpos('start', {-> 0}, 'end', 'bW', 'skip', 99, 100)", 'E729: Using a Funcref as a String') + call assert_fails("call searchpairpos('start', 'middle', {'one': 1}, 'bW', 'skip', 99, 100)", 'E731: Using a Dictionary as a String') + call assert_fails("call searchpairpos('start', 'middle', 'end', 'flags', 'skip', 99, 100)", 'E475: Invalid argument: flags') + call assert_fails("call searchpairpos('start', 'middle', 'end', 'bW', 'func', -99, 100)", 'E475: Invalid argument: -99') + call assert_fails("call searchpairpos('start', 'middle', 'end', 'bW', 'func', 99, -100)", 'E475: Invalid argument: -100') + call assert_fails("call searchpairpos('start', 'middle', 'end', 'e')", 'E475: Invalid argument: e') + call assert_fails("call searchpairpos('start', 'middle', 'end', 'sn')", 'E475: Invalid argument: sn') +endfunc + +func Test_searchpair_skip() + func Zero() + return 0 + endfunc + func Partial(x) + return a:x + endfunc + new + call setline(1, ['{', 'foo', 'foo', 'foo', '}']) + 3 | call assert_equal(1, searchpair('{', '', '}', 'bWn', '')) + 3 | call assert_equal(1, searchpair('{', '', '}', 'bWn', '0')) + 3 | call assert_equal(1, searchpair('{', '', '}', 'bWn', {-> 0})) + 3 | call assert_equal(1, searchpair('{', '', '}', 'bWn', function('Zero'))) + 3 | call assert_equal(1, searchpair('{', '', '}', 'bWn', function('Partial', [0]))) + bw! +endfunc + +func Test_searchpair_leak() + new + call setline(1, 'if one else another endif') + + " The error in the skip expression caused memory to leak. + call assert_fails("call searchpair('\\<if\\>', '\\<else\\>', '\\<endif\\>', '', '\"foo\" 2')", 'E15:') + + bwipe! +endfunc + +func Test_searchc() + " These commands used to cause memory overflow in searchc(). + new + norm ixx + exe "norm 0t\u93cf" + bw! +endfunc + +func Cmdline3_prep() + CheckFunction test_override + " need to disable char_avail, + " so that expansion of commandline works + call test_override("char_avail", 1) + new + call setline(1, [' 1', ' 2 the~e', ' 3 the theother']) + set incsearch +endfunc + +func Incsearch_cleanup() + CheckFunction test_override + set noincsearch + call test_override("char_avail", 0) + bw! +endfunc + +func Test_search_cmdline3() + CheckOption incsearch + + call Cmdline3_prep() + 1 + " first match + call feedkeys("/the\<c-l>\<cr>", 'tx') + call assert_equal(' 2 the~e', getline('.')) + + call Incsearch_cleanup() +endfunc + +func Test_search_cmdline3s() + CheckOption incsearch + + call Cmdline3_prep() + 1 + call feedkeys(":%s/the\<c-l>/xxx\<cr>", 'tx') + call assert_equal(' 2 xxxe', getline('.')) + undo + call feedkeys(":%subs/the\<c-l>/xxx\<cr>", 'tx') + call assert_equal(' 2 xxxe', getline('.')) + undo + call feedkeys(":%substitute/the\<c-l>/xxx\<cr>", 'tx') + call assert_equal(' 2 xxxe', getline('.')) + undo + call feedkeys(":%smagic/the.e/xxx\<cr>", 'tx') + call assert_equal(' 2 xxx', getline('.')) + undo + call assert_fails(":%snomagic/the.e/xxx\<cr>", 'E486') + " + call feedkeys(":%snomagic/the\\.e/xxx\<cr>", 'tx') + call assert_equal(' 2 xxx', getline('.')) + + call Incsearch_cleanup() +endfunc + +func Test_search_cmdline3g() + CheckOption incsearch + + call Cmdline3_prep() + 1 + call feedkeys(":g/the\<c-l>/d\<cr>", 'tx') + call assert_equal(' 3 the theother', getline(2)) + undo + call feedkeys(":global/the\<c-l>/d\<cr>", 'tx') + call assert_equal(' 3 the theother', getline(2)) + undo + call feedkeys(":g!/the\<c-l>/d\<cr>", 'tx') + call assert_equal(1, line('$')) + call assert_equal(' 2 the~e', getline(1)) + undo + call feedkeys(":global!/the\<c-l>/d\<cr>", 'tx') + call assert_equal(1, line('$')) + call assert_equal(' 2 the~e', getline(1)) + + call Incsearch_cleanup() +endfunc + +func Test_search_cmdline3v() + CheckOption incsearch + + call Cmdline3_prep() + 1 + call feedkeys(":v/the\<c-l>/d\<cr>", 'tx') + call assert_equal(1, line('$')) + call assert_equal(' 2 the~e', getline(1)) + undo + call feedkeys(":vglobal/the\<c-l>/d\<cr>", 'tx') + call assert_equal(1, line('$')) + call assert_equal(' 2 the~e', getline(1)) + + call Incsearch_cleanup() +endfunc + +" See test/functional/legacy/search_spec.lua +func Test_search_cmdline4() + CheckFunction test_override + CheckOption incsearch + + " need to disable char_avail, + " so that expansion of commandline works + call test_override("char_avail", 1) + new + call setline(1, [' 1 the first', ' 2 the second', ' 3 the third']) + set incsearch + $ + call feedkeys("?the\<c-g>\<cr>", 'tx') + call assert_equal(' 3 the third', getline('.')) + $ + call feedkeys("?the\<c-g>\<c-g>\<cr>", 'tx') + call assert_equal(' 1 the first', getline('.')) + $ + call feedkeys("?the\<c-g>\<c-g>\<c-g>\<cr>", 'tx') + call assert_equal(' 2 the second', getline('.')) + $ + call feedkeys("?the\<c-t>\<cr>", 'tx') + call assert_equal(' 1 the first', getline('.')) + $ + call feedkeys("?the\<c-t>\<c-t>\<cr>", 'tx') + call assert_equal(' 3 the third', getline('.')) + $ + call feedkeys("?the\<c-t>\<c-t>\<c-t>\<cr>", 'tx') + call assert_equal(' 2 the second', getline('.')) + " clean up + set noincsearch + call test_override("char_avail", 0) + bw! +endfunc + +func Test_search_cmdline5() + CheckOption incsearch + + " Do not call test_override("char_avail", 1) so that <C-g> and <C-t> work + " regardless char_avail. + new + call setline(1, [' 1 the first', ' 2 the second', ' 3 the third', '']) + set incsearch + 1 + call feedkeys("/the\<c-g>\<c-g>\<cr>", 'tx') + call assert_equal(' 3 the third', getline('.')) + $ + call feedkeys("?the\<c-t>\<c-t>\<c-t>\<cr>", 'tx') + call assert_equal(' 1 the first', getline('.')) + " clean up + set noincsearch + bw! +endfunc + +func Test_search_cmdline6() + " Test that consecutive matches + " are caught by <c-g>/<c-t> + CheckFunction test_override + CheckOption incsearch + + " need to disable char_avail, + " so that expansion of commandline works + call test_override("char_avail", 1) + new + call setline(1, [' bbvimb', '']) + set incsearch + " first match + norm! gg0 + call feedkeys("/b\<cr>", 'tx') + call assert_equal([0,1,2,0], getpos('.')) + " second match + norm! gg0 + call feedkeys("/b\<c-g>\<cr>", 'tx') + call assert_equal([0,1,3,0], getpos('.')) + " third match + norm! gg0 + call feedkeys("/b\<c-g>\<c-g>\<cr>", 'tx') + call assert_equal([0,1,7,0], getpos('.')) + " first match again + norm! gg0 + call feedkeys("/b\<c-g>\<c-g>\<c-g>\<cr>", 'tx') + call assert_equal([0,1,2,0], getpos('.')) + set nowrapscan + " last match + norm! gg0 + call feedkeys("/b\<c-g>\<c-g>\<c-g>\<cr>", 'tx') + call assert_equal([0,1,7,0], getpos('.')) + " clean up + set wrapscan&vim + set noincsearch + call test_override("char_avail", 0) + bw! +endfunc + +func Test_search_cmdline7() + CheckFunction test_override + " Test that pressing <c-g> in an empty command line + " does not move the cursor + if !exists('+incsearch') + return + endif + " need to disable char_avail, + " so that expansion of commandline works + call test_override("char_avail", 1) + new + let @/ = 'b' + call setline(1, [' bbvimb', '']) + set incsearch + " first match + norm! gg0 + " moves to next match of previous search pattern, just like /<cr> + call feedkeys("/\<c-g>\<cr>", 'tx') + call assert_equal([0,1,2,0], getpos('.')) + " moves to next match of previous search pattern, just like /<cr> + call feedkeys("/\<cr>", 'tx') + call assert_equal([0,1,3,0], getpos('.')) + " moves to next match of previous search pattern, just like /<cr> + call feedkeys("/\<c-t>\<cr>", 'tx') + call assert_equal([0,1,7,0], getpos('.')) + + " using an offset uses the last search pattern + call cursor(1, 1) + call setline(1, ['1 bbvimb', ' 2 bbvimb']) + let @/ = 'b' + call feedkeys("//e\<c-g>\<cr>", 'tx') + call assert_equal('1 bbvimb', getline('.')) + call assert_equal(4, col('.')) + + set noincsearch + call test_override("char_avail", 0) + bw! +endfunc + +func Test_search_cmdline8() + " Highlighting is cleared in all windows + " since hls applies to all windows + CheckOption incsearch + CheckFeature terminal + CheckNotGui + if has("win32") + throw "Skipped: Bug with sending <ESC> to terminal window not fixed yet" + endif + + let h = winheight(0) + if h < 3 + return + endif + " Prepare buffer text + let lines = ['abb vim vim vi', 'vimvivim'] + call writefile(lines, 'Xsearch.txt') + let buf = term_start([GetVimProg(), '--clean', '-c', 'set noswapfile', 'Xsearch.txt'], {'term_rows': 3}) + + call WaitForAssert({-> assert_equal(lines, [term_getline(buf, 1), term_getline(buf, 2)])}) + + call term_sendkeys(buf, ":set incsearch hlsearch\<cr>") + call term_sendkeys(buf, ":14vsp\<cr>") + call term_sendkeys(buf, "/vim\<cr>") + call term_sendkeys(buf, "/b\<esc>") + call term_sendkeys(buf, "gg0") + call TermWait(buf, 250) + let screen_line = term_scrape(buf, 1) + let [a0,a1,a2,a3] = [screen_line[3].attr, screen_line[4].attr, + \ screen_line[18].attr, screen_line[19].attr] + call assert_notequal(a0, a1) + call assert_notequal(a0, a3) + call assert_notequal(a1, a2) + call assert_equal(a0, a2) + call assert_equal(a1, a3) + " clean up + call delete('Xsearch.txt') + + bwipe! +endfunc + +" Tests for regexp with various magic settings +func Run_search_regexp_magic_opt() + put ='1 a aa abb abbccc' + exe 'normal! /a*b\{2}c\+/e' . "\<CR>" + call assert_equal([0, 2, 17, 0], getpos('.')) + + put ='2 d dd dee deefff' + exe 'normal! /\Md\*e\{2}f\+/e' . "\<CR>" + call assert_equal([0, 3, 17, 0], getpos('.')) + + set nomagic + put ='3 g gg ghh ghhiii' + exe 'normal! /g\*h\{2}i\+/e' . "\<CR>" + call assert_equal([0, 4, 17, 0], getpos('.')) + + put ='4 j jj jkk jkklll' + exe 'normal! /\mj*k\{2}l\+/e' . "\<CR>" + call assert_equal([0, 5, 17, 0], getpos('.')) + + put ='5 m mm mnn mnnooo' + exe 'normal! /\vm*n{2}o+/e' . "\<CR>" + call assert_equal([0, 6, 17, 0], getpos('.')) + + put ='6 x ^aa$ x' + exe 'normal! /\V^aa$' . "\<CR>" + call assert_equal([0, 7, 5, 0], getpos('.')) + + set magic + put ='7 (a)(b) abbaa' + exe 'normal! /\v(a)(b)\2\1\1/e' . "\<CR>" + call assert_equal([0, 8, 14, 0], getpos('.')) + + put ='8 axx [ab]xx' + exe 'normal! /\V[ab]\(\[xy]\)\1' . "\<CR>" + call assert_equal([0, 9, 7, 0], getpos('.')) + + %d +endfunc + +func Test_search_regexp() + enew! + + set regexpengine=1 + call Run_search_regexp_magic_opt() + set regexpengine=2 + call Run_search_regexp_magic_opt() + set regexpengine& + + set undolevels=100 + put ='9 foobar' + put ='' + exe "normal! a\<C-G>u\<Esc>" + normal G + exe 'normal! dv?bar?' . "\<CR>" + call assert_equal('9 foo', getline('.')) + call assert_equal([0, 2, 5, 0], getpos('.')) + call assert_equal(2, line('$')) + normal u + call assert_equal('9 foobar', getline('.')) + call assert_equal([0, 2, 6, 0], getpos('.')) + call assert_equal(3, line('$')) + + set undolevels& + enew! +endfunc + +func Test_search_cmdline_incsearch_highlight() + CheckFunction test_override + CheckOption incsearch + + set incsearch hlsearch + " need to disable char_avail, + " so that expansion of commandline works + call test_override("char_avail", 1) + new + call setline(1, ['aaa 1 the first', ' 2 the second', ' 3 the third']) + + 1 + call feedkeys("/second\<cr>", 'tx') + call assert_equal('second', @/) + call assert_equal(' 2 the second', getline('.')) + + " Canceling search won't change @/ + 1 + let @/ = 'last pattern' + call feedkeys("/third\<C-c>", 'tx') + call assert_equal('last pattern', @/) + call feedkeys("/third\<Esc>", 'tx') + call assert_equal('last pattern', @/) + call feedkeys("/3\<bs>\<bs>", 'tx') + call assert_equal('last pattern', @/) + call feedkeys("/third\<c-g>\<c-t>\<Esc>", 'tx') + call assert_equal('last pattern', @/) + + " clean up + set noincsearch nohlsearch + bw! +endfunc + +func Test_search_cmdline_incsearch_highlight_attr() + CheckOption incsearch + CheckFeature terminal + CheckNotGui + + let h = winheight(0) + if h < 3 + return + endif + + " Prepare buffer text + let lines = ['abb vim vim vi', 'vimvivim'] + call writefile(lines, 'Xsearch.txt') + let buf = term_start([GetVimProg(), '--clean', '-c', 'set noswapfile', 'Xsearch.txt'], {'term_rows': 3}) + + call WaitForAssert({-> assert_equal(lines, [term_getline(buf, 1), term_getline(buf, 2)])}) + " wait for vim to complete initialization + call TermWait(buf) + + " Get attr of normal(a0), incsearch(a1), hlsearch(a2) highlight + call term_sendkeys(buf, ":set incsearch hlsearch\<cr>") + call term_sendkeys(buf, '/b') + call TermWait(buf, 100) + let screen_line1 = term_scrape(buf, 1) + call assert_true(len(screen_line1) > 2) + " a0: attr_normal + let a0 = screen_line1[0].attr + " a1: attr_incsearch + let a1 = screen_line1[1].attr + " a2: attr_hlsearch + let a2 = screen_line1[2].attr + call assert_notequal(a0, a1) + call assert_notequal(a0, a2) + call assert_notequal(a1, a2) + call term_sendkeys(buf, "\<cr>gg0") + + " Test incremental highlight search + call term_sendkeys(buf, "/vim") + call TermWait(buf, 100) + " Buffer: + " abb vim vim vi + " vimvivim + " Search: /vim + let attr_line1 = [a0,a0,a0,a0,a1,a1,a1,a0,a2,a2,a2,a0,a0,a0] + let attr_line2 = [a2,a2,a2,a0,a0,a2,a2,a2] + call assert_equal(attr_line1, map(term_scrape(buf, 1)[:len(attr_line1)-1], 'v:val.attr')) + call assert_equal(attr_line2, map(term_scrape(buf, 2)[:len(attr_line2)-1], 'v:val.attr')) + + " Test <C-g> + call term_sendkeys(buf, "\<C-g>\<C-g>") + call TermWait(buf, 100) + let attr_line1 = [a0,a0,a0,a0,a2,a2,a2,a0,a2,a2,a2,a0,a0,a0] + let attr_line2 = [a1,a1,a1,a0,a0,a2,a2,a2] + call assert_equal(attr_line1, map(term_scrape(buf, 1)[:len(attr_line1)-1], 'v:val.attr')) + call assert_equal(attr_line2, map(term_scrape(buf, 2)[:len(attr_line2)-1], 'v:val.attr')) + + " Test <C-t> + call term_sendkeys(buf, "\<C-t>") + call TermWait(buf, 100) + let attr_line1 = [a0,a0,a0,a0,a2,a2,a2,a0,a1,a1,a1,a0,a0,a0] + let attr_line2 = [a2,a2,a2,a0,a0,a2,a2,a2] + call assert_equal(attr_line1, map(term_scrape(buf, 1)[:len(attr_line1)-1], 'v:val.attr')) + call assert_equal(attr_line2, map(term_scrape(buf, 2)[:len(attr_line2)-1], 'v:val.attr')) + + " Type Enter and a1(incsearch highlight) should become a2(hlsearch highlight) + call term_sendkeys(buf, "\<cr>") + call TermWait(buf, 100) + let attr_line1 = [a0,a0,a0,a0,a2,a2,a2,a0,a2,a2,a2,a0,a0,a0] + let attr_line2 = [a2,a2,a2,a0,a0,a2,a2,a2] + call assert_equal(attr_line1, map(term_scrape(buf, 1)[:len(attr_line1)-1], 'v:val.attr')) + call assert_equal(attr_line2, map(term_scrape(buf, 2)[:len(attr_line2)-1], 'v:val.attr')) + + " Test nohlsearch. a2(hlsearch highlight) should become a0(normal highlight) + call term_sendkeys(buf, ":1\<cr>") + call term_sendkeys(buf, ":set nohlsearch\<cr>") + call term_sendkeys(buf, "/vim") + call TermWait(buf, 100) + let attr_line1 = [a0,a0,a0,a0,a1,a1,a1,a0,a0,a0,a0,a0,a0,a0] + let attr_line2 = [a0,a0,a0,a0,a0,a0,a0,a0] + call assert_equal(attr_line1, map(term_scrape(buf, 1)[:len(attr_line1)-1], 'v:val.attr')) + call assert_equal(attr_line2, map(term_scrape(buf, 2)[:len(attr_line2)-1], 'v:val.attr')) + call delete('Xsearch.txt') + + call delete('Xsearch.txt') + bwipe! +endfunc + +func Test_incsearch_cmdline_modifier() + CheckFunction test_override + CheckOption incsearch + + call test_override("char_avail", 1) + new + call setline(1, ['foo']) + set incsearch + " Test that error E14 does not occur in parsing command modifier. + call feedkeys("V:tab", 'tx') + + call Incsearch_cleanup() +endfunc + +func Test_incsearch_scrolling() + CheckRunVimInTerminal + call assert_equal(0, &scrolloff) + call writefile([ + \ 'let dots = repeat(".", 120)', + \ 'set incsearch cmdheight=2 scrolloff=0', + \ 'call setline(1, [dots, dots, dots, "", "target", dots, dots])', + \ 'normal gg', + \ 'redraw', + \ ], 'Xscript') + let buf = RunVimInTerminal('-S Xscript', {'rows': 9, 'cols': 70}) + " Need to send one key at a time to force a redraw + call term_sendkeys(buf, '/') + sleep 100m + call term_sendkeys(buf, 't') + sleep 100m + call term_sendkeys(buf, 'a') + sleep 100m + call term_sendkeys(buf, 'r') + sleep 100m + call term_sendkeys(buf, 'g') + call VerifyScreenDump(buf, 'Test_incsearch_scrolling_01', {}) + + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) + call delete('Xscript') +endfunc + +func Test_incsearch_search_dump() + CheckOption incsearch + CheckScreendump + + call writefile([ + \ 'set incsearch hlsearch scrolloff=0', + \ 'for n in range(1, 8)', + \ ' call setline(n, "foo " . n)', + \ 'endfor', + \ '3', + \ ], 'Xis_search_script') + let buf = RunVimInTerminal('-S Xis_search_script', {'rows': 9, 'cols': 70}) + " Give Vim a chance to redraw to get rid of the spaces in line 2 caused by + " the 'ambiwidth' check. + sleep 100m + + " Need to send one key at a time to force a redraw. + call term_sendkeys(buf, '/fo') + call VerifyScreenDump(buf, 'Test_incsearch_search_01', {}) + call term_sendkeys(buf, "\<Esc>") + sleep 100m + + call term_sendkeys(buf, '/\v') + call VerifyScreenDump(buf, 'Test_incsearch_search_02', {}) + call term_sendkeys(buf, "\<Esc>") + + call StopVimInTerminal(buf) + call delete('Xis_search_script') +endfunc + +func Test_hlsearch_dump() + CheckOption hlsearch + CheckScreendump + + call writefile([ + \ 'set hlsearch cursorline', + \ 'call setline(1, ["xxx", "xxx", "xxx"])', + \ '/.*', + \ '2', + \ ], 'Xhlsearch_script') + let buf = RunVimInTerminal('-S Xhlsearch_script', {'rows': 6, 'cols': 50}) + call VerifyScreenDump(buf, 'Test_hlsearch_1', {}) + + call term_sendkeys(buf, "/\\_.*\<CR>") + call VerifyScreenDump(buf, 'Test_hlsearch_2', {}) + + call StopVimInTerminal(buf) + call delete('Xhlsearch_script') +endfunc + +func Test_hlsearch_and_visual() + CheckOption hlsearch + CheckScreendump + + call writefile([ + \ 'set hlsearch', + \ 'call setline(1, repeat(["xxx yyy zzz"], 3))', + \ 'hi Search cterm=bold', + \ '/yyy', + \ 'call cursor(1, 6)', + \ ], 'Xhlvisual_script') + let buf = RunVimInTerminal('-S Xhlvisual_script', {'rows': 6, 'cols': 40}) + call term_sendkeys(buf, "vjj") + call VerifyScreenDump(buf, 'Test_hlsearch_visual_1', {}) + call term_sendkeys(buf, "\<Esc>") + + call StopVimInTerminal(buf) + call delete('Xhlvisual_script') +endfunc + +func Test_hlsearch_block_visual_match() + CheckScreendump + + let lines =<< trim END + set hlsearch + call setline(1, ['aa', 'bbbb', 'cccccc']) + END + call writefile(lines, 'Xhlsearch_block') + let buf = RunVimInTerminal('-S Xhlsearch_block', {'rows': 9, 'cols': 60}) + + call term_sendkeys(buf, "G\<C-V>$kk\<Esc>") + sleep 100m + call term_sendkeys(buf, "/\\%V\<CR>") + sleep 100m + call VerifyScreenDump(buf, 'Test_hlsearch_block_visual_match', {}) + + call StopVimInTerminal(buf) + call delete('Xhlsearch_block') +endfunc + +func Test_incsearch_substitute() + CheckFunction test_override + CheckOption incsearch + + call test_override("char_avail", 1) + new + set incsearch + for n in range(1, 10) + call setline(n, 'foo ' . n) + endfor + 4 + call feedkeys(":.,.+2s/foo\<BS>o\<BS>o/xxx\<cr>", 'tx') + call assert_equal('foo 3', getline(3)) + call assert_equal('xxx 4', getline(4)) + call assert_equal('xxx 5', getline(5)) + call assert_equal('xxx 6', getline(6)) + call assert_equal('foo 7', getline(7)) + + call Incsearch_cleanup() +endfunc + +func Test_incsearch_substitute_long_line() + CheckFunction test_override + new + call test_override("char_avail", 1) + set incsearch + + call repeat('x', 100000)->setline(1) + call feedkeys(':s/\%c', 'xt') + redraw + call feedkeys("\<Esc>", 'xt') + + call Incsearch_cleanup() + bwipe! +endfunc + +func Test_hlsearch_cursearch() + CheckScreendump + + let lines =<< trim END + set hlsearch scrolloff=0 + call setline(1, ['one', 'foo', 'bar', 'baz', 'foo the foo and foo', 'bar']) + hi Search ctermbg=yellow + hi CurSearch ctermbg=blue + END + call writefile(lines, 'Xhlsearch_cursearch') + let buf = RunVimInTerminal('-S Xhlsearch_cursearch', {'rows': 9, 'cols': 60}) + + call term_sendkeys(buf, "gg/foo\<CR>") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_single_line_1', {}) + + call term_sendkeys(buf, "n") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_single_line_2', {}) + + call term_sendkeys(buf, "n") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_single_line_2a', {}) + + call term_sendkeys(buf, "n") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_single_line_2b', {}) + + call term_sendkeys(buf, ":call setline(5, 'foo')\<CR>") + call term_sendkeys(buf, "0?\<CR>") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_single_line_3', {}) + + call term_sendkeys(buf, "gg/foo\\nbar\<CR>") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_multiple_line_1', {}) + + call term_sendkeys(buf, ":call setline(1, ['---', 'abcdefg', 'hijkl', '---', 'abcdefg', 'hijkl'])\<CR>") + call term_sendkeys(buf, "gg/efg\\nhij\<CR>") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_multiple_line_2', {}) + call term_sendkeys(buf, "h\<C-L>") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_multiple_line_3', {}) + call term_sendkeys(buf, "j\<C-L>") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_multiple_line_4', {}) + call term_sendkeys(buf, "h\<C-L>") + call VerifyScreenDump(buf, 'Test_hlsearch_cursearch_multiple_line_5', {}) + + call StopVimInTerminal(buf) + call delete('Xhlsearch_cursearch') +endfunc + +" Similar to Test_incsearch_substitute() but with a screendump halfway. +func Test_incsearch_substitute_dump() + CheckOption incsearch + CheckScreendump + + call writefile([ + \ 'set incsearch hlsearch scrolloff=0', + \ 'for n in range(1, 10)', + \ ' call setline(n, "foo " . n)', + \ 'endfor', + \ 'call setline(11, "bar 11")', + \ '3', + \ ], 'Xis_subst_script') + let buf = RunVimInTerminal('-S Xis_subst_script', {'rows': 9, 'cols': 70}) + " Give Vim a chance to redraw to get rid of the spaces in line 2 caused by + " the 'ambiwidth' check. + sleep 100m + + " Need to send one key at a time to force a redraw. + " Select three lines at the cursor with typed pattern. + call term_sendkeys(buf, ':.,.+2s/') + sleep 100m + call term_sendkeys(buf, 'f') + sleep 100m + call term_sendkeys(buf, 'o') + sleep 100m + call term_sendkeys(buf, 'o') + call VerifyScreenDump(buf, 'Test_incsearch_substitute_01', {}) + call term_sendkeys(buf, "\<Esc>") + + " Select three lines at the cursor using previous pattern. + call term_sendkeys(buf, "/foo\<CR>") + sleep 100m + call term_sendkeys(buf, ':.,.+2s//') + call VerifyScreenDump(buf, 'Test_incsearch_substitute_02', {}) + + " Deleting last slash should remove the match. + call term_sendkeys(buf, "\<BS>") + call VerifyScreenDump(buf, 'Test_incsearch_substitute_03', {}) + call term_sendkeys(buf, "\<Esc>") + + " Reverse range is accepted + call term_sendkeys(buf, ':5,2s/foo') + call VerifyScreenDump(buf, 'Test_incsearch_substitute_04', {}) + call term_sendkeys(buf, "\<Esc>") + + " White space after the command is skipped + call term_sendkeys(buf, ':2,3sub /fo') + call VerifyScreenDump(buf, 'Test_incsearch_substitute_05', {}) + call term_sendkeys(buf, "\<Esc>") + + " Command modifiers are skipped + call term_sendkeys(buf, ':above below browse botr confirm keepmar keepalt keeppat keepjum filter xxx hide lockm leftabove noau noswap rightbel sandbox silent silent! $tab top unsil vert verbose 4,5s/fo.') + call VerifyScreenDump(buf, 'Test_incsearch_substitute_06', {}) + call term_sendkeys(buf, "\<Esc>") + + " Cursorline highlighting at match + call term_sendkeys(buf, ":set cursorline\<CR>") + call term_sendkeys(buf, 'G9G') + call term_sendkeys(buf, ':9,11s/bar') + call VerifyScreenDump(buf, 'Test_incsearch_substitute_07', {}) + call term_sendkeys(buf, "\<Esc>") + + " Cursorline highlighting at cursor when no match + call term_sendkeys(buf, ':9,10s/bar') + call VerifyScreenDump(buf, 'Test_incsearch_substitute_08', {}) + call term_sendkeys(buf, "\<Esc>") + + " Only \v handled as empty pattern, does not move cursor + call term_sendkeys(buf, '3G4G') + call term_sendkeys(buf, ":nohlsearch\<CR>") + call term_sendkeys(buf, ':6,7s/\v') + call VerifyScreenDump(buf, 'Test_incsearch_substitute_09', {}) + call term_sendkeys(buf, "\<Esc>") + + call term_sendkeys(buf, ":set nocursorline\<CR>") + + " All matches are highlighted for 'hlsearch' after the incsearch canceled + call term_sendkeys(buf, "1G*") + call term_sendkeys(buf, ":2,5s/foo") + sleep 100m + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_incsearch_substitute_10', {}) + + call term_sendkeys(buf, ":split\<CR>") + call term_sendkeys(buf, ":let @/ = 'xyz'\<CR>") + call term_sendkeys(buf, ":%s/.") + call VerifyScreenDump(buf, 'Test_incsearch_substitute_11', {}) + call term_sendkeys(buf, "\<BS>") + call VerifyScreenDump(buf, 'Test_incsearch_substitute_12', {}) + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_incsearch_substitute_13', {}) + call term_sendkeys(buf, ":%bwipe!\<CR>") + call term_sendkeys(buf, ":only!\<CR>") + + " get :'<,'>s command in history + call term_sendkeys(buf, ":set cmdheight=2\<CR>") + call term_sendkeys(buf, "aasdfasdf\<Esc>") + call term_sendkeys(buf, "V:s/a/b/g\<CR>") + " Using '<,'> does not give E20 + call term_sendkeys(buf, ":new\<CR>") + call term_sendkeys(buf, "aasdfasdf\<Esc>") + call term_sendkeys(buf, ":\<Up>\<Up>") + call VerifyScreenDump(buf, 'Test_incsearch_substitute_14', {}) + call term_sendkeys(buf, "<Esc>") + + call StopVimInTerminal(buf) + call delete('Xis_subst_script') +endfunc + +func Test_incsearch_highlighting() + CheckOption incsearch + CheckScreendump + + call writefile([ + \ 'set incsearch hlsearch', + \ 'call setline(1, "hello/there")', + \ ], 'Xis_subst_hl_script') + let buf = RunVimInTerminal('-S Xis_subst_hl_script', {'rows': 4, 'cols': 20}) + " Give Vim a chance to redraw to get rid of the spaces in line 2 caused by + " the 'ambiwidth' check. + sleep 300m + + " Using a different search delimiter should still highlight matches + " that contain a '/'. + call term_sendkeys(buf, ":%s;ello/the") + call VerifyScreenDump(buf, 'Test_incsearch_substitute_15', {}) + call term_sendkeys(buf, "<Esc>") + + call StopVimInTerminal(buf) + call delete('Xis_subst_hl_script') +endfunc + +func Test_incsearch_with_change() + CheckFeature timers + CheckOption incsearch + CheckScreendump + + call writefile([ + \ 'set incsearch hlsearch scrolloff=0', + \ 'call setline(1, ["one", "two ------ X", "three"])', + \ 'call timer_start(200, { _ -> setline(2, "x")})', + \ ], 'Xis_change_script') + let buf = RunVimInTerminal('-S Xis_change_script', {'rows': 9, 'cols': 70}) + " Give Vim a chance to redraw to get rid of the spaces in line 2 caused by + " the 'ambiwidth' check. + sleep 300m + + " Highlight X, it will be deleted by the timer callback. + call term_sendkeys(buf, ':%s/X') + call VerifyScreenDump(buf, 'Test_incsearch_change_01', {}) + call term_sendkeys(buf, "\<Esc>") + + call StopVimInTerminal(buf) + call delete('Xis_change_script') +endfunc + +" Similar to Test_incsearch_substitute_dump() for :sort +func Test_incsearch_sort_dump() + CheckOption incsearch + CheckScreendump + + call writefile([ + \ 'set incsearch hlsearch scrolloff=0', + \ 'call setline(1, ["another one 2", "that one 3", "the one 1"])', + \ ], 'Xis_sort_script') + let buf = RunVimInTerminal('-S Xis_sort_script', {'rows': 9, 'cols': 70}) + " Give Vim a chance to redraw to get rid of the spaces in line 2 caused by + " the 'ambiwidth' check. + sleep 100m + + call term_sendkeys(buf, ':sort ni u /on') + call VerifyScreenDump(buf, 'Test_incsearch_sort_01', {}) + call term_sendkeys(buf, "\<Esc>") + + call term_sendkeys(buf, ':sort! /on') + call VerifyScreenDump(buf, 'Test_incsearch_sort_02', {}) + call term_sendkeys(buf, "\<Esc>") + + call StopVimInTerminal(buf) + call delete('Xis_sort_script') +endfunc + +" Similar to Test_incsearch_substitute_dump() for :vimgrep famiry +func Test_incsearch_vimgrep_dump() + CheckOption incsearch + CheckScreendump + + call writefile([ + \ 'set incsearch hlsearch scrolloff=0', + \ 'call setline(1, ["another one 2", "that one 3", "the one 1"])', + \ ], 'Xis_vimgrep_script') + let buf = RunVimInTerminal('-S Xis_vimgrep_script', {'rows': 9, 'cols': 70}) + " Give Vim a chance to redraw to get rid of the spaces in line 2 caused by + " the 'ambiwidth' check. + sleep 100m + + " Need to send one key at a time to force a redraw. + call term_sendkeys(buf, ':vimgrep on') + call VerifyScreenDump(buf, 'Test_incsearch_vimgrep_01', {}) + call term_sendkeys(buf, "\<Esc>") + + call term_sendkeys(buf, ':vimg /on/ *.txt') + call VerifyScreenDump(buf, 'Test_incsearch_vimgrep_02', {}) + call term_sendkeys(buf, "\<Esc>") + + call term_sendkeys(buf, ':vimgrepadd "\<on') + call VerifyScreenDump(buf, 'Test_incsearch_vimgrep_03', {}) + call term_sendkeys(buf, "\<Esc>") + + call term_sendkeys(buf, ':lv "tha') + call VerifyScreenDump(buf, 'Test_incsearch_vimgrep_04', {}) + call term_sendkeys(buf, "\<Esc>") + + call term_sendkeys(buf, ':lvimgrepa "the" **/*.txt') + call VerifyScreenDump(buf, 'Test_incsearch_vimgrep_05', {}) + call term_sendkeys(buf, "\<Esc>") + + call StopVimInTerminal(buf) + call delete('Xis_vimgrep_script') +endfunc + +func Test_keep_last_search_pattern() + CheckFunction test_override + CheckOption incsearch + + new + call setline(1, ['foo', 'foo', 'foo']) + set incsearch + call test_override("char_avail", 1) + let @/ = 'bar' + call feedkeys(":/foo/s//\<Esc>", 'ntx') + call assert_equal('bar', @/) + + " no error message if pattern not found + call feedkeys(":/xyz/s//\<Esc>", 'ntx') + call assert_equal('bar', @/) + + bwipe! + call test_override("ALL", 0) + set noincsearch +endfunc + +func Test_word_under_cursor_after_match() + CheckFunction test_override + CheckOption incsearch + + new + call setline(1, 'foo bar') + set incsearch + call test_override("char_avail", 1) + try + call feedkeys("/foo\<C-R>\<C-W>\<CR>", 'ntx') + catch /E486:/ + endtry + call assert_equal('foobar', @/) + + bwipe! + call test_override("ALL", 0) + set noincsearch +endfunc + +func Test_subst_word_under_cursor() + CheckFunction test_override + CheckOption incsearch + + new + call setline(1, ['int SomeLongName;', 'for (xxx = 1; xxx < len; ++xxx)']) + set incsearch + call test_override("char_avail", 1) + call feedkeys("/LongName\<CR>", 'ntx') + call feedkeys(":%s/xxx/\<C-R>\<C-W>/g\<CR>", 'ntx') + call assert_equal('for (SomeLongName = 1; SomeLongName < len; ++SomeLongName)', getline(2)) + + bwipe! + call test_override("ALL", 0) + set noincsearch +endfunc + +func Test_search_skip_all_matches() + enew + call setline(1, ['no match here', + \ 'match this line', + \ 'nope', + \ 'match in this line', + \ 'last line', + \ ]) + call cursor(1, 1) + let lnum = search('this', '', 0, 0, 'getline(".") =~ "this line"') + " Only check that no match is found. Previously it searched forever. + call assert_equal(0, lnum) + + bwipe! +endfunc + +func Test_search_undefined_behaviour() + CheckFeature terminal + + let h = winheight(0) + if h < 3 + return + endif + " did cause an undefined left shift + let g:buf = term_start([GetVimProg(), '--clean', '-e', '-s', '-c', 'call search(getline("."))', 'samples/test000'], {'term_rows': 3}) + call assert_equal([''], getline(1, '$')) + call term_sendkeys(g:buf, ":qa!\<cr>") + bwipe! +endfunc + +func Test_search_undefined_behaviour2() + call search("\%UC0000000") +endfunc + +" Test for search('multi-byte char', 'bce') +func Test_search_multibyte() + let save_enc = &encoding + set encoding=utf8 + enew! + call append('$', 'A') + call cursor(2, 1) + call assert_equal(2, search('A', 'bce', line('.'))) + enew! + let &encoding = save_enc +endfunc + +" This was causing E874. Also causes an invalid read? +func Test_look_behind() + new + call setline(1, '0\|\&\n\@<=') + call search(getline(".")) + bwipe! +endfunc + +func Test_search_visual_area_linewise() + new + call setline(1, ['aa', 'bb', 'cc']) + exe "normal 2GV\<Esc>" + for engine in [1, 2] + exe 'set regexpengine=' .. engine + exe "normal gg/\\%'<\<CR>>" + call assert_equal([0, 2, 1, 0, 1], getcurpos(), 'engine ' .. engine) + exe "normal gg/\\%'>\<CR>" + call assert_equal([0, 2, 2, 0, 2], getcurpos(), 'engine ' .. engine) + endfor + + bwipe! + set regexpengine& +endfunc + +func Test_search_sentence() + new + " this used to cause a crash + /\%'( + / + bwipe +endfunc + +" Test that there is no crash when there is a last search pattern but no last +" substitute pattern. +func Test_no_last_substitute_pat() + " Use viminfo to set the last search pattern to a string and make the last + " substitute pattern the most recent used and make it empty (NULL). + call writefile(['~MSle0/bar', '~MSle0~&'], 'Xviminfo') + rviminfo! Xviminfo + call assert_fails('normal n', 'E35:') + + call delete('Xviminfo') +endfunc + +func Test_search_Ctrl_L_combining() + " Make sure, that Ctrl-L works correctly with combining characters. + " It uses an artificial example of an 'a' with 4 combining chars: + " 'a' U+0061 Dec:97 LATIN SMALL LETTER A a /\%u61\Z "\u0061" + " ' ̀' U+0300 Dec:768 COMBINING GRAVE ACCENT ̀ /\%u300\Z "\u0300" + " ' ́' U+0301 Dec:769 COMBINING ACUTE ACCENT ́ /\%u301\Z "\u0301" + " ' ̇' U+0307 Dec:775 COMBINING DOT ABOVE ̇ /\%u307\Z "\u0307" + " ' ̣' U+0323 Dec:803 COMBINING DOT BELOW ̣ /\%u323 "\u0323" + " Those should also appear on the commandline + CheckOption incsearch + + call Cmdline3_prep() + 1 + let bufcontent = ['', 'Miạ̀́̇m'] + call append('$', bufcontent) + call feedkeys("/Mi\<c-l>\<c-l>\<cr>", 'tx') + call assert_equal(5, line('.')) + call assert_equal(bufcontent[1], @/) + call Incsearch_cleanup() +endfunc + +func Test_large_hex_chars1() + " This used to cause a crash, the character becomes an NFA state. + try + /\%Ufffffc23 + catch + call assert_match('E678:', v:exception) + endtry + try + set re=1 + /\%Ufffffc23 + catch + call assert_match('E678:', v:exception) + endtry + set re& +endfunc + +func Test_large_hex_chars2() + " This used to cause a crash, the character becomes an NFA state. + try + /[\Ufffffc1f] + catch + call assert_match('E486:', v:exception) + endtry + try + set re=1 + /[\Ufffffc1f] + catch + call assert_match('E486:', v:exception) + endtry + set re& +endfunc + +func Test_one_error_msg() + " This was also giving an internal error + call assert_fails('call search(" \\((\\v[[=P=]]){185}+ ")', 'E871:') +endfunc + +func Test_incsearch_add_char_under_cursor() + CheckFunction test_override + CheckOption incsearch + + set incsearch + new + call setline(1, ['find match', 'anything']) + 1 + call test_override('char_avail', 1) + call feedkeys("fc/m\<C-L>\<C-L>\<C-L>\<C-L>\<C-L>\<CR>", 'tx') + call assert_equal('match', @/) + call test_override('char_avail', 0) + + set incsearch& + bwipe! +endfunc + +" Test for the search() function with match at the cursor position +func Test_search_match_at_curpos() + new + call append(0, ['foobar', '', 'one two', '']) + + normal gg + + eval 'foobar'->search('c') + call assert_equal([1, 1], [line('.'), col('.')]) + + normal j + call search('^$', 'c') + call assert_equal([2, 1], [line('.'), col('.')]) + + call search('^$', 'bc') + call assert_equal([2, 1], [line('.'), col('.')]) + + exe "normal /two\<CR>" + call search('.', 'c') + call assert_equal([3, 5], [line('.'), col('.')]) + + close! +endfunc + +" Test for error cases with the search() function +func Test_search_errors() + call assert_fails("call search('pat', [])", 'E730:') + call assert_fails("call search('pat', 'b', {})", 'E728:') + call assert_fails("call search('pat', 'b', 1, [])", 'E745:') + call assert_fails("call search('pat', 'ns')", 'E475:') + call assert_fails("call search('pat', 'mr')", 'E475:') + + new + call setline(1, ['foo', 'bar']) + call assert_fails('call feedkeys("/foo/;/bar/;\<CR>", "tx")', 'E386:') + bwipe! +endfunc + +func Test_search_display_pattern() + new + call setline(1, ['foo', 'bar', 'foobar']) + + call cursor(1, 1) + let @/ = 'foo' + let pat = @/->escape('()*?'. '\s\+') + let g:a = execute(':unsilent :norm! n') + call assert_match(pat, g:a) + + " right-left + if exists("+rightleft") + set rl + call cursor(1, 1) + let @/ = 'foo' + let pat = 'oof/\s\+' + let g:a = execute(':unsilent :norm! n') + call assert_match(pat, g:a) + set norl + endif +endfunc + +func Test_searchdecl() + let lines =<< trim END + int global; + + func() + { + int global; + if (cond) { + int local; + } + int local; + // comment + } + END + new + call setline(1, lines) + 10 + call assert_equal(0, searchdecl('local', 0, 0)) + call assert_equal(7, getcurpos()[1]) + + 10 + call assert_equal(0, 'local'->searchdecl(0, 1)) + call assert_equal(9, getcurpos()[1]) + + 10 + call assert_equal(0, searchdecl('global')) + call assert_equal(5, getcurpos()[1]) + + 10 + call assert_equal(0, searchdecl('global', 1)) + call assert_equal(1, getcurpos()[1]) + + bwipe! +endfunc + +func Test_search_special() + " this was causing illegal memory access and an endless loop + set t_PE= + exe "norm /\x80PS" +endfunc + +" Test for command failures when the last search pattern is not set. +" Need to run this in a new vim instance where last search pattern is not set. +func Test_search_with_no_last_pat() + let lines =<< trim [SCRIPT] + call assert_fails("normal i\<C-R>/\e", 'E35:') + call assert_fails("exe '/'", 'E35:') + call assert_fails("exe '?'", 'E35:') + call assert_fails("/", 'E35:') + call assert_fails("?", 'E35:') + call assert_fails("normal n", 'E35:') + call assert_fails("normal N", 'E35:') + call assert_fails("normal gn", 'E35:') + call assert_fails("normal gN", 'E35:') + call assert_fails("normal cgn", 'E35:') + call assert_fails("normal cgN", 'E35:') + let p = [] + let p = @/ + call assert_equal('', p) + call assert_fails("normal :\<C-R>/", 'E35:') + call assert_fails("//p", 'E35:') + call assert_fails(";//p", 'E35:') + call assert_fails("??p", 'E35:') + call assert_fails(";??p", 'E35:') + call assert_fails('g//p', ['E35:', 'E476:']) + call assert_fails('v//p', ['E35:', 'E476:']) + 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 using tilde (~) atom in search. This should use the last used +" substitute pattern +func Test_search_tilde_pat() + let lines =<< trim [SCRIPT] + set regexpengine=1 + call assert_fails('exe "normal /~\<CR>"', 'E33:') + call assert_fails('exe "normal ?~\<CR>"', 'E33:') + set regexpengine=2 + call assert_fails('exe "normal /~\<CR>"', ['E33:', 'E383:']) + call assert_fails('exe "normal ?~\<CR>"', ['E33:', 'E383:']) + set regexpengine& + 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 searching a pattern that is not present with 'nowrapscan' +func Test_search_pat_not_found() + new + set nowrapscan + let @/ = '1abcxyz2' + call assert_fails('normal n', 'E385:') + call assert_fails('normal N', 'E384:') + set wrapscan& + close +endfunc + +" Test for v:searchforward variable +func Test_searchforward_var() + new + call setline(1, ['foo', '', 'foo']) + call cursor(2, 1) + let @/ = 'foo' + let v:searchforward = 0 + normal N + call assert_equal(3, line('.')) + call cursor(2, 1) + let v:searchforward = 1 + normal N + call assert_equal(1, line('.')) + close! +endfunc + +" Test for invalid regular expressions +func Test_invalid_regexp() + set regexpengine=1 + call assert_fails("call search(repeat('\\(.\\)', 10))", 'E51:') + call assert_fails("call search('\\%(')", 'E53:') + call assert_fails("call search('\\(')", 'E54:') + call assert_fails("call search('\\)')", 'E55:') + call assert_fails("call search('x\\@#')", 'E59:') + call assert_fails('call search(''\v%(%(%(%(%(%(%(%(%(%(%(a){1}){1}){1}){1}){1}){1}){1}){1}){1}){1}){1}'')', 'E60:') + call assert_fails("call search('a\\+*')", 'E61:') + call assert_fails("call search('\\_m')", 'E63:') + call assert_fails("call search('\\+')", 'E64:') + call assert_fails("call search('\\1')", 'E65:') + call assert_fails("call search('\\z\\(\\)')", 'E66:') + call assert_fails("call search('\\z2')", 'E67:') + call assert_fails("call search('\\zx')", 'E68:') + call assert_fails("call search('\\%[ab')", 'E69:') + call assert_fails("call search('\\%[]')", 'E70:') + call assert_fails("call search('\\%a')", 'E71:') + call assert_fails("call search('ab\\%[\\(cd\\)]')", 'E369:') + call assert_fails("call search('ab\\%[\\%(cd\\)]')", 'E369:') + set regexpengine=2 + call assert_fails("call search('\\_')", 'E865:') + call assert_fails("call search('\\+')", 'E866:') + call assert_fails("call search('\\zx')", 'E867:') + call assert_fails("call search('\\%a')", 'E867:') + call assert_fails("call search('x\\@#')", 'E869:') + call assert_fails("call search(repeat('\\(.\\)', 10))", 'E872:') + call assert_fails("call search('\\_m')", 'E877:') + call assert_fails("call search('\\%(')", 'E53:') + call assert_fails("call search('\\(')", 'E54:') + call assert_fails("call search('\\)')", 'E55:') + call assert_fails("call search('\\z\\(\\)')", 'E66:') + call assert_fails("call search('\\z2')", 'E67:') + call assert_fails("call search('\\zx')", 'E867:') + call assert_fails("call search('\\%[ab')", 'E69:') + call assert_fails("call search('\\%[]')", 'E70:') + call assert_fails("call search('\\%9999999999999999999999999999v')", 'E951:') + set regexpengine& + call assert_fails("call search('\\%#=3ab')", 'E864:') +endfunc + +" Test for searching a very complex pattern in a string. Should switch the +" regexp engine from NFA to the old engine. +func Test_regexp_switch_engine() + let l = readfile('samples/re.freeze.txt') + let v = substitute(l[4], '..\@<!', '', '') + call assert_equal(l[4], v) +endfunc + +" Test for the \%V atom to search within visually selected text +func Test_search_in_visual_area() + new + call setline(1, ['foo bar1', 'foo bar2', 'foo bar3', 'foo bar4']) + exe "normal 2GVjo/\\%Vbar\<CR>\<Esc>" + call assert_equal([2, 5], [line('.'), col('.')]) + exe "normal 2GVj$?\\%Vbar\<CR>\<Esc>" + call assert_equal([3, 5], [line('.'), col('.')]) + close! +endfunc + +" Test for searching with 'smartcase' and 'ignorecase' +func Test_search_smartcase() + new + call setline(1, ['', 'Hello']) + set noignorecase nosmartcase + call assert_fails('exe "normal /\\a\\_.\\(.*\\)O\<CR>"', 'E486:') + + set ignorecase nosmartcase + exe "normal /\\a\\_.\\(.*\\)O\<CR>" + call assert_equal([2, 1], [line('.'), col('.')]) + + call cursor(1, 1) + set ignorecase smartcase + call assert_fails('exe "normal /\\a\\_.\\(.*\\)O\<CR>"', 'E486:') + + exe "normal /\\a\\_.\\(.*\\)o\<CR>" + call assert_equal([2, 1], [line('.'), col('.')]) + + " Test for using special atoms with 'smartcase' + call setline(1, ['', ' Hello\ ']) + call cursor(1, 1) + call feedkeys('/\_.\%(\uello\)\' .. "\<CR>", 'xt') + call assert_equal([2, 4], [line('.'), col('.')]) + + set ignorecase& smartcase& + close! +endfun + +" Test 'smartcase' with utf-8. +func Test_search_smartcase_utf8() + new + let save_enc = &encoding + set encoding=utf8 ignorecase smartcase + + call setline(1, 'Café cafÉ') + 1s/café/x/g + call assert_equal('x x', getline(1)) + + call setline(1, 'Café cafÉ') + 1s/cafÉ/x/g + call assert_equal('Café x', getline(1)) + + set ignorecase& smartcase& + let &encoding = save_enc + bwipe! +endfunc + +" Test searching past the end of a file +func Test_search_past_eof() + new + call setline(1, ['Line']) + exe "normal /\\n\\zs\<CR>" + call assert_equal([1, 4], [line('.'), col('.')]) + bwipe! +endfunc + +" Test setting the start of the match and still finding a next match in the +" same line. +func Test_search_set_start_same_line() + new + set cpo-=c + + call setline(1, ['1', '2', '3 .', '4', '5']) + exe "normal /\\_s\\zs\\S\<CR>" + call assert_equal([2, 1], [line('.'), col('.')]) + exe 'normal n' + call assert_equal([3, 1], [line('.'), col('.')]) + exe 'normal n' + call assert_equal([3, 3], [line('.'), col('.')]) + exe 'normal n' + call assert_equal([4, 1], [line('.'), col('.')]) + exe 'normal n' + call assert_equal([5, 1], [line('.'), col('.')]) + + set cpo+=c + bwipe! +endfunc + +" Test for various search offsets +func Test_search_offset() + " With /e, for a match in the first column of a line, the cursor should be + " placed at the end of the previous line. + new + call setline(1, ['one two', 'three four']) + call search('two\_.', 'e') + call assert_equal([1, 7], [line('.'), col('.')]) + + " with cursor at the beginning of the file, use /s+1 + call cursor(1, 1) + exe "normal /two/s+1\<CR>" + call assert_equal([1, 6], [line('.'), col('.')]) + + " with cursor at the end of the file, use /e-1 + call cursor(2, 10) + exe "normal ?three?e-1\<CR>" + call assert_equal([2, 4], [line('.'), col('.')]) + + " line offset - after the last line + call cursor(1, 1) + exe "normal /three/+1\<CR>" + call assert_equal([2, 1], [line('.'), col('.')]) + + " line offset - before the first line + call cursor(2, 1) + exe "normal ?one?-1\<CR>" + call assert_equal([1, 1], [line('.'), col('.')]) + + " character offset - before the first character in the file + call cursor(2, 1) + exe "normal ?one?s-1\<CR>" + call assert_equal([1, 1], [line('.'), col('.')]) + call cursor(2, 1) + exe "normal ?one?e-3\<CR>" + call assert_equal([1, 1], [line('.'), col('.')]) + + " character offset - after the last character in the file + call cursor(1, 1) + exe "normal /four/s+4\<CR>" + call assert_equal([2, 10], [line('.'), col('.')]) + call cursor(1, 1) + exe "normal /four/e+1\<CR>" + call assert_equal([2, 10], [line('.'), col('.')]) + + close! +endfunc + +" Test for searching for matching parenthesis using % +func Test_search_match_paren() + new + call setline(1, "abc(def')'ghi'('jk'\\t'lm)no") + " searching for a matching parenthesis should skip single quoted characters + call cursor(1, 4) + normal % + call assert_equal([1, 25], [line('.'), col('.')]) + normal % + call assert_equal([1, 4], [line('.'), col('.')]) + call cursor(1, 5) + normal ]) + call assert_equal([1, 25], [line('.'), col('.')]) + call cursor(1, 24) + normal [( + call assert_equal([1, 4], [line('.'), col('.')]) + + " matching parenthesis in 'virtualedit' mode with cursor after the eol + call setline(1, 'abc(defgh)') + set virtualedit=all + normal 20|% + call assert_equal(4, col('.')) + set virtualedit& + close! +endfunc + +" Test for searching a pattern and stopping before a specified line +func Test_search_stopline() + new + call setline(1, ['', '', '', 'vim']) + call assert_equal(0, search('vim', 'n', 3)) + call assert_equal(4, search('vim', 'n', 4)) + call setline(1, ['vim', '', '', '']) + call cursor(4, 1) + call assert_equal(0, search('vim', 'bn', 2)) + call assert_equal(1, search('vim', 'bn', 1)) + close! +endfunc + +func Test_incsearch_highlighting_newline() + CheckRunVimInTerminal + CheckOption incsearch + CheckScreendump + new + call test_override("char_avail", 1) + + let commands =<< trim [CODE] + set incsearch nohls + call setline(1, ['test', 'xxx']) + [CODE] + call writefile(commands, 'Xincsearch_nl') + let buf = RunVimInTerminal('-S Xincsearch_nl', {'rows': 5, 'cols': 10}) + call term_sendkeys(buf, '/test') + call VerifyScreenDump(buf, 'Test_incsearch_newline1', {}) + " Need to send one key at a time to force a redraw + call term_sendkeys(buf, '\n') + call VerifyScreenDump(buf, 'Test_incsearch_newline2', {}) + call term_sendkeys(buf, 'x') + call VerifyScreenDump(buf, 'Test_incsearch_newline3', {}) + call term_sendkeys(buf, 'x') + call VerifyScreenDump(buf, 'Test_incsearch_newline4', {}) + call term_sendkeys(buf, "\<CR>") + call VerifyScreenDump(buf, 'Test_incsearch_newline5', {}) + call StopVimInTerminal(buf) + + " clean up + call delete('Xincsearch_nl') + call test_override("char_avail", 0) + bw +endfunc + +func Test_incsearch_substitute_dump2() + CheckOption incsearch + CheckScreendump + + call writefile([ + \ 'set incsearch hlsearch scrolloff=0', + \ 'for n in range(1, 4)', + \ ' call setline(n, "foo " . n)', + \ 'endfor', + \ 'call setline(5, "abc|def")', + \ '3', + \ ], 'Xis_subst_script2', 'D') + let buf = RunVimInTerminal('-S Xis_subst_script2', {'rows': 9, 'cols': 70}) + + call term_sendkeys(buf, ':%s/\vabc|') + sleep 100m + call VerifyScreenDump(buf, 'Test_incsearch_sub_01', {}) + call term_sendkeys(buf, "\<Esc>") + + " The following should not be highlighted + call term_sendkeys(buf, ':1,5s/\v|') + sleep 100m + call VerifyScreenDump(buf, 'Test_incsearch_sub_02', {}) + + + call StopVimInTerminal(buf) +endfunc + +func Test_incsearch_restore_view() + CheckOption incsearch + CheckScreendump + + let lines =<< trim [CODE] + set incsearch nohlsearch + setlocal scrolloff=0 smoothscroll + call setline(1, [join(range(25), ' '), '', '', '', '', 'xxx']) + call feedkeys("2\<C-E>", 't') + [CODE] + call writefile(lines, 'Xincsearch_restore_view', 'D') + let buf = RunVimInTerminal('-S Xincsearch_restore_view', {'rows': 6, 'cols': 20}) + + call VerifyScreenDump(buf, 'Test_incsearch_restore_view_01', {}) + call term_sendkeys(buf, '/xx') + call VerifyScreenDump(buf, 'Test_incsearch_restore_view_02', {}) + call term_sendkeys(buf, 'x') + call VerifyScreenDump(buf, 'Test_incsearch_restore_view_03', {}) + call term_sendkeys(buf, "\<Esc>") + call VerifyScreenDump(buf, 'Test_incsearch_restore_view_01', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_pattern_is_uppercase_smartcase() + new + let input=['abc', 'ABC', 'Abc', 'abC'] + call setline(1, input) + call cursor(1,1) + " default, matches firstline + %s/abc//g + call assert_equal(['', 'ABC', 'Abc', 'abC'], + \ getline(1, '$')) + + set smartcase ignorecase + sil %d + call setline(1, input) + call cursor(1,1) + " with smartcase and incsearch set, matches everything + %s/abc//g + call assert_equal(['', '', '', ''], getline(1, '$')) + + sil %d + call setline(1, input) + call cursor(1,1) + " with smartcase and incsearch set and found an uppercase letter, + " match only that. + %s/abC//g + call assert_equal(['abc', 'ABC', 'Abc', ''], + \ getline(1, '$')) + + sil %d + call setline(1, input) + call cursor(1,1) + exe "norm! vG$\<esc>" + " \%V should not be detected as uppercase letter + %s/\%Vabc//g + call assert_equal(['', '', '', ''], getline(1, '$')) + + call setline(1, input) + call cursor(1,1) + exe "norm! vG$\<esc>" + " \v%V should not be detected as uppercase letter + %s/\v%Vabc//g + call assert_equal(['', '', '', ''], getline(1, '$')) + + call setline(1, input) + call cursor(1,1) + exe "norm! vG$\<esc>" + " \v%VabC should be detected as uppercase letter + %s/\v%VabC//g + call assert_equal(['abc', 'ABC', 'Abc', ''], + \ getline(1, '$')) + + call setline(1, input) + call cursor(1,1) + " \Vabc should match everything + %s/\Vabc//g + call assert_equal(['', '', '', ''], getline(1, '$')) + + call setline(1, input + ['_abc']) + " _ matches normally + %s/\v_.*//g + call assert_equal(['abc', 'ABC', 'Abc', 'abC', ''], getline(1, '$')) + + set smartcase& ignorecase& + bw! +endfunc + +func Test_no_last_search_pattern() + CheckOption incsearch + + let @/ = "" + set incsearch + " these were causing a crash + call feedkeys("//\<C-G>", 'xt') + call feedkeys("//\<C-T>", 'xt') + call feedkeys("??\<C-G>", 'xt') + call feedkeys("??\<C-T>", 'xt') +endfunc + +func Test_search_with_invalid_range() + new + let lines =<< trim END + /\%.v + 5/ + c + END + call writefile(lines, 'Xrangesearch') + source Xrangesearch + + bwipe! + call delete('Xrangesearch') +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_search_stat.vim b/test/old/testdir/test_search_stat.vim new file mode 100644 index 0000000000..a2523fc6c7 --- /dev/null +++ b/test/old/testdir/test_search_stat.vim @@ -0,0 +1,466 @@ +" Tests for search_stats, when "S" is not in 'shortmess' + +source check.vim +source screendump.vim + +func Test_search_stat() + new + set shortmess-=S + " Append 50 lines with text to search for, "foobar" appears 20 times + call append(0, repeat(['foobar', 'foo', 'fooooobar', 'foba', 'foobar'], 10)) + + call cursor(1, 1) + + " searchcount() returns an empty dictionary when previous pattern was not set + call assert_equal({}, searchcount(#{pattern: ''})) + " but setting @/ should also work (even 'n' nor 'N' was executed) + " recompute the count when the last position is different. + call assert_equal( + \ #{current: 1, exact_match: 1, total: 40, incomplete: 0, maxcount: 99}, + \ searchcount(#{pattern: 'foo'})) + call assert_equal( + \ #{current: 0, exact_match: 0, total: 10, incomplete: 0, maxcount: 99}, + \ searchcount(#{pattern: 'fooooobar'})) + call assert_equal( + \ #{current: 0, exact_match: 0, total: 10, incomplete: 0, maxcount: 99}, + \ searchcount(#{pattern: 'fooooobar', pos: [2, 1, 0]})) + call assert_equal( + \ #{current: 1, exact_match: 1, total: 10, incomplete: 0, maxcount: 99}, + \ searchcount(#{pattern: 'fooooobar', pos: [3, 1, 0]})) + " on last char of match + call assert_equal( + \ #{current: 1, exact_match: 1, total: 10, incomplete: 0, maxcount: 99}, + \ searchcount(#{pattern: 'fooooobar', pos: [3, 9, 0]})) + " on char after match + call assert_equal( + \ #{current: 1, exact_match: 0, total: 10, incomplete: 0, maxcount: 99}, + \ searchcount(#{pattern: 'fooooobar', pos: [3, 10, 0]})) + call assert_equal( + \ #{current: 1, exact_match: 0, total: 10, incomplete: 0, maxcount: 99}, + \ searchcount(#{pattern: 'fooooobar', pos: [4, 1, 0]})) + call assert_equal( + \ #{current: 1, exact_match: 0, total: 2, incomplete: 2, maxcount: 1}, + \ searchcount(#{pattern: 'fooooobar', pos: [4, 1, 0], maxcount: 1})) + call assert_equal( + \ #{current: 0, exact_match: 0, total: 2, incomplete: 2, maxcount: 1}, + \ searchcount(#{pattern: 'fooooobar', maxcount: 1})) + + " match at second line + let messages_before = execute('messages') + let @/ = 'fo*\(bar\?\)\?' + let g:a = execute(':unsilent :norm! n') + let stat = '\[2/50\]' + let pat = escape(@/, '()*?'). '\s\+' + call assert_match(pat .. stat, g:a) + call assert_equal( + \ #{current: 2, exact_match: 1, total: 50, incomplete: 0, maxcount: 99}, + \ searchcount(#{recompute: 0})) + " didn't get added to message history + call assert_equal(messages_before, execute('messages')) + + " Match at last line + call cursor(line('$')-2, 1) + let g:a = execute(':unsilent :norm! n') + let stat = '\[50/50\]' + call assert_match(pat .. stat, g:a) + call assert_equal( + \ #{current: 50, exact_match: 1, total: 50, incomplete: 0, maxcount: 99}, + \ searchcount(#{recompute: 0})) + + " No search stat + set shortmess+=S + call cursor(1, 1) + let stat = '\[2/50\]' + let g:a = execute(':unsilent :norm! n') + call assert_notmatch(pat .. stat, g:a) + " n does not update search stat + call assert_equal( + \ #{current: 50, exact_match: 1, total: 50, incomplete: 0, maxcount: 99}, + \ searchcount(#{recompute: 0})) + call assert_equal( + \ #{current: 2, exact_match: 1, total: 50, incomplete: 0, maxcount: 99}, + \ searchcount(#{recompute: v:true})) + set shortmess-=S + + " Many matches + call cursor(line('$')-2, 1) + let @/ = '.' + let pat = escape(@/, '()*?'). '\s\+' + let g:a = execute(':unsilent :norm! n') + let stat = '\[>99/>99\]' + call assert_match(pat .. stat, g:a) + call assert_equal( + \ #{current: 100, exact_match: 0, total: 100, incomplete: 2, maxcount: 99}, + \ searchcount(#{recompute: 0})) + call assert_equal( + \ #{current: 272, exact_match: 1, total: 280, incomplete: 0, maxcount: 0}, + \ searchcount(#{recompute: v:true, maxcount: 0, timeout: 200})) + call assert_equal( + \ #{current: 1, exact_match: 1, total: 280, incomplete: 0, maxcount: 0}, + \ searchcount(#{recompute: 1, maxcount: 0, pos: [1, 1, 0], timeout: 200})) + call cursor(line('$'), 1) + let g:a = execute(':unsilent :norm! n') + let stat = 'W \[1/>99\]' + call assert_match(pat .. stat, g:a) + call assert_equal( + \ #{current: 1, exact_match: 1, total: 100, incomplete: 2, maxcount: 99}, + \ searchcount(#{recompute: 0})) + call assert_equal( + \ #{current: 1, exact_match: 1, total: 280, incomplete: 0, maxcount: 0}, + \ searchcount(#{recompute: 1, maxcount: 0, timeout: 200})) + call assert_equal( + \ #{current: 271, exact_match: 1, total: 280, incomplete: 0, maxcount: 0}, + \ searchcount(#{recompute: 1, maxcount: 0, pos: [line('$')-2, 1, 0], timeout: 200})) + + " Many matches + call cursor(1, 1) + let g:a = execute(':unsilent :norm! n') + let stat = '\[2/>99\]' + call assert_match(pat .. stat, g:a) + call cursor(1, 1) + let g:a = execute(':unsilent :norm! N') + let stat = 'W \[>99/>99\]' + call assert_match(pat .. stat, g:a) + + " right-left + if exists("+rightleft") + set rl + call cursor(1,1) + let @/ = 'foobar' + let pat = 'raboof/\s\+' + let g:a = execute(':unsilent :norm! n') + let stat = '\[20/2\]' + call assert_match(pat .. stat, g:a) + set norl + endif + + " right-left bottom + if exists("+rightleft") + set rl + call cursor('$',1) + let pat = 'raboof?\s\+' + let g:a = execute(':unsilent :norm! N') + let stat = '\[20/20\]' + call assert_match(pat .. stat, g:a) + set norl + endif + + " right-left back at top + if exists("+rightleft") + set rl + call cursor('$',1) + let pat = 'raboof/\s\+' + let g:a = execute(':unsilent :norm! n') + let stat = 'W \[20/1\]' + call assert_match(pat .. stat, g:a) + set norl + endif + + " normal, back at bottom + call cursor(1,1) + let @/ = 'foobar' + let pat = '?foobar\s\+' + let g:a = execute(':unsilent :norm! N') + let stat = 'W \[20/20\]' + call assert_match(pat .. stat, g:a) + call assert_match('W \[20/20\]', Screenline(&lines)) + + " normal, no match + call cursor(1,1) + let @/ = 'zzzzzz' + let g:a = '' + try + let g:a = execute(':unsilent :norm! n') + catch /^Vim\%((\a\+)\)\=:E486/ + let stat = '' + " error message is not redir'ed to g:a, it is empty + call assert_true(empty(g:a)) + catch + call assert_false(1) + endtry + + " with count + call cursor(1, 1) + let @/ = 'fo*\(bar\?\)\?' + let g:a = execute(':unsilent :norm! 2n') + let stat = '\[3/50\]' + let pat = escape(@/, '()*?'). '\s\+' + call assert_match(pat .. stat, g:a) + let g:a = execute(':unsilent :norm! 2n') + let stat = '\[5/50\]' + call assert_match(pat .. stat, g:a) + + " with offset + call cursor(1, 1) + call feedkeys("/fo*\\(bar\\?\\)\\?/+1\<cr>", 'tx') + let g:a = execute(':unsilent :norm! n') + let stat = '\[5/50\]' + let pat = escape(@/ .. '/+1', '()*?'). '\s\+' + call assert_match(pat .. stat, g:a) + + " normal, n comes from a mapping + " Need to move over more than 64 lines to trigger char_avail(. + nnoremap n nzv + call cursor(1,1) + call append(50, repeat(['foobar', 'foo', 'fooooobar', 'foba', 'foobar'], 10)) + call setline(2, 'find this') + call setline(70, 'find this') + let @/ = 'find this' + let pat = '/find this\s\+' + let g:a = execute(':unsilent :norm n') + " g:a will contain several lines + let g:b = split(g:a, "\n")[-1] + let stat = '\[1/2\]' + call assert_match(pat .. stat, g:b) + unmap n + + " normal, but silent + call cursor(1,1) + let @/ = 'find this' + let pat = '/find this\s\+' + let g:a = execute(':norm! n') + let stat = '\[1/2\]' + call assert_notmatch(pat .. stat, g:a) + + " normal, n comes from a silent mapping + " First test a normal mapping, then a silent mapping + call cursor(1,1) + nnoremap n n + let @/ = 'find this' + let pat = '/find this\s\+' + let g:a = execute(':unsilent :norm n') + let g:b = split(g:a, "\n")[-1] + let stat = '\[1/2\]' + call assert_match(pat .. stat, g:b) + nnoremap <silent> n n + call cursor(1,1) + let g:a = execute(':unsilent :norm n') + let g:b = split(g:a, "\n")[-1] + let stat = '\[1/2\]' + call assert_notmatch(pat .. stat, g:b) + call assert_match(stat, g:b) + " Test that the message is not truncated + " it would insert '...' into the output. + call assert_match('^\s\+' .. stat, g:b) + unmap n + + " Time out + %delete _ + call append(0, repeat(['foobar', 'foo', 'fooooobar', 'foba', 'foobar'], 100000)) + call cursor(1, 1) + call assert_equal(1, searchcount(#{pattern: 'foo', maxcount: 0, timeout: 1}).incomplete) + + " Clean up + set shortmess+=S + " close the window + bwipe! +endfunc + +func Test_searchcount_fails() + call assert_fails('echo searchcount("boo!")', 'E1206:') + call assert_fails('echo searchcount({"timeout" : []})', 'E745:') + call assert_fails('echo searchcount({"maxcount" : []})', 'E745:') + call assert_fails('echo searchcount({"pattern" : []})', 'E730:') + call assert_fails('echo searchcount({"pos" : 1})', 'E475:') + call assert_fails('echo searchcount({"pos" : [1]})', 'E475:') + call assert_fails('echo searchcount({"pos" : [[], 2, 3]})', 'E745:') + call assert_fails('echo searchcount({"pos" : [1, [], 3]})', 'E745:') + call assert_fails('echo searchcount({"pos" : [1, 2, []]})', 'E745:') +endfunc + +func Test_search_stat_narrow_screen() + " This used to crash Vim + let save_columns = &columns + try + let after =<< trim [CODE] + set laststatus=2 + set columns=16 + set shortmess-=S showcmd + call setline(1, 'abc') + call feedkeys("/abc\<CR>:quit!\<CR>") + autocmd VimLeavePre * call writefile(["done"], "Xdone") + [CODE] + + if !RunVim([], after, '--clean') + return + endif + call assert_equal("done", readfile("Xdone")[0]) + call delete('Xdone') + finally + let &columns = save_columns + endtry +endfunc + +func Test_searchcount_in_statusline() + CheckScreendump + + let lines =<< trim END + set shortmess-=S + call append(0, 'this is something') + function TestSearchCount() abort + let search_count = searchcount() + if !empty(search_count) + return '[' . search_count.current . '/' . search_count.total . ']' + else + return '' + endif + endfunction + set hlsearch + set laststatus=2 statusline+=%{TestSearchCount()} + END + call writefile(lines, 'Xsearchstatusline') + let buf = RunVimInTerminal('-S Xsearchstatusline', #{rows: 10}) + call TermWait(buf) + call term_sendkeys(buf, "/something") + call VerifyScreenDump(buf, 'Test_searchstat_4', {}) + + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) + call delete('Xsearchstatusline') +endfunc + +func Test_search_stat_foldopen() + CheckScreendump + + let lines =<< trim END + set shortmess-=S + setl foldenable foldmethod=indent foldopen-=search + call append(0, ['if', "\tfoo", "\tfoo", 'endif']) + let @/ = 'foo' + call cursor(1,1) + norm n + END + call writefile(lines, 'Xsearchstat1') + + let buf = RunVimInTerminal('-S Xsearchstat1', #{rows: 10}) + call VerifyScreenDump(buf, 'Test_searchstat_3', {}) + + call term_sendkeys(buf, "n") + call VerifyScreenDump(buf, 'Test_searchstat_3', {}) + + call term_sendkeys(buf, "n") + call VerifyScreenDump(buf, 'Test_searchstat_3', {}) + + call StopVimInTerminal(buf) + call delete('Xsearchstat1') +endfunc + +func! Test_search_stat_screendump() + CheckScreendump + + let lines =<< trim END + set shortmess-=S + " Append 50 lines with text to search for, "foobar" appears 20 times + call append(0, repeat(['foobar', 'foo', 'fooooobar', 'foba', 'foobar'], 20)) + call setline(2, 'find this') + call setline(70, 'find this') + nnoremap n n + let @/ = 'find this' + call cursor(1,1) + norm n + END + call writefile(lines, 'Xsearchstat') + let buf = RunVimInTerminal('-S Xsearchstat', #{rows: 10}) + call VerifyScreenDump(buf, 'Test_searchstat_1', {}) + + call term_sendkeys(buf, ":nnoremap <silent> n n\<cr>") + call term_sendkeys(buf, "gg0n") + call VerifyScreenDump(buf, 'Test_searchstat_2', {}) + + call StopVimInTerminal(buf) + call delete('Xsearchstat') +endfunc + +func Test_search_stat_then_gd() + CheckScreendump + + let lines =<< trim END + call setline(1, ['int cat;', 'int dog;', 'cat = dog;']) + set shortmess-=S + set hlsearch + END + call writefile(lines, 'Xsearchstatgd') + + let buf = RunVimInTerminal('-S Xsearchstatgd', #{rows: 10}) + call term_sendkeys(buf, "/dog\<CR>") + call VerifyScreenDump(buf, 'Test_searchstatgd_1', {}) + + call term_sendkeys(buf, "G0gD") + call VerifyScreenDump(buf, 'Test_searchstatgd_2', {}) + + call StopVimInTerminal(buf) + call delete('Xsearchstatgd') +endfunc + +func Test_search_stat_and_incsearch() + CheckScreendump + + let lines =<< trim END + call setline(1, ['abc--c', '--------abc', '--abc']) + set hlsearch + set incsearch + set bg=dark + set showtabline=2 + + function MyTabLine() + try + let a=searchcount(#{recompute: 1, maxcount: -1}) + return a.current .. '/' .. a.total + catch + return '' + endtry + endfunction + + set tabline=%!MyTabLine() + END + call writefile(lines, 'Xsearchstat_inc', 'D') + + let buf = RunVimInTerminal('-S Xsearchstat_inc', #{rows: 10}) + call term_sendkeys(buf, "/abc") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_searchstat_inc_1', {}) + + call term_sendkeys(buf, "\<c-g>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_searchstat_inc_2', {}) + + call term_sendkeys(buf, "\<c-g>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_searchstat_inc_3', {}) + + call term_sendkeys(buf, "\<esc>:qa\<cr>") + call TermWait(buf) + + call StopVimInTerminal(buf) +endfunc + +func Test_search_stat_backwards() + CheckScreendump + + let lines =<< trim END + set shm-=S + call setline(1, ['test', '']) + END + call writefile(lines, 'Xsearchstat_back', 'D') + + let buf = RunVimInTerminal('-S Xsearchstat_back', #{rows: 10}) + call term_sendkeys(buf, "*") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_searchstat_back_1', {}) + + call term_sendkeys(buf, "N") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_searchstat_back_2', {}) + + call term_sendkeys(buf, ":set shm+=S\<cr>N") + call TermWait(buf) + " shows "Search Hit Bottom.." + call VerifyScreenDump(buf, 'Test_searchstat_back_3', {}) + + call term_sendkeys(buf, "\<esc>:qa\<cr>") + call TermWait(buf) + + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_searchpos.vim b/test/old/testdir/test_searchpos.vim new file mode 100644 index 0000000000..dd13c305c5 --- /dev/null +++ b/test/old/testdir/test_searchpos.vim @@ -0,0 +1,30 @@ +" Tests for searchpos() + +func Test_searchpos() + new one + 0put ='1a3' + 1put ='123xyz' + call cursor(1, 1) + call assert_equal([1, 1, 2], searchpos('\%(\([a-z]\)\|\_.\)\{-}xyz', 'pcW')) + call cursor(1, 2) + call assert_equal([2, 1, 1], '\%(\([a-z]\)\|\_.\)\{-}xyz'->searchpos('pcW')) + set cpo-=c + call cursor(1, 2) + call assert_equal([1, 2, 2], searchpos('\%(\([a-z]\)\|\_.\)\{-}xyz', 'pcW')) + call cursor(1, 3) + call assert_equal([1, 3, 1], searchpos('\%(\([a-z]\)\|\_.\)\{-}xyz', 'pcW')) + + " Now with \zs, first match is in column 0, "a" is matched. + call cursor(1, 3) + call assert_equal([2, 4, 2], searchpos('\%(\([a-z]\)\|\_.\)\{-}\zsxyz', 'pcW')) + " With z flag start at cursor column, don't see the "a". + call cursor(1, 3) + call assert_equal([2, 4, 1], searchpos('\%(\([a-z]\)\|\_.\)\{-}\zsxyz', 'pcWz')) + + set cpo+=c + " close the window + q! + +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_selectmode.vim b/test/old/testdir/test_selectmode.vim new file mode 100644 index 0000000000..59a1deba65 --- /dev/null +++ b/test/old/testdir/test_selectmode.vim @@ -0,0 +1,326 @@ +" Test for Select-mode + +source check.vim +" CheckNotGui +" CheckUnix + +source shared.vim +source mouse.vim + +" Test for select mode +func Test_selectmode_basic() + new + call setline(1, range(1,100)) + 50 + norm! gHy + call assert_equal('y51', getline('.')) + call setline(1, range(1,100)) + 50 + exe ":norm! V9jo\<c-g>y" + call assert_equal('y60', getline('.')) + call setline(1, range(1,100)) + 50 + " call feedkeys(":set im\n\<c-o>gHc\<c-o>:set noim\n", 'tx') + call feedkeys("i\<c-o>gHc\<esc>", 'tx') + call assert_equal('c51', getline('.')) + " clean up + bw! +endfunc + +" Test for starting selectmode +func Test_selectmode_start() + new + set selectmode=key keymodel=startsel + call setline(1, ['abc', 'def', 'ghi']) + call cursor(1, 4) + call feedkeys("A\<s-home>start\<esc>", 'txin') + call assert_equal(['startdef', 'ghi'], getline(1, '$')) + " start select mode again with gv + set selectmode=cmd + call feedkeys('gvabc', 'xt') + call assert_equal('abctdef', getline(1)) + " arrow keys without shift should not start selection + call feedkeys("A\<Home>\<Right>\<Left>ro", 'xt') + call assert_equal('roabctdef', getline(1)) + set selectmode= keymodel= + bw! +endfunc + +" Test for characterwise select mode +func Test_characterwise_select_mode() + new + + " Select mode maps + snoremap <lt>End> <End> + snoremap <lt>Down> <Down> + snoremap <lt>Del> <Del> + + " characterwise select mode: delete middle line + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + exe "normal Gkkgh\<End>\<Del>" + call assert_equal(['', 'b', 'c'], getline(1, '$')) + + " characterwise select mode: delete middle two lines + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + exe "normal Gkkgh\<Down>\<End>\<Del>" + call assert_equal(['', 'c'], getline(1, '$')) + + " characterwise select mode: delete last line + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + exe "normal Ggh\<End>\<Del>" + call assert_equal(['', 'a', 'b', ''], getline(1, '$')) + + " characterwise select mode: delete last two lines + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + exe "normal Gkgh\<Down>\<End>\<Del>" + call assert_equal(['', 'a', ''], getline(1, '$')) + + " CTRL-H in select mode behaves like 'x' + call setline(1, 'abcdef') + exe "normal! gggh\<Right>\<Right>\<Right>\<C-H>" + call assert_equal('ef', getline(1)) + + " CTRL-O in select mode switches to visual mode for one command + call setline(1, 'abcdef') + exe "normal! gggh\<C-O>3lm" + call assert_equal('mef', getline(1)) + + sunmap <lt>End> + sunmap <lt>Down> + sunmap <lt>Del> + bwipe! +endfunc + +" Test for linewise select mode +func Test_linewise_select_mode() + new + + " linewise select mode: delete middle line + call append('$', ['a', 'b', 'c']) + exe "normal GkkgH\<Del>" + call assert_equal(['', 'b', 'c'], getline(1, '$')) + + " linewise select mode: delete middle two lines + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + exe "normal GkkgH\<Down>\<Del>" + call assert_equal(['', 'c'], getline(1, '$')) + + " linewise select mode: delete last line + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + exe "normal GgH\<Del>" + call assert_equal(['', 'a', 'b'], getline(1, '$')) + + " linewise select mode: delete last two lines + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + exe "normal GkgH\<Down>\<Del>" + call assert_equal(['', 'a'], getline(1, '$')) + + bwipe! +endfunc + +" Test for blockwise select mode (g CTRL-H) +func Test_blockwise_select_mode() + new + call setline(1, ['foo', 'bar']) + call feedkeys("g\<BS>\<Right>\<Down>mm", 'xt') + call assert_equal(['mmo', 'mmr'], getline(1, '$')) + close! +endfunc + +" Test for using visual mode maps in select mode +func Test_select_mode_map() + new + vmap <buffer> <F2> 3l + call setline(1, 'Test line') + call feedkeys("gh\<F2>map", 'xt') + call assert_equal('map line', getline(1)) + + vmap <buffer> <F2> ygV + call feedkeys("0gh\<Right>\<Right>\<F2>cwabc", 'xt') + call assert_equal('abc line', getline(1)) + + vmap <buffer> <F2> :<C-U>let v=100<CR> + call feedkeys("gggh\<Right>\<Right>\<F2>foo", 'xt') + call assert_equal('foo line', getline(1)) + + " reselect the select mode using gv from a visual mode map + vmap <buffer> <F2> gv + set selectmode=cmd + call feedkeys("0gh\<F2>map", 'xt') + call assert_equal('map line', getline(1)) + set selectmode& + + close! +endfunc + +" Test double/triple/quadruple click to start 'select' mode +func Test_term_mouse_multiple_clicks_to_select_mode() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + + " 'mousetime' must be sufficiently large, or else the test is flaky when + " using a ssh connection with X forwarding; i.e. ssh -X. + " set mouse=a term=xterm mousetime=1000 + set mouse=a mousetime=1000 + set selectmode=mouse + new + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + + " Single-click and drag should 'select' the characters + call setline(1, ['foo [foo bar] foo', 'foo']) + call MouseLeftClick(1, 3) + call assert_equal(0, getcharmod(), msg) + call MouseLeftDrag(1, 13) + call MouseLeftRelease(1, 13) + norm! o + call assert_equal(['foo foo', 'foo'], getline(1, '$'), msg) + + " Double-click on word should visually 'select' the word. + call setline(1, ['foo [foo bar] foo', 'foo']) + call MouseLeftClick(1, 2) + call assert_equal(0, getcharmod(), msg) + call MouseLeftRelease(1, 2) + call MouseLeftClick(1, 2) + call assert_equal(32, getcharmod(), msg) " double-click + call MouseLeftRelease(1, 2) + call assert_equal('s', mode(), msg) + norm! bar + call assert_equal(['bar [foo bar] foo', 'foo'], getline(1, '$'), msg) + + " Double-click on opening square bracket should visually + " 'select' the whole [foo bar]. + call setline(1, ['foo [foo bar] foo', 'foo']) + call MouseLeftClick(1, 5) + call assert_equal(0, getcharmod(), msg) + call MouseLeftRelease(1, 5) + call MouseLeftClick(1, 5) + call assert_equal(32, getcharmod(), msg) " double-click + call MouseLeftRelease(1, 5) + call assert_equal('s', mode(), msg) + norm! bar + call assert_equal(['foo bar foo', 'foo'], getline(1, '$'), msg) + + " To guarantee that the next click is not counted as a triple click + call MouseRightClick(1, 1) + call MouseRightRelease(1, 1) + + " Triple-click should visually 'select' the whole line. + call setline(1, ['foo [foo bar] foo', 'foo']) + call MouseLeftClick(1, 3) + call assert_equal(0, getcharmod(), msg) + call MouseLeftRelease(1, 3) + call MouseLeftClick(1, 3) + call assert_equal(32, getcharmod(), msg) " double-click + call MouseLeftRelease(1, 3) + call MouseLeftClick(1, 3) + call assert_equal(64, getcharmod(), msg) " triple-click + call MouseLeftRelease(1, 3) + call assert_equal('S', mode(), msg) + norm! baz + call assert_equal(['bazfoo'], getline(1, '$'), msg) + + " Quadruple-click should start visual block 'select'. + call setline(1, ['aaaaaa', 'bbbbbb']) + call MouseLeftClick(1, 2) + call assert_equal(0, getcharmod(), msg) + call MouseLeftRelease(1, 2) + call MouseLeftClick(1, 2) + call assert_equal(32, getcharmod(), msg) " double-click + call MouseLeftRelease(1, 2) + call MouseLeftClick(1, 2) + call assert_equal(64, getcharmod(), msg) " triple-click + call MouseLeftRelease(1, 2) + call MouseLeftClick(1, 2) + call assert_equal(96, getcharmod(), msg) " quadruple-click + call MouseLeftDrag(2, 4) + call MouseLeftRelease(2, 4) + call assert_equal("\<c-s>", mode(), msg) + norm! x + call assert_equal(['axaa', 'bxbb'], getline(1, '$'), msg) + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + set mousetime& + set selectmode& + " call test_override('no_query_mouse', 0) + bwipe! +endfunc + +" Test for selecting a register with CTRL-R +func Test_selectmode_register() + new + + " Default behavior: use unnamed register + call setline(1, 'foo') + call setreg('"', 'bar') + call setreg('a', 'baz') + exe ":norm! v\<c-g>a" + call assert_equal(getline('.'), 'aoo') + call assert_equal('f', getreg('"')) + call assert_equal('baz', getreg('a')) + + " Use the black hole register + call setline(1, 'foo') + call setreg('"', 'bar') + call setreg('a', 'baz') + exe ":norm! v\<c-g>\<c-r>_a" + call assert_equal(getline('.'), 'aoo') + call assert_equal('bar', getreg('"')) + call assert_equal('baz', getreg('a')) + + " Invalid register: use unnamed register + call setline(1, 'foo') + call setreg('"', 'bar') + call setreg('a', 'baz') + exe ":norm! v\<c-g>\<c-r>?a" + call assert_equal(getline('.'), 'aoo') + call assert_equal('f', getreg('"')) + call assert_equal('baz', getreg('a')) + + " Use unnamed register + call setline(1, 'foo') + call setreg('"', 'bar') + call setreg('a', 'baz') + exe ":norm! v\<c-g>\<c-r>\"a" + call assert_equal(getline('.'), 'aoo') + call assert_equal('f', getreg('"')) + call assert_equal('baz', getreg('a')) + + " use specicifed register, unnamed register is also written + call setline(1, 'foo') + call setreg('"', 'bar') + call setreg('a', 'baz') + exe ":norm! v\<c-g>\<c-r>aa" + call assert_equal(getline('.'), 'aoo') + call assert_equal('f', getreg('"')) + call assert_equal('f', getreg('a')) + + bw! +endfunc + +func Test_ins_ctrl_o_in_insert_mode_resets_selectmode() + new + " ctrl-o in insert mode resets restart_VIsual_select + call setline(1, 'abcdef') + call cursor(1, 1) + exe "norm! \<c-v>\<c-g>\<c-o>c\<c-o>\<c-v>\<right>\<right>IABC" + call assert_equal('ABCbcdef', getline(1)) + + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_set.vim b/test/old/testdir/test_set.vim new file mode 100644 index 0000000000..7215772a00 --- /dev/null +++ b/test/old/testdir/test_set.vim @@ -0,0 +1,48 @@ +" Tests for the :set command + +function Test_set_backslash() + let isk_save = &isk + + set isk=a,b,c + set isk+=d + call assert_equal('a,b,c,d', &isk) + set isk+=\\,e + call assert_equal('a,b,c,d,\,e', &isk) + set isk-=e + call assert_equal('a,b,c,d,\', &isk) + set isk-=\\ + call assert_equal('a,b,c,d', &isk) + + let &isk = isk_save +endfunction + +function Test_set_add() + let wig_save = &wig + + set wildignore=*.png, + set wildignore+=*.jpg + call assert_equal('*.png,*.jpg', &wig) + + let &wig = wig_save +endfunction + + +" :set, :setlocal, :setglobal without arguments show values of options. +func Test_set_no_arg() + set textwidth=79 + let a = execute('set') + call assert_match("^\n--- Options ---\n.*textwidth=79\\>", a) + set textwidth& + + setlocal textwidth=78 + let a = execute('setlocal') + call assert_match("^\n--- Local option values ---\n.*textwidth=78\\>", a) + setlocal textwidth& + + setglobal textwidth=77 + let a = execute('setglobal') + call assert_match("^\n--- Global option values ---\n.*textwidth=77\\>", a) + setglobal textwidth& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_sha256.vim b/test/old/testdir/test_sha256.vim new file mode 100644 index 0000000000..f6f430b04e --- /dev/null +++ b/test/old/testdir/test_sha256.vim @@ -0,0 +1,22 @@ +" Tests for the sha256() function. + +source check.vim +CheckFeature cryptv +CheckFunction sha256 + +function Test_sha256() + " test for empty string: + call assert_equal('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', sha256("")) + + "'test for 1 char: + call assert_equal('ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb', sha256("a")) + " + "test for 3 chars: + call assert_equal('ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', "abc"->sha256()) + + " test for contains meta char: + call assert_equal('807eff6267f3f926a21d234f7b0cf867a86f47e07a532f15e8cc39ed110ca776', sha256("foo\nbar")) + + " test for contains non-ascii char: + call assert_equal('5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953', sha256("\xde\xad\xbe\xef")) +endfunction diff --git a/test/old/testdir/test_shell.vim b/test/old/testdir/test_shell.vim new file mode 100644 index 0000000000..c50161a8ed --- /dev/null +++ b/test/old/testdir/test_shell.vim @@ -0,0 +1,258 @@ +" Test for the shell related options ('shell', 'shellcmdflag', 'shellpipe', +" 'shellquote', 'shellredir', 'shellxescape', and 'shellxquote') + +source check.vim +source shared.vim + +func Test_shell_options() + if has('win32') + " FIXME: This test is flaky on MS-Windows. + let g:test_is_flaky = 1 + endif + + " The expected value of 'shellcmdflag', 'shellpipe', 'shellquote', + " 'shellredir', 'shellxescape', 'shellxquote' for the supported shells. + let shells = [] + if has('unix') + let shells += [['sh', '-c', '2>&1| tee', '', '>%s 2>&1', '', ''], + \ ['ksh', '-c', '2>&1| tee', '', '>%s 2>&1', '', ''], + \ ['mksh', '-c', '2>&1| tee', '', '>%s 2>&1', '', ''], + \ ['zsh', '-c', '2>&1| tee', '', '>%s 2>&1', '', ''], + \ ['zsh-beta', '-c', '2>&1| tee', '', '>%s 2>&1', '', ''], + \ ['bash', '-c', '2>&1| tee', '', '>%s 2>&1', '', ''], + \ ['fish', '-c', '2>&1| tee', '', '>%s 2>&1', '', ''], + \ ['ash', '-c', '2>&1| tee', '', '>%s 2>&1', '', ''], + \ ['dash', '-c', '2>&1| tee', '', '>%s 2>&1', '', ''], + \ ['csh', '-c', '|& tee', '', '>&', '', ''], + \ ['tcsh', '-c', '|& tee', '', '>&', '', '']] + endif + if has('win32') + let shells += [['cmd', '/s /c', '2>&1| tee', '', '>%s 2>&1', '', '"']] + endif + + " start a new Vim instance with 'shell' set to each of the supported shells + " and check the default shell option settings + let after =<< trim END + let l = [&shell, &shellcmdflag, &shellpipe, &shellquote] + let l += [&shellredir, &shellxescape, &shellxquote] + call writefile([json_encode(l)], 'Xtestout') + qall! + END + for e in shells + if RunVim([], after, '--cmd "set shell=' .. e[0] .. '"') + call assert_equal(e, json_decode(readfile('Xtestout')[0])) + endif + endfor + + " Test shellescape() for each of the shells. + for e in shells + exe 'set shell=' .. e[0] + if e[0] =~# '.*csh$' || e[0] =~# '.*csh.exe$' + let str1 = "'cmd \"arg1\" '\\''arg2'\\'' \\!%#'" + let str2 = "'cmd \"arg1\" '\\''arg2'\\'' \\\\!\\%\\#'" + elseif e[0] =~# '.*powershell$' || e[0] =~# '.*powershell.exe$' + let str1 = "'cmd \"arg1\" ''arg2'' !%#'" + let str2 = "'cmd \"arg1\" ''arg2'' \\!\\%\\#'" + else + let str1 = "'cmd \"arg1\" '\\''arg2'\\'' !%#'" + let str2 = "'cmd \"arg1\" '\\''arg2'\\'' \\!\\%\\#'" + endif + call assert_equal(str1, shellescape("cmd \"arg1\" 'arg2' !%#"), e[0]) + call assert_equal(str2, shellescape("cmd \"arg1\" 'arg2' !%#", 1), e[0]) + + " Try running an external command with the shell. + if executable(e[0]) + " set the shell options for the current 'shell' + let [&shellcmdflag, &shellpipe, &shellquote, &shellredir, + \ &shellxescape, &shellxquote] = e[1:6] + new + r !echo hello + call assert_equal('hello', substitute(getline(2), '\W', '', 'g'), e[0]) + bwipe! + endif + endfor + set shell& shellcmdflag& shellpipe& shellquote& + set shellredir& shellxescape& shellxquote& + call delete('Xtestout') +endfunc + +" Test for the 'shell' option +func Test_shell() + throw 'Skipped: Nvim missing :shell currently' + CheckUnix + let save_shell = &shell + set shell= + let caught_e91 = 0 + try + shell + catch /E91:/ + let caught_e91 = 1 + endtry + call assert_equal(1, caught_e91) + let &shell = save_shell +endfunc + +" Test for the 'shellquote' option +func Test_shellquote() + CheckUnix + set shellquote=# + set verbose=20 + redir => v + silent! !echo Hello + redir END + set verbose& + set shellquote& + call assert_match(': "#echo Hello#"', v) +endfunc + +" Test for the 'shellescape' option +func Test_shellescape() + let save_shell = &shell + set shell=bash + call assert_equal("'text'", shellescape('text')) + call assert_equal("'te\"xt'", 'te"xt'->shellescape()) + call assert_equal("'te'\\''xt'", shellescape("te'xt")) + + call assert_equal("'te%xt'", shellescape("te%xt")) + call assert_equal("'te\\%xt'", shellescape("te%xt", 1)) + call assert_equal("'te#xt'", shellescape("te#xt")) + call assert_equal("'te\\#xt'", shellescape("te#xt", 1)) + call assert_equal("'te!xt'", shellescape("te!xt")) + call assert_equal("'te\\!xt'", shellescape("te!xt", 1)) + + call assert_equal("'te\nxt'", shellescape("te\nxt")) + call assert_equal("'te\\\nxt'", shellescape("te\nxt", 1)) + set shell=tcsh + call assert_equal("'te\\!xt'", shellescape("te!xt")) + call assert_equal("'te\\\\!xt'", shellescape("te!xt", 1)) + call assert_equal("'te\\\nxt'", shellescape("te\nxt")) + call assert_equal("'te\\\\\nxt'", shellescape("te\nxt", 1)) + + let &shell = save_shell +endfunc + +" Test for 'shellslash' +func Test_shellslash() + CheckOption shellslash + let save_shellslash = &shellslash + " The shell and cmdflag, and expected slash in tempname with shellslash set or + " unset. The assert checks the file separator before the leafname. + " ".*\\\\[^\\\\]*$" + let shells = [['cmd', '/c', '/', '/'], + \ ['powershell', '-Command', '/', '/'], + \ ['sh', '-c', '/', '/']] + for e in shells + exe 'set shell=' .. e[0] .. ' | set shellcmdflag=' .. e[1] + set noshellslash + let file = tempname() + call assert_match('^.\+' .. e[2] .. '[^' .. e[2] .. ']\+$', file, e[0] .. ' ' .. e[1] .. ' nossl') + set shellslash + let file = tempname() + call assert_match('^.\+' .. e[3] .. '[^' .. e[3] .. ']\+$', file, e[0] .. ' ' .. e[1] .. ' ssl') + endfor + let &shellslash = save_shellslash +endfunc + +" Test for 'shellxquote' +func Test_shellxquote() + CheckUnix + + let save_shell = &shell + let save_sxq = &shellxquote + let save_sxe = &shellxescape + + call writefile(['#!/bin/sh', 'echo "Cmd: [$*]" > Xlog'], 'Xtestshell') + call setfperm('Xtestshell', "r-x------") + set shell=./Xtestshell + + set shellxquote=\\" + call feedkeys(":!pwd\<CR>\<CR>", 'xt') + call assert_equal(['Cmd: [-c "pwd"]'], readfile('Xlog')) + + set shellxquote=( + call feedkeys(":!pwd\<CR>\<CR>", 'xt') + call assert_equal(['Cmd: [-c (pwd)]'], readfile('Xlog')) + + set shellxquote=\\"( + call feedkeys(":!pwd\<CR>\<CR>", 'xt') + call assert_equal(['Cmd: [-c "(pwd)"]'], readfile('Xlog')) + + set shellxescape=\"&<<()@^ + set shellxquote=( + call feedkeys(":!pwd\"&<<{}@^\<CR>\<CR>", 'xt') + call assert_equal(['Cmd: [-c (pwd^"^&^<^<{}^@^^)]'], readfile('Xlog')) + + let &shell = save_shell + let &shellxquote = save_sxq + let &shellxescape = save_sxe + call delete('Xtestshell') + call delete('Xlog') +endfunc + +" Test for using the shell set in the $SHELL environment variable +func Test_set_shell() + let after =<< trim [CODE] + call writefile([&shell], "Xtestout") + quit! + [CODE] + + if has('win32') + let $SHELL = 'C:\with space\cmd.exe' + let expected = '"C:\with space\cmd.exe"' + else + let $SHELL = '/bin/with space/sh' + let expected = '"/bin/with space/sh"' + endif + + if RunVimPiped([], after, '', '') + let lines = readfile('Xtestout') + call assert_equal(expected, lines[0]) + endif + call delete('Xtestout') +endfunc + +func Test_shell_repeat() + CheckUnix + + let save_shell = &shell + + call writefile(['#!/bin/sh', 'echo "Cmd: [$*]" > Xlog'], 'Xtestshell', 'D') + call setfperm('Xtestshell', "r-x------") + set shell=./Xtestshell + defer delete('Xlog') + + call feedkeys(":!echo coconut\<CR>", 'xt') " Run command + call assert_equal(['Cmd: [-c echo coconut]'], readfile('Xlog')) + + call feedkeys(":!!\<CR>", 'xt') " Re-run previous + call assert_equal(['Cmd: [-c echo coconut]'], readfile('Xlog')) + + call writefile(['empty'], 'Xlog') + call feedkeys(":!\<CR>", 'xt') " :! + call assert_equal(['Cmd: [-c ]'], readfile('Xlog')) + + call feedkeys(":!!\<CR>", 'xt') " :! doesn't clear previous command + call assert_equal(['Cmd: [-c echo coconut]'], readfile('Xlog')) + + call feedkeys(":!echo banana\<CR>", 'xt') " Make sure setting previous command keeps working after a :! no-op + call assert_equal(['Cmd: [-c echo banana]'], readfile('Xlog')) + call feedkeys(":!!\<CR>", 'xt') + call assert_equal(['Cmd: [-c echo banana]'], readfile('Xlog')) + + let &shell = save_shell +endfunc + +func Test_shell_no_prevcmd() + " this doesn't do anything, just check it doesn't crash + let after =<< trim END + exe "normal !!\<CR>" + call writefile([v:errmsg, 'done'], 'Xtestdone') + qall! + END + if RunVim([], after, '--clean') + call assert_equal(['E34: No previous command', 'done'], readfile('Xtestdone')) + endif + call delete('Xtestdone') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_shift.vim b/test/old/testdir/test_shift.vim new file mode 100644 index 0000000000..ec357dac88 --- /dev/null +++ b/test/old/testdir/test_shift.vim @@ -0,0 +1,117 @@ +" Test shifting lines with :> and :< + +source check.vim + +func Test_ex_shift_right() + set shiftwidth=2 + + " shift right current line. + call setline(1, range(1, 5)) + 2 + > + 3 + >> + call assert_equal(['1', + \ ' 2', + \ ' 3', + \ '4', + \ '5'], getline(1, '$')) + + " shift right with range. + call setline(1, range(1, 4)) + 2,3>> + call assert_equal(['1', + \ ' 2', + \ ' 3', + \ '4', + \ '5'], getline(1, '$')) + + " shift right with range and count. + call setline(1, range(1, 4)) + 2>3 + call assert_equal(['1', + \ ' 2', + \ ' 3', + \ ' 4', + \ '5'], getline(1, '$')) + + bw! + set shiftwidth& +endfunc + +func Test_ex_shift_left() + set shiftwidth=2 + + call setline(1, range(1, 5)) + %>>> + + " left shift current line. + 2< + 3<< + 4<<<<< + call assert_equal([' 1', + \ ' 2', + \ ' 3', + \ '4', + \ ' 5'], getline(1, '$')) + + " shift right with range. + call setline(1, range(1, 5)) + %>>> + 2,3<< + call assert_equal([' 1', + \ ' 2', + \ ' 3', + \ ' 4', + \ ' 5'], getline(1, '$')) + + " shift right with range and count. + call setline(1, range(1, 5)) + %>>> + 2<<3 + call assert_equal([' 1', + \ ' 2', + \ ' 3', + \ ' 4', + \ ' 5'], getline(1, '$')) + + bw! + set shiftwidth& +endfunc + +func Test_ex_shift_rightleft() + CheckFeature rightleft + + set shiftwidth=2 rightleft + + call setline(1, range(1, 4)) + 2,3<< + call assert_equal(['1', + \ ' 2', + \ ' 3', + \ '4'], getline(1, '$')) + + 3,4> + call assert_equal(['1', + \ ' 2', + \ ' 3', + \ '4'], getline(1, '$')) + + bw! + set rightleft& shiftwidth& +endfunc + +func Test_ex_shift_errors() + call assert_fails('><', 'E488:') + call assert_fails('<>', 'E488:') + + call assert_fails('>!', 'E477:') + call assert_fails('<!', 'E477:') + + " call assert_fails('2,1>', 'E493:') + call assert_fails('execute "2,1>"', 'E493:') + " call assert_fails('2,1<', 'E493:') + call assert_fails('execute "2,1<"', 'E493:') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_signals.vim b/test/old/testdir/test_signals.vim new file mode 100644 index 0000000000..667448a7c2 --- /dev/null +++ b/test/old/testdir/test_signals.vim @@ -0,0 +1,165 @@ +" Test signal handling. + +source check.vim +source term_util.vim + +CheckUnix + +source shared.vim + +" Check whether a signal is available on this system. +func HasSignal(signal) + let signals = system('kill -l') + return signals =~# '\<' .. a:signal .. '\>' +endfunc + +" Test signal WINCH (window resize signal) +func Test_signal_WINCH() + throw 'skipped: Nvim cannot avoid terminal resize' + CheckNotGui + if !HasSignal('WINCH') + throw 'Skipped: WINCH signal not supported' + endif + + " We do not actually want to change the size of the terminal. + let old_WS = '' + if exists('&t_WS') + let old_WS = &t_WS + let &t_WS = '' + endif + + let old_lines = &lines + let old_columns = &columns + let new_lines = &lines - 2 + let new_columns = &columns - 2 + + exe 'set lines=' .. new_lines + exe 'set columns=' .. new_columns + call assert_equal(new_lines, &lines) + call assert_equal(new_columns, &columns) + + " Send signal and wait for signal to be processed. + " 'lines' and 'columns' should have been restored + " after handing signal WINCH. + exe 'silent !kill -s WINCH ' .. getpid() + call WaitForAssert({-> assert_equal(old_lines, &lines)}) + call assert_equal(old_columns, &columns) + + if old_WS != '' + let &t_WS = old_WS + endif +endfunc + +" Test signal PWR, which should update the swap file. +func Test_signal_PWR() + if !HasSignal('PWR') + throw 'Skipped: PWR signal not supported' + endif + + " Set a very large 'updatetime' and 'updatecount', so that we can be sure + " that swap file is updated as a result of sending PWR signal, and not + " because of exceeding 'updatetime' or 'updatecount' when changing buffer. + set updatetime=100000 updatecount=100000 + new Xtest_signal_PWR + let swap_name = swapname('%') + call setline(1, '123') + preserve + let swap_content = readfile(swap_name, 'b') + + " Update the buffer and check that the swap file is not yet updated, + " since we set 'updatetime' and 'updatecount' to large values. + call setline(1, 'abc') + call assert_equal(swap_content, readfile(swap_name, 'b')) + + " Sending PWR signal should update the swap file. + exe 'silent !kill -s PWR ' .. getpid() + call WaitForAssert({-> assert_notequal(swap_content, readfile(swap_name, 'b'))}) + + bwipe! + set updatetime& updatecount& +endfunc + +" Test signal INT. Handler sets got_int. It should be like typing CTRL-C. +func Test_signal_INT() + CheckRunVimInTerminal + if !HasSignal('INT') + throw 'Skipped: INT signal not supported' + endif + + " Skip the rest of the test when running with valgrind as signal INT is not + " received somehow by Vim when running with valgrind. + let cmd = GetVimCommand() + if cmd =~ 'valgrind' + throw 'Skipped: cannot test signal INT with valgrind' + endif + + let buf = RunVimInTerminal('', {'rows': 6}) + let pid_vim = term_getjob(buf)->job_info().process + + " Check that an endless loop in Vim is interrupted by signal INT. + call term_sendkeys(buf, ":while 1 | endwhile\n") + call WaitForAssert({-> assert_equal(':while 1 | endwhile', term_getline(buf, 6))}) + exe 'silent !kill -s INT ' .. pid_vim + call term_sendkeys(buf, ":call setline(1, 'INTERRUPTED')\n") + call WaitForAssert({-> assert_equal('INTERRUPTED', term_getline(buf, 1))}) + + call StopVimInTerminal(buf) +endfunc + +" Test a deadly signal. +" +" There are several deadly signals: SISEGV, SIBUS, SIGTERM... +" Test uses signal SIGTERM as it does not create a core +" dump file unlike SIGSEGV, SIGBUS, etc. See "man 7 signals. +" +" Vim should exit with a deadly signal and unsaved changes +" should be recoverable from the swap file preserved as a +" result of the deadly signal handler. +func Test_deadly_signal_TERM() + if !HasSignal('TERM') + throw 'Skipped: TERM signal not supported' + endif + CheckRunVimInTerminal + let cmd = GetVimCommand() + if cmd =~ 'valgrind' + throw 'Skipped: cannot test signal TERM with valgrind' + endif + + " If test fails once, it can leave temporary files and trying to rerun + " the test would then fail again if they are not deleted first. + call delete('.Xsig_TERM.swp') + call delete('XsetupAucmd') + call delete('XautoOut') + let lines =<< trim END + au VimLeave * call writefile(["VimLeave triggered"], "XautoOut", "as") + au VimLeavePre * call writefile(["VimLeavePre triggered"], "XautoOut", "as") + END + call writefile(lines, 'XsetupAucmd') + + let buf = RunVimInTerminal('-S XsetupAucmd Xsig_TERM', {'rows': 6}) + let pid_vim = term_getjob(buf)->job_info().process + + call term_sendkeys(buf, ":call setline(1, 'foo')\n") + call WaitForAssert({-> assert_equal('foo', term_getline(buf, 1))}) + + call assert_false(filereadable('Xsig_TERM')) + exe 'silent !kill -s TERM ' .. pid_vim + call WaitForAssert({-> assert_true(filereadable('.Xsig_TERM.swp'))}) + + " Don't call StopVimInTerminal() as it expects job to be still running. + call WaitForAssert({-> assert_equal("finished", term_getstatus(buf))}) + + new + silent recover .Xsig_TERM.swp + call assert_equal(['foo'], getline(1, '$')) + + let result = readfile('XautoOut') + call assert_equal(["VimLeavePre triggered", "VimLeave triggered"], result) + + %bwipe! + call delete('.Xsig_TERM.swp') + call delete('XsetupAucmd') + call delete('XautoOut') +endfunc + +" vim: ts=8 sw=2 sts=2 tw=80 fdm=marker diff --git a/test/old/testdir/test_signs.vim b/test/old/testdir/test_signs.vim new file mode 100644 index 0000000000..d7baa7e870 --- /dev/null +++ b/test/old/testdir/test_signs.vim @@ -0,0 +1,2033 @@ +" Test for signs + +source check.vim +CheckFeature signs + +source screendump.vim + +func Test_sign() + new + call setline(1, ['a', 'b', 'c', 'd']) + + " Define some signs. + " We can specify icons even if not all versions of vim support icons as + " icon is ignored when not supported. "(not supported)" is shown after + " the icon name when listing signs. + sign define Sign1 text=x + + call Sign_command_ignore_error('sign define Sign2 text=xy texthl=Title linehl=Error culhl=Search numhl=Number icon=../../pixmaps/stock_vim_find_help.png') + + " Test listing signs. + let a=execute('sign list') + call assert_match('^\nsign Sign1 text=x \nsign Sign2 ' . + \ 'icon=../../pixmaps/stock_vim_find_help.png .*text=xy ' . + \ 'linehl=Error texthl=Title culhl=Search numhl=Number$', a) + + let a=execute('sign list Sign1') + call assert_equal("\nsign Sign1 text=x ", a) + + " Split the window to the bottom to verify sign jump will stay in the + " current window if the buffer is displayed there. + let bn = bufnr('%') + let wn = winnr() + exe 'sign place 41 line=3 name=Sign1 buffer=' . bn + 1 + bot split + exe 'sign jump 41 buffer=' . bufnr('%') + call assert_equal('c', getline('.')) + call assert_equal(3, winnr()) + call assert_equal(bn, bufnr('%')) + call assert_notequal(wn, winnr()) + + " Create a new buffer and check that ":sign jump" switches to the old buffer. + 1 + new foo + call assert_notequal(bn, bufnr('%')) + exe 'sign jump 41 buffer=' . bn + call assert_equal(bn, bufnr('%')) + call assert_equal('c', getline('.')) + + " Redraw to make sure that screen redraw with sign gets exercised, + " with and without 'rightleft'. + if has('rightleft') + set rightleft + redraw + set norightleft + endif + redraw + + " Check that we can't change sign. + call assert_fails("sign place 40 name=Sign1 buffer=" . bufnr('%'), 'E885:') + + " Check placed signs + let a=execute('sign place') + call assert_equal("\n--- Signs ---\nSigns for [NULL]:\n" . + \ " line=3 id=41 name=Sign1 priority=10\n", a) + + " Unplace the sign and try jumping to it again should fail. + sign unplace 41 + 1 + call assert_fails("sign jump 41 buffer=" . bufnr('%'), 'E157:') + call assert_equal('a', getline('.')) + + " Unplace sign on current line. + exe 'sign place 42 line=4 name=Sign2 buffer=' . bufnr('%') + 4 + sign unplace + let a=execute('sign place') + call assert_equal("\n--- Signs ---\n", a) + + " Try again to unplace sign on current line, it should fail this time. + call assert_fails('sign unplace', 'E159:') + + " Unplace all signs. + exe 'sign place 41 line=3 name=Sign1 buffer=' . bufnr('%') + sign unplace * + let a=execute('sign place') + call assert_equal("\n--- Signs ---\n", a) + + " Place a sign without specifying the filename or buffer + sign place 77 line=9 name=Sign2 + let a=execute('sign place') + call assert_equal("\n--- Signs ---\nSigns for [NULL]:\n" . + \ " line=9 id=77 name=Sign2 priority=10\n", a) + sign unplace * + + " Check :jump with file=... + edit foo + call setline(1, ['A', 'B', 'C', 'D']) + + call Sign_command_ignore_error('sign define Sign3 text=y texthl=DoesNotExist linehl=DoesNotExist icon=doesnotexist.xpm') + + let fn = expand('%:p') + exe 'sign place 43 line=2 name=Sign3 file=' . fn + edit bar + call assert_notequal(fn, expand('%:p')) + exe 'sign jump 43 file=' . fn + call assert_equal('B', getline('.')) + + " Check for jumping to a sign in a hidden buffer + enew! | only! + edit foo + call setline(1, ['A', 'B', 'C', 'D']) + let fn = expand('%:p') + exe 'sign place 21 line=3 name=Sign3 file=' . fn + hide edit bar + exe 'sign jump 21 file=' . fn + call assert_equal('C', getline('.')) + + " can't define a sign with a non-printable character as text + call assert_fails("sign define Sign4 text=\e linehl=Comment", 'E239:') + call assert_fails("sign define Sign4 text=a\e linehl=Comment", 'E239:') + call assert_fails("sign define Sign4 text=\ea linehl=Comment", 'E239:') + + " Only 0, 1 or 2 character text is allowed + call assert_fails("sign define Sign4 text=abc linehl=Comment", 'E239:') + " call assert_fails("sign define Sign4 text= linehl=Comment", 'E239:') + call assert_fails("sign define Sign4 text=\\ ab linehl=Comment", 'E239:') + + " an empty highlight argument for an existing sign clears it + sign define SignY texthl=TextHl culhl=CulHl linehl=LineHl numhl=NumHl + let sl = sign_getdefined('SignY')[0] + call assert_equal('TextHl', sl.texthl) + call assert_equal('CulHl', sl.culhl) + call assert_equal('LineHl', sl.linehl) + call assert_equal('NumHl', sl.numhl) + + sign define SignY texthl= culhl=CulHl linehl=LineHl numhl=NumHl + let sl = sign_getdefined('SignY')[0] + call assert_false(has_key(sl, 'texthl')) + call assert_equal('CulHl', sl.culhl) + call assert_equal('LineHl', sl.linehl) + call assert_equal('NumHl', sl.numhl) + + sign define SignY linehl= + let sl = sign_getdefined('SignY')[0] + call assert_false(has_key(sl, 'linehl')) + call assert_equal('CulHl', sl.culhl) + call assert_equal('NumHl', sl.numhl) + + sign define SignY culhl= + let sl = sign_getdefined('SignY')[0] + call assert_false(has_key(sl, 'culhl')) + call assert_equal('NumHl', sl.numhl) + + sign define SignY numhl= + let sl = sign_getdefined('SignY')[0] + call assert_false(has_key(sl, 'numhl')) + + sign undefine SignY + + " define sign with whitespace + sign define Sign4 text=\ X linehl=Comment + sign undefine Sign4 + sign define Sign4 linehl=Comment text=\ X + sign undefine Sign4 + + sign define Sign5 text=X\ linehl=Comment + sign undefine Sign5 + sign define Sign5 linehl=Comment text=X\ + sign undefine Sign5 + + " define sign with backslash + sign define Sign4 text=\\\\ linehl=Comment + sign undefine Sign4 + sign define Sign4 text=\\ linehl=Comment + sign undefine Sign4 + + " define a sign with a leading 0 in the name + sign unplace * + sign define 004 text=#> linehl=Comment + let a = execute('sign list 4') + call assert_equal("\nsign 4 text=#> linehl=Comment", a) + exe 'sign place 20 line=3 name=004 buffer=' . bufnr('') + let a = execute('sign place') + call assert_equal("\n--- Signs ---\nSigns for foo:\n" . + \ " line=3 id=20 name=4 priority=10\n", a) + exe 'sign unplace 20 buffer=' . bufnr('') + sign undefine 004 + call assert_fails('sign list 4', 'E155:') + + " After undefining the sign, we should no longer be able to place it. + sign undefine Sign1 + sign undefine Sign2 + sign undefine Sign3 + call assert_fails("sign place 41 line=3 name=Sign1 buffer=" . + \ bufnr('%'), 'E155:') + + " Defining a sign without attributes is allowed. + sign define Sign1 + call assert_equal([{'name': 'Sign1'}], sign_getdefined()) + sign undefine Sign1 +endfunc + +func Test_sign_many_bytes() + new + set signcolumn=number + set number + call setline(1, 'some text') + " composing characters can use many bytes, check for overflow + sign define manyBytes text=▶᷄᷅᷆◀᷄᷅᷆᷇ + sign place 17 line=1 name=manyBytes + redraw + + bwipe! + sign undefine manyBytes +endfunc + +" Undefining placed sign is not recommended. +" Quoting :help sign +" +" :sign undefine {name} +" Deletes a previously defined sign. If signs with this {name} +" are still placed this will cause trouble. +func Test_sign_undefine_still_placed() + new foobar + sign define Sign text=x + exe 'sign place 41 line=1 name=Sign buffer=' . bufnr('%') + sign undefine Sign + + " Listing placed sign should show that sign is deleted. + let a=execute('sign place') + call assert_equal("\n--- Signs ---\nSigns for foobar:\n" . + \ " line=1 id=41 name=[Deleted] priority=10\n", a) + + sign unplace 41 + let a=execute('sign place') + call assert_equal("\n--- Signs ---\n", a) +endfunc + +func Test_sign_completion() + sign define Sign1 text=x + sign define Sign2 text=y + + call feedkeys(":sign \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign define jump list place undefine unplace', @:) + + call feedkeys(":sign define Sign \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign define Sign culhl= icon= linehl= numhl= text= texthl=', @:) + + for hl in ['culhl', 'linehl', 'numhl', 'texthl'] + call feedkeys(":sign define Sign "..hl.."=Spell\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign define Sign '..hl..'=SpellBad SpellCap ' . + \ 'SpellLocal SpellRare', @:) + endfor + + call writefile(repeat(["Sun is shining"], 30), "XsignOne") + call writefile(repeat(["Sky is blue"], 30), "XsignTwo") + call feedkeys(":sign define Sign icon=Xsig\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign define Sign icon=XsignOne XsignTwo', @:) + + " Test for completion of arguments to ':sign undefine' + call feedkeys(":sign undefine \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign undefine Sign1 Sign2', @:) + + call feedkeys(":sign place 1 \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign place 1 buffer= file= group= line= name= priority=', + \ @:) + + call feedkeys(":sign place 1 name=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign place 1 name=Sign1 Sign2', @:) + + edit XsignOne + sign place 1 name=Sign1 line=5 + sign place 1 name=Sign1 group=g1 line=10 + edit XsignTwo + sign place 1 name=Sign2 group=g2 line=15 + + " Test for completion of group= and file= arguments to ':sign place' + call feedkeys(":sign place 1 name=Sign1 file=Xsign\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign place 1 name=Sign1 file=XsignOne XsignTwo', @:) + call feedkeys(":sign place 1 name=Sign1 group=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign place 1 name=Sign1 group=g1 g2', @:) + + " Test for completion of arguments to 'sign place' without sign identifier + call feedkeys(":sign place \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign place buffer= file= group=', @:) + call feedkeys(":sign place file=Xsign\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign place file=XsignOne XsignTwo', @:) + call feedkeys(":sign place group=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign place group=g1 g2', @:) + call feedkeys(":sign place group=g1 file=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign place group=g1 file=XsignOne XsignTwo', @:) + + " Test for completion of arguments to ':sign unplace' + call feedkeys(":sign unplace 1 \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign unplace 1 buffer= file= group=', @:) + call feedkeys(":sign unplace 1 file=Xsign\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign unplace 1 file=XsignOne XsignTwo', @:) + call feedkeys(":sign unplace 1 group=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign unplace 1 group=g1 g2', @:) + call feedkeys(":sign unplace 1 group=g2 file=Xsign\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign unplace 1 group=g2 file=XsignOne XsignTwo', @:) + + " Test for completion of arguments to ':sign list' + call feedkeys(":sign list \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign list Sign1 Sign2', @:) + + " Test for completion of arguments to ':sign jump' + call feedkeys(":sign jump 1 \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign jump 1 buffer= file= group=', @:) + call feedkeys(":sign jump 1 file=Xsign\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign jump 1 file=XsignOne XsignTwo', @:) + call feedkeys(":sign jump 1 group=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign jump 1 group=g1 g2', @:) + + " Error cases + call feedkeys(":sign here\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"sign here', @:) + call feedkeys(":sign define Sign here=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"sign define Sign here=\<C-A>", @:) + call feedkeys(":sign place 1 here=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"sign place 1 here=\<C-A>", @:) + call feedkeys(":sign jump 1 here=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"sign jump 1 here=\<C-A>", @:) + call feedkeys(":sign here there\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"sign here there\<C-A>", @:) + call feedkeys(":sign here there=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"sign here there=\<C-A>", @:) + + sign unplace * group=* + sign undefine Sign1 + sign undefine Sign2 + enew + call delete('XsignOne') + call delete('XsignTwo') +endfunc + +func Test_sign_invalid_commands() + sign define Sign1 text=x + + call assert_fails('sign', 'E471:') + call assert_fails('sign jump', 'E471:') + call assert_fails('sign xxx', 'E160:') + call assert_fails('sign define', 'E156:') + call assert_fails('sign define Sign1 xxx', 'E475:') + call assert_fails('sign undefine', 'E156:') + call assert_fails('sign list xxx', 'E155:') + call assert_fails('sign place 1 buffer=999', 'E158:') + call assert_fails('sign place 1 name=Sign1 buffer=999', 'E158:') + call assert_fails('sign place buffer=999', 'E158:') + call assert_fails('sign jump buffer=999', 'E158:') + call assert_fails('sign jump 1 file=', 'E158:') + call assert_fails('sign jump 1 group=', 'E474:') + call assert_fails('sign jump 1 name=', 'E474:') + call assert_fails('sign jump 1 name=Sign1', 'E474:') + call assert_fails('sign jump 1 line=100', '474:') + " call assert_fails('sign define Sign2 text=', 'E239:') + " Non-numeric identifier for :sign place + call assert_fails("sign place abc line=3 name=Sign1 buffer=" . bufnr(''), + \ 'E474:') + " Non-numeric identifier for :sign unplace + call assert_fails("sign unplace abc name=Sign1 buffer=" . bufnr(''), + \ 'E474:') + " Number followed by an alphabet as sign identifier for :sign place + call assert_fails("sign place 1abc line=3 name=Sign1 buffer=" . bufnr(''), + \ 'E474:') + " Number followed by an alphabet as sign identifier for :sign unplace + call assert_fails("sign unplace 2abc name=Sign1 buffer=" . bufnr(''), + \ 'E474:') + " Sign identifier and '*' for :sign unplace + call assert_fails("sign unplace 2 *", 'E474:') + " Trailing characters after buffer number for :sign place + call assert_fails("sign place 1 line=3 name=Sign1 buffer=" . + \ bufnr('%') . 'xxx', 'E488:') + " Trailing characters after buffer number for :sign unplace + call assert_fails("sign unplace 1 buffer=" . bufnr('%') . 'xxx', 'E488:') + call assert_fails("sign unplace * buffer=" . bufnr('%') . 'xxx', 'E488:') + call assert_fails("sign unplace 1 xxx", 'E474:') + call assert_fails("sign unplace * xxx", 'E474:') + call assert_fails("sign unplace xxx", 'E474:') + " Placing a sign without line number + call assert_fails("sign place name=Sign1 buffer=" . bufnr('%'), 'E474:') + " Placing a sign without sign name + call assert_fails("sign place line=10 buffer=" . bufnr('%'), 'E474:') + " Unplacing a sign with line number + call assert_fails("sign unplace 2 line=10 buffer=" . bufnr('%'), 'E474:') + " Unplacing a sign with sign name + call assert_fails("sign unplace 2 name=Sign1 buffer=" . bufnr('%'), 'E474:') + " Placing a sign without sign name + call assert_fails("sign place 2 line=3 buffer=" . bufnr('%'), 'E474:') + " Placing a sign with only sign identifier + call assert_fails("sign place 2", 'E474:') + " Placing a sign with only a name + call assert_fails("sign place abc", 'E474:') + " Placing a sign with only line number + call assert_fails("sign place 5 line=3", 'E474:') + " Placing a sign with only sign group + call assert_fails("sign place 5 group=g1", 'E474:') + call assert_fails("sign place 5 group=*", 'E474:') + " Placing a sign with only sign priority + call assert_fails("sign place 5 priority=10", 'E474:') + + sign undefine Sign1 +endfunc + +func Test_sign_delete_buffer() + new + sign define Sign text=x + let bufnr = bufnr('%') + new + exe 'bd ' . bufnr + exe 'sign place 61 line=3 name=Sign buffer=' . bufnr + call assert_fails('sign jump 61 buffer=' . bufnr, 'E934:') + sign unplace 61 + sign undefine Sign +endfunc + +" Ignore error: E255: Couldn't read in sign data! +" This error can happen when running in the GUI. +" Some gui like Motif do not support the png icon format. +func Sign_command_ignore_error(cmd) + try + exe a:cmd + catch /E255:/ + endtry +endfunc + +" ignore error: E255: Couldn't read in sign data! +" This error can happen when running in gui. +func Sign_define_ignore_error(name, attr) + try + call sign_define(a:name, a:attr) + catch /E255:/ + endtry +endfunc + +" Test for Vim script functions for managing signs +func Test_sign_funcs() + " Remove all the signs + call sign_unplace('*') + call sign_undefine() + + " Tests for sign_define() + let attr = {'text' : '=>', 'linehl' : 'Search', 'texthl' : 'Error', + \ 'culhl': 'Visual', 'numhl': 'Number'} + call assert_equal(0, "sign1"->sign_define(attr)) + call assert_equal([{'name' : 'sign1', 'texthl' : 'Error', 'linehl' : 'Search', + \ 'culhl' : 'Visual', 'numhl': 'Number', 'text' : '=>'}], + \ sign_getdefined()) + + " Define a new sign without attributes and then update it + call sign_define("sign2") + let attr = {'text' : '!!', 'linehl' : 'DiffAdd', 'texthl' : 'DiffChange', + \ 'culhl': 'DiffDelete', 'numhl': 'Number', 'icon' : 'sign2.ico'} + call Sign_define_ignore_error("sign2", attr) + call assert_equal([{'name' : 'sign2', 'texthl' : 'DiffChange', + \ 'linehl' : 'DiffAdd', 'culhl' : 'DiffDelete', 'text' : '!!', + \ 'numhl': 'Number', 'icon' : 'sign2.ico'}], + \ "sign2"->sign_getdefined()) + + " Test for a sign name with digits + call assert_equal(0, sign_define(0002, {'linehl' : 'StatusLine'})) + call assert_equal([{'name' : '2', 'linehl' : 'StatusLine'}], + \ sign_getdefined(0002)) + eval 0002->sign_undefine() + + " Tests for invalid arguments to sign_define() + call assert_fails('call sign_define("sign4", {"text" : "===>"})', 'E239:') + " call assert_fails('call sign_define("sign5", {"text" : ""})', 'E239:') + call assert_fails('call sign_define({})', 'E731:') + call assert_fails('call sign_define("sign6", [])', 'E1206:') + + " Tests for sign_getdefined() + call assert_equal([], sign_getdefined("none")) + call assert_fails('call sign_getdefined({})', 'E731:') + + " Tests for sign_place() + call writefile(repeat(["Sun is shining"], 30), "Xsign") + edit Xsign + + call assert_equal(10, sign_place(10, '', 'sign1', 'Xsign', + \ {'lnum' : 20})) + call assert_equal([{'bufnr' : bufnr(''), 'signs' : + \ [{'id' : 10, 'group' : '', 'lnum' : 20, 'name' : 'sign1', + \ 'priority' : 10}]}], sign_getplaced('Xsign')) + call assert_equal([{'bufnr' : bufnr(''), 'signs' : + \ [{'id' : 10, 'group' : '', 'lnum' : 20, 'name' : 'sign1', + \ 'priority' : 10}]}], + \ '%'->sign_getplaced({'lnum' : 20})) + call assert_equal([{'bufnr' : bufnr(''), 'signs' : + \ [{'id' : 10, 'group' : '', 'lnum' : 20, 'name' : 'sign1', + \ 'priority' : 10}]}], + \ sign_getplaced('', {'id' : 10})) + + " Tests for invalid arguments to sign_place() + call assert_fails('call sign_place([], "", "mySign", 1)', 'E745:') + call assert_fails('call sign_place(5, "", "mySign", -1)', 'E158:') + call assert_fails('call sign_place(-1, "", "sign1", "Xsign", [])', 'E1206:') + call assert_fails('call sign_place(-1, "", "sign1", "Xsign", + \ {"lnum" : 30})', 'E474:') + call assert_fails('call sign_place(10, "", "xsign1x", "Xsign", + \ {"lnum" : 30})', 'E155:') + call assert_fails('call sign_place(10, "", "", "Xsign", + \ {"lnum" : 30})', 'E155:') + call assert_fails('call sign_place(10, "", [], "Xsign", + \ {"lnum" : 30})', 'E730:') + call assert_fails('call sign_place(5, "", "sign1", "abcxyz.xxx", + \ {"lnum" : 10})', 'E158:') + call assert_fails('call sign_place(5, "", "sign1", "@", {"lnum" : 10})', + \ 'E158:') + call assert_fails('call sign_place(5, "", "sign1", [], {"lnum" : 10})', + \ 'E730:') + call assert_fails('call sign_place(21, "", "sign1", "Xsign", + \ {"lnum" : -1})', 'E474:') + call assert_fails('call sign_place(22, "", "sign1", "Xsign", + \ {"lnum" : 0})', 'E474:') + call assert_fails('call sign_place(22, "", "sign1", "Xsign", + \ {"lnum" : []})', 'E745:') + call assert_equal(-1, sign_place(1, "*", "sign1", "Xsign", {"lnum" : 10})) + + " Tests for sign_getplaced() + call assert_equal([{'bufnr' : bufnr(''), 'signs' : + \ [{'id' : 10, 'group' : '', 'lnum' : 20, 'name' : 'sign1', + \ 'priority' : 10}]}], + \ sign_getplaced(bufnr('Xsign'))) + call assert_equal([{'bufnr' : bufnr(''), 'signs' : + \ [{'id' : 10, 'group' : '', 'lnum' : 20, 'name' : 'sign1', + \ 'priority' : 10}]}], + \ sign_getplaced()) + call assert_fails("call sign_getplaced('dummy.sign')", 'E158:') + call assert_fails('call sign_getplaced("&")', 'E158:') + call assert_fails('call sign_getplaced(-1)', 'E158:') + call assert_fails('call sign_getplaced("Xsign", [])', 'E1206:') + call assert_equal([{'bufnr' : bufnr(''), 'signs' : []}], + \ sign_getplaced('Xsign', {'lnum' : 1000000})) + call assert_fails("call sign_getplaced('Xsign', {'lnum' : []})", + \ 'E745:') + call assert_equal([{'bufnr' : bufnr(''), 'signs' : []}], + \ sign_getplaced('Xsign', {'id' : 44})) + call assert_fails("call sign_getplaced('Xsign', {'id' : []})", + \ 'E745:') + + " Tests for sign_unplace() + eval 20->sign_place('', 'sign2', 'Xsign', {"lnum" : 30}) + call assert_equal(0, sign_unplace('', + \ {'id' : 20, 'buffer' : 'Xsign'})) + call assert_equal(-1, ''->sign_unplace( + \ {'id' : 30, 'buffer' : 'Xsign'})) + call sign_place(20, '', 'sign2', 'Xsign', {"lnum" : 30}) + call assert_fails("call sign_unplace('', + \ {'id' : 20, 'buffer' : 'buffer.c'})", 'E158:') + call assert_fails("call sign_unplace('', + \ {'id' : 20, 'buffer' : '&'})", 'E158:') + call assert_fails("call sign_unplace('g1', + \ {'id' : 20, 'buffer' : 200})", 'E158:') + call assert_fails("call sign_unplace('g1', 'mySign')", 'E1206:') + + call sign_unplace('*') + + " Test for modifying a placed sign + call assert_equal(15, sign_place(15, '', 'sign1', 'Xsign', {'lnum' : 20})) + call assert_equal(15, sign_place(15, '', 'sign2', 'Xsign')) + call assert_equal([{'bufnr' : bufnr(''), 'signs' : + \ [{'id' : 15, 'group' : '', 'lnum' : 20, 'name' : 'sign2', + \ 'priority' : 10}]}], + \ sign_getplaced()) + + " Tests for sign_undefine() + call assert_equal(0, sign_undefine("sign1")) + call assert_equal([], sign_getdefined("sign1")) + call assert_fails('call sign_undefine("none")', 'E155:') + call assert_fails('call sign_undefine({})', 'E731:') + + " Test for using '.' as the line number for sign_place() + call Sign_define_ignore_error("sign1", attr) + call cursor(22, 1) + call assert_equal(15, sign_place(15, '', 'sign1', 'Xsign', + \ {'lnum' : '.'})) + call assert_equal([{'bufnr' : bufnr(''), 'signs' : + \ [{'id' : 15, 'group' : '', 'lnum' : 22, 'name' : 'sign1', + \ 'priority' : 10}]}], + \ sign_getplaced('%', {'lnum' : 22})) + + call delete("Xsign") + call sign_unplace('*') + call sign_undefine() + enew | only +endfunc + +" Tests for sign groups +func Test_sign_group() + enew | only + " Remove all the signs + call sign_unplace('*') + call sign_undefine() + + call writefile(repeat(["Sun is shining"], 30), "Xsign") + + let attr = {'text' : '=>', 'linehl' : 'Search', 'texthl' : 'Error'} + call assert_equal(0, sign_define("sign1", attr)) + + edit Xsign + let bnum = bufnr('%') + + " Error case + call assert_fails("call sign_place(5, [], 'sign1', 'Xsign', + \ {'lnum' : 30})", 'E730:') + + " place three signs with the same identifier. One in the global group and + " others in the named groups + call assert_equal(5, sign_place(5, '', 'sign1', 'Xsign', + \ {'lnum' : 10})) + call assert_equal(5, sign_place(5, 'g1', 'sign1', bnum, {'lnum' : 20})) + call assert_equal(5, sign_place(5, 'g2', 'sign1', bnum, {'lnum' : 30})) + + " Test for sign_getplaced() with group + let s = sign_getplaced('Xsign') + call assert_equal(1, len(s[0].signs)) + call assert_equal(s[0].signs[0].group, '') + let s = sign_getplaced(bnum, {'group' : ''}) + call assert_equal([{'id' : 5, 'group' : '', 'name' : 'sign1', 'lnum' : 10, + \ 'priority' : 10}], s[0].signs) + call assert_equal(1, len(s[0].signs)) + let s = sign_getplaced(bnum, {'group' : 'g2'}) + call assert_equal('g2', s[0].signs[0].group) + let s = sign_getplaced(bnum, {'group' : 'g3'}) + call assert_equal([], s[0].signs) + let s = sign_getplaced(bnum, {'group' : '*'}) + call assert_equal([{'id' : 5, 'group' : '', 'name' : 'sign1', 'lnum' : 10, + \ 'priority' : 10}, + \ {'id' : 5, 'group' : 'g1', 'name' : 'sign1', 'lnum' : 20, + \ 'priority' : 10}, + \ {'id' : 5, 'group' : 'g2', 'name' : 'sign1', 'lnum' : 30, + \ 'priority' : 10}], + \ s[0].signs) + + " Test for sign_getplaced() with id + let s = sign_getplaced(bnum, {'id' : 5}) + call assert_equal([{'id' : 5, 'group' : '', 'name' : 'sign1', 'lnum' : 10, + \ 'priority' : 10}], + \ s[0].signs) + let s = sign_getplaced(bnum, {'id' : 5, 'group' : 'g2'}) + call assert_equal( + \ [{'id' : 5, 'name' : 'sign1', 'lnum' : 30, 'group' : 'g2', + \ 'priority' : 10}], + \ s[0].signs) + let s = sign_getplaced(bnum, {'id' : 5, 'group' : '*'}) + call assert_equal([{'id' : 5, 'group' : '', 'name' : 'sign1', 'lnum' : 10, + \ 'priority' : 10}, + \ {'id' : 5, 'group' : 'g1', 'name' : 'sign1', 'lnum' : 20, + \ 'priority' : 10}, + \ {'id' : 5, 'group' : 'g2', 'name' : 'sign1', 'lnum' : 30, + \ 'priority' : 10}], + \ s[0].signs) + let s = sign_getplaced(bnum, {'id' : 5, 'group' : 'g3'}) + call assert_equal([], s[0].signs) + + " Test for sign_getplaced() with lnum + let s = sign_getplaced(bnum, {'lnum' : 20}) + call assert_equal([], s[0].signs) + let s = sign_getplaced(bnum, {'lnum' : 20, 'group' : 'g1'}) + call assert_equal( + \ [{'id' : 5, 'name' : 'sign1', 'lnum' : 20, 'group' : 'g1', + \ 'priority' : 10}], + \ s[0].signs) + let s = sign_getplaced(bnum, {'lnum' : 30, 'group' : '*'}) + call assert_equal( + \ [{'id' : 5, 'name' : 'sign1', 'lnum' : 30, 'group' : 'g2', + \ 'priority' : 10}], + \ s[0].signs) + let s = sign_getplaced(bnum, {'lnum' : 40, 'group' : '*'}) + call assert_equal([], s[0].signs) + + " Error case + call assert_fails("call sign_getplaced(bnum, {'group' : []})", + \ 'E730:') + + " Clear the sign in global group + call sign_unplace('', {'id' : 5, 'buffer' : bnum}) + let s = sign_getplaced(bnum, {'group' : '*'}) + call assert_equal([ + \ {'id' : 5, 'name' : 'sign1', 'lnum' : 20, 'group' : 'g1', + \ 'priority' : 10}, + \ {'id' : 5, 'name' : 'sign1', 'lnum' : 30, 'group' : 'g2', + \ 'priority' : 10}], + \ s[0].signs) + + " Clear the sign in one of the groups + call sign_unplace('g1', {'buffer' : 'Xsign'}) + let s = sign_getplaced(bnum, {'group' : '*'}) + call assert_equal([ + \ {'id' : 5, 'name' : 'sign1', 'lnum' : 30, 'group' : 'g2', + \ 'priority' : 10}], + \ s[0].signs) + + " Clear all the signs from the buffer + call sign_unplace('*', {'buffer' : bnum}) + call assert_equal([], sign_getplaced(bnum, {'group' : '*'})[0].signs) + + " Clear sign across groups using an identifier + call sign_place(25, '', 'sign1', bnum, {'lnum' : 10}) + call sign_place(25, 'g1', 'sign1', bnum, {'lnum' : 11}) + call sign_place(25, 'g2', 'sign1', bnum, {'lnum' : 12}) + call assert_equal(0, sign_unplace('*', {'id' : 25})) + call assert_equal([], sign_getplaced(bnum, {'group' : '*'})[0].signs) + + " Error case + call assert_fails("call sign_unplace({})", 'E1174:') + + " Place a sign in the global group and try to delete it using a group + call assert_equal(5, sign_place(5, '', 'sign1', bnum, {'lnum' : 10})) + call assert_equal(-1, sign_unplace('g1', {'id' : 5})) + + " Place signs in multiple groups and delete all the signs in one of the + " group + call assert_equal(5, sign_place(5, '', 'sign1', bnum, {'lnum' : 10})) + call assert_equal(6, sign_place(6, '', 'sign1', bnum, {'lnum' : 11})) + call assert_equal(5, sign_place(5, 'g1', 'sign1', bnum, {'lnum' : 10})) + call assert_equal(5, sign_place(5, 'g2', 'sign1', bnum, {'lnum' : 10})) + call assert_equal(6, sign_place(6, 'g1', 'sign1', bnum, {'lnum' : 11})) + call assert_equal(6, sign_place(6, 'g2', 'sign1', bnum, {'lnum' : 11})) + call assert_equal(0, sign_unplace('g1')) + let s = sign_getplaced(bnum, {'group' : 'g1'}) + call assert_equal([], s[0].signs) + let s = sign_getplaced(bnum) + call assert_equal(2, len(s[0].signs)) + let s = sign_getplaced(bnum, {'group' : 'g2'}) + call assert_equal('g2', s[0].signs[0].group) + call assert_equal(0, sign_unplace('', {'id' : 5})) + call assert_equal(0, sign_unplace('', {'id' : 6})) + let s = sign_getplaced(bnum, {'group' : 'g2'}) + call assert_equal('g2', s[0].signs[0].group) + call assert_equal(0, sign_unplace('', {'buffer' : bnum})) + + call sign_unplace('*') + + " Test for :sign command and groups + sign place 5 line=10 name=sign1 file=Xsign + sign place 5 group=g1 line=10 name=sign1 file=Xsign + sign place 5 group=g2 line=10 name=sign1 file=Xsign + + " Tests for the ':sign place' command + + " :sign place file={fname} + let a = execute('sign place file=Xsign') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 name=sign1 priority=10\n", a) + + " :sign place group={group} file={fname} + let a = execute('sign place group=g2 file=Xsign') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 group=g2 name=sign1 priority=10\n", a) + + " :sign place group=* file={fname} + let a = execute('sign place group=* file=Xsign') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 group=g2 name=sign1 priority=10\n" . + \ " line=10 id=5 group=g1 name=sign1 priority=10\n" . + \ " line=10 id=5 name=sign1 priority=10\n", a) + + " Error case: non-existing group + let a = execute('sign place group=xyz file=Xsign') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n", a) + + call sign_unplace('*') + let bnum = bufnr('Xsign') + exe 'sign place 5 line=10 name=sign1 buffer=' . bnum + exe 'sign place 5 group=g1 line=11 name=sign1 buffer=' . bnum + exe 'sign place 5 group=g2 line=12 name=sign1 buffer=' . bnum + + " :sign place buffer={fname} + let a = execute('sign place buffer=' . bnum) + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 name=sign1 priority=10\n", a) + + " :sign place group={group} buffer={fname} + let a = execute('sign place group=g2 buffer=' . bnum) + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=12 id=5 group=g2 name=sign1 priority=10\n", a) + + " :sign place group=* buffer={fname} + let a = execute('sign place group=* buffer=' . bnum) + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 name=sign1 priority=10\n" . + \ " line=11 id=5 group=g1 name=sign1 priority=10\n" . + \ " line=12 id=5 group=g2 name=sign1 priority=10\n", a) + + " Error case: non-existing group + let a = execute('sign place group=xyz buffer=' . bnum) + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n", a) + + " :sign place + let a = execute('sign place') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 name=sign1 priority=10\n", a) + + " Place signs in more than one buffer and list the signs + split foo + set buftype=nofile + sign place 25 line=76 name=sign1 priority=99 file=foo + let a = execute('sign place') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 name=sign1 priority=10\n" . + \ "Signs for foo:\n" . + \ " line=76 id=25 name=sign1 priority=99\n", a) + close + bwipe foo + + " :sign place group={group} + let a = execute('sign place group=g1') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=11 id=5 group=g1 name=sign1 priority=10\n", a) + + " :sign place group=* + let a = execute('sign place group=*') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 name=sign1 priority=10\n" . + \ " line=11 id=5 group=g1 name=sign1 priority=10\n" . + \ " line=12 id=5 group=g2 name=sign1 priority=10\n", a) + + " Test for ':sign jump' command with groups + sign jump 5 group=g1 file=Xsign + call assert_equal(11, line('.')) + call assert_equal('Xsign', bufname('')) + sign jump 5 group=g2 file=Xsign + call assert_equal(12, line('.')) + + " Test for :sign jump command without the filename or buffer + sign jump 5 + call assert_equal(10, line('.')) + sign jump 5 group=g1 + call assert_equal(11, line('.')) + + " Error cases + call assert_fails("sign place 3 group= name=sign1 buffer=" . bnum, 'E474:') + + call delete("Xsign") + call sign_unplace('*') + call sign_undefine() + enew | only +endfunc + +" Place signs used for ":sign unplace" command test +func Place_signs_for_test() + call sign_unplace('*') + + sign place 3 line=10 name=sign1 file=Xsign1 + sign place 3 group=g1 line=11 name=sign1 file=Xsign1 + sign place 3 group=g2 line=12 name=sign1 file=Xsign1 + sign place 4 line=15 name=sign1 file=Xsign1 + sign place 4 group=g1 line=16 name=sign1 file=Xsign1 + sign place 4 group=g2 line=17 name=sign1 file=Xsign1 + sign place 5 line=20 name=sign1 file=Xsign2 + sign place 5 group=g1 line=21 name=sign1 file=Xsign2 + sign place 5 group=g2 line=22 name=sign1 file=Xsign2 + sign place 6 line=25 name=sign1 file=Xsign2 + sign place 6 group=g1 line=26 name=sign1 file=Xsign2 + sign place 6 group=g2 line=27 name=sign1 file=Xsign2 +endfunc + +" Place multiple signs in a single line for test +func Place_signs_at_line_for_test() + call sign_unplace('*') + sign place 3 line=13 name=sign1 file=Xsign1 + sign place 3 group=g1 line=13 name=sign1 file=Xsign1 + sign place 3 group=g2 line=13 name=sign1 file=Xsign1 + sign place 4 line=13 name=sign1 file=Xsign1 + sign place 4 group=g1 line=13 name=sign1 file=Xsign1 + sign place 4 group=g2 line=13 name=sign1 file=Xsign1 +endfunc + +" Tests for the ':sign unplace' command +func Test_sign_unplace() + enew | only + " Remove all the signs + call sign_unplace('*') + call sign_undefine() + + " Create two files and define signs + call writefile(repeat(["Sun is shining"], 30), "Xsign1") + call writefile(repeat(["It is beautiful"], 30), "Xsign2") + + let attr = {'text' : '=>', 'linehl' : 'Search', 'texthl' : 'Error'} + call sign_define("sign1", attr) + + edit Xsign1 + let bnum1 = bufnr('%') + split Xsign2 + let bnum2 = bufnr('%') + + let signs1 = [{'id' : 3, 'name' : 'sign1', 'lnum' : 10, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 3, 'name' : 'sign1', 'lnum' : 11, 'group' : 'g1', + \ 'priority' : 10}, + \ {'id' : 3, 'name' : 'sign1', 'lnum' : 12, 'group' : 'g2', + \ 'priority' : 10}, + \ {'id' : 4, 'name' : 'sign1', 'lnum' : 15, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 4, 'name' : 'sign1', 'lnum' : 16, 'group' : 'g1', + \ 'priority' : 10}, + \ {'id' : 4, 'name' : 'sign1', 'lnum' : 17, 'group' : 'g2', + \ 'priority' : 10},] + let signs2 = [{'id' : 5, 'name' : 'sign1', 'lnum' : 20, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 5, 'name' : 'sign1', 'lnum' : 21, 'group' : 'g1', + \ 'priority' : 10}, + \ {'id' : 5, 'name' : 'sign1', 'lnum' : 22, 'group' : 'g2', + \ 'priority' : 10}, + \ {'id' : 6, 'name' : 'sign1', 'lnum' : 25, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 6, 'name' : 'sign1', 'lnum' : 26, 'group' : 'g1', + \ 'priority' : 10}, + \ {'id' : 6, 'name' : 'sign1', 'lnum' : 27, 'group' : 'g2', + \ 'priority' : 10},] + + " Test for :sign unplace {id} file={fname} + call Place_signs_for_test() + sign unplace 3 file=Xsign1 + sign unplace 6 file=Xsign2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 3 || val.group != ''}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.id != 6 || val.group != ''}), + \ sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace {id} group={group} file={fname} + call Place_signs_for_test() + sign unplace 4 group=g1 file=Xsign1 + sign unplace 5 group=g2 file=Xsign2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 4 || val.group != 'g1'}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.id != 5 || val.group != 'g2'}), + \ sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace {id} group=* file={fname} + call Place_signs_for_test() + sign unplace 3 group=* file=Xsign1 + sign unplace 6 group=* file=Xsign2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 3}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.id != 6}), + \ sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace * file={fname} + call Place_signs_for_test() + sign unplace * file=Xsign1 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.group != ''}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal(signs2, sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace * group={group} file={fname} + call Place_signs_for_test() + sign unplace * group=g1 file=Xsign1 + sign unplace * group=g2 file=Xsign2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.group != 'g1'}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.group != 'g2'}), + \ sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace * group=* file={fname} + call Place_signs_for_test() + sign unplace * group=* file=Xsign2 + call assert_equal(signs1, sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal([], sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace {id} buffer={nr} + call Place_signs_for_test() + exe 'sign unplace 3 buffer=' . bnum1 + exe 'sign unplace 6 buffer=' . bnum2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 3 || val.group != ''}), + \ sign_getplaced(bnum1, {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.id != 6 || val.group != ''}), + \ sign_getplaced(bnum2, {'group' : '*'})[0].signs) + + " Test for :sign unplace {id} group={group} buffer={nr} + call Place_signs_for_test() + exe 'sign unplace 4 group=g1 buffer=' . bnum1 + exe 'sign unplace 5 group=g2 buffer=' . bnum2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 4 || val.group != 'g1'}), + \ sign_getplaced(bnum1, {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.id != 5 || val.group != 'g2'}), + \ sign_getplaced(bnum2, {'group' : '*'})[0].signs) + + " Test for :sign unplace {id} group=* buffer={nr} + call Place_signs_for_test() + exe 'sign unplace 3 group=* buffer=' . bnum1 + exe 'sign unplace 6 group=* buffer=' . bnum2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 3}), + \ sign_getplaced(bnum1, {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.id != 6}), + \ sign_getplaced(bnum2, {'group' : '*'})[0].signs) + + " Test for :sign unplace * buffer={nr} + call Place_signs_for_test() + exe 'sign unplace * buffer=' . bnum1 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.group != ''}), + \ sign_getplaced(bnum1, {'group' : '*'})[0].signs) + call assert_equal(signs2, sign_getplaced(bnum2, {'group' : '*'})[0].signs) + + " Test for :sign unplace * group={group} buffer={nr} + call Place_signs_for_test() + exe 'sign unplace * group=g1 buffer=' . bnum1 + exe 'sign unplace * group=g2 buffer=' . bnum2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.group != 'g1'}), + \ sign_getplaced(bnum1, {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.group != 'g2'}), + \ sign_getplaced(bnum2, {'group' : '*'})[0].signs) + + " Test for :sign unplace * group=* buffer={nr} + call Place_signs_for_test() + exe 'sign unplace * group=* buffer=' . bnum2 + call assert_equal(signs1, sign_getplaced(bnum1, {'group' : '*'})[0].signs) + call assert_equal([], sign_getplaced(bnum2, {'group' : '*'})[0].signs) + + " Test for :sign unplace {id} + call Place_signs_for_test() + sign unplace 4 + sign unplace 6 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 4 || val.group != ''}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.id != 6 || val.group != ''}), + \ sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace {id} group={group} + call Place_signs_for_test() + sign unplace 4 group=g1 + sign unplace 6 group=g2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 4 || val.group != 'g1'}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.id != 6 || val.group != 'g2'}), + \ sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace {id} group=* + call Place_signs_for_test() + sign unplace 3 group=* + sign unplace 5 group=* + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 3}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.id != 5}), + \ sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace * + call Place_signs_for_test() + sign unplace * + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.group != ''}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.group != ''}), + \ sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace * group={group} + call Place_signs_for_test() + sign unplace * group=g1 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.group != 'g1'}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal( + \ filter(copy(signs2), + \ {idx, val -> val.group != 'g1'}), + \ sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Test for :sign unplace * group=* + call Place_signs_for_test() + sign unplace * group=* + call assert_equal([], sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal([], sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Negative test cases + call Place_signs_for_test() + sign unplace 3 group=xy file=Xsign1 + sign unplace * group=xy file=Xsign1 + silent! sign unplace * group=* file=FileNotPresent + call assert_equal(signs1, sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + call assert_equal(signs2, sign_getplaced('Xsign2', {'group' : '*'})[0].signs) + + " Tests for removing sign at the current cursor position + + " Test for ':sign unplace' + let signs1 = [{'id' : 4, 'name' : 'sign1', 'lnum' : 13, 'group' : 'g2', + \ 'priority' : 10}, + \ {'id' : 4, 'name' : 'sign1', 'lnum' : 13, 'group' : 'g1', + \ 'priority' : 10}, + \ {'id' : 4, 'name' : 'sign1', 'lnum' : 13, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 3, 'name' : 'sign1', 'lnum' : 13, 'group' : 'g2', + \ 'priority' : 10}, + \ {'id' : 3, 'name' : 'sign1', 'lnum' : 13, 'group' : 'g1', + \ 'priority' : 10}, + \ {'id' : 3, 'name' : 'sign1', 'lnum' : 13, 'group' : '', + \ 'priority' : 10},] + exe bufwinnr('Xsign1') . 'wincmd w' + call cursor(13, 1) + + " Should remove only one sign in the global group + call Place_signs_at_line_for_test() + sign unplace + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 4 || val.group != ''}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + " Should remove the second sign in the global group + sign unplace + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.group != ''}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + + " Test for ':sign unplace group={group}' + call Place_signs_at_line_for_test() + " Should remove only one sign in group g1 + sign unplace group=g1 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 4 || val.group != 'g1'}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + sign unplace group=g2 + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 4 || val.group == ''}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + + " Test for ':sign unplace group=*' + call Place_signs_at_line_for_test() + sign unplace group=* + sign unplace group=* + sign unplace group=* + call assert_equal( + \ filter(copy(signs1), + \ {idx, val -> val.id != 4}), + \ sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + sign unplace group=* + sign unplace group=* + sign unplace group=* + call assert_equal([], sign_getplaced('Xsign1', {'group' : '*'})[0].signs) + + call sign_unplace('*') + call sign_undefine() + enew | only + call delete("Xsign1") + call delete("Xsign2") +endfunc + +" Tests for auto-generating the sign identifier. +func Test_aaa_sign_id_autogen() + enew | only + call sign_unplace('*') + call sign_undefine() + + let attr = {'text' : '=>', 'linehl' : 'Search', 'texthl' : 'Error'} + call assert_equal(0, sign_define("sign1", attr)) + + call writefile(repeat(["Sun is shining"], 30), "Xsign") + edit Xsign + + call assert_equal(1, sign_place(0, '', 'sign1', 'Xsign', + \ {'lnum' : 10})) + call assert_equal(2, sign_place(2, '', 'sign1', 'Xsign', + \ {'lnum' : 12})) + call assert_equal(3, sign_place(0, '', 'sign1', 'Xsign', + \ {'lnum' : 14})) + call sign_unplace('', {'buffer' : 'Xsign', 'id' : 2}) + call assert_equal(4, sign_place(0, '', 'sign1', 'Xsign', + \ {'lnum' : 12})) + + call assert_equal(1, sign_place(0, 'g1', 'sign1', 'Xsign', + \ {'lnum' : 11})) + " Check for the next generated sign id in this group + call assert_equal(2, sign_place(0, 'g1', 'sign1', 'Xsign', + \ {'lnum' : 12})) + call assert_equal(0, sign_unplace('g1', {'id' : 1})) + call assert_equal(10, + \ sign_getplaced('Xsign', {'id' : 1})[0].signs[0].lnum) + + call delete("Xsign") + call sign_unplace('*') + call sign_undefine() + enew | only +endfunc + +" Test for sign priority +func Test_sign_priority() + enew | only + call sign_unplace('*') + call sign_undefine() + + let attr = {'text' : '=>', 'linehl' : 'Search', 'texthl' : 'Search'} + call sign_define("sign1", attr) + call sign_define("sign2", attr) + call sign_define("sign3", attr) + + " Place three signs with different priority in the same line + call writefile(repeat(["Sun is shining"], 30), "Xsign") + edit Xsign + + call sign_place(1, 'g1', 'sign1', 'Xsign', + \ {'lnum' : 11, 'priority' : 50}) + call sign_place(2, 'g2', 'sign2', 'Xsign', + \ {'lnum' : 11, 'priority' : 100}) + call sign_place(3, '', 'sign3', 'Xsign', {'lnum' : 11}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 11, 'group' : 'g2', + \ 'priority' : 100}, + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 11, 'group' : 'g1', + \ 'priority' : 50}, + \ {'id' : 3, 'name' : 'sign3', 'lnum' : 11, 'group' : '', + \ 'priority' : 10}], + \ s[0].signs) + + call sign_unplace('*') + + " Three signs on different lines with changing priorities + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 11, 'priority' : 50}) + call sign_place(2, '', 'sign2', 'Xsign', + \ {'lnum' : 12, 'priority' : 60}) + call sign_place(3, '', 'sign3', 'Xsign', + \ {'lnum' : 13, 'priority' : 70}) + call sign_place(2, '', 'sign2', 'Xsign', + \ {'lnum' : 12, 'priority' : 40}) + call sign_place(3, '', 'sign3', 'Xsign', + \ {'lnum' : 13, 'priority' : 30}) + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 11, 'priority' : 50}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 11, 'group' : '', + \ 'priority' : 50}, + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 12, 'group' : '', + \ 'priority' : 40}, + \ {'id' : 3, 'name' : 'sign3', 'lnum' : 13, 'group' : '', + \ 'priority' : 30}], + \ s[0].signs) + + call sign_unplace('*') + + " Two signs on the same line with changing priorities + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 20}) + call sign_place(2, '', 'sign2', 'Xsign', + \ {'lnum' : 4, 'priority' : 30}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 30}, + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}], + \ s[0].signs) + " Change the priority of the last sign to highest + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 40}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 40}, + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 30}], + \ s[0].signs) + " Change the priority of the first sign to lowest + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 25}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 30}, + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 25}], + \ s[0].signs) + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 45}) + call sign_place(2, '', 'sign2', 'Xsign', + \ {'lnum' : 4, 'priority' : 55}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 55}, + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 45}], + \ s[0].signs) + + call sign_unplace('*') + + " Three signs on the same line with changing priorities + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 40}) + call sign_place(2, '', 'sign2', 'Xsign', + \ {'lnum' : 4, 'priority' : 30}) + call sign_place(3, '', 'sign3', 'Xsign', + \ {'lnum' : 4, 'priority' : 20}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 40}, + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 30}, + \ {'id' : 3, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}], + \ s[0].signs) + + " Change the priority of the middle sign to the highest + call sign_place(2, '', 'sign2', 'Xsign', + \ {'lnum' : 4, 'priority' : 50}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 50}, + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 40}, + \ {'id' : 3, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}], + \ s[0].signs) + + " Change the priority of the middle sign to the lowest + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 15}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 50}, + \ {'id' : 3, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}, + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 15}], + \ s[0].signs) + + " Change the priority of the last sign to the highest + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 55}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 55}, + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 50}, + \ {'id' : 3, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}], + \ s[0].signs) + + " Change the priority of the first sign to the lowest + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 15}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 50}, + \ {'id' : 3, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}, + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 15}], + \ s[0].signs) + + call sign_unplace('*') + + " Three signs on the same line with changing priorities along with other + " signs + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 2, 'priority' : 10}) + call sign_place(2, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 30}) + call sign_place(3, '', 'sign2', 'Xsign', + \ {'lnum' : 4, 'priority' : 20}) + call sign_place(4, '', 'sign3', 'Xsign', + \ {'lnum' : 4, 'priority' : 25}) + call sign_place(5, '', 'sign2', 'Xsign', + \ {'lnum' : 6, 'priority' : 80}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 2, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 2, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 30}, + \ {'id' : 4, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 25}, + \ {'id' : 3, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}, + \ {'id' : 5, 'name' : 'sign2', 'lnum' : 6, 'group' : '', + \ 'priority' : 80}], + \ s[0].signs) + + " Change the priority of the first sign to lowest + call sign_place(2, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 15}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 2, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 4, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 25}, + \ {'id' : 3, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}, + \ {'id' : 2, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 15}, + \ {'id' : 5, 'name' : 'sign2', 'lnum' : 6, 'group' : '', + \ 'priority' : 80}], + \ s[0].signs) + + " Change the priority of the last sign to highest + call sign_place(2, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 30}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 2, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 2, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 30}, + \ {'id' : 4, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 25}, + \ {'id' : 3, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}, + \ {'id' : 5, 'name' : 'sign2', 'lnum' : 6, 'group' : '', + \ 'priority' : 80}], + \ s[0].signs) + + " Change the priority of the middle sign to lowest + call sign_place(4, '', 'sign3', 'Xsign', + \ {'lnum' : 4, 'priority' : 15}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 2, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 2, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 30}, + \ {'id' : 3, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}, + \ {'id' : 4, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 15}, + \ {'id' : 5, 'name' : 'sign2', 'lnum' : 6, 'group' : '', + \ 'priority' : 80}], + \ s[0].signs) + + " Change the priority of the middle sign to highest + call sign_place(3, '', 'sign2', 'Xsign', + \ {'lnum' : 4, 'priority' : 35}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 2, 'group' : '', + \ 'priority' : 10}, + \ {'id' : 3, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 35}, + \ {'id' : 2, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 30}, + \ {'id' : 4, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 15}, + \ {'id' : 5, 'name' : 'sign2', 'lnum' : 6, 'group' : '', + \ 'priority' : 80}], + \ s[0].signs) + + call sign_unplace('*') + + " Multiple signs with the same priority on the same line + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 20}) + call sign_place(2, '', 'sign2', 'Xsign', + \ {'lnum' : 4, 'priority' : 20}) + call sign_place(3, '', 'sign3', 'Xsign', + \ {'lnum' : 4, 'priority' : 20}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + let se = [ + \ {'id' : 3, 'name' : 'sign3', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}, + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}, + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 4, 'group' : '', + \ 'priority' : 20}] + call assert_equal(se, s[0].signs) + + " Nvim: signs are always sorted lnum->priority->sign_id->last_modified + " Last modified does not take precedence over sign_id here. + + " Place the last sign again with the same priority + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 20}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal(se, s[0].signs) + " Place the first sign again with the same priority + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 4, 'priority' : 20}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal(se, s[0].signs) + " Place the middle sign again with the same priority + call sign_place(3, '', 'sign3', 'Xsign', + \ {'lnum' : 4, 'priority' : 20}) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal(se, s[0].signs) + + call sign_unplace('*') + + " Place multiple signs with same id on a line with different priority + call sign_place(1, '', 'sign1', 'Xsign', + \ {'lnum' : 5, 'priority' : 20}) + call sign_place(1, '', 'sign2', 'Xsign', + \ {'lnum' : 5, 'priority' : 10}) + let s = sign_getplaced('Xsign', {'lnum' : 5}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign2', 'lnum' : 5, 'group' : '', + \ 'priority' : 10}], + \ s[0].signs) + call sign_place(1, '', 'sign2', 'Xsign', + \ {'lnum' : 5, 'priority' : 5}) + let s = sign_getplaced('Xsign', {'lnum' : 5}) + call assert_equal([ + \ {'id' : 1, 'name' : 'sign2', 'lnum' : 5, 'group' : '', + \ 'priority' : 5}], + \ s[0].signs) + + " Error case + call assert_fails("call sign_place(1, 'g1', 'sign1', 'Xsign', [])", 'E1206:') + call assert_fails("call sign_place(1, 'g1', 'sign1', 'Xsign', + \ {'priority' : []})", 'E745:') + call sign_unplace('*') + + " Tests for the :sign place command with priority + sign place 5 line=10 name=sign1 priority=30 file=Xsign + sign place 5 group=g1 line=10 name=sign1 priority=20 file=Xsign + sign place 5 group=g2 line=10 name=sign1 priority=25 file=Xsign + let a = execute('sign place group=*') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 name=sign1 priority=30\n" . + \ " line=10 id=5 group=g2 name=sign1 priority=25\n" . + \ " line=10 id=5 group=g1 name=sign1 priority=20\n", a) + + " Test for :sign place group={group} + let a = execute('sign place group=g1') + call assert_equal("\n--- Signs ---\nSigns for Xsign:\n" . + \ " line=10 id=5 group=g1 name=sign1 priority=20\n", a) + + call sign_unplace('*') + call sign_undefine() + enew | only + call delete("Xsign") +endfunc + +" Tests for memory allocation failures in sign functions +func Test_sign_memfailures() + CheckFunction test_alloc_fail + call writefile(repeat(["Sun is shining"], 30), "Xsign") + edit Xsign + + call test_alloc_fail(GetAllocId('sign_getdefined'), 0, 0) + call assert_fails('call sign_getdefined("sign1")', 'E342:') + call test_alloc_fail(GetAllocId('sign_getplaced'), 0, 0) + call assert_fails('call sign_getplaced("Xsign")', 'E342:') + call test_alloc_fail(GetAllocId('sign_define_by_name'), 0, 0) + let attr = {'text' : '=>', 'linehl' : 'Search', 'texthl' : 'Error'} + call assert_fails('call sign_define("sign1", attr)', 'E342:') + + let attr = {'text' : '=>', 'linehl' : 'Search', 'texthl' : 'Error'} + call sign_define("sign1", attr) + call test_alloc_fail(GetAllocId('sign_getlist'), 0, 0) + call assert_fails('call sign_getdefined("sign1")', 'E342:') + + call sign_place(3, 'g1', 'sign1', 'Xsign', {'lnum' : 10}) + call test_alloc_fail(GetAllocId('sign_getplaced_dict'), 0, 0) + call assert_fails('call sign_getplaced("Xsign")', 'E342:') + call test_alloc_fail(GetAllocId('sign_getplaced_list'), 0, 0) + call assert_fails('call sign_getplaced("Xsign")', 'E342:') + + call test_alloc_fail(GetAllocId('insert_sign'), 0, 0) + call assert_fails('call sign_place(4, "g1", "sign1", "Xsign", {"lnum" : 11})', + \ 'E342:') + + call test_alloc_fail(GetAllocId('sign_getinfo'), 0, 0) + call assert_fails('call getbufinfo()', 'E342:') + call sign_place(4, 'g1', 'sign1', 'Xsign', {'lnum' : 11}) + call test_alloc_fail(GetAllocId('sign_getinfo'), 0, 0) + call assert_fails('let binfo=getbufinfo("Xsign")', 'E342:') + call assert_equal([{'lnum': 11, 'id': 4, 'name': 'sign1', + \ 'priority': 10, 'group': 'g1'}], binfo[0].signs) + + call sign_unplace('*') + call sign_undefine() + enew | only + call delete("Xsign") +endfunc + +" Test for auto-adjusting the line number of a placed sign. +func Test_sign_lnum_adjust() + enew! | only! + + sign define sign1 text=#> linehl=Comment + call setline(1, ['A', 'B', 'C', 'D', 'E']) + exe 'sign place 5 line=3 name=sign1 buffer=' . bufnr('') + let l = sign_getplaced(bufnr('')) + call assert_equal(3, l[0].signs[0].lnum) + + " Add some lines before the sign and check the sign line number + call append(2, ['BA', 'BB', 'BC']) + let l = sign_getplaced(bufnr('')) + call assert_equal(6, l[0].signs[0].lnum) + + " Delete some lines before the sign and check the sign line number + call deletebufline('%', 1, 2) + let l = sign_getplaced(bufnr('')) + call assert_equal(4, l[0].signs[0].lnum) + + " Insert some lines after the sign and check the sign line number + call append(5, ['DA', 'DB']) + let l = sign_getplaced(bufnr('')) + call assert_equal(4, l[0].signs[0].lnum) + + " Delete some lines after the sign and check the sign line number + call deletebufline('', 6, 7) + let l = sign_getplaced(bufnr('')) + call assert_equal(4, l[0].signs[0].lnum) + + " Break the undo. Otherwise the undo operation below will undo all the + " changes made by this function. + let &g:undolevels=&g:undolevels + + " Nvim: deleting a line removes the signs along with it. + + " " Delete the line with the sign + " call deletebufline('', 4) + " let l = sign_getplaced(bufnr('')) + " call assert_equal(4, l[0].signs[0].lnum) + + " " Undo the delete operation + " undo + " let l = sign_getplaced(bufnr('')) + " call assert_equal(5, l[0].signs[0].lnum) + + " " Break the undo + " let &g:undolevels=&g:undolevels + + " " Delete few lines at the end of the buffer including the line with the sign + " " Sign line number should not change (as it is placed outside of the buffer) + " call deletebufline('', 3, 6) + " let l = sign_getplaced(bufnr('')) + " call assert_equal(5, l[0].signs[0].lnum) + + " " Undo the delete operation. Sign should be restored to the previous line + " undo + " let l = sign_getplaced(bufnr('')) + " call assert_equal(5, l[0].signs[0].lnum) + + " set signcolumn& + + sign unplace * group=* + sign undefine sign1 + enew! +endfunc + +" Test for changing the type of a placed sign +func Test_sign_change_type() + enew! | only! + + sign define sign1 text=#> linehl=Comment + sign define sign2 text=@@ linehl=Comment + + call setline(1, ['A', 'B', 'C', 'D']) + exe 'sign place 4 line=3 name=sign1 buffer=' . bufnr('') + let l = sign_getplaced(bufnr('')) + call assert_equal('sign1', l[0].signs[0].name) + exe 'sign place 4 name=sign2 buffer=' . bufnr('') + let l = sign_getplaced(bufnr('')) + call assert_equal('sign2', l[0].signs[0].name) + call sign_place(4, '', 'sign1', '') + let l = sign_getplaced(bufnr('')) + call assert_equal('sign1', l[0].signs[0].name) + + exe 'sign place 4 group=g1 line=4 name=sign1 buffer=' . bufnr('') + let l = sign_getplaced(bufnr(''), {'group' : 'g1'}) + call assert_equal('sign1', l[0].signs[0].name) + exe 'sign place 4 group=g1 name=sign2 buffer=' . bufnr('') + let l = sign_getplaced(bufnr(''), {'group' : 'g1'}) + call assert_equal('sign2', l[0].signs[0].name) + call sign_place(4, 'g1', 'sign1', '') + let l = sign_getplaced(bufnr(''), {'group' : 'g1'}) + call assert_equal('sign1', l[0].signs[0].name) + + sign unplace * group=* + sign undefine sign1 + sign undefine sign2 + enew! +endfunc + +" Test for the sign_jump() function +func Test_sign_jump_func() + enew! | only! + + sign define sign1 text=#> linehl=Comment + + edit foo + set buftype=nofile + call setline(1, ['A', 'B', 'C', 'D', 'E']) + call sign_place(5, '', 'sign1', '', {'lnum' : 2}) + call sign_place(5, 'g1', 'sign1', '', {'lnum' : 3}) + call sign_place(6, '', 'sign1', '', {'lnum' : 4}) + call sign_place(6, 'g1', 'sign1', '', {'lnum' : 5}) + split bar + set buftype=nofile + call setline(1, ['P', 'Q', 'R', 'S', 'T']) + call sign_place(5, '', 'sign1', '', {'lnum' : 2}) + call sign_place(5, 'g1', 'sign1', '', {'lnum' : 3}) + call sign_place(6, '', 'sign1', '', {'lnum' : 4}) + call sign_place(6, 'g1', 'sign1', '', {'lnum' : 5}) + + let r = sign_jump(5, '', 'foo') + call assert_equal(2, r) + call assert_equal(2, line('.')) + let r = 6->sign_jump('g1', 'foo') + call assert_equal(5, r) + call assert_equal(5, line('.')) + let r = sign_jump(5, '', 'bar') + call assert_equal(2, r) + call assert_equal(2, line('.')) + + " Error cases + call assert_fails("call sign_jump(99, '', 'bar')", 'E157:') + call assert_fails("call sign_jump(0, '', 'foo')", 'E474:') + call assert_fails("call sign_jump(5, 'g5', 'foo')", 'E157:') + call assert_fails('call sign_jump([], "", "foo")', 'E745:') + call assert_fails('call sign_jump(2, [], "foo")', 'E730:') + call assert_fails('call sign_jump(2, "", {})', 'E731:') + call assert_fails('call sign_jump(2, "", "baz")', 'E158:') + + sign unplace * group=* + sign undefine sign1 + enew! | only! +endfunc + +" Test for correct cursor position after the sign column appears or disappears. +func Test_sign_cursor_position() + CheckRunVimInTerminal + + let lines =<< trim END + call setline(1, [repeat('x', 75), 'mmmm', 'yyyy']) + call cursor(2,1) + sign define s1 texthl=Search text==> + redraw + sign place 10 line=2 name=s1 + END + call writefile(lines, 'XtestSigncolumn') + let buf = RunVimInTerminal('-S XtestSigncolumn', {'rows': 6}) + call VerifyScreenDump(buf, 'Test_sign_cursor_1', {}) + + " Change the sign text + call term_sendkeys(buf, ":sign define s1 text=-)\<CR>") + call VerifyScreenDump(buf, 'Test_sign_cursor_2', {}) + + " update cursor position calculation + call term_sendkeys(buf, "lh") + call term_sendkeys(buf, ":sign unplace 10\<CR>") + call VerifyScreenDump(buf, 'Test_sign_cursor_3', {}) + + + " clean up + call StopVimInTerminal(buf) + call delete('XtestSigncolumn') +endfunc + +" Return the 'len' characters in screen starting from (row,col) +func s:ScreenLine(row, col, len) + let s = '' + for i in range(a:len) + let s .= nr2char(screenchar(a:row, a:col + i)) + endfor + return s +endfunc + +" Test for 'signcolumn' set to 'number'. +func Test_sign_numcol() + new + call append(0, "01234") + " With 'signcolumn' set to 'number', make sure sign is displayed in the + " number column and line number is not displayed. + set numberwidth=2 + set number + set signcolumn=number + sign define sign1 text==> + sign define sign2 text=V + sign place 10 line=1 name=sign1 + redraw! + call assert_equal("=> 01234", s:ScreenLine(1, 1, 8)) + + " With 'signcolumn' set to 'number', when there is no sign, make sure line + " number is displayed in the number column + sign unplace 10 + redraw! + call assert_equal("1 01234", s:ScreenLine(1, 1, 7)) + + " Disable number column. Check whether sign is displayed in the sign column + set numberwidth=4 + set nonumber + sign place 10 line=1 name=sign1 + redraw! + call assert_equal("=>01234", s:ScreenLine(1, 1, 7)) + + " Enable number column. Check whether sign is displayed in the number column + set number + redraw! + call assert_equal(" => 01234", s:ScreenLine(1, 1, 9)) + + " Disable sign column. Make sure line number is displayed + set signcolumn=no + redraw! + call assert_equal(" 1 01234", s:ScreenLine(1, 1, 9)) + + " Enable auto sign column. Make sure both sign and line number are displayed + set signcolumn=auto + redraw! + call assert_equal("=> 1 01234", s:ScreenLine(1, 1, 11)) + + " Test displaying signs in the number column with width 1 + call sign_unplace('*') + call append(1, "abcde") + call append(2, "01234") + " Enable number column with width 1 + set number numberwidth=1 signcolumn=auto + redraw! + call assert_equal("3 01234", s:ScreenLine(3, 1, 7)) + " Place a sign and make sure number column width remains the same + sign place 20 line=2 name=sign1 + redraw! + call assert_equal("=>2 abcde", s:ScreenLine(2, 1, 9)) + call assert_equal(" 3 01234", s:ScreenLine(3, 1, 9)) + " Set 'signcolumn' to 'number', make sure the number column width increases + set signcolumn=number + redraw! + call assert_equal("=> abcde", s:ScreenLine(2, 1, 8)) + call assert_equal(" 3 01234", s:ScreenLine(3, 1, 8)) + " Set 'signcolumn' to 'auto', make sure the number column width is 1. + set signcolumn=auto + redraw! + call assert_equal("=>2 abcde", s:ScreenLine(2, 1, 9)) + call assert_equal(" 3 01234", s:ScreenLine(3, 1, 9)) + " Set 'signcolumn' to 'number', make sure the number column width is 2. + set signcolumn=number + redraw! + call assert_equal("=> abcde", s:ScreenLine(2, 1, 8)) + call assert_equal(" 3 01234", s:ScreenLine(3, 1, 8)) + " Disable 'number' column + set nonumber + redraw! + call assert_equal("=>abcde", s:ScreenLine(2, 1, 7)) + call assert_equal(" 01234", s:ScreenLine(3, 1, 7)) + " Enable 'number' column + set number + redraw! + call assert_equal("=> abcde", s:ScreenLine(2, 1, 8)) + call assert_equal(" 3 01234", s:ScreenLine(3, 1, 8)) + " Remove the sign and make sure the width of the number column is 1. + call sign_unplace('', {'id' : 20}) + redraw! + call assert_equal("3 01234", s:ScreenLine(3, 1, 7)) + " When the first sign is placed with 'signcolumn' set to number, verify that + " the number column width increases + sign place 30 line=1 name=sign1 + redraw! + call assert_equal("=> 01234", s:ScreenLine(1, 1, 8)) + call assert_equal(" 2 abcde", s:ScreenLine(2, 1, 8)) + " Add sign with multi-byte text + set numberwidth=4 + sign place 40 line=2 name=sign2 + redraw! + call assert_equal(" => 01234", s:ScreenLine(1, 1, 9)) + call assert_equal(" V abcde", s:ScreenLine(2, 1, 9)) + + sign unplace * group=* + sign undefine sign1 + set signcolumn& + set number& + enew! | close +endfunc + +" Test for managing multiple signs using the sign functions +func Test_sign_funcs_multi() + call writefile(repeat(["Sun is shining"], 30), "Xsign") + edit Xsign + let bnum = bufnr('') + + " Define multiple signs at once + call assert_equal([0, 0, 0, 0], sign_define([ + \ {'name' : 'sign1', 'text' : '=>', 'linehl' : 'Search', + \ 'texthl' : 'Search'}, + \ {'name' : 'sign2', 'text' : '=>', 'linehl' : 'Search', + \ 'texthl' : 'Search'}, + \ {'name' : 'sign3', 'text' : '=>', 'linehl' : 'Search', + \ 'texthl' : 'Search'}, + \ {'name' : 'sign4', 'text' : '=>', 'linehl' : 'Search', + \ 'texthl' : 'Search'}])) + + " Negative cases for sign_define() + call assert_equal([], sign_define([])) + call assert_equal([-1], sign_define([{}])) + call assert_fails('call sign_define([6])', 'E715:') + call assert_fails('call sign_define(["abc"])', 'E715:') + call assert_fails('call sign_define([[]])', 'E715:') + + " Place multiple signs at once with specific sign identifier + let l = sign_placelist([{'id' : 1, 'group' : 'g1', 'name' : 'sign1', + \ 'buffer' : 'Xsign', 'lnum' : 11, 'priority' : 50}, + \ {'id' : 2, 'group' : 'g2', 'name' : 'sign2', + \ 'buffer' : 'Xsign', 'lnum' : 11, 'priority' : 100}, + \ {'id' : 3, 'group' : '', 'name' : 'sign3', + \ 'buffer' : 'Xsign', 'lnum' : 11}]) + call assert_equal([1, 2, 3], l) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 2, 'name' : 'sign2', 'lnum' : 11, + \ 'group' : 'g2', 'priority' : 100}, + \ {'id' : 1, 'name' : 'sign1', 'lnum' : 11, + \ 'group' : 'g1', 'priority' : 50}, + \ {'id' : 3, 'name' : 'sign3', 'lnum' : 11, + \ 'group' : '', 'priority' : 10}], s[0].signs) + + call sign_unplace('*') + + " Place multiple signs at once with auto-generated sign identifier + " Nvim: next sign id is not reset and is always incremented + call assert_equal([2, 3, 4], sign_placelist([ + \ {'group' : 'g1', 'name' : 'sign1', + \ 'buffer' : 'Xsign', 'lnum' : 11}, + \ {'group' : 'g2', 'name' : 'sign2', + \ 'buffer' : 'Xsign', 'lnum' : 11}, + \ {'group' : '', 'name' : 'sign3', + \ 'buffer' : 'Xsign', 'lnum' : 11}])) + let s = sign_getplaced('Xsign', {'group' : '*'}) + call assert_equal([ + \ {'id' : 4, 'name' : 'sign3', 'lnum' : 11, + \ 'group' : '', 'priority' : 10}, + \ {'id' : 3, 'name' : 'sign2', 'lnum' : 11, + \ 'group' : 'g2', 'priority' : 10}, + \ {'id' : 2, 'name' : 'sign1', 'lnum' : 11, + \ 'group' : 'g1', 'priority' : 10}], s[0].signs) + + " Change an existing sign without specifying the group + call assert_equal([4], [{'id' : 4, 'name' : 'sign1', 'buffer' : 'Xsign'}]->sign_placelist()) + let s = sign_getplaced('Xsign', {'id' : 4, 'group' : ''}) + call assert_equal([{'id' : 4, 'name' : 'sign1', 'lnum' : 11, + \ 'group' : '', 'priority' : 10}], s[0].signs) + + " Place a sign using '.' as the line number + call cursor(23, 1) + call assert_equal([7], sign_placelist([ + \ {'id' : 7, 'name' : 'sign1', 'buffer' : '%', 'lnum' : '.'}])) + let s = sign_getplaced('%', {'lnum' : '.'}) + call assert_equal([{'id' : 7, 'name' : 'sign1', 'lnum' : 23, + \ 'group' : '', 'priority' : 10}], s[0].signs) + + " Place sign without a sign name + call assert_equal([-1], sign_placelist([{'id' : 10, 'buffer' : 'Xsign', + \ 'lnum' : 12, 'group' : ''}])) + + " Place sign without a buffer + call assert_equal([-1], sign_placelist([{'id' : 10, 'name' : 'sign1', + \ 'lnum' : 12, 'group' : ''}])) + + " Invalid arguments + call assert_equal([], sign_placelist([])) + call assert_fails('call sign_placelist({})', "E714:") + call assert_fails('call sign_placelist([[]])', "E715:") + call assert_fails('call sign_placelist(["abc"])', "E715:") + call assert_fails('call sign_placelist([100])', "E715:") + + " Unplace multiple signs + call assert_equal([0, 0, 0], sign_unplacelist([{'id' : 4}, + \ {'id' : 2, 'group' : 'g1'}, {'id' : 3, 'group' : 'g2'}])) + + " Invalid arguments + call assert_equal([], []->sign_unplacelist()) + call assert_fails('call sign_unplacelist({})', "E714:") + call assert_fails('call sign_unplacelist([[]])', "E715:") + call assert_fails('call sign_unplacelist(["abc"])', "E715:") + call assert_fails('call sign_unplacelist([100])', "E715:") + call assert_fails("call sign_unplacelist([{'id' : -1}])", 'E474') + + call assert_equal([0, 0, 0, 0], + \ sign_undefine(['sign1', 'sign2', 'sign3', 'sign4'])) + call assert_equal([], sign_getdefined()) + + " Invalid arguments + call assert_equal([], sign_undefine([])) + call assert_fails('call sign_undefine([[]])', 'E730:') + call assert_fails('call sign_undefine([{}])', 'E731:') + call assert_fails('call sign_undefine(["1abc2"])', 'E155:') + + call sign_unplace('*') + call sign_undefine() + enew! + call delete("Xsign") +endfunc diff --git a/test/old/testdir/test_sleep.vim b/test/old/testdir/test_sleep.vim new file mode 100644 index 0000000000..a428f380b0 --- /dev/null +++ b/test/old/testdir/test_sleep.vim @@ -0,0 +1,27 @@ +" Test for sleep and sleep! commands + +func! s:get_time_ms() + let timestr = reltimestr(reltime()) + let dotidx = stridx(timestr, '.') + let sec = str2nr(timestr[:dotidx]) + let msec = str2nr(timestr[dotidx + 1:]) + return (sec * 1000) + (msec / 1000) +endfunc + +func! s:assert_takes_longer(cmd, time_ms) + let start = s:get_time_ms() + execute a:cmd + let end = s:get_time_ms() + call assert_true(end - start >=# a:time_ms) +endfun + +func! Test_sleep_bang() + call s:assert_takes_longer('sleep 50m', 50) + call s:assert_takes_longer('sleep! 50m', 50) + call s:assert_takes_longer('sl 50m', 50) + call s:assert_takes_longer('sl! 50m', 50) + call s:assert_takes_longer('1sleep', 1000) + call s:assert_takes_longer('normal 1gs', 1000) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_smartindent.vim b/test/old/testdir/test_smartindent.vim new file mode 100644 index 0000000000..e2d028e828 --- /dev/null +++ b/test/old/testdir/test_smartindent.vim @@ -0,0 +1,136 @@ +" Tests for smartindent + +" Tests for not doing smart indenting when it isn't set. +func Test_nosmartindent() + new + call append(0, [" some test text", + \ " test text", + \ "test text", + \ " test text"]) + set nocindent nosmartindent autoindent + exe "normal! gg/some\<CR>" + exe "normal! 2cc#test\<Esc>" + call assert_equal(" #test", getline(1)) + enew! | close +endfunc + +func MyIndent() +endfunc + +" When 'indentexpr' is set, setting 'si' has no effect. +func Test_smartindent_has_no_effect() + new + exe "normal! i\<Tab>one\<Esc>" + setlocal noautoindent smartindent indentexpr= + exe "normal! Gotwo\<Esc>" + call assert_equal("\ttwo", getline("$")) + + set indentexpr=MyIndent + exe "normal! Gothree\<Esc>" + call assert_equal("three", getline("$")) + + delfunction! MyIndent + bwipe! +endfunc + +" Test for inserting '{' and '} with smartindent +func Test_smartindent_braces() + new + setlocal smartindent shiftwidth=4 + call setline(1, [' if (a)', "\tif (b)", "\t return 1"]) + normal 2ggO{ + normal 3ggA { + normal 4ggo} + normal o} + normal 4ggO#define FOO 1 + call assert_equal([ + \ ' if (a)', + \ ' {', + \ "\tif (b) {", + \ '#define FOO 1', + \ "\t return 1", + \ "\t}", + \ ' }' + \ ], getline(1, '$')) + close! +endfunc + +" Test for adding a new line before and after comments with smartindent +func Test_si_add_line_around_comment() + new + setlocal smartindent shiftwidth=4 + call setline(1, [' A', '# comment1', '# comment2']) + exe "normal GoC\<Esc>2GOB" + call assert_equal([' A', ' B', '# comment1', '# comment2', ' C'], + \ getline(1, '$')) + close! +endfunc + +" After a C style comment, indent for a following line should line up with the +" line containing the start of the comment. +func Test_si_indent_after_c_comment() + new + setlocal smartindent shiftwidth=4 fo+=ro + exe "normal i\<C-t>/*\ncomment\n/\n#define FOOBAR\n75\<Esc>ggOabc" + normal 3jOcont + call assert_equal([' abc', ' /*', ' * comment', ' * cont', + \ ' */', '#define FOOBAR', ' 75'], getline(1, '$')) + close! +endfunc + +" Test for indenting a statement after a if condition split across lines +func Test_si_if_cond_split_across_lines() + new + setlocal smartindent shiftwidth=4 + exe "normal i\<C-t>if (cond1 &&\n\<C-t>cond2) {\ni = 10;\n}" + call assert_equal([' if (cond1 &&', "\t cond2) {", "\ti = 10;", + \ ' }'], getline(1, '$')) + close! +endfunc + +" Test for inserting lines before and after a one line comment +func Test_si_one_line_comment() + new + setlocal smartindent shiftwidth=4 + exe "normal i\<C-t>abc;\n\<C-t>/* comment */" + normal oi = 10; + normal kOj = 1; + call assert_equal([' abc;', "\tj = 1;", "\t/* comment */", "\ti = 10;"], + \ getline(1, '$')) + close! +endfunc + +" Test for smartindent with a comment continued across multiple lines +func Test_si_comment_line_continuation() + new + setlocal smartindent shiftwidth=4 + call setline(1, ['# com1', '# com2 \', ' contd', '# com3', ' xyz']) + normal ggOabc + call assert_equal([' abc', '# com1', '# com2 \', ' contd', '# com3', + \ ' xyz'], getline(1, '$')) + close! +endfunc + +func Test_si_after_completion() + new + setlocal ai smartindent indentexpr= + call setline(1, 'foo foot') + call feedkeys("o f\<C-X>\<C-N>#", 'tx') + call assert_equal(' foo#', getline(2)) + + call setline(2, '') + call feedkeys("1Go f\<C-X>\<C-N>}", 'tx') + call assert_equal(' foo}', getline(2)) + + bwipe! +endfunc + +func Test_no_si_after_completion() + new + call setline(1, 'foo foot') + call feedkeys("o f\<C-X>\<C-N>#", 'tx') + call assert_equal(' foo#', getline(2)) + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_sort.vim b/test/old/testdir/test_sort.vim new file mode 100644 index 0000000000..94a35e3cb5 --- /dev/null +++ b/test/old/testdir/test_sort.vim @@ -0,0 +1,1523 @@ +" Tests for the "sort()" function and for the ":sort" command. + +source check.vim + +func Compare1(a, b) abort + call sort(range(3), 'Compare2') + return a:a - a:b +endfunc + +func Compare2(a, b) abort + return a:a - a:b +endfunc + +func Test_sort_strings() + " numbers compared as strings + call assert_equal([1, 2, 3], sort([3, 2, 1])) + call assert_equal([13, 28, 3], sort([3, 28, 13])) + + call assert_equal(['A', 'O', 'P', 'a', 'o', 'p', 'Ä', 'Ô', 'ä', 'ô', 'Œ', 'œ'], + \ sort(['A', 'O', 'P', 'a', 'o', 'p', 'Ä', 'Ô', 'ä', 'ô', 'œ', 'Œ'])) + + call assert_equal(['A', 'a', 'o', 'O', 'p', 'P', 'Ä', 'Ô', 'ä', 'ô', 'Œ', 'œ'], + \ sort(['A', 'a', 'o', 'O', 'œ', 'Œ', 'p', 'P', 'Ä', 'ä', 'ô', 'Ô'], 'i')) + + " This does not appear to work correctly on Mac. + if !has('mac') + if v:collate =~? '^\(en\|fr\)_ca.utf-\?8$' + " with Canadian English capitals come before lower case. + " 'Œ' is omitted because it can sort before or after 'œ' + call assert_equal(['A', 'a', 'Ä', 'ä', 'O', 'o', 'Ô', 'ô', 'œ', 'P', 'p'], + \ sort(['A', 'a', 'o', 'O', 'œ', 'p', 'P', 'Ä', 'ä', 'ô', 'Ô'], 'l')) + elseif v:collate =~? '^\(en\|es\|de\|fr\|it\|nl\).*\.utf-\?8$' + " With the following locales, the accentuated letters are ordered + " similarly to the non-accentuated letters... + call assert_equal(['a', 'A', 'ä', 'Ä', 'o', 'O', 'ô', 'Ô', 'œ', 'Œ', 'p', 'P'], + \ sort(['A', 'a', 'o', 'O', 'œ', 'Œ', 'p', 'P', 'Ä', 'ä', 'ô', 'Ô'], 'l')) + elseif v:collate =~? '^sv.*utf-\?8$' + " ... whereas with a Swedish locale, the accentuated letters are ordered + " after Z. + call assert_equal(['a', 'A', 'o', 'O', 'p', 'P', 'ä', 'Ä', 'œ', 'œ', 'ô', 'Ô'], + \ sort(['A', 'a', 'o', 'O', 'œ', 'œ', 'p', 'P', 'Ä', 'ä', 'ô', 'Ô'], 'l')) + endif + endif +endfunc + +func Test_sort_null_string() + " null strings are sorted as empty strings. + call assert_equal(['', 'a', 'b'], sort(['b', v:_null_string, 'a'])) +endfunc + +func Test_sort_numeric() + call assert_equal([1, 2, 3], sort([3, 2, 1], 'n')) + call assert_equal([3, 13, 28], sort([13, 28, 3], 'n')) + " strings are not sorted + call assert_equal(['13', '28', '3'], sort(['13', '28', '3'], 'n')) +endfunc + +func Test_sort_numbers() + call assert_equal([3, 13, 28], sort([13, 28, 3], 'N')) + call assert_equal(['3', '13', '28'], sort(['13', '28', '3'], 'N')) + call assert_equal([3997, 4996], sort([4996, 3997], 'Compare1')) +endfunc + +func Test_sort_float() + CheckFeature float + call assert_equal([0.28, 3, 13.5], sort([13.5, 0.28, 3], 'f')) +endfunc + +func Test_sort_nested() + " test ability to call sort() from a compare function + call assert_equal([1, 3, 5], sort([3, 1, 5], 'Compare1')) +endfunc + +func Test_sort_default() + CheckFeature float + + " docs say omitted, empty or zero argument sorts on string representation. + call assert_equal(['2', 'A', 'AA', 'a', 1, 3.3], sort([3.3, 1, "2", "A", "a", "AA"])) + call assert_equal(['2', 'A', 'AA', 'a', 1, 3.3], sort([3.3, 1, "2", "A", "a", "AA"], '')) + call assert_equal(['2', 'A', 'AA', 'a', 1, 3.3], sort([3.3, 1, "2", "A", "a", "AA"], 0)) + call assert_equal(['2', 'A', 'a', 'AA', 1, 3.3], sort([3.3, 1, "2", "A", "a", "AA"], 1)) + call assert_fails('call sort([3.3, 1, "2"], 3)', "E474:") +endfunc + +" Tests for the ":sort" command. +func Test_sort_cmd() + let tests = [ + \ { + \ 'name' : 'Alphabetical sort', + \ 'cmd' : '%sort', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ], + \ 'expected' : [ + \ ' 123b', + \ 'a', + \ 'a122', + \ 'a123', + \ 'a321', + \ 'ab', + \ 'abc', + \ 'b123', + \ 'b321', + \ 'b321', + \ 'b321b', + \ 'b322b', + \ 'c123d', + \ 'c321d' + \ ] + \ }, + \ { + \ 'name' : 'Numeric sort', + \ 'cmd' : '%sort n', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'a', + \ 'x-22', + \ 'b321', + \ 'b123', + \ '', + \ 'c123d', + \ '-24', + \ ' 123b', + \ 'c321d', + \ '0', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '-24', + \ 'x-22', + \ '0', + \ 'a122', + \ 'a123', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b321', + \ 'b321b', + \ 'b322b' + \ ] + \ }, + \ { + \ 'name' : 'Hexadecimal sort', + \ 'cmd' : '%sort x', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ], + \ 'expected' : [ + \ 'a', + \ 'ab', + \ 'abc', + \ ' 123b', + \ 'a122', + \ 'a123', + \ 'a321', + \ 'b123', + \ 'b321', + \ 'b321', + \ 'b321b', + \ 'b322b', + \ 'c123d', + \ 'c321d' + \ ] + \ }, + \ { + \ 'name' : 'Alphabetical unique sort', + \ 'cmd' : '%sort u', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ], + \ 'expected' : [ + \ ' 123b', + \ 'a', + \ 'a122', + \ 'a123', + \ 'a321', + \ 'ab', + \ 'abc', + \ 'b123', + \ 'b321', + \ 'b321b', + \ 'b322b', + \ 'c123d', + \ 'c321d' + \ ] + \ }, + \ { + \ 'name' : 'Alphabetical reverse sort', + \ 'cmd' : '%sort!', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ], + \ 'expected' : [ + \ 'c321d', + \ 'c123d', + \ 'b322b', + \ 'b321b', + \ 'b321', + \ 'b321', + \ 'b123', + \ 'abc', + \ 'ab', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'a', + \ ' 123b', + \ ] + \ }, + \ { + \ 'name' : 'Numeric reverse sort', + \ 'cmd' : '%sort! n', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ], + \ 'expected' : [ + \ 'b322b', + \ 'b321b', + \ 'b321', + \ 'c321d', + \ 'b321', + \ 'a321', + \ ' 123b', + \ 'c123d', + \ 'b123', + \ 'a123', + \ 'a122', + \ 'a', + \ 'ab', + \ 'abc' + \ ] + \ }, + \ { + \ 'name' : 'Unique reverse sort', + \ 'cmd' : 'sort! u', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ], + \ 'expected' : [ + \ 'c321d', + \ 'c123d', + \ 'b322b', + \ 'b321b', + \ 'b321', + \ 'b123', + \ 'abc', + \ 'ab', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'a', + \ ' 123b', + \ ] + \ }, + \ { + \ 'name' : 'Octal sort', + \ 'cmd' : 'sort o', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a122', + \ 'a123', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b321', + \ 'b321b', + \ 'b322b' + \ ] + \ }, + \ { + \ 'name' : 'Reverse hexadecimal sort', + \ 'cmd' : 'sort! x', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'c321d', + \ 'c123d', + \ 'b322b', + \ 'b321b', + \ 'b321', + \ 'b321', + \ 'b123', + \ 'a321', + \ 'a123', + \ 'a122', + \ ' 123b', + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '' + \ ] + \ }, + \ { + \ 'name' : 'Alpha (skip first character) sort', + \ 'cmd' : 'sort/./', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'a', + \ '', + \ '', + \ 'a122', + \ 'a123', + \ 'b123', + \ ' 123b', + \ 'c123d', + \ 'a321', + \ 'b321', + \ 'b321', + \ 'b321b', + \ 'c321d', + \ 'b322b', + \ 'ab', + \ 'abc' + \ ] + \ }, + \ { + \ 'name' : 'Alpha (skip first 2 characters) sort', + \ 'cmd' : 'sort/../', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a321', + \ 'b321', + \ 'b321', + \ 'b321b', + \ 'c321d', + \ 'a122', + \ 'b322b', + \ 'a123', + \ 'b123', + \ ' 123b', + \ 'c123d', + \ 'abc' + \ ] + \ }, + \ { + \ 'name' : 'alpha, unique, skip first 2 characters', + \ 'cmd' : 'sort/../u', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'ab', + \ 'a', + \ '', + \ 'a321', + \ 'b321', + \ 'b321b', + \ 'c321d', + \ 'a122', + \ 'b322b', + \ 'a123', + \ 'b123', + \ ' 123b', + \ 'c123d', + \ 'abc' + \ ] + \ }, + \ { + \ 'name' : 'numeric, skip first character', + \ 'cmd' : 'sort/./n', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a122', + \ 'a123', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b321', + \ 'b321b', + \ 'b322b' + \ ] + \ }, + \ { + \ 'name' : 'alpha, sort on first character', + \ 'cmd' : 'sort/./r', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ '', + \ '', + \ ' 123b', + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ 'c123d', + \ 'c321d' + \ ] + \ }, + \ { + \ 'name' : 'alpha, sort on first 2 characters', + \ 'cmd' : 'sort/../r', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'a', + \ '', + \ '', + \ ' 123b', + \ 'a123', + \ 'a122', + \ 'a321', + \ 'abc', + \ 'ab', + \ 'b123', + \ 'b321', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ 'c123d', + \ 'c321d' + \ ] + \ }, + \ { + \ 'name' : 'numeric, sort on first character', + \ 'cmd' : 'sort/./rn', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ] + \ }, + \ { + \ 'name' : 'alpha, skip past first digit', + \ 'cmd' : 'sort/\d/', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a321', + \ 'b321', + \ 'b321', + \ 'b321b', + \ 'c321d', + \ 'a122', + \ 'b322b', + \ 'a123', + \ 'b123', + \ ' 123b', + \ 'c123d' + \ ] + \ }, + \ { + \ 'name' : 'alpha, sort on first digit', + \ 'cmd' : 'sort/\d/r', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a123', + \ 'a122', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ] + \ }, + \ { + \ 'name' : 'numeric, skip past first digit', + \ 'cmd' : 'sort/\d/n', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b321', + \ 'b321b', + \ 'a122', + \ 'b322b', + \ 'a123', + \ 'b123', + \ 'c123d', + \ ' 123b' + \ ] + \ }, + \ { + \ 'name' : 'numeric, sort on first digit', + \ 'cmd' : 'sort/\d/rn', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a123', + \ 'a122', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ] + \ }, + \ { + \ 'name' : 'alpha, skip past first 2 digits', + \ 'cmd' : 'sort/\d\d/', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a321', + \ 'b321', + \ 'b321', + \ 'b321b', + \ 'c321d', + \ 'a122', + \ 'b322b', + \ 'a123', + \ 'b123', + \ ' 123b', + \ 'c123d' + \ ] + \ }, + \ { + \ 'name' : 'numeric, skip past first 2 digits', + \ 'cmd' : 'sort/\d\d/n', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b321', + \ 'b321b', + \ 'a122', + \ 'b322b', + \ 'a123', + \ 'b123', + \ 'c123d', + \ ' 123b' + \ ] + \ }, + \ { + \ 'name' : 'hexadecimal, skip past first 2 digits', + \ 'cmd' : 'sort/\d\d/x', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a321', + \ 'b321', + \ 'b321', + \ 'a122', + \ 'a123', + \ 'b123', + \ 'b321b', + \ 'c321d', + \ 'b322b', + \ ' 123b', + \ 'c123d' + \ ] + \ }, + \ { + \ 'name' : 'alpha, sort on first 2 digits', + \ 'cmd' : 'sort/\d\d/r', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a123', + \ 'a122', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ] + \ }, + \ { + \ 'name' : 'numeric, sort on first 2 digits', + \ 'cmd' : 'sort/\d\d/rn', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a123', + \ 'a122', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ] + \ }, + \ { + \ 'name' : 'hexadecimal, sort on first 2 digits', + \ 'cmd' : 'sort/\d\d/rx', + \ 'input' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ 'a321', + \ 'a123', + \ 'a122', + \ 'b321', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ 'abc', + \ 'ab', + \ 'a', + \ '', + \ '', + \ 'a123', + \ 'a122', + \ 'b123', + \ 'c123d', + \ ' 123b', + \ 'a321', + \ 'b321', + \ 'c321d', + \ 'b322b', + \ 'b321', + \ 'b321b' + \ ] + \ }, + \ { + \ 'name' : 'binary', + \ 'cmd' : 'sort b', + \ 'input' : [ + \ '0b111000', + \ '0b101100', + \ '0b101001', + \ '0b101001', + \ '0b101000', + \ '0b000000', + \ '0b001000', + \ '0b010000', + \ '0b101000', + \ '0b100000', + \ '0b101010', + \ '0b100010', + \ '0b100100', + \ '0b100010', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ '', + \ '', + \ '0b000000', + \ '0b001000', + \ '0b010000', + \ '0b100000', + \ '0b100010', + \ '0b100010', + \ '0b100100', + \ '0b101000', + \ '0b101000', + \ '0b101001', + \ '0b101001', + \ '0b101010', + \ '0b101100', + \ '0b111000' + \ ] + \ }, + \ { + \ 'name' : 'binary with leading characters', + \ 'cmd' : 'sort b', + \ 'input' : [ + \ '0b100010', + \ '0b010000', + \ ' 0b101001', + \ 'b0b101100', + \ '0b100010', + \ ' 0b100100', + \ 'a0b001000', + \ '0b101000', + \ '0b101000', + \ 'a0b101001', + \ 'ab0b100000', + \ '0b101010', + \ '0b000000', + \ 'b0b111000', + \ '', + \ '' + \ ], + \ 'expected' : [ + \ '', + \ '', + \ '0b000000', + \ 'a0b001000', + \ '0b010000', + \ 'ab0b100000', + \ '0b100010', + \ '0b100010', + \ ' 0b100100', + \ '0b101000', + \ '0b101000', + \ ' 0b101001', + \ 'a0b101001', + \ '0b101010', + \ 'b0b101100', + \ 'b0b111000' + \ ] + \ }, + \ { + \ 'name' : 'alphabetical, sorted input', + \ 'cmd' : 'sort', + \ 'input' : [ + \ 'a', + \ 'b', + \ 'c', + \ ], + \ 'expected' : [ + \ 'a', + \ 'b', + \ 'c', + \ ] + \ }, + \ { + \ 'name' : 'alphabetical, sorted input, unique at end', + \ 'cmd' : 'sort u', + \ 'input' : [ + \ 'aa', + \ 'bb', + \ 'cc', + \ 'cc', + \ ], + \ 'expected' : [ + \ 'aa', + \ 'bb', + \ 'cc', + \ ] + \ }, + \ { + \ 'name' : 'sort one line buffer', + \ 'cmd' : 'sort', + \ 'input' : [ + \ 'single line' + \ ], + \ 'expected' : [ + \ 'single line' + \ ] + \ }, + \ { + \ 'name' : 'sort ignoring case', + \ 'cmd' : '%sort i', + \ 'input' : [ + \ 'BB', + \ 'Cc', + \ 'aa' + \ ], + \ 'expected' : [ + \ 'aa', + \ 'BB', + \ 'Cc' + \ ] + \ }, + \ ] + + " This does not appear to work correctly on Mac. + if !has('mac') + if v:collate =~? '^\(en\|fr\)_ca.utf-\?8$' + " en_CA.utf-8 sorts capitals before lower case + " 'Œ' is omitted because it can sort before or after 'œ' + let tests += [ + \ { + \ 'name' : 'sort with locale ' .. v:collate, + \ 'cmd' : '%sort l', + \ 'input' : [ + \ 'A', + \ 'E', + \ 'O', + \ 'À', + \ 'È', + \ 'É', + \ 'Ô', + \ 'Z', + \ 'a', + \ 'e', + \ 'o', + \ 'à', + \ 'è', + \ 'é', + \ 'ô', + \ 'œ', + \ 'z' + \ ], + \ 'expected' : [ + \ 'A', + \ 'a', + \ 'À', + \ 'à', + \ 'E', + \ 'e', + \ 'É', + \ 'é', + \ 'È', + \ 'è', + \ 'O', + \ 'o', + \ 'Ô', + \ 'ô', + \ 'œ', + \ 'Z', + \ 'z' + \ ] + \ }, + \ ] + elseif v:collate =~? '^\(en\|es\|de\|fr\|it\|nl\).*\.utf-\?8$' + " With these locales, the accentuated letters are ordered + " similarly to the non-accentuated letters. + let tests += [ + \ { + \ 'name' : 'sort with locale ' .. v:collate, + \ 'cmd' : '%sort l', + \ 'input' : [ + \ 'A', + \ 'E', + \ 'O', + \ 'À', + \ 'È', + \ 'É', + \ 'Ô', + \ 'Œ', + \ 'Z', + \ 'a', + \ 'e', + \ 'o', + \ 'à', + \ 'è', + \ 'é', + \ 'ô', + \ 'œ', + \ 'z' + \ ], + \ 'expected' : [ + \ 'a', + \ 'A', + \ 'à', + \ 'À', + \ 'e', + \ 'E', + \ 'é', + \ 'É', + \ 'è', + \ 'È', + \ 'o', + \ 'O', + \ 'ô', + \ 'Ô', + \ 'œ', + \ 'Œ', + \ 'z', + \ 'Z' + \ ] + \ }, + \ ] + endif + endif + + for t in tests + enew! + call append(0, t.input) + $delete _ + setlocal nomodified + execute t.cmd + + call assert_equal(t.expected, getline(1, '$'), t.name) + + " Previously, the ":sort" command would set 'modified' even if the buffer + " contents did not change. Here, we check that this problem is fixed. + if t.input == t.expected + call assert_false(&modified, t.name . ': &mod is not correct') + else + call assert_true(&modified, t.name . ': &mod is not correct') + endif + endfor + + " Needs at least two lines for this test + call setline(1, ['line1', 'line2']) + call assert_fails('sort no', 'E474:') + call assert_fails('sort c', 'E475:') + call assert_fails('sort #pat%', 'E654:') + call assert_fails('sort /\%(/', 'E53:') + + enew! +endfunc + +func Test_sort_large_num() + new + a +-2147483648 +-2147483647 + +-1 +0 +1 +-2147483646 +2147483646 +2147483647 +2147483647 +-2147483648 +abc + +. + " Numerical sort. Non-numeric lines are ordered before numerical lines. + " Ordering of non-numerical is stable. + sort n + call assert_equal(['', + \ 'abc', + \ '', + \ '-2147483648', + \ '-2147483648', + \ '-2147483647', + \ '-2147483646', + \ '-1', + \ '0', + \ '1', + \ '2147483646', + \ '2147483647', + \ '2147483647'], getline(1, '$')) + bwipe! + + new + a +-9223372036854775808 +-9223372036854775807 + +-1 +0 +1 +-9223372036854775806 +9223372036854775806 +9223372036854775807 +9223372036854775807 +-9223372036854775808 +abc + +. + sort n + call assert_equal(['', + \ 'abc', + \ '', + \ '-9223372036854775808', + \ '-9223372036854775808', + \ '-9223372036854775807', + \ '-9223372036854775806', + \ '-1', + \ '0', + \ '1', + \ '9223372036854775806', + \ '9223372036854775807', + \ '9223372036854775807'], getline(1, '$')) + bwipe! +endfunc + + +func Test_sort_cmd_report() + enew! + call append(0, repeat([1], 3) + repeat([2], 3) + repeat([3], 3)) + $delete _ + setlocal nomodified + let res = execute('%sort u') + + call assert_equal([1,2,3], map(getline(1, '$'), 'v:val+0')) + call assert_match("6 fewer lines", res) + enew! + call append(0, repeat([1], 3) + repeat([2], 3) + repeat([3], 3)) + $delete _ + setlocal nomodified report=10 + let res = execute('%sort u') + + call assert_equal([1,2,3], map(getline(1, '$'), 'v:val+0')) + call assert_equal("", res) + enew! + call append(0, repeat([1], 3) + repeat([2], 3) + repeat([3], 3)) + $delete _ + setl report&vim + setlocal nomodified + let res = execute('1g/^/%sort u') + + call assert_equal([1,2,3], map(getline(1, '$'), 'v:val+0')) + " the output comes from the :g command, not from the :sort + call assert_match("6 fewer lines", res) + enew! +endfunc + +" Test for a :sort command followed by another command +func Test_sort_followed_by_cmd() + new + let var = '' + call setline(1, ['cc', 'aa', 'bb']) + %sort | let var = "sortcmdtest" + call assert_equal(var, "sortcmdtest") + call assert_equal(['aa', 'bb', 'cc'], getline(1, '$')) + " Test for :sort followed by a comment + call setline(1, ['3b', '1c', '2a']) + %sort /\d\+/ " sort alphabetically + call assert_equal(['2a', '3b', '1c'], getline(1, '$')) + close! +endfunc + +" Test for :sort using last search pattern +func Test_sort_last_search_pat() + new + let @/ = '\d\+' + call setline(1, ['3b', '1c', '2a']) + sort // + call assert_equal(['2a', '3b', '1c'], getline(1, '$')) + close! +endfunc + +" Test for :sort with no last search pattern +func Test_sort_with_no_last_search_pat() + let lines =<< trim [SCRIPT] + call setline(1, ['3b', '1c', '2a']) + call assert_fails('sort //', 'E35:') + 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 retaining marks across a :sort +func Test_sort_with_marks() + new + call setline(1, ['cc', 'aa', 'bb']) + call setpos("'c", [0, 1, 0, 0]) + call setpos("'a", [0, 2, 0, 0]) + call setpos("'b", [0, 3, 0, 0]) + %sort + call assert_equal(['aa', 'bb', 'cc'], getline(1, '$')) + call assert_equal(2, line("'a")) + call assert_equal(3, line("'b")) + call assert_equal(1, line("'c")) + close! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_source.vim b/test/old/testdir/test_source.vim new file mode 100644 index 0000000000..d4d96e36bf --- /dev/null +++ b/test/old/testdir/test_source.vim @@ -0,0 +1,113 @@ +" Tests for the :source command. + +source check.vim +source view_util.vim + +func Test_source_autocmd() + call writefile([ + \ 'let did_source = 1', + \ ], 'Xsourced') + au SourcePre *source* let did_source_pre = 1 + au SourcePost *source* let did_source_post = 1 + + source Xsourced + + call assert_equal(g:did_source, 1) + call assert_equal(g:did_source_pre, 1) + call assert_equal(g:did_source_post, 1) + + call delete('Xsourced') + au! SourcePre + au! SourcePost + unlet g:did_source + unlet g:did_source_pre + unlet g:did_source_post +endfunc + +func Test_source_cmd() + au SourceCmd *source* let did_source = expand('<afile>') + au SourcePre *source* let did_source_pre = 2 + au SourcePost *source* let did_source_post = 2 + + source Xsourced + + call assert_equal(g:did_source, 'Xsourced') + call assert_false(exists('g:did_source_pre')) + call assert_equal(g:did_source_post, 2) + + au! SourceCmd + au! SourcePre + au! SourcePost +endfunc + +func Test_source_sandbox() + new + call writefile(["Ohello\<Esc>"], 'Xsourcehello') + source! Xsourcehello | echo + call assert_equal('hello', getline(1)) + call assert_fails('sandbox source! Xsourcehello', 'E48:') + bwipe! + call delete('Xsourcehello') +endfunc + +" When deleting a file and immediately creating a new one the inode may be +" recycled. Vim should not recognize it as the same script. +func Test_different_script() + call writefile(['let s:var = "asdf"'], 'XoneScript') + source XoneScript + call delete('XoneScript') + call writefile(['let g:var = s:var'], 'XtwoScript') + call assert_fails('source XtwoScript', 'E121:') + call delete('XtwoScript') +endfunc + +" When sourcing a vim script, shebang should be ignored. +func Test_source_ignore_shebang() + call writefile(['#!./xyzabc', 'let g:val=369'], 'Xfile.vim') + source Xfile.vim + call assert_equal(g:val, 369) + call delete('Xfile.vim') +endfunc + +" Test for expanding <sfile> in a autocmd and for <slnum> and <sflnum> +func Test_source_autocmd_sfile() + let code =<< trim [CODE] + let g:SfileName = '' + augroup sfiletest + au! + autocmd User UserAutoCmd let g:Sfile = '<sfile>:t' + augroup END + doautocmd User UserAutoCmd + let g:Slnum = expand('<slnum>') + let g:Sflnum = expand('<sflnum>') + augroup! sfiletest + [CODE] + call writefile(code, 'Xscript.vim') + source Xscript.vim + call assert_equal('Xscript.vim', g:Sfile) + call assert_equal('7', g:Slnum) + call assert_equal('8', g:Sflnum) + call delete('Xscript.vim') +endfunc + +func Test_source_error() + call assert_fails('scriptencoding utf-8', 'E167:') + call assert_fails('finish', 'E168:') + " call assert_fails('scriptversion 2', 'E984:') +endfunc + +" Test for sourcing a script recursively +func Test_nested_script() + CheckRunVimInTerminal + call writefile([':source! Xscript.vim', ''], 'Xscript.vim') + let buf = RunVimInTerminal('', {'rows': 6}) + call term_wait(buf) + call term_sendkeys(buf, ":set noruler\n") + call term_sendkeys(buf, ":source! Xscript.vim\n") + call term_wait(buf) + call WaitForAssert({-> assert_match('E22: Scripts nested too deep\s*', term_getline(buf, 6))}) + call delete('Xscript.vim') + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_source_utf8.vim b/test/old/testdir/test_source_utf8.vim new file mode 100644 index 0000000000..66fabe0442 --- /dev/null +++ b/test/old/testdir/test_source_utf8.vim @@ -0,0 +1,61 @@ +" Test the :source! command +source check.vim + +func Test_source_utf8() + " check that sourcing a script with 0x80 as second byte works + new + call setline(1, [':%s/àx/--à1234--/g', ':%s/Àx/--À1234--/g']) + write! Xscript + bwipe! + new + call setline(1, [' àx ', ' Àx ']) + source! Xscript | echo + call assert_equal(' --à1234-- ', getline(1)) + call assert_equal(' --À1234-- ', getline(2)) + bwipe! + call delete('Xscript') +endfunc + +func Test_source_latin() + " check that sourcing a latin1 script with a 0xc0 byte works + new + call setline(1, ["call feedkeys('r')", "call feedkeys('\xc0', 'xt')"]) + write! Xscript + bwipe! + new + call setline(1, ['xxx']) + source Xscript + call assert_equal("\u00c0xx", getline(1)) + bwipe! + call delete('Xscript') +endfunc + +" Test for sourcing a file with CTRL-V's at the end of the line +func Test_source_ctrl_v() + call writefile(['map __1 afirst', + \ 'map __2 asecond', + \ 'map __3 athird', + \ 'map __4 afourth', + \ 'map __5 afifth', + \ "map __1 asd\<C-V>", + \ "map __2 asd\<C-V>\<C-V>", + \ "map __3 asd\<C-V>\<C-V>", + \ "map __4 asd\<C-V>\<C-V>\<C-V>", + \ "map __5 asd\<C-V>\<C-V>\<C-V>", + \ ], 'Xtestfile') + source Xtestfile + enew! + exe "normal __1\<Esc>\<Esc>__2\<Esc>__3\<Esc>\<Esc>__4\<Esc>__5\<Esc>" + exe "%s/\<C-J>/0/g" + call assert_equal(['sd', + \ "map __2 asd\<Esc>secondsd\<Esc>sd0map __5 asd0fifth"], + \ getline(1, 2)) + + enew! + call delete('Xtestfile') + unmap __1 + unmap __2 + unmap __3 + unmap __4 + unmap __5 +endfunc diff --git a/test/old/testdir/test_spell.vim b/test/old/testdir/test_spell.vim new file mode 100644 index 0000000000..a19b64a7de --- /dev/null +++ b/test/old/testdir/test_spell.vim @@ -0,0 +1,1561 @@ +" Test spell checking +" Note: this file uses latin1 encoding, but is used with utf-8 encoding. + +source check.vim +CheckFeature spell + +source screendump.vim + +func TearDown() + set nospell + call delete('Xtest.aff') + call delete('Xtest.dic') + call delete('Xtest.latin1.add') + call delete('Xtest.latin1.add.spl') + call delete('Xtest.latin1.spl') + call delete('Xtest.latin1.sug') + " set 'encoding' to clear the word list + set encoding=utf-8 +endfunc + +func Test_wrap_search() + new + call setline(1, ['The', '', 'A plong line with two zpelling mistakes', '', 'End']) + set spell wrapscan + normal ]s + call assert_equal('plong', expand('<cword>')) + normal ]s + call assert_equal('zpelling', expand('<cword>')) + normal ]s + call assert_equal('plong', expand('<cword>')) + bwipe! + set nospell +endfunc + +func Test_curswant() + new + call setline(1, ['Another plong line', 'abcdefghijklmnopq']) + set spell wrapscan + normal 0]s + call assert_equal('plong', expand('<cword>')) + normal j + call assert_equal(9, getcurpos()[2]) + normal 0[s + call assert_equal('plong', expand('<cword>')) + normal j + call assert_equal(9, getcurpos()[2]) + + normal 0]S + call assert_equal('plong', expand('<cword>')) + normal j + call assert_equal(9, getcurpos()[2]) + normal 0[S + call assert_equal('plong', expand('<cword>')) + normal j + call assert_equal(9, getcurpos()[2]) + + normal 1G0 + call assert_equal('plong', spellbadword()[0]) + normal j + call assert_equal(9, getcurpos()[2]) + + bwipe! + set nospell +endfunc + +func Test_z_equal_on_invalid_utf8_word() + split + set spell + call setline(1, "\xff") + norm z= + set nospell + bwipe! +endfunc + +func Test_z_equal_on_single_character() + " this was decrementing the index below zero + new + norm a0\ + norm zW + norm z= + + bwipe! +endfunc + +" Test spellbadword() with argument +func Test_spellbadword() + set spell + + call assert_equal(['bycycle', 'bad'], spellbadword('My bycycle.')) + call assert_equal(['another', 'caps'], 'A sentence. another sentence'->spellbadword()) + + call assert_equal(['TheCamelWord', 'bad'], spellbadword('TheCamelWord asdf')) + set spelloptions=camel + call assert_equal(['asdf', 'bad'], spellbadword('TheCamelWord asdf')) + set spelloptions= + + set spelllang=en + call assert_equal(['', ''], spellbadword('centre')) + call assert_equal(['', ''], spellbadword('center')) + set spelllang=en_us + call assert_equal(['centre', 'local'], spellbadword('centre')) + call assert_equal(['', ''], spellbadword('center')) + set spelllang=en_gb + call assert_equal(['', ''], spellbadword('centre')) + call assert_equal(['center', 'local'], spellbadword('center')) + + " Create a small word list to test that spellbadword('...') + " can return ['...', 'rare']. + e Xwords + insert +foo +foobar/? +. + w! + mkspell! Xwords.spl Xwords + set spelllang=Xwords.spl + call assert_equal(['foobar', 'rare'], spellbadword('foo foobar')) + + " Typo should be detected even without the 'spell' option. + set spelllang=en_gb nospell + call assert_equal(['', ''], spellbadword('centre')) + call assert_equal(['bycycle', 'bad'], spellbadword('My bycycle.')) + call assert_equal(['another', 'caps'], spellbadword('A sentence. another sentence')) + + set spelllang= + call assert_fails("call spellbadword('maxch')", 'E756:') + + call delete('Xwords.spl') + call delete('Xwords') + set spelllang& + set spell& +endfunc + +func Test_spell_camelcase() + set spell spelloptions=camel + let words = [ + \ 'UPPER', + \ 'lower', + \ 'mixedCase', + \ 'HTML', + \ 'XMLHttpRequest', + \ 'foo123bar', + \ '12345678', + \ 'HELLO123world', + \] + + for word in words + call assert_equal(['', ''], spellbadword(word)) + endfor + + set spell& spelloptions& +endfunc + +func Test_spell_file_missing() + let s:spell_file_missing = 0 + augroup TestSpellFileMissing + autocmd! SpellFileMissing * let s:spell_file_missing += 1 + augroup END + + set spell spelllang=ab_cd + let messages = GetMessages() + " This message is not shown in Nvim because of #3027 + " call assert_equal('Warning: Cannot find word list "ab.utf-8.spl" or "ab.ascii.spl"', messages[-1]) + call assert_equal(1, s:spell_file_missing) + + new XTestSpellFileMissing + augroup TestSpellFileMissing + autocmd! SpellFileMissing * bwipe + augroup END + call assert_fails('set spell spelllang=ab_cd', 'E937:') + + " clean up + augroup TestSpellFileMissing + autocmd! SpellFileMissing + augroup END + augroup! TestSpellFileMissing + unlet s:spell_file_missing + set spell& spelllang& + %bwipe! +endfunc + +func Test_spell_file_missing_bwipe() + " this was using a window that was wiped out in a SpellFileMissing autocmd + set spelllang=xy + au SpellFileMissing * n0 + set spell + au SpellFileMissing * bw + snext somefile + + au! SpellFileMissing + bwipe! + set nospell spelllang=en +endfunc + +func Test_spelldump() + " In case the spell file is not found avoid getting the download dialog, we + " would get stuck at the prompt. + let g:en_not_found = 0 + augroup TestSpellFileMissing + au! SpellFileMissing * let g:en_not_found = 1 + augroup END + set spell spelllang=en + spellrare! emacs + if g:en_not_found + call assert_report("Could not find English spell file") + else + spelldump + + " Check assumption about region: 1: us, 2: au, 3: ca, 4: gb, 5: nz. + call assert_equal('/regions=usaucagbnz', getline(1)) + call assert_notequal(0, search('^theater/1$')) " US English only. + call assert_notequal(0, search('^theatre/2345$')) " AU, CA, GB or NZ English. + + call assert_notequal(0, search('^emacs/?$')) " ? for a rare word. + call assert_notequal(0, search('^the the/!$')) " ! for a wrong word. + endif + + " clean up + unlet g:en_not_found + augroup TestSpellFileMissing + autocmd! SpellFileMissing + augroup END + augroup! TestSpellFileMissing + bwipe + set spell& +endfunc + +func Test_spelldump_bang() + new + call setline(1, 'This is a sample sentence.') + redraw + + " In case the spell file is not found avoid getting the download dialog, we + " would get stuck at the prompt. + let g:en_not_found = 0 + augroup TestSpellFileMissing + au! SpellFileMissing * let g:en_not_found = 1 + augroup END + + set spell + + if g:en_not_found + call assert_report("Could not find English spell file") + else + redraw + spelldump! + + " :spelldump! includes the number of times a word was found while updating + " the screen. + " Common word count starts at 10, regular word count starts at 0. + call assert_notequal(0, search("^is\t11$")) " common word found once. + call assert_notequal(0, search("^the\t10$")) " common word never found. + call assert_notequal(0, search("^sample\t1$")) " regular word found once. + call assert_equal(0, search("^screen\t")) " regular word never found. + endif + + " clean up + unlet g:en_not_found + augroup TestSpellFileMissing + autocmd! SpellFileMissing + augroup END + augroup! TestSpellFileMissing + %bwipe! + set spell& +endfunc + +func Test_spelllang_inv_region() + set spell spelllang=en_xx + let messages = GetMessages() + call assert_equal('Warning: region xx not supported', messages[-1]) + set spell& spelllang& +endfunc + +func Test_compl_with_CTRL_X_CTRL_K_using_spell() + " When spell checking is enabled and 'dictionary' is empty, + " CTRL-X CTRL-K in insert mode completes using the spelling dictionary. + new + set spell spelllang=en dictionary= + + set ignorecase + call feedkeys("Senglis\<c-x>\<c-k>\<esc>", 'tnx') + call assert_equal(['English'], getline(1, '$')) + call feedkeys("SEnglis\<c-x>\<c-k>\<esc>", 'tnx') + call assert_equal(['English'], getline(1, '$')) + + set noignorecase + call feedkeys("Senglis\<c-x>\<c-k>\<esc>", 'tnx') + call assert_equal(['englis'], getline(1, '$')) + call feedkeys("SEnglis\<c-x>\<c-k>\<esc>", 'tnx') + call assert_equal(['English'], getline(1, '$')) + + set spelllang=en_us + call feedkeys("Stheat\<c-x>\<c-k>\<esc>", 'tnx') + call assert_equal(['theater'], getline(1, '$')) + set spelllang=en_gb + call feedkeys("Stheat\<c-x>\<c-k>\<esc>", 'tnx') + call assert_equal(['theatre'], getline(1, '$')) + + bwipe! + set spell& spelllang& dictionary& ignorecase& +endfunc + +func Test_spellrepall() + new + set spell + call assert_fails('spellrepall', 'E752:') + call setline(1, ['A speling mistake. The same speling mistake.', + \ 'Another speling mistake.']) + call feedkeys(']s1z=', 'tx') + call assert_equal('A spelling mistake. The same speling mistake.', getline(1)) + call assert_equal('Another speling mistake.', getline(2)) + spellrepall + call assert_equal('A spelling mistake. The same spelling mistake.', getline(1)) + call assert_equal('Another spelling mistake.', getline(2)) + call assert_fails('spellrepall', 'E753:') + set spell& + bwipe! +endfunc + +func Test_spell_dump_word_length() + " this was running over MAXWLEN + new + noremap 0 0a0zW0000000 + sil! norm 0z=0 + sil norm 0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + sil! norm 0z=0 + + bwipe! + nunmap 0 +endfunc + +" Test spellsuggest({word} [, {max} [, {capital}]]) +func Test_spellsuggest() + " Verify suggestions are given even when spell checking is not enabled. + set nospell + call assert_equal(['march', 'March'], spellsuggest('marrch', 2)) + + set spell + + " With 1 argument. + call assert_equal(['march', 'March'], spellsuggest('marrch')[0:1]) + + " With 2 arguments. + call assert_equal(['march', 'March'], spellsuggest('marrch', 2)) + + " With 3 arguments. + call assert_equal(['march'], spellsuggest('marrch', 1, 0)) + call assert_equal(['March'], spellsuggest('marrch', 1, 1)) + + " Test with digits and hyphen. + call assert_equal('Carbon-14', spellsuggest('Carbon-15')[0]) + + " Comment taken from spellsuggest.c explains the following test cases: + " + " If there are more UPPER than lower case letters suggest an + " ALLCAP word. Otherwise, if the first letter is UPPER then + " suggest ONECAP. Exception: "ALl" most likely should be "All", + " require three upper case letters. + call assert_equal(['THIRD', 'third'], spellsuggest('thIRD', 2)) + call assert_equal(['third', 'THIRD'], spellsuggest('tHIrd', 2)) + call assert_equal(['Third'], spellsuggest('THird', 1)) + call assert_equal(['All'], spellsuggest('ALl', 1)) + + " Special suggestion for repeated 'the the'. + call assert_inrange(0, 2, index(spellsuggest('the the', 3), 'the')) + call assert_inrange(0, 2, index(spellsuggest('the the', 3), 'the')) + call assert_inrange(0, 2, index(spellsuggest('The the', 3), 'The')) + + call assert_fails("call spellsuggest('maxch', [])", 'E745:') + call assert_fails("call spellsuggest('maxch', 2, [])", 'E745:') + + set spelllang= + call assert_fails("call spellsuggest('maxch')", 'E756:') + set spelllang& + + set spell& +endfunc + +" Test 'spellsuggest' option with methods fast, best and double. +func Test_spellsuggest_option_methods() + set spell + + for e in ['utf-8'] + exe 'set encoding=' .. e + + set spellsuggest=fast + call assert_equal(['Stick', 'Stitch'], spellsuggest('Stich', 2), e) + + " With best or double option, "Stitch" should become the top suggestion + " because of better phonetic matching. + set spellsuggest=best + call assert_equal(['Stitch', 'Stick'], spellsuggest('Stich', 2), e) + + set spellsuggest=double + call assert_equal(['Stitch', 'Stick'], spellsuggest('Stich', 2), e) + endfor + + set spell& spellsuggest& encoding& +endfunc + +" Test 'spellsuggest' option with value file:{filename} +func Test_spellsuggest_option_file() + set spell spellsuggest=file:Xspellsuggest + call writefile(['emacs/vim', + \ 'theribal/terrible', + \ 'teribal/terrrible', + \ 'terribal'], + \ 'Xspellsuggest') + + call assert_equal(['vim'], spellsuggest('emacs', 2)) + call assert_equal(['terrible'], spellsuggest('theribal',2)) + + " If the suggestion is misspelled (*terrrible* with 3 r), + " it should not be proposed. + " The entry for "terribal" should be ignored because of missing slash. + call assert_equal([], spellsuggest('teribal', 2)) + call assert_equal([], spellsuggest('terribal', 2)) + + set spell spellsuggest=best,file:Xspellsuggest + call assert_equal(['vim', 'Emacs'], spellsuggest('emacs', 2)) + call assert_equal(['terrible', 'tribal'], spellsuggest('theribal', 2)) + call assert_equal(['tribal'], spellsuggest('teribal', 1)) + call assert_equal(['tribal'], spellsuggest('terribal', 1)) + + call delete('Xspellsuggest') + call assert_fails("call spellsuggest('vim')", "E484: Can't open file Xspellsuggest") + + set spellsuggest& spell& +endfunc + +" Test 'spellsuggest' option with value {number} +" to limit the number of suggestions +func Test_spellsuggest_option_number() + set spell spellsuggest=2,best + new + + " We limited the number of suggestions to 2, so selecting + " the 1st and 2nd suggestion should correct the word, but + " selecting a 3rd suggestion should do nothing. + call setline(1, 'A baord') + norm $1z= + call assert_equal('A board', getline(1)) + + call setline(1, 'A baord') + norm $2z= + call assert_equal('A bard', getline(1)) + + call setline(1, 'A baord') + norm $3z= + call assert_equal('A baord', getline(1)) + + let a = execute('norm $z=') + call assert_equal( + \ "\n" + \ .. "Change \"baord\" to:\n" + \ .. " 1 \"board\"\n" + \ .. " 2 \"bard\"\n" + \ .. "Type number and <Enter> or click with the mouse (q or empty cancels): ", a) + + set spell spellsuggest=0 + call assert_equal("\nSorry, no suggestions", execute('norm $z=')) + + " Unlike z=, function spellsuggest(...) should not be affected by the + " max number of suggestions (2) set by the 'spellsuggest' option. + call assert_equal(['board', 'bard', 'broad'], spellsuggest('baord', 3)) + + set spellsuggest& spell& + bwipe! +endfunc + +" Test 'spellsuggest' option with value expr:{expr} +func Test_spellsuggest_option_expr() + " A silly 'spellsuggest' function which makes suggestions all uppercase + " and makes the score of each suggestion the length of the suggested word. + " So shorter suggestions are preferred. + func MySuggest() + let spellsuggest_save = &spellsuggest + set spellsuggest=3,best + let result = map(spellsuggest(v:val, 3), "[toupper(v:val), len(v:val)]") + let &spellsuggest = spellsuggest_save + return result + endfunc + + set spell spellsuggest=expr:MySuggest() + call assert_equal(['BARD', 'BOARD', 'BROAD'], spellsuggest('baord', 3)) + + new + call setline(1, 'baord') + let a = execute('norm z=') + call assert_equal( + \ "\n" + \ .. "Change \"baord\" to:\n" + \ .. " 1 \"BARD\"\n" + \ .. " 2 \"BOARD\"\n" + \ .. " 3 \"BROAD\"\n" + \ .. "Type number and <Enter> or click with the mouse (q or empty cancels): ", a) + + " With verbose, z= should show the score i.e. word length with + " our SpellSuggest() function. + set verbose=1 + let a = execute('norm z=') + call assert_equal( + \ "\n" + \ .. "Change \"baord\" to:\n" + \ .. " 1 \"BARD\" (4 - 0)\n" + \ .. " 2 \"BOARD\" (5 - 0)\n" + \ .. " 3 \"BROAD\" (5 - 0)\n" + \ .. "Type number and <Enter> or click with the mouse (q or empty cancels): ", a) + + set spell& spellsuggest& verbose& + bwipe! +endfunc + +" Test for 'spellsuggest' expr errors +func Test_spellsuggest_expr_errors() + " 'spellsuggest' + func MySuggest() + return range(3) + endfunc + set spell spellsuggest=expr:MySuggest() + call assert_equal([], spellsuggest('baord', 3)) + + " Test for 'spellsuggest' expression returning a non-list value + func! MySuggest2() + return 'good' + endfunc + set spellsuggest=expr:MySuggest2() + call assert_equal([], spellsuggest('baord')) + + " Test for 'spellsuggest' expression returning a list with dict values + func! MySuggest3() + return [[{}, {}]] + endfunc + set spellsuggest=expr:MySuggest3() + call assert_fails("call spellsuggest('baord')", 'E731:') + + set nospell spellsuggest& + delfunc MySuggest + delfunc MySuggest2 + delfunc MySuggest3 +endfunc + +func Test_spellsuggest_timeout() + set spellsuggest=timeout:30 + set spellsuggest=timeout:-123 + set spellsuggest=timeout:999999 + call assert_fails('set spellsuggest=timeout', 'E474:') + call assert_fails('set spellsuggest=timeout:x', 'E474:') + call assert_fails('set spellsuggest=timeout:-x', 'E474:') + call assert_fails('set spellsuggest=timeout:--9', 'E474:') +endfunc + +func Test_spellsuggest_visual_end_of_line() + let enc_save = &encoding + " set encoding=iso8859 + + " This was reading beyond the end of the line. + norm R00000000000 + sil norm 0 + sil! norm i00000) + sil! norm i00000) + call feedkeys("\<CR>") + norm z= + + let &encoding = enc_save +endfunc + +func Test_spellinfo() + throw 'Skipped: Nvim does not support enc=latin1' + new + let runtime = substitute($VIMRUNTIME, '\\', '/', 'g') + + set enc=latin1 spell spelllang=en + call assert_match("^\nfile: " .. runtime .. "/spell/en.latin1.spl\n$", execute('spellinfo')) + + set enc=cp1250 spell spelllang=en + call assert_match("^\nfile: " .. runtime .. "/spell/en.ascii.spl\n$", execute('spellinfo')) + + set enc=utf-8 spell spelllang=en + call assert_match("^\nfile: " .. runtime .. "/spell/en.utf-8.spl\n$", execute('spellinfo')) + + set enc=latin1 spell spelllang=en_us,en_nz + call assert_match("^\n" . + \ "file: " .. runtime .. "/spell/en.latin1.spl\n" . + \ "file: " .. runtime .. "/spell/en.latin1.spl\n$", execute('spellinfo')) + + set spell spelllang= + call assert_fails('spellinfo', 'E756:') + + set nospell spelllang=en + call assert_fails('spellinfo', 'E756:') + + call assert_fails('set spelllang=foo/bar', 'E474:') + call assert_fails('set spelllang=foo\ bar', 'E474:') + call assert_fails("set spelllang=foo\\\nbar", 'E474:') + call assert_fails("set spelllang=foo\\\rbar", 'E474:') + call assert_fails("set spelllang=foo+bar", 'E474:') + + set enc& spell& spelllang& + bwipe +endfunc + +func Test_zz_basic() + call LoadAffAndDic(g:test_data_aff1, g:test_data_dic1) + call RunGoodBad("wrong OK puts. Test the end", + \ "bad: inputs comment ok Ok. test d\xE9\xF4l end the", + \["Comment", "deol", "d\xE9\xF4r", "input", "OK", "output", "outputs", "outtest", "put", "puts", + \ "test", "testen", "testn", "the end", "uk", "wrong"], + \[ + \ ["bad", ["put", "uk", "OK"]], + \ ["inputs", ["input", "puts", "outputs"]], + \ ["comment", ["Comment", "outtest", "the end"]], + \ ["ok", ["OK", "uk", "put"]], + \ ["Ok", ["OK", "Uk", "Put"]], + \ ["test", ["Test", "testn", "testen"]], + \ ["d\xE9\xF4l", ["deol", "d\xE9\xF4r", "test"]], + \ ["end", ["put", "uk", "test"]], + \ ["the", ["put", "uk", "test"]], + \ ] + \ ) + + call assert_equal("gebletegek", soundfold('goobledygoook')) + call assert_equal("kepereneven", 'koprnven'->soundfold()) + call assert_equal("everles gesvets etele", soundfold('oeverloos gezwets edale')) +endfunc + +" Postponed prefixes +func Test_zz_prefixes() + call LoadAffAndDic(g:test_data_aff2, g:test_data_dic1) + call RunGoodBad("puts", + \ "bad: inputs comment ok Ok end the. test d\xE9\xF4l", + \ ["Comment", "deol", "d\xE9\xF4r", "OK", "put", "input", "output", "puts", "outputs", "test", "outtest", "testen", "testn", "the end", "uk", "wrong"], + \ [ + \ ["bad", ["put", "uk", "OK"]], + \ ["inputs", ["input", "puts", "outputs"]], + \ ["comment", ["Comment"]], + \ ["ok", ["OK", "uk", "put"]], + \ ["Ok", ["OK", "Uk", "Put"]], + \ ["end", ["put", "uk", "deol"]], + \ ["the", ["put", "uk", "test"]], + \ ["test", ["Test", "testn", "testen"]], + \ ["d\xE9\xF4l", ["deol", "d\xE9\xF4r", "test"]], + \ ]) +endfunc + +"Compound words +func Test_zz_compound() + call LoadAffAndDic(g:test_data_aff3, g:test_data_dic3) + call RunGoodBad("foo m\xEF foobar foofoobar barfoo barbarfoo", + \ "bad: bar la foom\xEF barm\xEF m\xEFfoo m\xEFbar m\xEFm\xEF lala m\xEFla lam\xEF foola labar", + \ ["foo", "m\xEF"], + \ [ + \ ["bad", ["foo", "m\xEF"]], + \ ["bar", ["barfoo", "foobar", "foo"]], + \ ["la", ["m\xEF", "foo"]], + \ ["foom\xEF", ["foo m\xEF", "foo", "foofoo"]], + \ ["barm\xEF", ["barfoo", "m\xEF", "barbar"]], + \ ["m\xEFfoo", ["m\xEF foo", "foo", "foofoo"]], + \ ["m\xEFbar", ["foobar", "barbar", "m\xEF"]], + \ ["m\xEFm\xEF", ["m\xEF m\xEF", "m\xEF"]], + \ ["lala", []], + \ ["m\xEFla", ["m\xEF", "m\xEF m\xEF"]], + \ ["lam\xEF", ["m\xEF", "m\xEF m\xEF"]], + \ ["foola", ["foo", "foobar", "foofoo"]], + \ ["labar", ["barbar", "foobar"]], + \ ]) + + call LoadAffAndDic(g:test_data_aff4, g:test_data_dic4) + call RunGoodBad("word util bork prebork start end wordutil wordutils pro-ok bork borkbork borkborkbork borkborkborkbork borkborkborkborkbork tomato tomatotomato startend startword startwordword startwordend startwordwordend startwordwordwordend prebork preborkbork preborkborkbork nouword", + \ "bad: wordutilize pro borkborkborkborkborkbork tomatotomatotomato endstart endend startstart wordend wordstart preborkprebork preborkpreborkbork startwordwordwordwordend borkpreborkpreborkbork utilsbork startnouword", + \ ["bork", "prebork", "end", "pro-ok", "start", "tomato", "util", "utilize", "utils", "word", "nouword"], + \ [ + \ ["bad", ["end", "bork", "word"]], + \ ["wordutilize", ["word utilize", "wordutils", "wordutil"]], + \ ["pro", ["bork", "word", "end"]], + \ ["borkborkborkborkborkbork", ["bork borkborkborkborkbork", "borkbork borkborkborkbork", "borkborkbork borkborkbork"]], + \ ["tomatotomatotomato", ["tomato tomatotomato", "tomatotomato tomato", "tomato tomato tomato"]], + \ ["endstart", ["end start", "start"]], + \ ["endend", ["end end", "end"]], + \ ["startstart", ["start start"]], + \ ["wordend", ["word end", "word", "wordword"]], + \ ["wordstart", ["word start", "bork start"]], + \ ["preborkprebork", ["prebork prebork", "preborkbork", "preborkborkbork"]], + \ ["preborkpreborkbork", ["prebork preborkbork", "preborkborkbork", "preborkborkborkbork"]], + \ ["startwordwordwordwordend", ["startwordwordwordword end", "startwordwordwordword", "start wordwordwordword end"]], + \ ["borkpreborkpreborkbork", ["bork preborkpreborkbork", "bork prebork preborkbork", "bork preborkprebork bork"]], + \ ["utilsbork", ["utilbork", "utils bork", "util bork"]], + \ ["startnouword", ["start nouword", "startword", "startborkword"]], + \ ]) + +endfunc + +"Test affix flags with two characters +func Test_zz_affix() + call LoadAffAndDic(g:test_data_aff5, g:test_data_dic5) + call RunGoodBad("fooa1 fooa\xE9 bar prebar barbork prebarbork startprebar start end startend startmiddleend nouend", + \ "bad: foo fooa2 prabar probarbirk middle startmiddle middleend endstart startprobar startnouend", + \ ["bar", "barbork", "end", "fooa1", "fooa\xE9", "nouend", "prebar", "prebarbork", "start"], + \ [ + \ ["bad", ["bar", "end", "fooa1"]], + \ ["foo", ["fooa1", "fooa\xE9", "bar"]], + \ ["fooa2", ["fooa1", "fooa\xE9", "bar"]], + \ ["prabar", ["prebar", "bar", "bar bar"]], + \ ["probarbirk", ["prebarbork"]], + \ ["middle", []], + \ ["startmiddle", ["startmiddleend", "startmiddlebar"]], + \ ["middleend", []], + \ ["endstart", ["end start", "start"]], + \ ["startprobar", ["startprebar", "start prebar", "startbar"]], + \ ["startnouend", ["start nouend", "startend"]], + \ ]) + + call LoadAffAndDic(g:test_data_aff6, g:test_data_dic6) + call RunGoodBad("meea1 meea\xE9 bar prebar barbork prebarbork leadprebar lead end leadend leadmiddleend", + \ "bad: mee meea2 prabar probarbirk middle leadmiddle middleend endlead leadprobar", + \ ["bar", "barbork", "end", "lead", "meea1", "meea\xE9", "prebar", "prebarbork"], + \ [ + \ ["bad", ["bar", "end", "lead"]], + \ ["mee", ["meea1", "meea\xE9", "bar"]], + \ ["meea2", ["meea1", "meea\xE9", "lead"]], + \ ["prabar", ["prebar", "bar", "leadbar"]], + \ ["probarbirk", ["prebarbork"]], + \ ["middle", []], + \ ["leadmiddle", ["leadmiddleend", "leadmiddlebar"]], + \ ["middleend", []], + \ ["endlead", ["end lead", "lead", "end end"]], + \ ["leadprobar", ["leadprebar", "lead prebar", "leadbar"]], + \ ]) + + call LoadAffAndDic(g:test_data_aff7, g:test_data_dic7) + call RunGoodBad("meea1 meezero meea\xE9 bar prebar barmeat prebarmeat leadprebar lead tail leadtail leadmiddletail", + \ "bad: mee meea2 prabar probarmaat middle leadmiddle middletail taillead leadprobar", + \ ["bar", "barmeat", "lead", "meea1", "meea\xE9", "meezero", "prebar", "prebarmeat", "tail"], + \ [ + \ ["bad", ["bar", "lead", "tail"]], + \ ["mee", ["meea1", "meea\xE9", "bar"]], + \ ["meea2", ["meea1", "meea\xE9", "lead"]], + \ ["prabar", ["prebar", "bar", "leadbar"]], + \ ["probarmaat", ["prebarmeat"]], + \ ["middle", []], + \ ["leadmiddle", ["leadmiddlebar"]], + \ ["middletail", []], + \ ["taillead", ["tail lead", "tail"]], + \ ["leadprobar", ["leadprebar", "lead prebar", "leadbar"]], + \ ]) +endfunc + +func Test_zz_NOSLITSUGS() + call LoadAffAndDic(g:test_data_aff8, g:test_data_dic8) + call RunGoodBad("foo bar faabar", "bad: foobar barfoo", + \ ["bar", "faabar", "foo"], + \ [ + \ ["bad", ["bar", "foo"]], + \ ["foobar", ["faabar", "foo bar", "bar"]], + \ ["barfoo", ["bar foo", "bar", "foo"]], + \ ]) +endfunc + +" Numbers +func Test_zz_Numbers() + call LoadAffAndDic(g:test_data_aff9, g:test_data_dic9) + call RunGoodBad("0b1011 0777 1234 0x01ff", "", + \ ["bar", "foo"], + \ [ + \ ]) +endfunc + +" Affix flags +func Test_zz_affix_flags() + call LoadAffAndDic(g:test_data_aff10, g:test_data_dic10) + call RunGoodBad("drink drinkable drinkables drinktable drinkabletable", + \ "bad: drinks drinkstable drinkablestable", + \ ["drink", "drinkable", "drinkables", "table"], + \ [['bad', []], + \ ['drinks', ['drink']], + \ ['drinkstable', ['drinktable', 'drinkable', 'drink table']], + \ ['drinkablestable', ['drinkabletable', 'drinkables table', 'drinkable table']], + \ ]) +endfunc + +function FirstSpellWord() + call feedkeys("/^start:\n", 'tx') + normal ]smm + let [str, a] = spellbadword() + return str +endfunc + +function SecondSpellWord() + normal `m]s + let [str, a] = spellbadword() + return str +endfunc + +"Test with SAL instead of SOFO items; test automatic reloading +func Test_zz_sal_and_addition() + throw 'skipped: Nvim does not support enc=latin1' + set enc=latin1 + set spellfile= + call writefile(g:test_data_dic1, "Xtest.dic") + call writefile(g:test_data_aff_sal, "Xtest.aff") + mkspell! Xtest Xtest + set spl=Xtest.latin1.spl spell + call assert_equal('kbltykk', soundfold('goobledygoook')) + call assert_equal('kprnfn', soundfold('koprnven')) + call assert_equal('*fls kswts tl', soundfold('oeverloos gezwets edale')) + + "also use an addition file + call writefile(["/regions=usgbnz", "elequint/2", "elekwint/3"], "Xtest.latin1.add") + mkspell! Xtest.latin1.add.spl Xtest.latin1.add + + bwipe! + call setline(1, ["start: elequint test elekwint test elekwent asdf"]) + + set spellfile=Xtest.latin1.add + call assert_equal("elekwent", FirstSpellWord()) + + set spl=Xtest_us.latin1.spl + call assert_equal("elequint", FirstSpellWord()) + call assert_equal("elekwint", SecondSpellWord()) + + set spl=Xtest_gb.latin1.spl + call assert_equal("elekwint", FirstSpellWord()) + call assert_equal("elekwent", SecondSpellWord()) + + set spl=Xtest_nz.latin1.spl + call assert_equal("elequint", FirstSpellWord()) + call assert_equal("elekwent", SecondSpellWord()) + + set spl=Xtest_ca.latin1.spl + call assert_equal("elequint", FirstSpellWord()) + call assert_equal("elekwint", SecondSpellWord()) + + bwipe! + set spellfile= + set spl& +endfunc + +func Test_spellfile_value() + set spellfile=Xdir/Xtest.latin1.add + set spellfile=Xdir/Xtest.utf-8.add,Xtest_other.add +endfunc + +func Test_region_error() + messages clear + call writefile(["/regions=usgbnz", "elequint/0"], "Xtest.latin1.add") + mkspell! Xtest.latin1.add.spl Xtest.latin1.add + call assert_match('Invalid region nr in Xtest.latin1.add line 2: 0', execute('messages')) + call delete('Xtest.latin1.add') + call delete('Xtest.latin1.add.spl') +endfunc + +" Check using z= in new buffer (crash fixed by patch 7.4a.028). +func Test_zeq_crash() + new + set spell + call feedkeys('iasdz=:\"', 'tx') + + bwipe! +endfunc + +" Check that z= works even when 'nospell' is set. This test uses one of the +" tests in Test_spellsuggest_option_number() just to verify that z= basically +" works and that "E756: Spell checking is not enabled" is not generated. +func Test_zeq_nospell() + new + set nospell spellsuggest=1,best + call setline(1, 'A baord') + try + norm $1z= + call assert_equal('A board', getline(1)) + catch + call assert_report("Caught exception: " . v:exception) + endtry + set spell& spellsuggest& + bwipe! +endfunc + +" Check that "E756: Spell checking is not possible" is reported when z= is +" executed and 'spelllang' is empty. +func Test_zeq_no_spelllang() + new + set spelllang= spellsuggest=1,best + call setline(1, 'A baord') + call assert_fails('normal $1z=', 'E756:') + set spelllang& spellsuggest& + bwipe! +endfunc + +" Check handling a word longer than MAXWLEN. +func Test_spell_long_word() + set enc=utf-8 + new + call setline(1, "d\xCC\xB4\xCC\xBD\xCD\x88\xCD\x94a\xCC\xB5\xCD\x84\xCD\x84\xCC\xA8\xCD\x9Cr\xCC\xB5\xCC\x8E\xCD\x85\xCD\x85k\xCC\xB6\xCC\x89\xCC\x9D \xCC\xB6\xCC\x83\xCC\x8F\xCC\xA4\xCD\x8Ef\xCC\xB7\xCC\x81\xCC\x80\xCC\xA9\xCC\xB0\xCC\xAC\xCC\xA2\xCD\x95\xCD\x87\xCD\x8D\xCC\x9E\xCD\x99\xCC\xAD\xCC\xAB\xCC\x97\xCC\xBBo\xCC\xB6\xCC\x84\xCC\x95\xCC\x8C\xCC\x8B\xCD\x9B\xCD\x9C\xCC\xAFr\xCC\xB7\xCC\x94\xCD\x83\xCD\x97\xCC\x8C\xCC\x82\xCD\x82\xCD\x80\xCD\x91\xCC\x80\xCC\xBE\xCC\x82\xCC\x8F\xCC\xA3\xCD\x85\xCC\xAE\xCD\x8D\xCD\x99\xCC\xBC\xCC\xAB\xCC\xA7\xCD\x88c\xCC\xB7\xCD\x83\xCC\x84\xCD\x92\xCC\x86\xCC\x83\xCC\x88\xCC\x92\xCC\x94\xCC\xBE\xCC\x9D\xCC\xAF\xCC\x98\xCC\x9D\xCC\xBB\xCD\x8E\xCC\xBB\xCC\xB3\xCC\xA3\xCD\x8E\xCD\x99\xCC\xA5\xCC\xAD\xCC\x99\xCC\xB9\xCC\xAE\xCC\xA5\xCC\x9E\xCD\x88\xCC\xAE\xCC\x9E\xCC\xA9\xCC\x97\xCC\xBC\xCC\x99\xCC\xA5\xCD\x87\xCC\x97\xCD\x8E\xCD\x94\xCC\x99\xCC\x9D\xCC\x96\xCD\x94\xCC\xAB\xCC\xA7\xCC\xA5\xCC\x98\xCC\xBB\xCC\xAF\xCC\xABe\xCC\xB7\xCC\x8E\xCC\x82\xCD\x86\xCD\x9B\xCC\x94\xCD\x83\xCC\x85\xCD\x8A\xCD\x8C\xCC\x8B\xCD\x92\xCD\x91\xCC\x8F\xCC\x81\xCD\x95\xCC\xA2\xCC\xB9\xCC\xB2\xCD\x9C\xCC\xB1\xCC\xA6\xCC\xB3\xCC\xAF\xCC\xAE\xCC\x9C\xCD\x99s\xCC\xB8\xCC\x8C\xCC\x8E\xCC\x87\xCD\x81\xCD\x82\xCC\x86\xCD\x8C\xCD\x8C\xCC\x8B\xCC\x84\xCC\x8C\xCD\x84\xCD\x9B\xCD\x86\xCC\x93\xCD\x90\xCC\x85\xCC\x94\xCD\x98\xCD\x84\xCD\x92\xCD\x8B\xCC\x90\xCC\x83\xCC\x8F\xCD\x84\xCD\x81\xCD\x9B\xCC\x90\xCD\x81\xCC\x8F\xCC\xBD\xCC\x88\xCC\xBF\xCC\x88\xCC\x84\xCC\x8E\xCD\x99\xCD\x94\xCC\x99\xCD\x99\xCC\xB0\xCC\xA8\xCC\xA3\xCC\xA8\xCC\x96\xCC\x99\xCC\xAE\xCC\xBC\xCC\x99\xCD\x9A\xCC\xB2\xCC\xB1\xCC\x9F\xCC\xBB\xCC\xA6\xCD\x85\xCC\xAA\xCD\x89\xCC\x9D\xCC\x99\xCD\x96\xCC\xB1\xCC\xB1\xCC\x99\xCC\xA6\xCC\xA5\xCD\x95\xCC\xB2\xCC\xA0\xCD\x99 within") + set spell spelllang=en + redraw + redraw! + bwipe! + set nospell +endfunc + +func Test_spellsuggest_too_deep() + " This was incrementing "depth" over MAXWLEN. + new + norm s000G00000000000000 + sil norm ..vzG................vvzG0 v z= + bwipe! +endfunc + +func Test_spell_good_word_invalid() + " This was adding a word with a 0x02 byte, which causes havoc. + enew + norm o0 + sil! norm rzzWs00/ + 2 + sil! norm VzGprzzW + sil! norm z= + + bwipe! +endfunc + +func Test_spell_good_word_slash() + " This caused E1280. + new + norm afoo / + 1 + norm zG + + bwipe! +endfunc + +func LoadAffAndDic(aff_contents, dic_contents) + throw 'skipped: Nvim does not support enc=latin1' + set enc=latin1 + set spellfile= + call writefile(a:aff_contents, "Xtest.aff") + call writefile(a:dic_contents, "Xtest.dic") + " Generate a .spl file from a .dic and .aff file. + mkspell! Xtest Xtest + " use that spell file + set spl=Xtest.latin1.spl spell +endfunc + +func ListWords() + spelldump + %yank + quit + return split(@", "\n") +endfunc + +func TestGoodBadBase() + exe '1;/^good:' + normal 0f:]s + let prevbad = '' + let result = [] + while 1 + let [bad, a] = spellbadword() + if bad == '' || bad == prevbad || bad == 'badend' + break + endif + let prevbad = bad + let lst = bad->spellsuggest(3) + normal mm + + call add(result, [bad, lst]) + normal `m]s + endwhile + return result +endfunc + +func RunGoodBad(good, bad, expected_words, expected_bad_words) + bwipe! + call setline(1, ["good: ", a:good, a:bad, " badend "]) + let words = ListWords() + call assert_equal(a:expected_words, words[1:-1]) + let bad_words = TestGoodBadBase() + call assert_equal(a:expected_bad_words, bad_words) + bwipe! +endfunc + +func Test_spell_screendump() + CheckScreendump + + let lines =<< trim END + call test_override('alloc_lines', 1) + call setline(1, [ + \ "This is some text without any spell errors. Everything", + \ "should just be black, nothing wrong here.", + \ "", + \ "This line has a sepll error. and missing caps.", + \ "And and this is the the duplication.", + \ "with missing caps here.", + \ ]) + set spell spelllang=en_nz + END + call writefile(lines, 'XtestSpell', 'D') + let buf = RunVimInTerminal('-S XtestSpell', {'rows': 8}) + call VerifyScreenDump(buf, 'Test_spell_1', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_spell_screendump_spellcap() + CheckScreendump + + let lines =<< trim END + call test_override('alloc_lines', 1) + call setline(1, [ + \ " This line has a sepll error. and missing caps and trailing spaces. ", + \ "another missing cap here.", + \ "", + \ "and here.", + \ " ", + \ "and here." + \ ]) + set spell spelllang=en + END + call writefile(lines, 'XtestSpellCap', 'D') + let buf = RunVimInTerminal('-S XtestSpellCap', {'rows': 8}) + call VerifyScreenDump(buf, 'Test_spell_2', {}) + + " After adding word missing Cap in next line is updated + call term_sendkeys(buf, "3GANot\<Esc>") + call VerifyScreenDump(buf, 'Test_spell_3', {}) + + " Deleting a full stop removes missing Cap in next line + call term_sendkeys(buf, "5Gdd\<C-L>k$x") + call VerifyScreenDump(buf, 'Test_spell_4', {}) + + " Undo also updates the next line (go to command line to remove message) + call term_sendkeys(buf, "u:\<Esc>") + call VerifyScreenDump(buf, 'Test_spell_5', {}) + + " Folding an empty line does not remove Cap in next line + call term_sendkeys(buf, "uzfk:\<Esc>") + call VerifyScreenDump(buf, 'Test_spell_6', {}) + + " Folding the end of a sentence does not remove Cap in next line + " and editing a line does not remove Cap in current line + call term_sendkeys(buf, "Jzfkk$x") + call VerifyScreenDump(buf, 'Test_spell_7', {}) + + " Cap is correctly applied in the first row of a window + call term_sendkeys(buf, "\<C-E>\<C-L>") + call VerifyScreenDump(buf, 'Test_spell_8', {}) + + " Adding an empty line does not remove Cap in "mod_bot" area + call term_sendkeys(buf, "zbO\<Esc>") + call VerifyScreenDump(buf, 'Test_spell_9', {}) + + " Multiple empty lines does not remove Cap in the line after + call term_sendkeys(buf, "O\<Esc>\<C-L>") + call VerifyScreenDump(buf, 'Test_spell_10', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_spell_compatible() + CheckScreendump + + let lines =<< trim END + call test_override('alloc_lines', 1) + call setline(1, [ + \ "test "->repeat(20), + \ "", + \ "end", + \ ]) + set spell cpo+=$ + END + call writefile(lines, 'XtestSpellComp', 'D') + let buf = RunVimInTerminal('-S XtestSpellComp', {'rows': 8}) + + call term_sendkeys(buf, "51|C") + call VerifyScreenDump(buf, 'Test_spell_compatible_1', {}) + + call term_sendkeys(buf, "x") + call VerifyScreenDump(buf, 'Test_spell_compatible_2', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_z_equal_with_large_count() + split + set spell + call setline(1, "ff") + norm 0z=337203685477580 + set nospell + bwipe! +endfunc + +let g:test_data_aff1 = [ + \"SET ISO8859-1", + \"TRY esianrtolcdugmphbyfvkwjkqxz-\xEB\xE9\xE8\xEA\xEF\xEE\xE4\xE0\xE2\xF6\xFC\xFB'ESIANRTOLCDUGMPHBYFVKWJKQXZ", + \"", + \"FOL \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"LOW \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"UPP \xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xFF", + \"", + \"SOFOFROM abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xBF", + \"SOFOTO ebctefghejklnnepkrstevvkesebctefghejklnnepkrstevvkeseeeeeeeceeeeeeeedneeeeeeeeeeepseeeeeeeeceeeeeeeedneeeeeeeeeeep?", + \"", + \"MIDWORD\t'-", + \"", + \"KEP =", + \"RAR ?", + \"BAD !", + \"", + \"PFX I N 1", + \"PFX I 0 in .", + \"", + \"PFX O Y 1", + \"PFX O 0 out .", + \"", + \"SFX S Y 2", + \"SFX S 0 s [^s]", + \"SFX S 0 es s", + \"", + \"SFX N N 3", + \"SFX N 0 en [^n]", + \"SFX N 0 nen n", + \"SFX N 0 n .", + \"", + \"REP 3", + \"REP g ch", + \"REP ch g", + \"REP svp s.v.p.", + \"", + \"MAP 9", + \"MAP a\xE0\xE1\xE2\xE3\xE4\xE5", + \"MAP e\xE8\xE9\xEA\xEB", + \"MAP i\xEC\xED\xEE\xEF", + \"MAP o\xF2\xF3\xF4\xF5\xF6", + \"MAP u\xF9\xFA\xFB\xFC", + \"MAP n\xF1", + \"MAP c\xE7", + \"MAP y\xFF\xFD", + \"MAP s\xDF", + \ ] +let g:test_data_dic1 = [ + \"123456", + \"test/NO", + \"# comment", + \"wrong", + \"Comment", + \"OK", + \"uk", + \"put/ISO", + \"the end", + \"deol", + \"d\xE9\xF4r", + \ ] +let g:test_data_aff2 = [ + \"SET ISO8859-1", + \"", + \"FOL \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"LOW \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"UPP \xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xFF", + \"", + \"PFXPOSTPONE", + \"", + \"MIDWORD\t'-", + \"", + \"KEP =", + \"RAR ?", + \"BAD !", + \"", + \"PFX I N 1", + \"PFX I 0 in .", + \"", + \"PFX O Y 1", + \"PFX O 0 out [a-z]", + \"", + \"SFX S Y 2", + \"SFX S 0 s [^s]", + \"SFX S 0 es s", + \"", + \"SFX N N 3", + \"SFX N 0 en [^n]", + \"SFX N 0 nen n", + \"SFX N 0 n .", + \"", + \"REP 3", + \"REP g ch", + \"REP ch g", + \"REP svp s.v.p.", + \"", + \"MAP 9", + \"MAP a\xE0\xE1\xE2\xE3\xE4\xE5", + \"MAP e\xE8\xE9\xEA\xEB", + \"MAP i\xEC\xED\xEE\xEF", + \"MAP o\xF2\xF3\xF4\xF5\xF6", + \"MAP u\xF9\xFA\xFB\xFC", + \"MAP n\xF1", + \"MAP c\xE7", + \"MAP y\xFF\xFD", + \"MAP s\xDF", + \ ] +let g:test_data_aff3 = [ + \"SET ISO8859-1", + \"", + \"COMPOUNDMIN 3", + \"COMPOUNDRULE m*", + \"NEEDCOMPOUND x", + \ ] +let g:test_data_dic3 = [ + \"1234", + \"foo/m", + \"bar/mx", + \"m\xEF/m", + \"la/mx", + \ ] +let g:test_data_aff4 = [ + \"SET ISO8859-1", + \"", + \"FOL \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"LOW \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"UPP \xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xFF", + \"", + \"COMPOUNDRULE m+", + \"COMPOUNDRULE sm*e", + \"COMPOUNDRULE sm+", + \"COMPOUNDMIN 3", + \"COMPOUNDWORDMAX 3", + \"COMPOUNDFORBIDFLAG t", + \"", + \"COMPOUNDSYLMAX 5", + \"SYLLABLE a\xE1e\xE9i\xEDo\xF3\xF6\xF5u\xFA\xFC\xFBy/aa/au/ea/ee/ei/ie/oa/oe/oo/ou/uu/ui", + \"", + \"MAP 9", + \"MAP a\xE0\xE1\xE2\xE3\xE4\xE5", + \"MAP e\xE8\xE9\xEA\xEB", + \"MAP i\xEC\xED\xEE\xEF", + \"MAP o\xF2\xF3\xF4\xF5\xF6", + \"MAP u\xF9\xFA\xFB\xFC", + \"MAP n\xF1", + \"MAP c\xE7", + \"MAP y\xFF\xFD", + \"MAP s\xDF", + \"", + \"NEEDAFFIX x", + \"", + \"PFXPOSTPONE", + \"", + \"MIDWORD '-", + \"", + \"SFX q N 1", + \"SFX q 0 -ok .", + \"", + \"SFX a Y 2", + \"SFX a 0 s .", + \"SFX a 0 ize/t .", + \"", + \"PFX p N 1", + \"PFX p 0 pre .", + \"", + \"PFX P N 1", + \"PFX P 0 nou .", + \ ] +let g:test_data_dic4 = [ + \"1234", + \"word/mP", + \"util/am", + \"pro/xq", + \"tomato/m", + \"bork/mp", + \"start/s", + \"end/e", + \ ] +let g:test_data_aff5 = [ + \"SET ISO8859-1", + \"", + \"FLAG long", + \"", + \"NEEDAFFIX !!", + \"", + \"COMPOUNDRULE ssmm*ee", + \"", + \"NEEDCOMPOUND xx", + \"COMPOUNDPERMITFLAG pp", + \"", + \"SFX 13 Y 1", + \"SFX 13 0 bork .", + \"", + \"SFX a1 Y 1", + \"SFX a1 0 a1 .", + \"", + \"SFX a\xE9 Y 1", + \"SFX a\xE9 0 a\xE9 .", + \"", + \"PFX zz Y 1", + \"PFX zz 0 pre/pp .", + \"", + \"PFX yy Y 1", + \"PFX yy 0 nou .", + \ ] +let g:test_data_dic5 = [ + \"1234", + \"foo/a1a\xE9!!", + \"bar/zz13ee", + \"start/ss", + \"end/eeyy", + \"middle/mmxx", + \ ] +let g:test_data_aff6 = [ + \"SET ISO8859-1", + \"", + \"FLAG caplong", + \"", + \"NEEDAFFIX A!", + \"", + \"COMPOUNDRULE sMm*Ee", + \"", + \"NEEDCOMPOUND Xx", + \"", + \"COMPOUNDPERMITFLAG p", + \"", + \"SFX N3 Y 1", + \"SFX N3 0 bork .", + \"", + \"SFX A1 Y 1", + \"SFX A1 0 a1 .", + \"", + \"SFX A\xE9 Y 1", + \"SFX A\xE9 0 a\xE9 .", + \"", + \"PFX Zz Y 1", + \"PFX Zz 0 pre/p .", + \ ] +let g:test_data_dic6 = [ + \"1234", + \"mee/A1A\xE9A!", + \"bar/ZzN3Ee", + \"lead/s", + \"end/Ee", + \"middle/MmXx", + \ ] +let g:test_data_aff7 = [ + \"SET ISO8859-1", + \"", + \"FLAG num", + \"", + \"NEEDAFFIX 9999", + \"", + \"COMPOUNDRULE 2,77*123", + \"", + \"NEEDCOMPOUND 1", + \"COMPOUNDPERMITFLAG 432", + \"", + \"SFX 61003 Y 1", + \"SFX 61003 0 meat .", + \"", + \"SFX 0 Y 1", + \"SFX 0 0 zero .", + \"", + \"SFX 391 Y 1", + \"SFX 391 0 a1 .", + \"", + \"SFX 111 Y 1", + \"SFX 111 0 a\xE9 .", + \"", + \"PFX 17 Y 1", + \"PFX 17 0 pre/432 .", + \ ] +let g:test_data_dic7 = [ + \"1234", + \"mee/0,391,111,9999", + \"bar/17,61003,123", + \"lead/2", + \"tail/123", + \"middle/77,1", + \ ] +let g:test_data_aff8 = [ + \"SET ISO8859-1", + \"", + \"NOSPLITSUGS", + \ ] +let g:test_data_dic8 = [ + \"1234", + \"foo", + \"bar", + \"faabar", + \ ] +let g:test_data_aff9 = [ + \ ] +let g:test_data_dic9 = [ + \"1234", + \"foo", + \"bar", + \ ] +let g:test_data_aff10 = [ + \"COMPOUNDRULE se", + \"COMPOUNDPERMITFLAG p", + \"", + \"SFX A Y 1", + \"SFX A 0 able/Mp .", + \"", + \"SFX M Y 1", + \"SFX M 0 s .", + \ ] +let g:test_data_dic10 = [ + \"1234", + \"drink/As", + \"table/e", + \ ] +let g:test_data_aff_sal = [ + \"SET ISO8859-1", + \"TRY esianrtolcdugmphbyfvkwjkqxz-\xEB\xE9\xE8\xEA\xEF\xEE\xE4\xE0\xE2\xF6\xFC\xFB'ESIANRTOLCDUGMPHBYFVKWJKQXZ", + \"", + \"FOL \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"LOW \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"UPP \xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xFF", + \"", + \"MIDWORD\t'-", + \"", + \"KEP =", + \"RAR ?", + \"BAD !", + \"", + \"PFX I N 1", + \"PFX I 0 in .", + \"", + \"PFX O Y 1", + \"PFX O 0 out .", + \"", + \"SFX S Y 2", + \"SFX S 0 s [^s]", + \"SFX S 0 es s", + \"", + \"SFX N N 3", + \"SFX N 0 en [^n]", + \"SFX N 0 nen n", + \"SFX N 0 n .", + \"", + \"REP 3", + \"REP g ch", + \"REP ch g", + \"REP svp s.v.p.", + \"", + \"MAP 9", + \"MAP a\xE0\xE1\xE2\xE3\xE4\xE5", + \"MAP e\xE8\xE9\xEA\xEB", + \"MAP i\xEC\xED\xEE\xEF", + \"MAP o\xF2\xF3\xF4\xF5\xF6", + \"MAP u\xF9\xFA\xFB\xFC", + \"MAP n\xF1", + \"MAP c\xE7", + \"MAP y\xFF\xFD", + \"MAP s\xDF", + \"", + \"SAL AH(AEIOUY)-^ *H", + \"SAL AR(AEIOUY)-^ *R", + \"SAL A(HR)^ *", + \"SAL A^ *", + \"SAL AH(AEIOUY)- H", + \"SAL AR(AEIOUY)- R", + \"SAL A(HR) _", + \"SAL \xC0^ *", + \"SAL \xC5^ *", + \"SAL BB- _", + \"SAL B B", + \"SAL CQ- _", + \"SAL CIA X", + \"SAL CH X", + \"SAL C(EIY)- S", + \"SAL CK K", + \"SAL COUGH^ KF", + \"SAL CC< C", + \"SAL C K", + \"SAL DG(EIY) K", + \"SAL DD- _", + \"SAL D T", + \"SAL \xC9< E", + \"SAL EH(AEIOUY)-^ *H", + \"SAL ER(AEIOUY)-^ *R", + \"SAL E(HR)^ *", + \"SAL ENOUGH^$ *NF", + \"SAL E^ *", + \"SAL EH(AEIOUY)- H", + \"SAL ER(AEIOUY)- R", + \"SAL E(HR) _", + \"SAL FF- _", + \"SAL F F", + \"SAL GN^ N", + \"SAL GN$ N", + \"SAL GNS$ NS", + \"SAL GNED$ N", + \"SAL GH(AEIOUY)- K", + \"SAL GH _", + \"SAL GG9 K", + \"SAL G K", + \"SAL H H", + \"SAL IH(AEIOUY)-^ *H", + \"SAL IR(AEIOUY)-^ *R", + \"SAL I(HR)^ *", + \"SAL I^ *", + \"SAL ING6 N", + \"SAL IH(AEIOUY)- H", + \"SAL IR(AEIOUY)- R", + \"SAL I(HR) _", + \"SAL J K", + \"SAL KN^ N", + \"SAL KK- _", + \"SAL K K", + \"SAL LAUGH^ LF", + \"SAL LL- _", + \"SAL L L", + \"SAL MB$ M", + \"SAL MM M", + \"SAL M M", + \"SAL NN- _", + \"SAL N N", + \"SAL OH(AEIOUY)-^ *H", + \"SAL OR(AEIOUY)-^ *R", + \"SAL O(HR)^ *", + \"SAL O^ *", + \"SAL OH(AEIOUY)- H", + \"SAL OR(AEIOUY)- R", + \"SAL O(HR) _", + \"SAL PH F", + \"SAL PN^ N", + \"SAL PP- _", + \"SAL P P", + \"SAL Q K", + \"SAL RH^ R", + \"SAL ROUGH^ RF", + \"SAL RR- _", + \"SAL R R", + \"SAL SCH(EOU)- SK", + \"SAL SC(IEY)- S", + \"SAL SH X", + \"SAL SI(AO)- X", + \"SAL SS- _", + \"SAL S S", + \"SAL TI(AO)- X", + \"SAL TH @", + \"SAL TCH-- _", + \"SAL TOUGH^ TF", + \"SAL TT- _", + \"SAL T T", + \"SAL UH(AEIOUY)-^ *H", + \"SAL UR(AEIOUY)-^ *R", + \"SAL U(HR)^ *", + \"SAL U^ *", + \"SAL UH(AEIOUY)- H", + \"SAL UR(AEIOUY)- R", + \"SAL U(HR) _", + \"SAL V^ W", + \"SAL V F", + \"SAL WR^ R", + \"SAL WH^ W", + \"SAL W(AEIOU)- W", + \"SAL X^ S", + \"SAL X KS", + \"SAL Y(AEIOU)- Y", + \"SAL ZZ- _", + \"SAL Z S", + \ ] + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_spell_utf8.vim b/test/old/testdir/test_spell_utf8.vim new file mode 100644 index 0000000000..91ada1ed38 --- /dev/null +++ b/test/old/testdir/test_spell_utf8.vim @@ -0,0 +1,831 @@ +" Test for spell checking with 'encoding' set to utf-8 + +source check.vim +CheckFeature spell + +scriptencoding utf-8 + +func TearDown() + set nospell + call delete('Xtest.aff') + call delete('Xtest.dic') + call delete('Xtest.utf-8.add') + call delete('Xtest.utf-8.add.spl') + call delete('Xtest.utf-8.spl') + call delete('Xtest.utf-8.sug') + " set 'encoding' to clear the word list + set encoding=utf-8 +endfunc + +let g:test_data_aff1 = [ + \"SET ISO8859-1", + \"TRY esianrtolcdugmphbyfvkwjkqxz-ëéèêïîäàâöüû'ESIANRTOLCDUGMPHBYFVKWJKQXZ", + \"", + \"FOL àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ", + \"LOW àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþßÿ", + \"UPP ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßÿ", + \"", + \"SOFOFROM abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xBF", + \"SOFOTO ebctefghejklnnepkrstevvkesebctefghejklnnepkrstevvkeseeeeeeeceeeeeeeedneeeeeeeeeeepseeeeeeeeceeeeeeeedneeeeeeeeeeep?", + \"", + \"MIDWORD\t'-", + \"", + \"KEP =", + \"RAR ?", + \"BAD !", + \"", + \"PFX I N 1", + \"PFX I 0 in .", + \"", + \"PFX O Y 1", + \"PFX O 0 out .", + \"", + \"SFX S Y 2", + \"SFX S 0 s [^s]", + \"SFX S 0 es s", + \"", + \"SFX N N 3", + \"SFX N 0 en [^n]", + \"SFX N 0 nen n", + \"SFX N 0 n .", + \"", + \"REP 3", + \"REP g ch", + \"REP ch g", + \"REP svp s.v.p.", + \"", + \"MAP 9", + \"MAP a\xE0\xE1\xE2\xE3\xE4\xE5", + \"MAP e\xE8\xE9\xEA\xEB", + \"MAP i\xEC\xED\xEE\xEF", + \"MAP o\xF2\xF3\xF4\xF5\xF6", + \"MAP u\xF9\xFA\xFB\xFC", + \"MAP n\xF1", + \"MAP c\xE7", + \"MAP y\xFF\xFD", + \"MAP s\xDF" + \ ] +let g:test_data_dic1 = [ + \"123456", + \"test/NO", + \"# comment", + \"wrong", + \"Comment", + \"OK", + \"uk", + \"put/ISO", + \"the end", + \"deol", + \"d\xE9\xF4r", + \ ] +let g:test_data_aff2 = [ + \"SET ISO8859-1", + \"", + \"FOL \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"LOW \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"UPP \xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xFF", + \"", + \"PFXPOSTPONE", + \"", + \"MIDWORD\t'-", + \"", + \"KEP =", + \"RAR ?", + \"BAD !", + \"", + \"PFX I N 1", + \"PFX I 0 in .", + \"", + \"PFX O Y 1", + \"PFX O 0 out [a-z]", + \"", + \"SFX S Y 2", + \"SFX S 0 s [^s]", + \"SFX S 0 es s", + \"", + \"SFX N N 3", + \"SFX N 0 en [^n]", + \"SFX N 0 nen n", + \"SFX N 0 n .", + \"", + \"REP 3", + \"REP g ch", + \"REP ch g", + \"REP svp s.v.p.", + \"", + \"MAP 9", + \"MAP a\xE0\xE1\xE2\xE3\xE4\xE5", + \"MAP e\xE8\xE9\xEA\xEB", + \"MAP i\xEC\xED\xEE\xEF", + \"MAP o\xF2\xF3\xF4\xF5\xF6", + \"MAP u\xF9\xFA\xFB\xFC", + \"MAP n\xF1", + \"MAP c\xE7", + \"MAP y\xFF\xFD", + \"MAP s\xDF", + \ ] +let g:test_data_aff3 = [ + \"SET ISO8859-1", + \"", + \"COMPOUNDMIN 3", + \"COMPOUNDRULE m*", + \"NEEDCOMPOUND x", + \ ] +let g:test_data_dic3 = [ + \"1234", + \"foo/m", + \"bar/mx", + \"m\xEF/m", + \"la/mx", + \ ] +let g:test_data_aff4 = [ + \"SET ISO8859-1", + \"", + \"FOL \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"LOW \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"UPP \xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xFF", + \"", + \"COMPOUNDRULE m+", + \"COMPOUNDRULE sm*e", + \"COMPOUNDRULE sm+", + \"COMPOUNDMIN 3", + \"COMPOUNDWORDMAX 3", + \"COMPOUNDFORBIDFLAG t", + \"", + \"COMPOUNDSYLMAX 5", + \"SYLLABLE a\xE1e\xE9i\xEDo\xF3\xF6\xF5u\xFA\xFC\xFBy/aa/au/ea/ee/ei/ie/oa/oe/oo/ou/uu/ui", + \"", + \"MAP 9", + \"MAP a\xE0\xE1\xE2\xE3\xE4\xE5", + \"MAP e\xE8\xE9\xEA\xEB", + \"MAP i\xEC\xED\xEE\xEF", + \"MAP o\xF2\xF3\xF4\xF5\xF6", + \"MAP u\xF9\xFA\xFB\xFC", + \"MAP n\xF1", + \"MAP c\xE7", + \"MAP y\xFF\xFD", + \"MAP s\xDF", + \"", + \"NEEDAFFIX x", + \"", + \"PFXPOSTPONE", + \"", + \"MIDWORD '-", + \"", + \"SFX q N 1", + \"SFX q 0 -ok .", + \"", + \"SFX a Y 2", + \"SFX a 0 s .", + \"SFX a 0 ize/t .", + \"", + \"PFX p N 1", + \"PFX p 0 pre .", + \"", + \"PFX P N 1", + \"PFX P 0 nou .", + \ ] +let g:test_data_dic4 = [ + \"1234", + \"word/mP", + \"util/am", + \"pro/xq", + \"tomato/m", + \"bork/mp", + \"start/s", + \"end/e", + \ ] +let g:test_data_aff5 = [ + \"SET ISO8859-1", + \"", + \"FLAG long", + \"", + \"NEEDAFFIX !!", + \"", + \"COMPOUNDRULE ssmm*ee", + \"", + \"NEEDCOMPOUND xx", + \"COMPOUNDPERMITFLAG pp", + \"", + \"SFX 13 Y 1", + \"SFX 13 0 bork .", + \"", + \"SFX a1 Y 1", + \"SFX a1 0 a1 .", + \"", + \"SFX a\xE9 Y 1", + \"SFX a\xE9 0 a\xE9 .", + \"", + \"PFX zz Y 1", + \"PFX zz 0 pre/pp .", + \"", + \"PFX yy Y 1", + \"PFX yy 0 nou .", + \ ] +let g:test_data_dic5 = [ + \"1234", + \"foo/a1a\xE9!!", + \"bar/zz13ee", + \"start/ss", + \"end/eeyy", + \"middle/mmxx", + \ ] +let g:test_data_aff6 = [ + \"SET ISO8859-1", + \"", + \"FLAG caplong", + \"", + \"NEEDAFFIX A!", + \"", + \"COMPOUNDRULE sMm*Ee", + \"", + \"NEEDCOMPOUND Xx", + \"", + \"COMPOUNDPERMITFLAG p", + \"", + \"SFX N3 Y 1", + \"SFX N3 0 bork .", + \"", + \"SFX A1 Y 1", + \"SFX A1 0 a1 .", + \"", + \"SFX A\xE9 Y 1", + \"SFX A\xE9 0 a\xE9 .", + \"", + \"PFX Zz Y 1", + \"PFX Zz 0 pre/p .", + \ ] +let g:test_data_dic6 = [ + \"1234", + \"mee/A1A\xE9A!", + \"bar/ZzN3Ee", + \"lead/s", + \"end/Ee", + \"middle/MmXx", + \ ] +let g:test_data_aff7 = [ + \"SET ISO8859-1", + \"", + \"FLAG num", + \"", + \"NEEDAFFIX 9999", + \"", + \"COMPOUNDRULE 2,77*123", + \"", + \"NEEDCOMPOUND 1", + \"COMPOUNDPERMITFLAG 432", + \"", + \"SFX 61003 Y 1", + \"SFX 61003 0 meat .", + \"", + \"SFX 0 Y 1", + \"SFX 0 0 zero .", + \"", + \"SFX 391 Y 1", + \"SFX 391 0 a1 .", + \"", + \"SFX 111 Y 1", + \"SFX 111 0 a\xE9 .", + \"", + \"PFX 17 Y 1", + \"PFX 17 0 pre/432 .", + \ ] +let g:test_data_dic7 = [ + \"1234", + \"mee/0,391,111,9999", + \"bar/17,61003,123", + \"lead/2", + \"tail/123", + \"middle/77,1", + \ ] +let g:test_data_aff8 = [ + \"SET ISO8859-1", + \"", + \"NOSPLITSUGS", + \ ] +let g:test_data_dic8 = [ + \"1234", + \"foo", + \"bar", + \"faabar", + \ ] +let g:test_data_aff9 = [ + \ ] +let g:test_data_dic9 = [ + \"1234", + \"foo", + \"bar", + \ ] +let g:test_data_aff10 = [ + \"COMPOUNDRULE se", + \"COMPOUNDPERMITFLAG p", + \"", + \"SFX A Y 1", + \"SFX A 0 able/Mp .", + \"", + \"SFX M Y 1", + \"SFX M 0 s .", + \ ] +let g:test_data_dic10 = [ + \"1234", + \"drink/As", + \"table/e", + \ ] +let g:test_data_aff_sal = [ + \"SET ISO8859-1", + \"TRY esianrtolcdugmphbyfvkwjkqxz-\xEB\xE9\xE8\xEA\xEF\xEE\xE4\xE0\xE2\xF6\xFC\xFB'ESIANRTOLCDUGMPHBYFVKWJKQXZ", + \"", + \"FOL \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"LOW \xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xDF\xFF", + \"UPP \xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xFF", + \"", + \"MIDWORD\t'-", + \"", + \"KEP =", + \"RAR ?", + \"BAD !", + \"", + \"PFX I N 1", + \"PFX I 0 in .", + \"", + \"PFX O Y 1", + \"PFX O 0 out .", + \"", + \"SFX S Y 2", + \"SFX S 0 s [^s]", + \"SFX S 0 es s", + \"", + \"SFX N N 3", + \"SFX N 0 en [^n]", + \"SFX N 0 nen n", + \"SFX N 0 n .", + \"", + \"REP 3", + \"REP g ch", + \"REP ch g", + \"REP svp s.v.p.", + \"", + \"MAP 9", + \"MAP a\xE0\xE1\xE2\xE3\xE4\xE5", + \"MAP e\xE8\xE9\xEA\xEB", + \"MAP i\xEC\xED\xEE\xEF", + \"MAP o\xF2\xF3\xF4\xF5\xF6", + \"MAP u\xF9\xFA\xFB\xFC", + \"MAP n\xF1", + \"MAP c\xE7", + \"MAP y\xFF\xFD", + \"MAP s\xDF", + \"", + \"SAL AH(AEIOUY)-^ *H", + \"SAL AR(AEIOUY)-^ *R", + \"SAL A(HR)^ *", + \"SAL A^ *", + \"SAL AH(AEIOUY)- H", + \"SAL AR(AEIOUY)- R", + \"SAL A(HR) _", + \"SAL \xC0^ *", + \"SAL \xC5^ *", + \"SAL BB- _", + \"SAL B B", + \"SAL CQ- _", + \"SAL CIA X", + \"SAL CH X", + \"SAL C(EIY)- S", + \"SAL CK K", + \"SAL COUGH^ KF", + \"SAL CC< C", + \"SAL C K", + \"SAL DG(EIY) K", + \"SAL DD- _", + \"SAL D T", + \"SAL \xC9< E", + \"SAL EH(AEIOUY)-^ *H", + \"SAL ER(AEIOUY)-^ *R", + \"SAL E(HR)^ *", + \"SAL ENOUGH^$ *NF", + \"SAL E^ *", + \"SAL EH(AEIOUY)- H", + \"SAL ER(AEIOUY)- R", + \"SAL E(HR) _", + \"SAL FF- _", + \"SAL F F", + \"SAL GN^ N", + \"SAL GN$ N", + \"SAL GNS$ NS", + \"SAL GNED$ N", + \"SAL GH(AEIOUY)- K", + \"SAL GH _", + \"SAL GG9 K", + \"SAL G K", + \"SAL H H", + \"SAL IH(AEIOUY)-^ *H", + \"SAL IR(AEIOUY)-^ *R", + \"SAL I(HR)^ *", + \"SAL I^ *", + \"SAL ING6 N", + \"SAL IH(AEIOUY)- H", + \"SAL IR(AEIOUY)- R", + \"SAL I(HR) _", + \"SAL J K", + \"SAL KN^ N", + \"SAL KK- _", + \"SAL K K", + \"SAL LAUGH^ LF", + \"SAL LL- _", + \"SAL L L", + \"SAL MB$ M", + \"SAL MM M", + \"SAL M M", + \"SAL NN- _", + \"SAL N N", + \"SAL OH(AEIOUY)-^ *H", + \"SAL OR(AEIOUY)-^ *R", + \"SAL O(HR)^ *", + \"SAL O^ *", + \"SAL OH(AEIOUY)- H", + \"SAL OR(AEIOUY)- R", + \"SAL O(HR) _", + \"SAL PH F", + \"SAL PN^ N", + \"SAL PP- _", + \"SAL P P", + \"SAL Q K", + \"SAL RH^ R", + \"SAL ROUGH^ RF", + \"SAL RR- _", + \"SAL R R", + \"SAL SCH(EOU)- SK", + \"SAL SC(IEY)- S", + \"SAL SH X", + \"SAL SI(AO)- X", + \"SAL SS- _", + \"SAL S S", + \"SAL TI(AO)- X", + \"SAL TH @", + \"SAL TCH-- _", + \"SAL TOUGH^ TF", + \"SAL TT- _", + \"SAL T T", + \"SAL UH(AEIOUY)-^ *H", + \"SAL UR(AEIOUY)-^ *R", + \"SAL U(HR)^ *", + \"SAL U^ *", + \"SAL UH(AEIOUY)- H", + \"SAL UR(AEIOUY)- R", + \"SAL U(HR) _", + \"SAL V^ W", + \"SAL V F", + \"SAL WR^ R", + \"SAL WH^ W", + \"SAL W(AEIOU)- W", + \"SAL X^ S", + \"SAL X KS", + \"SAL Y(AEIOU)- Y", + \"SAL ZZ- _", + \"SAL Z S", + \ ] + +func LoadAffAndDic(aff_contents, dic_contents) + set spellfile= + call writefile(a:aff_contents, "Xtest.aff") + call writefile(a:dic_contents, "Xtest.dic") + " Generate a .spl file from a .dic and .aff file. + mkspell! Xtest Xtest + " use that spell file + set spl=Xtest.utf-8.spl spell +endfunc + +func ListWords() + spelldump + %yank + quit + return split(@", "\n") +endfunc + +func TestGoodBadBase() + exe '1;/^good:' + normal 0f:]s + let prevbad = '' + let result = [] + while 1 + let [bad, a] = spellbadword() + if bad == '' || bad == prevbad || bad == 'badend' + break + endif + let prevbad = bad + let lst = bad->spellsuggest(3) + normal mm + + call add(result, [bad, lst]) + normal `m]s + endwhile + return result +endfunc + +func RunGoodBad(good, bad, expected_words, expected_bad_words) + %bwipe! + call setline(1, ['', "good: ", a:good, a:bad, " badend "]) + let words = ListWords() + call assert_equal(a:expected_words, words[1:-1]) + let bad_words = TestGoodBadBase() + call assert_equal(a:expected_bad_words, bad_words) + %bwipe! +endfunc + +func Test_spell_basic() + call LoadAffAndDic(g:test_data_aff1, g:test_data_dic1) + call RunGoodBad("wrong OK puts. Test the end", + \ "bad: inputs comment ok Ok. test d\u00E9\u00F4l end the", + \["Comment", "deol", "d\u00E9\u00F4r", "input", "OK", "output", "outputs", "outtest", "put", "puts", + \ "test", "testen", "testn", "the end", "uk", "wrong"], + \[ + \ ["bad", ["put", "uk", "OK"]], + \ ["inputs", ["input", "puts", "outputs"]], + \ ["comment", ["Comment", "outtest", "the end"]], + \ ["ok", ["OK", "uk", "put"]], + \ ["Ok", ["OK", "Uk", "Put"]], + \ ["test", ["Test", "testn", "testen"]], + \ ["d\u00E9\u00F4l", ["deol", "d\u00E9\u00F4r", "test"]], + \ ["end", ["put", "uk", "test"]], + \ ["the", ["put", "uk", "test"]], + \ ] + \ ) + + call assert_equal("gebletegek", soundfold('goobledygoook')) + call assert_equal("kepereneven", 'kóopërÿnôven'->soundfold()) + call assert_equal("everles gesvets etele", soundfold('oeverloos gezwets edale')) +endfunc + +" Postponed prefixes +func Test_spell_prefixes() + call LoadAffAndDic(g:test_data_aff2, g:test_data_dic1) + call RunGoodBad("puts", + \ "bad: inputs comment ok Ok end the. test d\u00E9\u00F4l", + \ ["Comment", "deol", "d\u00E9\u00F4r", "OK", "put", "input", "output", "puts", "outputs", "test", "outtest", "testen", "testn", "the end", "uk", "wrong"], + \ [ + \ ["bad", ["put", "uk", "OK"]], + \ ["inputs", ["input", "puts", "outputs"]], + \ ["comment", ["Comment"]], + \ ["ok", ["OK", "uk", "put"]], + \ ["Ok", ["OK", "Uk", "Put"]], + \ ["end", ["put", "uk", "deol"]], + \ ["the", ["put", "uk", "test"]], + \ ["test", ["Test", "testn", "testen"]], + \ ["d\u00E9\u00F4l", ["deol", "d\u00E9\u00F4r", "test"]], + \ ]) +endfunc + +"Compound words +func Test_spell_compound() + call LoadAffAndDic(g:test_data_aff3, g:test_data_dic3) + call RunGoodBad("foo m\u00EF foobar foofoobar barfoo barbarfoo", + \ "bad: bar la foom\u00EF barm\u00EF m\u00EFfoo m\u00EFbar m\u00EFm\u00EF lala m\u00EFla lam\u00EF foola labar", + \ ["foo", "m\u00EF"], + \ [ + \ ["bad", ["foo", "m\u00EF"]], + \ ["bar", ["barfoo", "foobar", "foo"]], + \ ["la", ["m\u00EF", "foo"]], + \ ["foom\u00EF", ["foo m\u00EF", "foo", "foofoo"]], + \ ["barm\u00EF", ["barfoo", "m\u00EF", "barbar"]], + \ ["m\u00EFfoo", ["m\u00EF foo", "foo", "foofoo"]], + \ ["m\u00EFbar", ["foobar", "barbar", "m\u00EF"]], + \ ["m\u00EFm\u00EF", ["m\u00EF m\u00EF", "m\u00EF"]], + \ ["lala", []], + \ ["m\u00EFla", ["m\u00EF", "m\u00EF m\u00EF"]], + \ ["lam\u00EF", ["m\u00EF", "m\u00EF m\u00EF"]], + \ ["foola", ["foo", "foobar", "foofoo"]], + \ ["labar", ["barbar", "foobar"]], + \ ]) + + call LoadAffAndDic(g:test_data_aff4, g:test_data_dic4) + call RunGoodBad("word util bork prebork start end wordutil wordutils pro-ok bork borkbork borkborkbork borkborkborkbork borkborkborkborkbork tomato tomatotomato startend startword startwordword startwordend startwordwordend startwordwordwordend prebork preborkbork preborkborkbork nouword", + \ "bad: wordutilize pro borkborkborkborkborkbork tomatotomatotomato endstart endend startstart wordend wordstart preborkprebork preborkpreborkbork startwordwordwordwordend borkpreborkpreborkbork utilsbork startnouword", + \ ["bork", "prebork", "end", "pro-ok", "start", "tomato", "util", "utilize", "utils", "word", "nouword"], + \ [ + \ ["bad", ["end", "bork", "word"]], + \ ["wordutilize", ["word utilize", "wordutils", "wordutil"]], + \ ["pro", ["bork", "word", "end"]], + \ ["borkborkborkborkborkbork", ["bork borkborkborkborkbork", "borkbork borkborkborkbork", "borkborkbork borkborkbork"]], + \ ["tomatotomatotomato", ["tomato tomatotomato", "tomatotomato tomato", "tomato tomato tomato"]], + \ ["endstart", ["end start", "start"]], + \ ["endend", ["end end", "end"]], + \ ["startstart", ["start start"]], + \ ["wordend", ["word end", "word", "wordword"]], + \ ["wordstart", ["word start", "bork start"]], + \ ["preborkprebork", ["prebork prebork", "preborkbork", "preborkborkbork"]], + \ ["preborkpreborkbork", ["prebork preborkbork", "preborkborkbork", "preborkborkborkbork"]], + \ ["startwordwordwordwordend", ["startwordwordwordword end", "startwordwordwordword", "start wordwordwordword end"]], + \ ["borkpreborkpreborkbork", ["bork preborkpreborkbork", "bork prebork preborkbork", "bork preborkprebork bork"]], + \ ["utilsbork", ["utilbork", "utils bork", "util bork"]], + \ ["startnouword", ["start nouword", "startword", "startborkword"]], + \ ]) + +endfunc + +" Test affix flags with two characters +func Test_spell_affix() + call LoadAffAndDic(g:test_data_aff5, g:test_data_dic5) + call RunGoodBad("fooa1 fooa\u00E9 bar prebar barbork prebarbork startprebar start end startend startmiddleend nouend", + \ "bad: foo fooa2 prabar probarbirk middle startmiddle middleend endstart startprobar startnouend", + \ ["bar", "barbork", "end", "fooa1", "fooa\u00E9", "nouend", "prebar", "prebarbork", "start"], + \ [ + \ ["bad", ["bar", "end", "fooa1"]], + \ ["foo", ["fooa1", "bar", "end"]], + \ ["fooa2", ["fooa1", "fooa\u00E9", "bar"]], + \ ["prabar", ["prebar", "bar", "bar bar"]], + \ ["probarbirk", ["prebarbork"]], + \ ["middle", []], + \ ["startmiddle", ["startmiddleend", "startmiddlebar"]], + \ ["middleend", []], + \ ["endstart", ["end start", "start"]], + \ ["startprobar", ["startprebar", "start prebar", "startbar"]], + \ ["startnouend", ["start nouend", "startend"]], + \ ]) + + call LoadAffAndDic(g:test_data_aff6, g:test_data_dic6) + call RunGoodBad("meea1 meea\u00E9 bar prebar barbork prebarbork leadprebar lead end leadend leadmiddleend", + \ "bad: mee meea2 prabar probarbirk middle leadmiddle middleend endlead leadprobar", + \ ["bar", "barbork", "end", "lead", "meea1", "meea\u00E9", "prebar", "prebarbork"], + \ [ + \ ["bad", ["bar", "end", "lead"]], + \ ["mee", ["meea1", "bar", "end"]], + \ ["meea2", ["meea1", "meea\u00E9", "lead"]], + \ ["prabar", ["prebar", "bar", "leadbar"]], + \ ["probarbirk", ["prebarbork"]], + \ ["middle", []], + \ ["leadmiddle", ["leadmiddleend", "leadmiddlebar"]], + \ ["middleend", []], + \ ["endlead", ["end lead", "lead", "end end"]], + \ ["leadprobar", ["leadprebar", "lead prebar", "leadbar"]], + \ ]) + + call LoadAffAndDic(g:test_data_aff7, g:test_data_dic7) + call RunGoodBad("meea1 meezero meea\u00E9 bar prebar barmeat prebarmeat leadprebar lead tail leadtail leadmiddletail", + \ "bad: mee meea2 prabar probarmaat middle leadmiddle middletail taillead leadprobar", + \ ["bar", "barmeat", "lead", "meea1", "meea\u00E9", "meezero", "prebar", "prebarmeat", "tail"], + \ [ + \ ["bad", ["bar", "lead", "tail"]], + \ ["mee", ["meea1", "bar", "lead"]], + \ ["meea2", ["meea1", "meea\u00E9", "lead"]], + \ ["prabar", ["prebar", "bar", "leadbar"]], + \ ["probarmaat", ["prebarmeat"]], + \ ["middle", []], + \ ["leadmiddle", ["leadmiddlebar"]], + \ ["middletail", []], + \ ["taillead", ["tail lead", "tail"]], + \ ["leadprobar", ["leadprebar", "lead prebar", "leadbar"]], + \ ]) +endfunc + +func Test_spell_NOSLITSUGS() + call LoadAffAndDic(g:test_data_aff8, g:test_data_dic8) + call RunGoodBad("foo bar faabar", "bad: foobar barfoo", + \ ["bar", "faabar", "foo"], + \ [ + \ ["bad", ["bar", "foo"]], + \ ["foobar", ["faabar", "foo bar", "bar"]], + \ ["barfoo", ["bar foo", "bar", "foo"]], + \ ]) +endfunc + +" Numbers +func Test_spell_Numbers() + call LoadAffAndDic(g:test_data_aff9, g:test_data_dic9) + call RunGoodBad("0b1011 0777 1234 0x01ff", "", + \ ["bar", "foo"], + \ [ + \ ]) +endfunc + +" Affix flags +func Test_spell_affix_flags() + call LoadAffAndDic(g:test_data_aff10, g:test_data_dic10) + call RunGoodBad("drink drinkable drinkables drinktable drinkabletable", + \ "bad: drinks drinkstable drinkablestable", + \ ["drink", "drinkable", "drinkables", "table"], + \ [['bad', []], + \ ['drinks', ['drink']], + \ ['drinkstable', ['drinktable', 'drinkable', 'drink table']], + \ ['drinkablestable', ['drinkabletable', 'drinkables table', 'drinkable table']], + \ ]) +endfunc + +function FirstSpellWord() + call feedkeys("/^start:\n", 'tx') + normal ]smm + let [str, a] = spellbadword() + return str +endfunc + +function SecondSpellWord() + normal `m]s + let [str, a] = spellbadword() + return str +endfunc + +" Test with SAL instead of SOFO items; test automatic reloading +func Test_spell_sal_and_addition() + set spellfile= + call writefile(g:test_data_dic1, "Xtest.dic") + call writefile(g:test_data_aff_sal, "Xtest.aff") + mkspell! Xtest Xtest + set spl=Xtest.utf-8.spl spell + call assert_equal('kbltykk', soundfold('goobledygoook')) + call assert_equal('kprnfn', soundfold('kóopërÿnôven')) + call assert_equal('*fls kswts tl', soundfold('oeverloos gezwets edale')) + + "also use an addition file + call writefile(["/regions=usgbnz", "elequint/2", "elekwint/3"], "Xtest.utf-8.add") + mkspell! Xtest.utf-8.add.spl Xtest.utf-8.add + + bwipe! + call setline(1, ["start: elequint test elekwint test elekwent asdf"]) + + set spellfile=Xtest.utf-8.add + call assert_equal("elekwent", FirstSpellWord()) + + set spl=Xtest_us.utf-8.spl + call assert_equal("elequint", FirstSpellWord()) + call assert_equal("elekwint", SecondSpellWord()) + + set spl=Xtest_gb.utf-8.spl + call assert_equal("elekwint", FirstSpellWord()) + call assert_equal("elekwent", SecondSpellWord()) + + set spl=Xtest_nz.utf-8.spl + call assert_equal("elequint", FirstSpellWord()) + call assert_equal("elekwent", SecondSpellWord()) + + set spl=Xtest_ca.utf-8.spl + call assert_equal("elequint", FirstSpellWord()) + call assert_equal("elekwint", SecondSpellWord()) + + bwipe! + set spellfile= + set spl& +endfunc + +func Test_spellfile_value() + set spellfile=Xdir/Xtest.utf-8.add + set spellfile=Xdir/Xtest.utf-8.add,Xtest_other.add + set spellfile= +endfunc + +func Test_no_crash_with_weird_text() + new + let lines =<< trim END + r<sfile> + + + + + END + call setline(1, lines) + try + exe "%norm \<C-v>ez=>\<C-v>wzG" + catch /E1280:/ + let caught = 'yes' + endtry + call assert_equal('yes', caught) + + bwipe! +endfunc + +" Invalid bytes may cause trouble when creating the word list. +func Test_check_for_valid_word() + call assert_fails("spellgood! 0\xac", 'E1280:') +endfunc + +" This was going over the end of the word +func Test_word_index() + new + norm R0 + spellgood! fl0 + sil norm z= + + bwipe! + call delete('Xtmpfile') +endfunc + +func Test_check_empty_line() + " This was using freed memory + enew + spellgood! fl + norm z= + norm yy + sil! norm P]svc + norm P]s + + bwipe! +endfunc + +func Test_spell_suggest_too_long() + " this was creating a word longer than MAXWLEN + new + call setline(1, 'a' .. repeat("\u0333", 150)) + norm! z= + bwipe! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_spellfile.vim b/test/old/testdir/test_spellfile.vim new file mode 100644 index 0000000000..4d2a6cf35f --- /dev/null +++ b/test/old/testdir/test_spellfile.vim @@ -0,0 +1,1086 @@ +" Test for commands that operate on the spellfile. + +source shared.vim +source check.vim + +CheckFeature spell +CheckFeature syntax + +func Test_spell_normal() + new + call append(0, ['1 good', '2 goood', '3 goood']) + set spell spellfile=./Xspellfile.add spelllang=en + let oldlang=v:lang + lang C + + " Test for zg + 1 + norm! ]s + call assert_equal('2 goood', getline('.')) + norm! zg + 1 + let a=execute('unsilent :norm! ]s') + call assert_equal('1 good', getline('.')) + call assert_equal('search hit BOTTOM, continuing at TOP', a[1:]) + let cnt=readfile('./Xspellfile.add') + call assert_equal('goood', cnt[0]) + + " zg should fail in operator-pending mode + call assert_beeps('norm! czg') + + " zg fails in visual mode when not able to get the visual text + call assert_beeps('norm! ggVjzg') + norm! V + + " zg fails for a non-identifier word + call append(line('$'), '###') + call assert_fails('norm! Gzg', 'E349:') + $d + + " Test for zw + 2 + norm! $zw + 1 + norm! ]s + call assert_equal('2 goood', getline('.')) + let cnt=readfile('./Xspellfile.add') + call assert_equal('#oood', cnt[0]) + call assert_equal('goood/!', cnt[1]) + + " Test for :spellrare + spellrare rare + let cnt=readfile('./Xspellfile.add') + call assert_equal(['#oood', 'goood/!', 'rare/?'], cnt) + + " Make sure :spellundo works for rare words. + spellundo rare + let cnt=readfile('./Xspellfile.add') + call assert_equal(['#oood', 'goood/!', '#are/?'], cnt) + + " Test for zg in visual mode + let a=execute('unsilent :norm! V$zg') + call assert_equal("Word '2 goood' added to ./Xspellfile.add", a[1:]) + 1 + norm! ]s + call assert_equal('3 goood', getline('.')) + let cnt=readfile('./Xspellfile.add') + call assert_equal('2 goood', cnt[3]) + " Remove "2 good" from spellfile + 2 + let a=execute('unsilent norm! V$zw') + call assert_equal("Word '2 goood' added to ./Xspellfile.add", a[1:]) + let cnt=readfile('./Xspellfile.add') + call assert_equal('2 goood/!', cnt[4]) + + " Test for zG + let a=execute('unsilent norm! V$zG') + call assert_match("Word '2 goood' added to .*", a) + let fname=matchstr(a, 'to\s\+\zs\f\+$') + let cnt=readfile(fname) + call assert_equal('2 goood', cnt[0]) + + " Test for zW + let a=execute('unsilent norm! V$zW') + call assert_match("Word '2 goood' added to .*", a) + let cnt=readfile(fname) + call assert_equal('# goood', cnt[0]) + call assert_equal('2 goood/!', cnt[1]) + + " Test for zuW + let a=execute('unsilent norm! V$zuW') + call assert_match("Word '2 goood' removed from .*", a) + let cnt=readfile(fname) + call assert_equal('# goood', cnt[0]) + call assert_equal('# goood/!', cnt[1]) + + " Test for zuG + let a=execute('unsilent norm! $zG') + call assert_match("Word 'goood' added to .*", a) + let cnt=readfile(fname) + call assert_equal('# goood', cnt[0]) + call assert_equal('# goood/!', cnt[1]) + call assert_equal('goood', cnt[2]) + let a=execute('unsilent norm! $zuG') + let cnt=readfile(fname) + call assert_match("Word 'goood' removed from .*", a) + call assert_equal('# goood', cnt[0]) + call assert_equal('# goood/!', cnt[1]) + call assert_equal('#oood', cnt[2]) + " word not found in wordlist + let a=execute('unsilent norm! V$zuG') + let cnt=readfile(fname) + call assert_match("", a) + call assert_equal('# goood', cnt[0]) + call assert_equal('# goood/!', cnt[1]) + call assert_equal('#oood', cnt[2]) + + " Test for zug + call delete('./Xspellfile.add') + 2 + let a=execute('unsilent norm! $zg') + let cnt=readfile('./Xspellfile.add') + call assert_equal('goood', cnt[0]) + let a=execute('unsilent norm! $zug') + call assert_match("Word 'goood' removed from \./Xspellfile.add", a) + let cnt=readfile('./Xspellfile.add') + call assert_equal('#oood', cnt[0]) + " word not in wordlist + let a=execute('unsilent norm! V$zug') + call assert_match('', a) + let cnt=readfile('./Xspellfile.add') + call assert_equal('#oood', cnt[0]) + + " Test for zuw + call delete('./Xspellfile.add') + 2 + let a=execute('unsilent norm! Vzw') + let cnt=readfile('./Xspellfile.add') + call assert_equal('2 goood/!', cnt[0]) + let a=execute('unsilent norm! Vzuw') + call assert_match("Word '2 goood' removed from \./Xspellfile.add", a) + let cnt=readfile('./Xspellfile.add') + call assert_equal('# goood/!', cnt[0]) + " word not in wordlist + let a=execute('unsilent norm! $zug') + call assert_match('', a) + let cnt=readfile('./Xspellfile.add') + call assert_equal('# goood/!', cnt[0]) + + " add second entry to spellfile setting + set spellfile=./Xspellfile.add,./Xspellfile2.add + call delete('./Xspellfile.add') + 2 + let a=execute('unsilent norm! $2zg') + let cnt=readfile('./Xspellfile2.add') + call assert_match("Word 'goood' added to ./Xspellfile2.add", a) + call assert_equal('goood', cnt[0]) + + " Test for :spellgood! + let temp = execute(':spe!0/0') + call assert_match('Invalid region', temp) + let spellfile = matchstr(temp, 'Invalid region nr in \zs.*\ze line \d: 0') + call assert_equal(['# goood', '# goood/!', '#oood', '0/0'], readfile(spellfile)) + + " Test for :spellrare! + :spellrare! raare + call assert_equal(['# goood', '# goood/!', '#oood', '0/0', 'raare/?'], readfile(spellfile)) + call delete(spellfile) + + " clean up + exe "lang" oldlang + call delete("./Xspellfile.add") + call delete("./Xspellfile2.add") + call delete("./Xspellfile.add.spl") + call delete("./Xspellfile2.add.spl") + + " zux -> no-op + 2 + norm! $zux + call assert_equal([], glob('Xspellfile.add',0,1)) + call assert_equal([], glob('Xspellfile2.add',0,1)) + + set spellfile= spell& spelllang& + bw! +endfunc + +" Spell file content test. Write 'content' to the spell file prefixed by the +" spell file header and then enable spell checking. If 'emsg' is not empty, +" then check for error. +func Spellfile_Test(content, emsg) + let splfile = './Xtest/spell/Xtest.utf-8.spl' + " Add the spell file header and version (VIMspell2) + let v = 0z56494D7370656C6C32 + a:content + call writefile(v, splfile, 'b') + set runtimepath=./Xtest + set spelllang=Xtest + if a:emsg != '' + call assert_fails('set spell', a:emsg) + else + " FIXME: With some invalid spellfile contents, there are no error + " messages. So don't know how to check for the test result. + set spell + endif + set nospell spelllang& rtp& +endfunc + +" Test for spell file format errors. +" The spell file format is described in spellfile.c +func Test_spellfile_format_error() + let save_rtp = &rtp + call mkdir('Xtest/spell', 'p') + let splfile = './Xtest/spell/Xtest.utf-8.spl' + + " empty spell file + call writefile([], splfile) + set runtimepath=./Xtest + set spelllang=Xtest + call assert_fails('set spell', 'E757:') + set nospell spelllang& + + " invalid file ID + call writefile(0z56494D, splfile, 'b') + set runtimepath=./Xtest + set spelllang=Xtest + call assert_fails('set spell', 'E757:') + set nospell spelllang& + + " missing version number + call writefile(0z56494D7370656C6C, splfile, 'b') + set runtimepath=./Xtest + set spelllang=Xtest + call assert_fails('set spell', 'E771:') + set nospell spelllang& + + " invalid version number + call writefile(0z56494D7370656C6C7A, splfile, 'b') + set runtimepath=./Xtest + set spelllang=Xtest + call assert_fails('set spell', 'E772:') + set nospell spelllang& + + " no sections + call Spellfile_Test(0z, 'E758:') + + " missing section length + call Spellfile_Test(0z00, 'E758:') + + " unsupported required section + call Spellfile_Test(0z7A0100000004, 'E770:') + + " unsupported not-required section + call Spellfile_Test(0z7A0000000004, 'E758:') + + " SN_REGION: invalid number of region names + call Spellfile_Test(0z0000000000FF, 'E759:') + + " SN_CHARFLAGS: missing <charflagslen> length + call Spellfile_Test(0z010000000004, 'E758:') + + " SN_CHARFLAGS: invalid <charflagslen> length + call Spellfile_Test(0z0100000000010201, '') + + " SN_CHARFLAGS: charflagslen == 0 and folcharslen != 0 + call Spellfile_Test(0z01000000000400000101, 'E759:') + + " SN_CHARFLAGS: missing <folcharslen> length + call Spellfile_Test(0z01000000000100, 'E758:') + + " SN_PREFCOND: invalid prefcondcnt + call Spellfile_Test(0z03000000000100, 'E759:') + + " SN_PREFCOND: invalid condlen + call Spellfile_Test(0z0300000000020001, 'E759:') + + " SN_REP: invalid repcount + call Spellfile_Test(0z04000000000100, 'E758:') + + " SN_REP: missing rep + call Spellfile_Test(0z0400000000020004, 'E758:') + + " SN_REP: zero repfromlen + call Spellfile_Test(0z040000000003000100, 'E759:') + + " SN_REP: invalid reptolen + call Spellfile_Test(0z0400000000050001014101, '') + + " SN_REP: zero reptolen + call Spellfile_Test(0z0400000000050001014100, 'E759:') + + " SN_SAL: missing salcount + call Spellfile_Test(0z05000000000102, 'E758:') + + " SN_SAL: missing salfromlen + call Spellfile_Test(0z050000000003080001, 'E758:') + + " SN_SAL: missing saltolen + call Spellfile_Test(0z0500000000050400010161, 'E758:') + + " SN_WORDS: non-NUL terminated word + call Spellfile_Test(0z0D000000000376696D, 'E758:') + + " SN_WORDS: very long word + let v = eval('0z0D000000012C' .. repeat('41', 300)) + call Spellfile_Test(v, 'E759:') + + " SN_SOFO: missing sofofromlen + call Spellfile_Test(0z06000000000100, 'E758:') + + " SN_SOFO: missing sofotolen + call Spellfile_Test(0z06000000000400016100, 'E758:') + + " SN_SOFO: missing sofoto + call Spellfile_Test(0z0600000000050001610000, 'E759:') + + " SN_COMPOUND: compmax is less than 2 + call Spellfile_Test(0z08000000000101, 'E759:') + + " SN_COMPOUND: missing compsylmax and other options + call Spellfile_Test(0z0800000000020401, 'E759:') + + " SN_COMPOUND: missing compoptions + call Spellfile_Test(0z080000000005040101, 'E758:') + + " SN_INFO: missing info + call Spellfile_Test(0z0F0000000005040101, '') + + " SN_MIDWORD: missing midword + call Spellfile_Test(0z0200000000040102, '') + + " SN_MAP: missing midword + call Spellfile_Test(0z0700000000040102, '') + + " SN_SYLLABLE: missing SYLLABLE item + call Spellfile_Test(0z0900000000040102, '') + + " SN_SYLLABLE: More than SY_MAXLEN size + let v = eval('0z090000000022612F' .. repeat('62', 32)) + call Spellfile_Test(v, '') + + " LWORDTREE: missing + call Spellfile_Test(0zFF, 'E758:') + + " LWORDTREE: missing tree node + call Spellfile_Test(0zFF00000004, 'E758:') + + " LWORDTREE: missing tree node value + call Spellfile_Test(0zFF0000000402, 'E758:') + + " KWORDTREE: missing tree node + call Spellfile_Test(0zFF0000000000000004, 'E758:') + + " PREFIXTREE: missing tree node + call Spellfile_Test(0zFF000000000000000000000004, 'E758:') + + let &rtp = save_rtp + call delete('Xtest', 'rf') +endfunc + +" Test for format errors in suggest file +func Test_sugfile_format_error() + let save_rtp = &rtp + call mkdir('Xtest/spell', 'p') + let splfile = './Xtest/spell/Xtest.utf-8.spl' + let sugfile = './Xtest/spell/Xtest.utf-8.sug' + + " create an empty spell file with a suggest timestamp + call writefile(0z56494D7370656C6C320B00000000080000000000000044FF000000000000000000000000, splfile, 'b') + + " 'encoding' is set before each test to clear the previously loaded suggest + " file from memory. + + " empty suggest file + set encoding=utf-8 + call writefile([], sugfile) + set runtimepath=./Xtest + set spelllang=Xtest + set spell + call assert_fails("let s = spellsuggest('abc')", 'E778:') + set nospell spelllang& + + " zero suggest version + set encoding=utf-8 + call writefile(0z56494D73756700, sugfile) + set runtimepath=./Xtest + set spelllang=Xtest + set spell + call assert_fails("let s = spellsuggest('abc')", 'E779:') + set nospell spelllang& + + " unsupported suggest version + set encoding=utf-8 + call writefile(0z56494D7375671F, sugfile) + set runtimepath=./Xtest + set spelllang=Xtest + set spell + call assert_fails("let s = spellsuggest('abc')", 'E780:') + set nospell spelllang& + + " missing suggest timestamp + set encoding=utf-8 + call writefile(0z56494D73756701, sugfile) + set runtimepath=./Xtest + set spelllang=Xtest + set spell + call assert_fails("let s = spellsuggest('abc')", 'E781:') + set nospell spelllang& + + " incorrect suggest timestamp + set encoding=utf-8 + call writefile(0z56494D7375670100000000000000FF, sugfile) + set runtimepath=./Xtest + set spelllang=Xtest + set spell + call assert_fails("let s = spellsuggest('abc')", 'E781:') + set nospell spelllang& + + " missing suggest wordtree + set encoding=utf-8 + call writefile(0z56494D737567010000000000000044, sugfile) + set runtimepath=./Xtest + set spelllang=Xtest + set spell + call assert_fails("let s = spellsuggest('abc')", 'E782:') + set nospell spelllang& + + " invalid suggest word count in SUGTABLE + set encoding=utf-8 + call writefile(0z56494D7375670100000000000000440000000022, sugfile) + set runtimepath=./Xtest + set spelllang=Xtest + set spell + call assert_fails("let s = spellsuggest('abc')", 'E782:') + set nospell spelllang& + + " missing sugline in SUGTABLE + set encoding=utf-8 + call writefile(0z56494D7375670100000000000000440000000000000005, sugfile) + set runtimepath=./Xtest + set spelllang=Xtest + set spell + call assert_fails("let s = spellsuggest('abc')", 'E782:') + set nospell spelllang& + + let &rtp = save_rtp + call delete('Xtest', 'rf') +endfunc + +" Test for using :mkspell to create a spell file from a list of words +func Test_wordlist_dic() + " duplicate encoding + let lines =<< trim [END] + # This is an example word list + + /encoding=latin1 + /encoding=latin1 + example + [END] + call writefile(lines, 'Xwordlist.dic') + let output = execute('mkspell Xwordlist.spl Xwordlist.dic') + call assert_match('Duplicate /encoding= line ignored in Xwordlist.dic line 4: /encoding=latin1', output) + + " multiple encoding for a word + let lines =<< trim [END] + example + /encoding=latin1 + example + [END] + call writefile(lines, 'Xwordlist.dic') + let output = execute('mkspell! Xwordlist.spl Xwordlist.dic') + call assert_match('/encoding= line after word ignored in Xwordlist.dic line 2: /encoding=latin1', output) + + " unsupported encoding for a word + let lines =<< trim [END] + /encoding=Xtest + example + [END] + call writefile(lines, 'Xwordlist.dic') + let output = execute('mkspell! Xwordlist.spl Xwordlist.dic') + call assert_match('Conversion in Xwordlist.dic not supported: from Xtest to utf-8', output) + + " duplicate region + let lines =<< trim [END] + /regions=usca + /regions=usca + example + [END] + call writefile(lines, 'Xwordlist.dic') + let output = execute('mkspell! Xwordlist.spl Xwordlist.dic') + call assert_match('Duplicate /regions= line ignored in Xwordlist.dic line 2: regions=usca', output) + + " maximum regions + let lines =<< trim [END] + /regions=uscauscauscauscausca + example + [END] + call writefile(lines, 'Xwordlist.dic') + let output = execute('mkspell! Xwordlist.spl Xwordlist.dic') + call assert_match('Too many regions in Xwordlist.dic line 1: uscauscauscauscausca', output) + + " unsupported '/' value + let lines =<< trim [END] + /test=abc + example + [END] + call writefile(lines, 'Xwordlist.dic') + let output = execute('mkspell! Xwordlist.spl Xwordlist.dic') + call assert_match('/ line ignored in Xwordlist.dic line 1: /test=abc', output) + + " unsupported flag + let lines =<< trim [END] + example/+ + [END] + call writefile(lines, 'Xwordlist.dic') + let output = execute('mkspell! Xwordlist.spl Xwordlist.dic') + call assert_match('Unrecognized flags in Xwordlist.dic line 1: +', output) + + " non-ascii word + call writefile(["ʀʀ"], 'Xwordlist.dic') + let output = execute('mkspell! -ascii Xwordlist.spl Xwordlist.dic') + call assert_match('Ignored 1 words with non-ASCII characters', output) + + call delete('Xwordlist.spl') + call delete('Xwordlist.dic') +endfunc + +" Test for the :mkspell command +func Test_mkspell() + call assert_fails('mkspell Xtest_us.spl', 'E751:') + call assert_fails('mkspell a b c d e f g h i j k', 'E754:') + + call writefile([], 'Xtest.spl') + call writefile([], 'Xtest.dic') + call assert_fails('mkspell Xtest.spl Xtest.dic', 'E13:') + call delete('Xtest.spl') + call delete('Xtest.dic') + + call mkdir('Xtest.spl') + call assert_fails('mkspell! Xtest.spl Xtest.dic', 'E17:') + call delete('Xtest.spl', 'rf') + + " can't write the .spl file as its directory does not exist + call writefile([], 'Xtest.aff') + call writefile([], 'Xtest.dic') + call assert_fails('mkspell DOES_NOT_EXIT/Xtest.spl Xtest.dic', 'E484:') + call delete('Xtest.aff') + call delete('Xtest.dic') + + call assert_fails('mkspell en en_US abc_xyz', 'E755:') +endfunc + +" Tests for :mkspell with a .dic and .aff file +func Test_aff_file_format_error() + " FIXME: For some reason, the :mkspell command below doesn't fail on the + " MS-Windows CI build. Disable this test on MS-Windows for now. + CheckNotMSWindows + + " No word count in .dic file + call writefile([], 'Xtest.dic') + call writefile([], 'Xtest.aff') + call assert_fails('mkspell! Xtest.spl Xtest', 'E760:') + + " create a .dic file for the tests below + call writefile(['1', 'work'], 'Xtest.dic') + + " Invalid encoding in .aff file + call writefile(['# comment', 'SET Xinvalidencoding'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Conversion in Xtest.aff not supported: from xinvalidencoding', output) + + " Invalid flag in .aff file + call writefile(['FLAG xxx'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Invalid value for FLAG in Xtest.aff line 1: xxx', output) + + " set FLAGS after using flag for an affix + call writefile(['SFX L Y 1', 'SFX L 0 re [^x]', 'FLAG long'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('FLAG after using flags in Xtest.aff line 3: long', output) + + " INFO in affix file + let save_encoding = &encoding + call mkdir('Xrtp/spell', 'p') + call writefile(['1', 'work'], 'Xrtp/spell/Xtest.dic') + call writefile(['NAME klingon', 'VERSION 1.4', 'AUTHOR Spock'], + \ 'Xrtp/spell/Xtest.aff') + silent mkspell! Xrtp/spell/Xtest.utf-8.spl Xrtp/spell/Xtest + let save_rtp = &rtp + set runtimepath=./Xrtp + set spelllang=Xtest + set spell + let output = split(execute('spellinfo'), "\n") + call assert_equal("NAME klingon", output[1]) + call assert_equal("VERSION 1.4", output[2]) + call assert_equal("AUTHOR Spock", output[3]) + let &rtp = save_rtp + call delete('Xrtp', 'rf') + set spell& spelllang& spellfile& + %bw! + " 'encoding' must be set again to clear the spell file in memory + let &encoding = save_encoding + + " COMPOUNDFORBIDFLAG flag after PFX in an affix file + call writefile(['PFX L Y 1', 'PFX L 0 re x', 'COMPOUNDFLAG c', 'COMPOUNDFORBIDFLAG x'], + \ 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Defining COMPOUNDFORBIDFLAG after PFX item may give wrong results in Xtest.aff line 4', output) + + " COMPOUNDPERMITFLAG flag after PFX in an affix file + call writefile(['PFX L Y 1', 'PFX L 0 re x', 'COMPOUNDPERMITFLAG c'], + \ 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Defining COMPOUNDPERMITFLAG after PFX item may give wrong results in Xtest.aff line 3', output) + + " Wrong COMPOUNDRULES flag value in an affix file + call writefile(['COMPOUNDRULES a'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Wrong COMPOUNDRULES value in Xtest.aff line 1: a', output) + + " Wrong COMPOUNDWORDMAX flag value in an affix file + call writefile(['COMPOUNDWORDMAX 0'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Wrong COMPOUNDWORDMAX value in Xtest.aff line 1: 0', output) + + " Wrong COMPOUNDMIN flag value in an affix file + call writefile(['COMPOUNDMIN 0'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Wrong COMPOUNDMIN value in Xtest.aff line 1: 0', output) + + " Wrong COMPOUNDSYLMAX flag value in an affix file + call writefile(['COMPOUNDSYLMAX 0'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Wrong COMPOUNDSYLMAX value in Xtest.aff line 1: 0', output) + + " Wrong CHECKCOMPOUNDPATTERN flag value in an affix file + call writefile(['CHECKCOMPOUNDPATTERN 0'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Wrong CHECKCOMPOUNDPATTERN value in Xtest.aff line 1: 0', output) + + " Both compounding and NOBREAK specified + call writefile(['COMPOUNDFLAG c', 'NOBREAK'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Warning: both compounding and NOBREAK specified', output) + + " Duplicate affix entry in an affix file + call writefile(['PFX L Y 1', 'PFX L 0 re x', 'PFX L Y 1', 'PFX L 0 re x'], + \ 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Duplicate affix in Xtest.aff line 3: L', output) + + " Duplicate affix entry in an affix file + call writefile(['PFX L Y 1', 'PFX L Y 1'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Unrecognized or duplicate item in Xtest.aff line 2: PFX', output) + + " Different combining flags in an affix file + call writefile(['PFX L Y 1', 'PFX L 0 re x', 'PFX L N 1'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Different combining flag in continued affix block in Xtest.aff line 3', output) + + " Try to reuse a affix used for BAD flag + call writefile(['BAD x', 'PFX x Y 1', 'PFX x 0 re x'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Affix also used for BAD/RARE/KEEPCASE/NEEDAFFIX/NEEDCOMPOUND/NOSUGGEST in Xtest.aff line 2: x', output) + + " Trailing characters in an affix entry + call writefile(['PFX L Y 1 Test', 'PFX L 0 re x'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Trailing text in Xtest.aff line 1: Test', output) + + " Trailing characters in an affix entry + call writefile(['PFX L Y 1', 'PFX L 0 re x Test'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Trailing text in Xtest.aff line 2: Test', output) + + " Incorrect combine flag in an affix entry + call writefile(['PFX L X 1', 'PFX L 0 re x'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Expected Y or N in Xtest.aff line 1: X', output) + + " Invalid count for REP item + call writefile(['REP a'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Expected REP(SAL) count in Xtest.aff line 1', output) + + " Trailing characters in REP item + call writefile(['REP 1', 'REP f ph test'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Trailing text in Xtest.aff line 2: test', output) + + " Invalid count for MAP item + call writefile(['MAP a'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Expected MAP count in Xtest.aff line 1', output) + + " Duplicate character in a MAP item + call writefile(['MAP 2', 'MAP xx', 'MAP yy'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Duplicate character in MAP in Xtest.aff line 2', output) + + " Use COMPOUNDSYLMAX without SYLLABLE + call writefile(['COMPOUNDSYLMAX 2'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('COMPOUNDSYLMAX used without SYLLABLE', output) + + " Missing SOFOTO + call writefile(['SOFOFROM abcdef'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Missing SOFOTO line in Xtest.aff', output) + + " Length of SOFOFROM and SOFOTO differ + call writefile(['SOFOFROM abcde', 'SOFOTO ABCD'], 'Xtest.aff') + call assert_fails('mkspell! Xtest.spl Xtest', 'E759:') + + " Both SAL and SOFOFROM/SOFOTO items + call writefile(['SOFOFROM abcd', 'SOFOTO ABCD', 'SAL CIA X'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Both SAL and SOFO lines in Xtest.aff', output) + + " use an alphabet flag when FLAG is num + call writefile(['FLAG num', 'SFX L Y 1', 'SFX L 0 re [^x]'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Flag is not a number in Xtest.aff line 2: L', output) + + " use number and alphabet flag when FLAG is num + call writefile(['FLAG num', 'SFX 4f Y 1', 'SFX 4f 0 re [^x]'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Affix name too long in Xtest.aff line 2: 4f', output) + + " use a single character flag when FLAG is long + call writefile(['FLAG long', 'SFX L Y 1', 'SFX L 0 re [^x]'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('Illegal flag in Xtest.aff line 2: L', output) + + " duplicate word in the .dic file + call writefile(['2', 'good', 'good', 'good'], 'Xtest.dic') + call writefile(['NAME vim'], 'Xtest.aff') + let output = execute('mkspell! Xtest.spl Xtest') + call assert_match('First duplicate word in Xtest.dic line 3: good', output) + call assert_match('2 duplicate word(s) in Xtest.dic', output) + + call delete('Xtest.dic') + call delete('Xtest.aff') + call delete('Xtest.spl') + call delete('Xtest.sug') +endfunc + +func Test_spell_add_word() + set spellfile= + call assert_fails('spellgood abc', 'E764:') + + set spellfile=Xtest.utf-8.add + call assert_fails('2spellgood abc', 'E765:') + + edit Xtest.utf-8.add + call setline(1, 'sample') + call assert_fails('spellgood abc', 'E139:') + set spellfile& + %bw! +endfunc + +func Test_spellfile_verbose() + call writefile(['1', 'one'], 'XtestVerbose.dic') + call writefile([], 'XtestVerbose.aff') + mkspell! XtestVerbose-utf8.spl XtestVerbose + set spell + + " First time: the spl file should be read. + let a = execute('3verbose set spelllang=XtestVerbose-utf8.spl') + call assert_match('Reading spell file "XtestVerbose-utf8.spl"', a) + + " Second time time: the spl file should not be read (already read). + let a = execute('3verbose set spelllang=XtestVerbose-utf8.spl') + call assert_notmatch('Reading spell file "XtestVerbose-utf8.spl"', a) + + set spell& spelllang& + call delete('XtestVerbose.dic') + call delete('XtestVerbose.aff') + call delete('XtestVerbose-utf8.spl') +endfunc + +" Test NOBREAK (see :help spell-NOBREAK) +func Test_NOBREAK() + call writefile(['3', 'one', 'two', 'three' ], 'XtestNOBREAK.dic') + call writefile(['NOBREAK' ], 'XtestNOBREAK.aff') + + mkspell! XtestNOBREAK-utf8.spl XtestNOBREAK + set spell spelllang=XtestNOBREAK-utf8.spl + + call assert_equal(['', ''], spellbadword('One two three onetwo onetwothree threetwoone')) + + call assert_equal(['x', 'bad'], spellbadword('x')) + call assert_equal(['y', 'bad'], spellbadword('yone')) + call assert_equal(['z', 'bad'], spellbadword('onez')) + call assert_equal(['zero', 'bad'], spellbadword('Onetwozerothree')) + + new + call setline(1, 'Onetwwothree') + norm! fw1z= + call assert_equal('Onetwothree', getline(1)) + call setline(1, 'Onetwothre') + norm! fh1z= + call assert_equal('Onetwothree', getline(1)) + + bw! + set spell& spelllang& + call delete('XtestNOBREAK.dic') + call delete('XtestNOBREAK.aff') + call delete('XtestNOBREAK-utf8.spl') +endfunc + +" Test CHECKCOMPOUNDPATTERN (see :help spell-CHECKCOMPOUNDPATTERN) +func Test_spellfile_CHECKCOMPOUNDPATTERN() + call writefile(['4', + \ 'one/c', + \ 'two/c', + \ 'three/c', + \ 'four'], 'XtestCHECKCOMPOUNDPATTERN.dic') + " Forbid compound words where first word ends with 'wo' and second starts with 'on'. + call writefile(['CHECKCOMPOUNDPATTERN 1', + \ 'CHECKCOMPOUNDPATTERN wo on', + \ 'COMPOUNDFLAG c'], 'XtestCHECKCOMPOUNDPATTERN.aff') + + mkspell! XtestCHECKCOMPOUNDPATTERN-utf8.spl XtestCHECKCOMPOUNDPATTERN + set spell spelllang=XtestCHECKCOMPOUNDPATTERN-utf8.spl + + " Check valid words with and without valid compounds. + for goodword in ['one', 'two', 'three', 'four', + \ 'oneone', 'onetwo', 'onethree', + \ 'twotwo', 'twothree', + \ 'threeone', 'threetwo', 'threethree', + \ 'onetwothree', 'onethreetwo', 'twothreeone', 'oneoneone'] + call assert_equal(['', ''], spellbadword(goodword), goodword) + endfor + + " Compounds 'twoone' or 'threetwoone' should be forbidden by CHECKCOMPOUNPATTERN. + " 'four' does not have the 'c' flag in *.aff file so no compound. + " 'five' is not in the *.dic file. + for badword in ['five', 'onetwox', + \ 'twoone', 'threetwoone', + \ 'fourone', 'onefour'] + call assert_equal([badword, 'bad'], spellbadword(badword)) + endfor + + set spell& spelllang& + call delete('XtestCHECKCOMPOUNDPATTERN.dic') + call delete('XtestCHECKCOMPOUNDPATTERN.aff') + call delete('XtestCHECKCOMPOUNDPATTERN-utf8.spl') +endfunc + +" Test NOCOMPOUNDSUGS (see :help spell-NOCOMPOUNDSUGS) +func Test_spellfile_NOCOMPOUNDSUGS() + call writefile(['3', + \ 'one/c', + \ 'two/c', + \ 'three/c'], 'XtestNOCOMPOUNDSUGS.dic') + + " pass 0 tests without NOCOMPOUNDSUGS, pass 1 tests with NOCOMPOUNDSUGS + for pass in [0, 1] + if pass == 0 + call writefile(['COMPOUNDFLAG c'], 'XtestNOCOMPOUNDSUGS.aff') + else + call writefile(['NOCOMPOUNDSUGS', + \ 'COMPOUNDFLAG c'], 'XtestNOCOMPOUNDSUGS.aff') + endif + + mkspell! XtestNOCOMPOUNDSUGS-utf8.spl XtestNOCOMPOUNDSUGS + set spell spelllang=XtestNOCOMPOUNDSUGS-utf8.spl + + for goodword in ['one', 'two', 'three', + \ 'oneone', 'onetwo', 'onethree', + \ 'twoone', 'twotwo', 'twothree', + \ 'threeone', 'threetwo', 'threethree', + \ 'onetwothree', 'onethreetwo', 'twothreeone', 'oneoneone'] + call assert_equal(['', ''], spellbadword(goodword), goodword) + endfor + + for badword in ['four', 'onetwox', 'onexone'] + call assert_equal([badword, 'bad'], spellbadword(badword)) + endfor + + if pass == 0 + call assert_equal(['one', 'oneone'], spellsuggest('onne', 2)) + call assert_equal(['onethree', 'one three'], spellsuggest('onethre', 2)) + else + call assert_equal(['one', 'one one'], spellsuggest('onne', 2)) + call assert_equal(['one three'], spellsuggest('onethre', 2)) + endif + endfor + + set spell& spelllang& + call delete('XtestNOCOMPOUNDSUGS.dic') + call delete('XtestNOCOMPOUNDSUGS.aff') + call delete('XtestNOCOMPOUNDSUGS-utf8.spl') +endfunc + +" Test COMMON (better suggestions with common words, see :help spell-COMMON) +func Test_spellfile_COMMON() + call writefile(['7', + \ 'and', + \ 'ant', + \ 'end', + \ 'any', + \ 'tee', + \ 'the', + \ 'ted'], 'XtestCOMMON.dic') + call writefile(['COMMON the and'], 'XtestCOMMON.aff') + + mkspell! XtestCOMMON-utf8.spl XtestCOMMON + set spell spelllang=XtestCOMMON-utf8.spl + + " COMMON words 'and' and 'the' should be the top suggestions. + call assert_equal(['and', 'ant'], spellsuggest('anr', 2)) + call assert_equal(['and', 'end'], spellsuggest('ond', 2)) + call assert_equal(['the', 'ted'], spellsuggest('tha', 2)) + call assert_equal(['the', 'tee'], spellsuggest('dhe', 2)) + + set spell& spelllang& + call delete('XtestCOMMON.dic') + call delete('XtestCOMMON.aff') + call delete('XtestCOMMON-utf8.spl') +endfunc + +" Test NOSUGGEST (see :help spell-COMMON) +func Test_spellfile_NOSUGGEST() + call writefile(['2', 'foo/X', 'fog'], 'XtestNOSUGGEST.dic') + call writefile(['NOSUGGEST X'], 'XtestNOSUGGEST.aff') + + mkspell! XtestNOSUGGEST-utf8.spl XtestNOSUGGEST + set spell spelllang=XtestNOSUGGEST-utf8.spl + + for goodword in ['foo', 'Foo', 'FOO', 'fog', 'Fog', 'FOG'] + call assert_equal(['', ''], spellbadword(goodword), goodword) + endfor + for badword in ['foO', 'fOO', 'fooo', 'foog', 'foofog', 'fogfoo'] + call assert_equal([badword, 'bad'], spellbadword(badword)) + endfor + + call assert_equal(['fog'], spellsuggest('fooo', 1)) + call assert_equal(['fog'], spellsuggest('fOo', 1)) + call assert_equal(['fog'], spellsuggest('foG', 1)) + call assert_equal(['fog'], spellsuggest('fogg', 1)) + + set spell& spelllang& + call delete('XtestNOSUGGEST.dic') + call delete('XtestNOSUGGEST.aff') + call delete('XtestNOSUGGEST-utf8.spl') +endfunc + + +" Test CIRCUMFIX (see: :help spell-CIRCUMFIX) +func Test_spellfile_CIRCUMFIX() + " Example taken verbatim from https://github.com/hunspell/hunspell/tree/master/tests + call writefile(['1', + \ 'nagy/C po:adj'], 'XtestCIRCUMFIX.dic') + call writefile(['# circumfixes: ~ obligate prefix/suffix combinations', + \ '# superlative in Hungarian: leg- (prefix) AND -bb (suffix)', + \ '', + \ 'CIRCUMFIX X', + \ '', + \ 'PFX A Y 1', + \ 'PFX A 0 leg/X .', + \ '', + \ 'PFX B Y 1', + \ 'PFX B 0 legesleg/X .', + \ '', + \ 'SFX C Y 3', + \ 'SFX C 0 obb . is:COMPARATIVE', + \ 'SFX C 0 obb/AX . is:SUPERLATIVE', + \ 'SFX C 0 obb/BX . is:SUPERSUPERLATIVE'], 'XtestCIRCUMFIX.aff') + + mkspell! XtestCIRCUMFIX-utf8.spl XtestCIRCUMFIX + set spell spelllang=XtestCIRCUMFIX-utf8.spl + + " From https://catalog.ldc.upenn.edu/docs/LDC2008T01/acta04.pdf: + " Hungarian English + " --------- ------- + " nagy great + " nagyobb greater + " legnagyobb greatest + " legeslegnagyob most greatest + call assert_equal(['', ''], spellbadword('nagy nagyobb legnagyobb legeslegnagyobb')) + + for badword in ['legnagy', 'legeslegnagy', 'legobb', 'legeslegobb'] + call assert_equal([badword, 'bad'], spellbadword(badword)) + endfor + + set spell& spelllang& + call delete('XtestCIRCUMFIX.dic') + call delete('XtestCIRCUMFIX.aff') + call delete('XtestCIRCUMFIX-utf8.spl') +endfunc + +" Test SFX that strips/chops characters +func Test_spellfile_SFX_strip() + " Simplified conjugation of Italian verbs ending in -are (first conjugation). + call writefile(['SFX A Y 4', + \ 'SFX A are iamo [^icg]are', + \ 'SFX A are hiamo [cg]are', + \ 'SFX A re mo iare', + \ 'SFX A re vamo are'], + \ 'XtestSFX.aff') + " Examples of Italian verbs: + " - cantare = to sing + " - cercare = to search + " - odiare = to hate + call writefile(['3', 'cantare/A', 'cercare/A', 'odiare/A'], 'XtestSFX.dic') + + mkspell! XtestSFX-utf8.spl XtestSFX + set spell spelllang=XtestSFX-utf8.spl + + " To sing, we're singing, we were singing. + call assert_equal(['', ''], spellbadword('cantare cantiamo cantavamo')) + + " To search, we're searching, we were searching. + call assert_equal(['', ''], spellbadword('cercare cerchiamo cercavamo')) + + " To hate, we hate, we were hating. + call assert_equal(['', ''], spellbadword('odiare odiamo odiavamo')) + + for badword in ['canthiamo', 'cerciamo', 'cantarevamo', 'odiiamo'] + call assert_equal([badword, 'bad'], spellbadword(badword)) + endfor + + call assert_equal(['cantiamo'], spellsuggest('canthiamo', 1)) + call assert_equal(['cerchiamo'], spellsuggest('cerciamo', 1)) + call assert_equal(['cantavamo'], spellsuggest('cantarevamo', 1)) + call assert_equal(['odiamo'], spellsuggest('odiiamo', 1)) + + set spell& spelllang& + call delete('XtestSFX.dic') + call delete('XtestSFX.aff') + call delete('XtestSFX-utf8.spl') +endfunc + +" When 'spellfile' is not set, adding a new good word will automatically set +" the 'spellfile' +func Test_init_spellfile() + let save_rtp = &rtp + let save_encoding = &encoding + call mkdir('Xrtp/spell', 'p') + call writefile(['vim'], 'Xrtp/spell/Xtest.dic') + silent mkspell Xrtp/spell/Xtest.utf-8.spl Xrtp/spell/Xtest.dic + set runtimepath=./Xrtp + set spelllang=Xtest + set spell + silent spellgood abc + call assert_equal('./Xrtp/spell/Xtest.utf-8.add', &spellfile) + call assert_equal(['abc'], readfile('Xrtp/spell/Xtest.utf-8.add')) + call assert_true(filereadable('Xrtp/spell/Xtest.utf-8.spl')) + set spell& spelllang& spellfile& + call delete('Xrtp', 'rf') + let &encoding = save_encoding + let &rtp = save_rtp + %bw! +endfunc + +" Test for the 'mkspellmem' option +func Test_mkspellmem_opt() + call assert_fails('set mkspellmem=1000', 'E474:') + call assert_fails('set mkspellmem=1000,', 'E474:') + call assert_fails('set mkspellmem=1000,50', 'E474:') + call assert_fails('set mkspellmem=1000,50,', 'E474:') + call assert_fails('set mkspellmem=1000,50,10,', 'E474:') + call assert_fails('set mkspellmem=1000,50,0', 'E474:') +endfunc + +" 'spellfile' accepts '@' on top of 'isfname'. +func Test_spellfile_allow_at_character() + call mkdir('Xtest/the foo@bar,dir', 'p') + let &spellfile = './Xtest/the foo@bar,dir/Xspellfile.add' + let &spellfile = '' + call delete('Xtest', 'rf') +endfunc + +" this was using a NULL pointer +func Test_mkspell_empty_dic() + call writefile(['1'], 'XtestEmpty.dic') + call writefile(['SOFOFROM abcd', 'SOFOTO ABCD', 'SAL CIA X'], 'XtestEmpty.aff') + mkspell! XtestEmpty.spl XtestEmpty + + call delete('XtestEmpty.dic') + call delete('XtestEmpty.aff') + call delete('XtestEmpty.spl') +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_startup.vim b/test/old/testdir/test_startup.vim new file mode 100644 index 0000000000..db9f0c4c13 --- /dev/null +++ b/test/old/testdir/test_startup.vim @@ -0,0 +1,1278 @@ +" Tests for startup. + +source shared.vim +source screendump.vim +source term_util.vim +source check.vim + +" Check that loading startup.vim works. +func Test_startup_script() + throw 'skipped: Nvim does not need defaults.vim' + set compatible + source $VIMRUNTIME/defaults.vim + + call assert_equal(0, &compatible) + " Restore some options, so that the following tests doesn't break + set nomore + set noshowmode +endfunc + +" Verify the order in which plugins are loaded: +" 1. plugins in non-after directories +" 2. packages +" 3. plugins in after directories +func Test_after_comes_later() + if !has('packages') + return + endif + let before =<< trim [CODE] + set nocp viminfo+=nviminfo + set guioptions+=M + let $HOME = "/does/not/exist" + set loadplugins + set rtp=Xhere,Xdir/after,Xanother + set packpath=Xhere,Xdir/after + set nomore + let g:sequence = "" + [CODE] + + let after =<< trim [CODE] + redir! > Xtestout + scriptnames + redir END + redir! > Xsequence + echo g:sequence + redir END + quit + [CODE] + + call mkdir('Xhere/plugin', 'p') + call writefile(['let g:sequence .= "here "'], 'Xhere/plugin/here.vim') + call mkdir('Xanother/plugin', 'p') + call writefile(['let g:sequence .= "another "'], 'Xanother/plugin/another.vim') + call mkdir('Xhere/pack/foo/start/foobar/plugin', 'p') + call writefile(['let g:sequence .= "pack "'], 'Xhere/pack/foo/start/foobar/plugin/foo.vim') + + call mkdir('Xdir/after/plugin', 'p') + call writefile(['let g:sequence .= "after "'], 'Xdir/after/plugin/later.vim') + + if RunVim(before, after, '') + + let lines = readfile('Xtestout') + let expected = ['Xbefore.vim', 'here.vim', 'another.vim', 'foo.vim', 'later.vim', 'Xafter.vim'] + let found = [] + for line in lines + for one in expected + if line =~ one + call add(found, one) + endif + endfor + endfor + call assert_equal(expected, found) + endif + + call assert_equal('here another pack after', substitute(join(readfile('Xsequence', 1), ''), '\s\+$', '', '')) + + call delete('Xtestout') + call delete('Xsequence') + call delete('Xhere', 'rf') + call delete('Xanother', 'rf') + call delete('Xdir', 'rf') +endfunc + +func Test_pack_in_rtp_when_plugins_run() + if !has('packages') + return + endif + let before =<< trim [CODE] + set nocp viminfo+=nviminfo + set guioptions+=M + let $HOME = "/does/not/exist" + set loadplugins + set rtp=Xhere + set packpath=Xhere + set nomore + [CODE] + + let after = [ + \ 'quit', + \ ] + call mkdir('Xhere/plugin', 'p') + call writefile(['redir! > Xtestout', 'silent set runtimepath?', 'silent! call foo#Trigger()', 'redir END'], 'Xhere/plugin/here.vim') + call mkdir('Xhere/pack/foo/start/foobar/autoload', 'p') + call writefile(['function! foo#Trigger()', 'echo "autoloaded foo"', 'endfunction'], 'Xhere/pack/foo/start/foobar/autoload/foo.vim') + + if RunVim(before, after, '') + + let lines = filter(readfile('Xtestout'), '!empty(v:val)') + call assert_match('runtimepath=Xhere', get(lines, 0)) + call assert_match('autoloaded foo', get(lines, 1)) + endif + + call delete('Xtestout') + call delete('Xhere', 'rf') +endfunc + +func Test_help_arg() + " This does not work with a GUI-only binary, such as on MS-Windows. + CheckAnyOf Unix NotGui + + if RunVim([], [], '--help >Xtestout') + let lines = readfile('Xtestout') + call assert_true(len(lines) > 20) + call assert_match('Usage:', lines[0]) + + " check if couple of lines are there + let found = [] + for line in lines + if line =~ '-l.*Execute Lua' + call add(found, 'Execute Lua') + endif + " Watch out for a second --version line in the Gnome version. + if line =~ '--version.*Print version information' + call add(found, "--version") + endif + endfor + call assert_equal(['Execute Lua', '--version'], found) + endif + call delete('Xtestout') +endfunc + +func Test_compatible_args() + throw "skipped: Nvim is always 'nocompatible'" + let after =<< trim [CODE] + call writefile([string(&compatible)], "Xtestout") + set viminfo+=nviminfo + quit + [CODE] + + if RunVim([], after, '-C') + let lines = readfile('Xtestout') + call assert_equal('1', lines[0]) + endif + + if RunVim([], after, '-N') + let lines = readfile('Xtestout') + call assert_equal('0', lines[0]) + endif + + call delete('Xtestout') +endfunc + +" Test the -o[N] and -O[N] arguments to open N windows split +" horizontally or vertically. +func Test_o_arg() + let after =<< trim [CODE] + call writefile([winnr("$"), + \ winheight(1), winheight(2), &lines, + \ winwidth(1), winwidth(2), &columns, + \ bufname(winbufnr(1)), bufname(winbufnr(2))], + \ "Xtestout") + qall + [CODE] + + if RunVim([], after, '-o2') + " Open 2 windows split horizontally. Expect: + " - 2 windows + " - both windows should have the same or almost the same height + " - sum of both windows height (+ 3 for both statusline and Ex command) + " should be equal to the number of lines + " - both windows should have the same width which should be equal to the + " number of columns + " - buffer of both windows should have no name + let [wn, wh1, wh2, ln, ww1, ww2, cn, bn1, bn2] = readfile('Xtestout') + call assert_equal('2', wn) + call assert_inrange(0, 1, wh1 - wh2) + call assert_equal(string(wh1 + wh2 + 3), ln) + call assert_equal(ww1, ww2) + call assert_equal(ww1, cn) + call assert_equal('', bn1) + call assert_equal('', bn2) + endif + + if RunVim([], after, '-o foo bar') + " Same expectations as for -o2 but buffer names should be foo and bar + let [wn, wh1, wh2, ln, ww1, ww2, cn, bn1, bn2] = readfile('Xtestout') + call assert_equal('2', wn) + call assert_inrange(0, 1, wh1 - wh2) + call assert_equal(string(wh1 + wh2 + 3), ln) + call assert_equal(ww1, ww2) + call assert_equal(ww1, cn) + call assert_equal('foo', bn1) + call assert_equal('bar', bn2) + endif + + if RunVim([], after, '-O2') + " Open 2 windows split vertically. Expect: + " - 2 windows + " - both windows should have the same or almost the same width + " - sum of both windows width (+ 1 for the separator) should be equal to + " the number of columns + " - both windows should have the same height + " - window height (+ 2 for the statusline and Ex command) should be equal + " to the number of lines + " - buffer of both windows should have no name + let [wn, wh1, wh2, ln, ww1, ww2, cn, bn1, bn2] = readfile('Xtestout') + call assert_equal('2', wn) + call assert_inrange(0, 1, ww1 - ww2) + call assert_equal(string(ww1 + ww2 + 1), cn) + call assert_equal(wh1, wh2) + call assert_equal(string(wh1 + 2), ln) + call assert_equal('', bn1) + call assert_equal('', bn2) + endif + + if RunVim([], after, '-O foo bar') + " Same expectations as for -O2 but buffer names should be foo and bar + let [wn, wh1, wh2, ln, ww1, ww2, cn, bn1, bn2] = readfile('Xtestout') + call assert_equal('2', wn) + call assert_inrange(0, 1, ww1 - ww2) + call assert_equal(string(ww1 + ww2 + 1), cn) + call assert_equal(wh1, wh2) + call assert_equal(string(wh1 + 2), ln) + call assert_equal('foo', bn1) + call assert_equal('bar', bn2) + endif + + call delete('Xtestout') +endfunc + +" Test the -p[N] argument to open N tabpages. +func Test_p_arg() + let after =<< trim [CODE] + call writefile(split(execute("tabs"), "\n"), "Xtestout") + qall + [CODE] + + if RunVim([], after, '-p2') + let lines = readfile('Xtestout') + call assert_equal(4, len(lines)) + call assert_equal('Tab page 1', lines[0]) + call assert_equal('> [No Name]', lines[1]) + call assert_equal('Tab page 2', lines[2]) + call assert_equal('# [No Name]', lines[3]) + endif + + if RunVim([], after, '-p foo bar') + let lines = readfile('Xtestout') + call assert_equal(4, len(lines)) + call assert_equal('Tab page 1', lines[0]) + call assert_equal('> foo', lines[1]) + call assert_equal('Tab page 2', lines[2]) + call assert_equal('# bar', lines[3]) + endif + + call delete('Xtestout') +endfunc + +" Test the -V[N] argument to set the 'verbose' option to [N] +func Test_V_arg() + " Can't catch the output of gvim. + CheckNotGui + + let out = system(GetVimCommand() . ' --clean -es -X -V0 -c "set verbose?" -cq') + call assert_equal(" verbose=0\n", out) + + let out = system(GetVimCommand() . ' --clean -es -X -V2 -c "set verbose?" -cq') + " call assert_match("sourcing \"$VIMRUNTIME[\\/]defaults\.vim\"\r\nline \\d\\+: sourcing \"[^\"]*runtime[\\/]filetype\.vim\".*\n", out) + call assert_match(" verbose=2\n", out) + + let out = system(GetVimCommand() . ' --clean -es -X -V15 -c "set verbose?" -cq') + " call assert_match("sourcing \"$VIMRUNTIME[\\/]defaults\.vim\"\r\nline 1: \" The default vimrc file\..* verbose=15\n", out) +endfunc + +" Test the '-q [errorfile]' argument. +func Test_q_arg() + CheckFeature quickfix + + let lines =<< trim END + /* some file with an error */ + main() { + functionCall(arg; arg, arg); + return 666 + } + END + call writefile(lines, 'Xbadfile.c') + + let after =<< trim [CODE] + call writefile([&errorfile, string(getpos("."))], "XtestoutQarg") + copen + w >> XtestoutQarg + qall + [CODE] + + " Test with default argument '-q'. + call assert_equal('errors.err', &errorfile) + call writefile(["Xbadfile.c:4:12: error: expected ';' before '}' token"], 'errors.err') + if RunVim([], after, '-q') + let lines = readfile('XtestoutQarg') + call assert_equal(['errors.err', + \ '[0, 4, 12, 0]', + \ "Xbadfile.c|4 col 12| error: expected ';' before '}' token"], + \ lines) + endif + call delete('XtestoutQarg') + call delete('errors.err') + + " Test with explicit argument '-q XerrorsQarg' (with space). + call writefile(["Xbadfile.c:4:12: error: expected ';' before '}' token"], 'XerrorsQarg') + if RunVim([], after, '-q XerrorsQarg') + let lines = readfile('XtestoutQarg') + call assert_equal(['XerrorsQarg', + \ '[0, 4, 12, 0]', + \ "Xbadfile.c|4 col 12| error: expected ';' before '}' token"], + \ lines) + endif + call delete('XtestoutQarg') + + " Test with explicit argument '-qXerrorsQarg' (without space). + if RunVim([], after, '-qXerrorsQarg') + let lines = readfile('XtestoutQarg') + call assert_equal(['XerrorsQarg', + \ '[0, 4, 12, 0]', + \ "Xbadfile.c|4 col 12| error: expected ';' before '}' token"], + \ lines) + endif + + " Test with a non-existing error file (exits with value 3) + let out = system(GetVimCommand() .. ' -q xyz.err') + call assert_equal(3, v:shell_error) + + call delete('Xbadfile.c') + call delete('XtestoutQarg') + call delete('XerrorsQarg') +endfunc + +" Test the -V[N]{filename} argument to set the 'verbose' option to N +" and set 'verbosefile' to filename. +func Test_V_file_arg() + if RunVim([], [], ' --clean -V2Xverbosefile -c "set verbose? verbosefile?" -cq') + let out = join(readfile('Xverbosefile'), "\n") + " call assert_match("sourcing \"$VIMRUNTIME[\\/]defaults\.vim\"\n", out) + call assert_match("\n verbose=2\n", out) + call assert_match("\n verbosefile=Xverbosefile", out) + endif + + call delete('Xverbosefile') +endfunc + +" Test the -m, -M and -R arguments: +" -m resets 'write' +" -M resets 'modifiable' and 'write' +" -R sets 'readonly' +func Test_m_M_R() + let after =<< trim [CODE] + call writefile([&write, &modifiable, &readonly, &updatecount], "Xtestout") + qall + [CODE] + + if RunVim([], after, '') + let lines = readfile('Xtestout') + call assert_equal(['1', '1', '0', '200'], lines) + endif + if RunVim([], after, '-m') + let lines = readfile('Xtestout') + call assert_equal(['0', '1', '0', '200'], lines) + endif + if RunVim([], after, '-M') + let lines = readfile('Xtestout') + call assert_equal(['0', '0', '0', '200'], lines) + endif + if RunVim([], after, '-R') + let lines = readfile('Xtestout') + call assert_equal(['1', '1', '1', '10000'], lines) + endif + + call delete('Xtestout') +endfunc + +" Test the -A and -H arguments (Arabic and Hebrew modes). +func Test_A_H_arg() + let after =<< trim [CODE] + call writefile([&rightleft, &arabic, 0, &hkmap, &keymap], "Xtestout") + qall + [CODE] + + " Use silent Ex mode to avoid the hit-Enter prompt for the warning that + " 'encoding' is not utf-8. + if has('arabic') && &encoding == 'utf-8' && RunVim([], after, '-e -s -A') + let lines = readfile('Xtestout') + call assert_equal(['1', '1', '0', '0', 'arabic'], lines) + endif + + if has('rightleft') && RunVim([], after, '-H') + let lines = readfile('Xtestout') + call assert_equal(['1', '0', '0', '0', 'hebrew'], lines) + endif + + call delete('Xtestout') +endfunc + +" Test the --echo-wid argument (for GTK GUI only). +func Test_echo_wid() + CheckCanRunGui + CheckFeature gui_gtk + + if RunVim([], [], '-g --echo-wid -cq >Xtest_echo_wid') + let lines = readfile('Xtest_echo_wid') + call assert_equal(1, len(lines)) + call assert_match('^WID: \d\+$', lines[0]) + endif + + call delete('Xtest_echo_wid') +endfunction + +" Test the -reverse and +reverse arguments (for GUI only). +func Test_reverse() + CheckCanRunGui + CheckAnyOf Feature:gui_gtk Feature:gui_motif + + let after =<< trim [CODE] + call writefile([&background], "Xtest_reverse") + qall + [CODE] + if RunVim([], after, '-f -g -reverse') + let lines = readfile('Xtest_reverse') + call assert_equal(['dark'], lines) + endif + if RunVim([], after, '-f -g +reverse') + let lines = readfile('Xtest_reverse') + call assert_equal(['light'], lines) + endif + + call delete('Xtest_reverse') +endfunc + +" Test the -background and -foreground arguments (for GUI only). +func Test_background_foreground() + CheckCanRunGui + CheckAnyOf Feature:gui_gtk Feature:gui_motif + + " Is there a better way to check the effect of -background & -foreground + " other than merely looking at &background (dark or light)? + let after =<< trim [CODE] + call writefile([&background], "Xtest_fg_bg") + qall + [CODE] + if RunVim([], after, '-f -g -background darkred -foreground yellow') + let lines = readfile('Xtest_fg_bg') + call assert_equal(['dark'], lines) + endif + if RunVim([], after, '-f -g -background ivory -foreground darkgreen') + let lines = readfile('Xtest_fg_bg') + call assert_equal(['light'], lines) + endif + + call delete('Xtest_fg_bg') +endfunc + +" Test the -font argument (for GUI only). +func Test_font() + CheckCanRunGui + CheckNotMSWindows + + if has('gui_gtk') + let font = 'Courier 14' + elseif has('gui_motif') + let font = '-misc-fixed-bold-*' + else + throw 'Skipped: test does not set a valid font for this GUI' + endif + + let after =<< trim [CODE] + call writefile([&guifont], "Xtest_font") + qall + [CODE] + + if RunVim([], after, '--nofork -g -font "' .. font .. '"') + let lines = readfile('Xtest_font') + call assert_equal([font], lines) + endif + + call delete('Xtest_font') +endfunc + +" Test the -geometry argument (for GUI only). +func Test_geometry() + CheckCanRunGui + CheckAnyOf Feature:gui_gtk Feature:gui_motif + + if has('gui_motif') + " FIXME: With GUI Motif the value of getwinposx(), + " getwinposy() and getwinpos() do not match exactly the + " value given in -geometry. Why? + " So only check &columns and &lines for those GUIs. + let after =<< trim [CODE] + call writefile([&columns, &lines], "Xtest_geometry") + qall + [CODE] + if RunVim([], after, '-f -g -geometry 31x13+41+43') + let lines = readfile('Xtest_geometry') + call assert_equal(['31', '13'], lines) + endif + else + let after =<< trim [CODE] + call writefile([&columns, &lines, getwinposx(), getwinposy(), string(getwinpos())], "Xtest_geometry") + qall + [CODE] + " Some window managers have a bar at the top that pushes windows down, + " need to use at least 130, let's do 150 + if RunVim([], after, '-f -g -geometry 31x13+41+150') + let lines = readfile('Xtest_geometry') + " Depending on the GUI library and the windowing system the final size + " might be a bit different, allow for some tolerance. Tuned based on + " actual failures. + call assert_inrange(31, 35, str2nr(lines[0])) + call assert_equal('13', lines[1]) + call assert_equal('41', lines[2]) + call assert_equal('150', lines[3]) + call assert_equal('[41, 150]', lines[4]) + endif + endif + + call delete('Xtest_geometry') +endfunc + +" Test the -iconic argument (for GUI only). +func Test_iconic() + CheckCanRunGui + CheckAnyOf Feature:gui_gtk Feature:gui_motif + + call RunVim([], [], '-f -g -iconic -cq') + + " TODO: currently only start vim iconified, but does not + " check that vim is iconified. How could this be checked? +endfunc + + +func Test_invalid_args() + " must be able to get the output of Vim. + CheckUnix + CheckNotGui + + for opt in ['-Y', '--does-not-exist'] + let out = split(system(GetVimCommand() .. ' ' .. opt), "\n") + call assert_equal(1, v:shell_error) + call assert_equal('nvim: Unknown option argument: "' .. opt .. '"', out[0]) + call assert_equal('More info with "nvim -h"', out[1]) + endfor + + for opt in ['-c', '-i', '-s', '-t', '-u', '-U', '-w', '-W', '--cmd', '--startuptime'] + let out = split(system(GetVimCommand() .. ' ' .. opt), "\n") + call assert_equal(1, v:shell_error) + call assert_equal('nvim: Argument missing after: "' .. opt .. '"', out[0]) + call assert_equal('More info with "nvim -h"', out[1]) + endfor + + if has('clientserver') + for opt in ['--remote', '--remote-send', '--remote-silent', '--remote-expr', + \ '--remote-tab', '--remote-tab-wait', + \ '--remote-tab-wait-silent', '--remote-tab-silent', + \ '--remote-wait', '--remote-wait-silent', + \ '--servername', + \ ] + let out = split(system(GetVimCommand() .. ' ' .. opt), "\n") + call assert_equal(1, v:shell_error) + call assert_match('^VIM - Vi IMproved .* (.*)$', out[0]) + call assert_equal('Argument missing after: "' .. opt .. '"', out[1]) + call assert_equal('More info with: "vim -h"', out[2]) + endfor + endif + + if has('gui_gtk') + let out = split(system(GetVimCommand() .. ' --display'), "\n") + call assert_equal(1, v:shell_error) + call assert_match('^VIM - Vi IMproved .* (.*)$', out[0]) + call assert_equal('Argument missing after: "--display"', out[1]) + call assert_equal('More info with: "vim -h"', out[2]) + endif + + if has('xterm_clipboard') + let out = split(system(GetVimCommand() .. ' -display'), "\n") + call assert_equal(1, v:shell_error) + call assert_match('^VIM - Vi IMproved .* (.*)$', out[0]) + call assert_equal('Argument missing after: "-display"', out[1]) + call assert_equal('More info with: "vim -h"', out[2]) + endif + + let out = split(system(GetVimCommand() .. ' -ix'), "\n") + call assert_equal(1, v:shell_error) + call assert_equal('nvim: Garbage after option argument: "-ix"', out[0]) + call assert_equal('More info with "nvim -h"', out[1]) + + " Not an error in Nvim. The "-" file is allowed with -t, -q, or [file]. + let out = split(system(GetVimCommand() .. ' - xxx -cq'), "\n") + call assert_equal(0, v:shell_error) + + if has('quickfix') + " Detect invalid repeated arguments '-t foo -t foo', '-q foo -q foo'. + for opt in ['-t', '-q'] + let out = split(system(GetVimCommand() .. repeat(' ' .. opt .. ' foo', 2)), "\n") + call assert_equal(1, v:shell_error) + call assert_equal('nvim: Too many edit arguments: "' .. opt .. '"', out[0]) + call assert_equal('More info with "nvim -h"', out[1]) + endfor + endif + + for opt in [' -cq', ' --cmd q', ' +', ' -S foo'] + let out = split(system(GetVimCommand() .. repeat(opt, 11)), "\n") + call assert_equal(1, v:shell_error) + " FIXME: The error message given by Vim is not ideal in case of repeated + " -S foo since it does not mention -S. + call assert_equal('nvim: Too many "+command", "-c command" or "--cmd command" arguments', out[0]) + call assert_equal('More info with "nvim -h"', out[1]) + endfor + + if has('gui_gtk') + let out = split(system(GetVimCommand() .. ' --socketid'), "\n") + call assert_equal(1, v:shell_error) + call assert_match('^VIM - Vi IMproved .* (.*)$', out[0]) + call assert_equal('Argument missing after: "--socketid"', out[1]) + call assert_equal('More info with: "vim -h"', out[2]) + + for opt in ['--socketid x', '--socketid 0xg'] + let out = split(system(GetVimCommand() .. ' ' .. opt), "\n") + call assert_equal(1, v:shell_error) + call assert_match('^VIM - Vi IMproved .* (.*)$', out[0]) + call assert_equal('Invalid argument for: "--socketid"', out[1]) + call assert_equal('More info with: "vim -h"', out[2]) + endfor + + endif +endfunc + +func Test_file_args() + let after =<< trim [CODE] + call writefile(argv(), "Xtestout") + qall + [CODE] + + if RunVim([], after, '') + let lines = readfile('Xtestout') + call assert_equal(0, len(lines)) + endif + + if RunVim([], after, 'one') + let lines = readfile('Xtestout') + call assert_equal(1, len(lines)) + call assert_equal('one', lines[0]) + endif + + if RunVim([], after, 'one two three') + let lines = readfile('Xtestout') + call assert_equal(3, len(lines)) + call assert_equal('one', lines[0]) + call assert_equal('two', lines[1]) + call assert_equal('three', lines[2]) + endif + + if RunVim([], after, 'one -c echo two') + let lines = readfile('Xtestout') + call assert_equal(2, len(lines)) + call assert_equal('one', lines[0]) + call assert_equal('two', lines[1]) + endif + + if RunVim([], after, 'one -- -c echo two') + let lines = readfile('Xtestout') + call assert_equal(4, len(lines)) + call assert_equal('one', lines[0]) + call assert_equal('-c', lines[1]) + call assert_equal('echo', lines[2]) + call assert_equal('two', lines[3]) + endif + + call delete('Xtestout') +endfunc + +func Test_startuptime() + if !has('startuptime') + return + endif + let after = ['qall'] + if RunVim([], after, '--startuptime Xtestout one') + let lines = readfile('Xtestout') + let expected = ['parsing arguments', 'inits 3', 'opening buffers'] + let found = [] + for line in lines + for exp in expected + if line =~ exp + call add(found, exp) + endif + endfor + endfor + call assert_equal(expected, found) + endif + call delete('Xtestout') +endfunc + +func Test_read_stdin() + let after =<< trim [CODE] + write Xtestout + quit! + [CODE] + + if RunVimPiped([], after, '-', 'echo something | ') + let lines = readfile('Xtestout') + " MS-Windows adds a space after the word + call assert_equal(['something'], split(lines[0])) + endif + call delete('Xtestout') +endfunc + +func Test_progpath() + " Tests normally run with "./vim" or "../vim", these must have been expanded + " to a full path. + if has('unix') + call assert_equal('/', v:progpath[0]) + elseif has('win32') + call assert_equal(':', v:progpath[1]) + call assert_match('[/\\]', v:progpath[2]) + endif + + " Only expect "vim" to appear in v:progname. + call assert_match('vim\c', v:progname) +endfunc + +func Test_silent_ex_mode() + " must be able to get the output of Vim. + CheckUnix + CheckNotGui + + " This caused an ml_get error. + let out = system(GetVimCommand() . ' -u NONE -es -c''set verbose=1|h|exe "%norm\<c-y>\<c-d>"'' -c cq') + call assert_notmatch('E315:', out) +endfunc + +func Test_default_term() + " must be able to get the output of Vim. + CheckUnix + CheckNotGui + + let save_term = $TERM + let $TERM = 'unknownxxx' + let out = system(GetVimCommand() . ' -c ''echo &term'' -c cq') + call assert_match('nvim', out) + let $TERM = save_term +endfunc + +func Test_zzz_startinsert() + " Test :startinsert + call writefile(['123456'], 'Xtestout') + let after =<< trim [CODE] + :startinsert + call feedkeys("foobar\<c-o>:wq\<cr>","t") + [CODE] + + if RunVim([], after, 'Xtestout') + let lines = readfile('Xtestout') + call assert_equal(['foobar123456'], lines) + endif + " Test :startinsert! + call writefile(['123456'], 'Xtestout') + let after =<< trim [CODE] + :startinsert! + call feedkeys("foobar\<c-o>:wq\<cr>","t") + [CODE] + + if RunVim([], after, 'Xtestout') + let lines = readfile('Xtestout') + call assert_equal(['123456foobar'], lines) + endif + call delete('Xtestout') +endfunc + +func Test_issue_3969() + " Can't catch the output of gvim. + CheckNotGui + + " Check that message is not truncated. + let out = system(GetVimCommand() . ' -es -X -V1 -c "echon ''hello''" -cq') + call assert_equal('hello', out) +endfunc + +func Test_start_with_tabs() + CheckRunVimInTerminal + + let buf = RunVimInTerminal('-p a b c', {}) + call VerifyScreenDump(buf, 'Test_start_with_tabs', {}) + + " clean up + call StopVimInTerminal(buf) +endfunc + +func Test_v_argv() + let out = system(GetVimCommand() . ' -es -V1 -X arg1 --cmd "echo v:argv" --cmd q') + let list = split(out, "', '") + call assert_match('vim', list[0]) + let idx = index(list, 'arg1') + call assert_true(idx > 2) + call assert_equal(['arg1', '--cmd', 'echo v:argv', '--cmd', 'q'']'], list[idx:]) +endfunc + +" Test for the "-r" recovery mode option +func Test_r_arg() + throw 'Skipped: Nvim has different directories' + " Can't catch the output of gvim. + CheckNotGui + CheckUnix + CheckEnglish + let cmd = GetVimCommand() + " There can be swap files anywhere, only check for the headers. + let expected =<< trim END + Swap files found:.* + In current directory:.* + In directory \~/tmp:.* + In directory /var/tmp:.* + In directory /tmp:.* + END + call assert_match(join(expected, ""), system(cmd .. " -r")->substitute("[\r\n]\\+", '', '')) +endfunc + +" Test for the '-t' option to jump to a tag +func Test_t_arg() + let before =<< trim [CODE] + set tags=Xtags + [CODE] + let after =<< trim [CODE] + let s = bufname('') .. ':L' .. line('.') .. 'C' .. col('.') + call writefile([s], "Xtestout") + qall + [CODE] + + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "first\tXfile1\t/^ \\zsfirst$/", + \ "second\tXfile1\t/^ \\zssecond$/", + \ "third\tXfile1\t/^ \\zsthird$/"], + \ 'Xtags') + call writefile([' first', ' second', ' third'], 'Xfile1') + + for t_arg in ['-t second', '-tsecond'] + if RunVim(before, after, t_arg) + call assert_equal(['Xfile1:L2C5'], readfile('Xtestout'), t_arg) + call delete('Xtestout') + endif + endfor + + call delete('Xtags') + call delete('Xfile1') +endfunc + +" Test the '-T' argument which sets the 'term' option. +func Test_T_arg() + throw 'skipped: Nvim does not support "-T" argument' + CheckNotGui + let after =<< trim [CODE] + call writefile([&term], "Xtest_T_arg") + qall + [CODE] + + for t in ['builtin_dumb', 'builtin_ansi'] + if RunVim([], after, '-T ' .. t) + let lines = readfile('Xtest_T_arg') + call assert_equal([t], lines) + endif + endfor + + call delete('Xtest_T_arg') +endfunc + +" Test the '-x' argument to read/write encrypted files. +func Test_x_arg() + CheckRunVimInTerminal + CheckFeature cryptv + + " Create an encrypted file Xtest_x_arg. + let buf = RunVimInTerminal('-n -x Xtest_x_arg', #{rows: 10, wait_for_ruler: 0}) + call WaitForAssert({-> assert_match('^Enter encryption key: ', term_getline(buf, 10))}) + call term_sendkeys(buf, "foo\n") + call WaitForAssert({-> assert_match('^Enter same key again: ', term_getline(buf, 10))}) + call term_sendkeys(buf, "foo\n") + call WaitForAssert({-> assert_match(' All$', term_getline(buf, 10))}) + call term_sendkeys(buf, "itest\<Esc>:w\<Enter>") + call WaitForAssert({-> assert_match('"Xtest_x_arg" \[New\]\[blowfish2\] 1L, 5B written', + \ term_getline(buf, 10))}) + call StopVimInTerminal(buf) + + " Read the encrypted file and check that it contains the expected content "test" + let buf = RunVimInTerminal('-n -x Xtest_x_arg', #{rows: 10, wait_for_ruler: 0}) + call WaitForAssert({-> assert_match('^Enter encryption key: ', term_getline(buf, 10))}) + call term_sendkeys(buf, "foo\n") + call WaitForAssert({-> assert_match('^Enter same key again: ', term_getline(buf, 10))}) + call term_sendkeys(buf, "foo\n") + call WaitForAssert({-> assert_match('^test', term_getline(buf, 1))}) + call StopVimInTerminal(buf) + + call delete('Xtest_x_arg') +endfunc + +" Test for entering the insert mode on startup +func Test_start_insertmode() + throw "Skipped: Nvim does not support setting 'insertmode'" + let before =<< trim [CODE] + set insertmode + [CODE] + let after =<< trim [CODE] + call writefile(['insertmode=' .. &insertmode], 'Xtestout') + qall + [CODE] + if RunVim(before, after, '') + call assert_equal(['insertmode=1'], readfile('Xtestout')) + call delete('Xtestout') + endif +endfunc + +" Test for enabling the binary mode on startup +func Test_b_arg() + let after =<< trim [CODE] + call writefile(['binary=' .. &binary], 'Xtestout') + qall + [CODE] + if RunVim([], after, '-b') + call assert_equal(['binary=1'], readfile('Xtestout')) + call delete('Xtestout') + endif +endfunc + +" Test for enabling the lisp mode on startup +func Test_l_arg() + throw 'Skipped: Nvim -l arg differs from Vim' + let after =<< trim [CODE] + let s = 'lisp=' .. &lisp .. ', showmatch=' .. &showmatch + call writefile([s], 'Xtestout') + qall + [CODE] + if RunVim([], after, '-l') + call assert_equal(['lisp=1, showmatch=1'], readfile('Xtestout')) + call delete('Xtestout') + endif +endfunc + +" Test for specifying a non-existing vimrc file using "-u" +func Test_missing_vimrc() + CheckRunVimInTerminal + let after =<< trim [CODE] + call assert_match('^E282:', v:errmsg) + call writefile(v:errors, 'Xtestout') + [CODE] + call writefile(after, 'Xafter') + + let cmd = GetVimCommandCleanTerm() . ' -u Xvimrc_missing -S Xafter' + let buf = term_start(cmd, {'term_rows' : 10}) + call WaitForAssert({-> assert_equal("running", term_getstatus(buf))}) + call TermWait(buf) + call term_sendkeys(buf, "\n:") + call TermWait(buf) + call WaitForAssert({-> assert_match(':', term_getline(buf, 10))}) + call StopVimInTerminal(buf) + call assert_equal([], readfile('Xtestout')) + call delete('Xafter') + call delete('Xtestout') +endfunc + +" Test for using the $VIMINIT environment variable +func Test_VIMINIT() + let after =<< trim [CODE] + call assert_equal(1, exists('viminit_found')) + call assert_equal('yes', viminit_found) + call writefile(v:errors, 'Xtestout') + qall + [CODE] + call writefile(after, 'Xafter') + " let cmd = GetVimProg() . ' --not-a-term -S Xafter --cmd "set enc=utf8"' + let cmd = GetVimProg() . ' -S Xafter --cmd "set enc=utf8"' + call setenv('VIMINIT', 'let viminit_found="yes"') + exe "silent !" . cmd + call assert_equal([], readfile('Xtestout')) + call delete('Xtestout') + call delete('Xafter') +endfunc + +" Test for using the $EXINIT environment variable +func Test_EXINIT() + let after =<< trim [CODE] + call assert_equal(1, exists('exinit_found')) + call assert_equal('yes', exinit_found) + call writefile(v:errors, 'Xtestout') + qall + [CODE] + call writefile(after, 'Xafter') + " let cmd = GetVimProg() . ' --not-a-term -S Xafter --cmd "set enc=utf8"' + let cmd = GetVimProg() . ' -S Xafter --cmd "set enc=utf8"' + call setenv('EXINIT', 'let exinit_found="yes"') + exe "silent !" . cmd + call assert_equal([], readfile('Xtestout')) + call delete('Xtestout') + call delete('Xafter') +endfunc + +" Test for using the 'exrc' option +func Test_exrc() + throw 'Skipped: Nvim requires user input for the exrc option' + let after =<< trim [CODE] + call assert_equal(1, &exrc) + call assert_equal(1, &secure) + call assert_equal(37, exrc_found) + call writefile(v:errors, 'Xtestout') + qall + [CODE] + call mkdir('Xdir') + call writefile(['let exrc_found=37'], 'Xdir/.exrc') + call writefile(after, 'Xdir/Xafter') + " let cmd = GetVimProg() . ' --not-a-term -S Xafter --cmd "cd Xdir" --cmd "set enc=utf8 exrc secure"' + let cmd = GetVimProg() . ' -S Xafter --cmd "cd Xdir" --cmd "set enc=utf8 exrc secure"' + exe "silent !" . cmd + call assert_equal([], readfile('Xdir/Xtestout')) + call delete('Xdir', 'rf') +endfunc + +" Test for starting Vim with a non-terminal as input/output +func Test_io_not_a_terminal() + throw 'Skipped: Nvim does not support --ttyfail' + " Can't catch the output of gvim. + CheckNotGui + CheckUnix + CheckEnglish + let l = systemlist(GetVimProg() .. ' --ttyfail') + call assert_equal(['Vim: Warning: Output is not to a terminal', + \ 'Vim: Warning: Input is not from a terminal'], l) +endfunc + +" Test for not being a term avoiding escape codes. +func Test_not_a_term() + CheckUnix + CheckNotGui + + if &shellredir =~ '%s' + let redir = printf(&shellredir, 'Xvimout') + else + let redir = &shellredir .. ' Xvimout' + endif + + " As nvim checks the environment by itself there will be no escape sequences + " This will also happen to take two (2) seconds. + let cmd = GetVimProg() .. ' --cmd quit ' .. redir + exe "silent !" . cmd + call assert_notmatch("\e", readfile('Xvimout')->join()) + call delete('Xvimout') + + " --not-a-term flag has thus been deleted +endfunc + + +" Test for the "-w scriptout" argument +func Test_w_arg() + " Can't catch the output of gvim. + CheckNotGui + + call writefile(["iVim Editor\<Esc>:q!\<CR>"], 'Xscriptin', 'b') + if RunVim([], [], '-s Xscriptin -w Xscriptout') + call assert_equal(["iVim Editor\e:q!\r"], readfile('Xscriptout')) + call delete('Xscriptout') + endif + call delete('Xscriptin') + + " Test for failing to open the script output file. This test works only when + " the language is English. + if !has('win32') && (v:lang == "C" || v:lang =~ '^[Ee]n') + call mkdir("Xdir") + let m = system(GetVimCommand() .. " -w Xdir") + call assert_equal("Cannot open for script output: \"Xdir\"\n", m) + call delete("Xdir", 'rf') + endif + + " A number argument sets the 'window' option + call writefile(["iwindow \<C-R>=&window\<CR>\<Esc>:wq! Xresult\<CR>"], 'Xscriptin', 'b') + for w_arg in ['-w 17', '-w17'] + if RunVim([], [], '-s Xscriptin ' .. w_arg) + call assert_equal(["window 17"], readfile('Xresult'), w_arg) + call delete('Xresult') + endif + endfor + call delete('Xscriptin') +endfunc + +" Test for the "-s scriptin" argument +func Test_s_arg() + " Can't catch the output of gvim. + CheckNotGui + CheckEnglish + " Test for failing to open the script input file. + let m = system(GetVimCommand() .. " -s abcxyz") + " call assert_equal("Cannot open for reading: \"abcxyz\"\n", m) + call assert_equal("Cannot open for reading: \"abcxyz\": no such file or directory\n", m) + + call writefile([], 'Xinput') + let m = system(GetVimCommand() .. " -s Xinput -s Xinput") + call assert_equal("Attempt to open script file again: \"-s Xinput\"\n", m) + call delete('Xinput') +endfunc + +" Test for the "-n" (no swap file) argument +func Test_n_arg() + let after =<< trim [CODE] + call assert_equal(0, &updatecount) + call writefile(v:errors, 'Xtestout') + qall + [CODE] + if RunVim([], after, '-n') + call assert_equal([], readfile('Xtestout')) + call delete('Xtestout') + endif +endfunc + +" Test for the "-h" (help) argument +func Test_h_arg() + throw 'Skipped: Nvim has different output for "-h" argument' + " Can't catch the output of gvim. + CheckNotGui + let l = systemlist(GetVimProg() .. ' -h') + call assert_match('^VIM - Vi IMproved', l[0]) + let l = systemlist(GetVimProg() .. ' -?') + call assert_match('^VIM - Vi IMproved', l[0]) +endfunc + +" Test for the "-F" (farsi) argument +func Test_F_arg() + throw 'Skipped: Nvim does not recognize "-F" argument' + " Can't catch the output of gvim. + CheckNotGui + let l = systemlist(GetVimProg() .. ' -F') + call assert_match('^E27:', l[0]) +endfunc + +" Test for the "-E" (improved Ex mode) argument +func Test_E_arg() + let after =<< trim [CODE] + call assert_equal('cv', mode(1)) + call writefile(v:errors, 'Xtestout') + qall + [CODE] + if RunVim([], after, '-E') + call assert_equal([], readfile('Xtestout')) + call delete('Xtestout') + endif +endfunc + +" Test for the "-D" (debugger) argument +func Test_D_arg() + CheckRunVimInTerminal + + let cmd = GetVimCommandCleanTerm() .. ' -D' + let buf = term_start(cmd, {'term_rows' : 10}) + call WaitForAssert({-> assert_equal("running", term_getstatus(buf))}) + + call WaitForAssert({-> assert_equal('Entering Debug mode. Type "cont" to continue.', + \ term_getline(buf, 7))}) + call WaitForAssert({-> assert_equal('>', term_getline(buf, 10))}) + + call StopVimInTerminal(buf) +endfunc + +" Test for too many edit argument errors +func Test_too_many_edit_args() + throw 'Skipped: N/A' + " Can't catch the output of gvim. + CheckNotGui + CheckEnglish + let l = systemlist(GetVimProg() .. ' - -') + call assert_match('^Too many edit arguments: "-"', l[1]) +endfunc + +" Test starting vim with various names: vim, ex, view, evim, etc. +func Test_progname() + CheckUnix + + call mkdir('Xprogname', 'p') + call writefile(['silent !date', + \ 'call writefile([mode(1), ' + \ .. '&insertmode, &diff, &readonly, &updatecount, ' + \ .. 'join(split(execute("message"), "\n")[1:])], "Xprogname_out")', + \ 'qall'], 'Xprogname_after') + + " +---------------------------------------------- progname + " | +--------------------------------- mode(1) + " | | +--------------------------- &insertmode + " | | | +---------------------- &diff + " | | | | +----------------- &readonly + " | | | | | +-------- &updatecount + " | | | | | | +--- :messages + " | | | | | | | + " let expectations = { + " \ 'vim': ['n', '0', '0', '0', '200', ''], + " \ 'gvim': ['n', '0', '0', '0', '200', ''], + " \ 'ex': ['ce', '0', '0', '0', '200', ''], + " \ 'exim': ['cv', '0', '0', '0', '200', ''], + " \ 'view': ['n', '0', '0', '1', '10000', ''], + " \ 'gview': ['n', '0', '0', '1', '10000', ''], + " \ 'evim': ['n', '1', '0', '0', '200', ''], + " \ 'eview': ['n', '1', '0', '1', '10000', ''], + " \ 'rvim': ['n', '0', '0', '0', '200', 'line 1: E145: Shell commands and some functionality not allowed in rvim'], + " \ 'rgvim': ['n', '0', '0', '0', '200', 'line 1: E145: Shell commands and some functionality not allowed in rvim'], + " \ 'rview': ['n', '0', '0', '1', '10000', 'line 1: E145: Shell commands and some functionality not allowed in rvim'], + " \ 'rgview': ['n', '0', '0', '1', '10000', 'line 1: E145: Shell commands and some functionality not allowed in rvim'], + " \ 'vimdiff': ['n', '0', '1', '0', '200', ''], + " \ 'gvimdiff': ['n', '0', '1', '0', '200', '']} + let expectations = {'nvim': ['n', '0', '0', '0', '200', '']} + + " let prognames = ['vim', 'gvim', 'ex', 'exim', 'view', 'gview', + " \ 'evim', 'eview', 'rvim', 'rgvim', 'rview', 'rgview', + " \ 'vimdiff', 'gvimdiff'] + let prognames = ['nvim'] + + for progname in prognames + let run_with_gui = (progname =~# 'g') || (has('gui') && (progname ==# 'evim' || progname ==# 'eview')) + + if empty($DISPLAY) && run_with_gui + " Can't run gvim, gview (etc.) if $DISPLAY is not setup. + continue + endif + + exe 'silent !ln -s -f ' ..exepath(GetVimProg()) .. ' Xprogname/' .. progname + + let stdout_stderr = '' + if progname =~# 'g' + let stdout_stderr = system('Xprogname/'..progname..' -f --clean --not-a-term -S Xprogname_after') + else + exe 'sil !Xprogname/'..progname..' -f --clean -S Xprogname_after' + endif + + if progname =~# 'g' && !has('gui') + call assert_equal("E25: GUI cannot be used: Not enabled at compile time\n", stdout_stderr, progname) + else + " GUI motif can output some warnings like this: + " Warning: + " Name: subMenu + " Class: XmCascadeButton + " Illegal mnemonic character; Could not convert X KEYSYM to a keycode + " So don't check that stderr is empty with GUI Motif. + if run_with_gui && !has('gui_motif') + call assert_equal('', stdout_stderr, progname) + endif + call assert_equal(expectations[progname], readfile('Xprogname_out'), progname) + endif + + call delete('Xprogname/' .. progname) + call delete('Xprogname_out') + endfor + + call delete('Xprogname_after') + call delete('Xprogname', 'd') +endfunc + +" Test for doing a write from .vimrc +func Test_write_in_vimrc() + call writefile(['silent! write'], 'Xvimrc') + let after =<< trim [CODE] + call assert_match('E32: ', v:errmsg) + call writefile(v:errors, 'Xtestout') + qall + [CODE] + if RunVim([], after, '-u Xvimrc') + call assert_equal([], readfile('Xtestout')) + call delete('Xtestout') + endif + call delete('Xvimrc') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_startup_utf8.vim b/test/old/testdir/test_startup_utf8.vim new file mode 100644 index 0000000000..1684d80c80 --- /dev/null +++ b/test/old/testdir/test_startup_utf8.vim @@ -0,0 +1,82 @@ +" Tests for startup using utf-8. + +source check.vim +source shared.vim +source screendump.vim + +func Test_read_stdin_utf8() + let linesin = ['テスト', '€ÀÈÌÒÙ'] + call writefile(linesin, 'Xtestin') + let before = [ + \ 'set enc=utf-8', + \ 'set fencs=cp932,utf-8', + \ ] + let after = [ + \ 'write ++enc=utf-8 Xtestout', + \ 'quit!', + \ ] + if has('win32') + let pipecmd = 'type Xtestin | ' + else + let pipecmd = 'cat Xtestin | ' + endif + if RunVimPiped(before, after, '-', pipecmd) + let lines = readfile('Xtestout') + call assert_equal(linesin, lines) + else + call assert_equal('', 'RunVimPiped failed.') + endif + call delete('Xtestout') + call delete('Xtestin') +endfunc + +func Test_read_fifo_utf8() + if !has('unix') + return + endif + " Using bash/zsh's process substitution. + if executable('bash') + set shell=bash + elseif executable('zsh') + set shell=zsh + else + return + endif + let linesin = ['テスト', '€ÀÈÌÒÙ'] + call writefile(linesin, 'Xtestin') + let before = [ + \ 'set enc=utf-8', + \ 'set fencs=cp932,utf-8', + \ ] + let after = [ + \ 'write ++enc=utf-8 Xtestout', + \ 'quit!', + \ ] + if RunVim(before, after, '<(cat Xtestin)') + let lines = readfile('Xtestout') + call assert_equal(linesin, lines) + else + call assert_equal('', 'RunVim failed.') + endif + call delete('Xtestout') + call delete('Xtestin') +endfunc + +func Test_detect_ambiwidth() + CheckRunVimInTerminal + + " Use the title termcap entries to output the escape sequence. + call writefile([ + \ 'set enc=utf-8', + \ 'set ambiwidth=double', + \ 'call test_option_not_set("ambiwidth")', + \ 'redraw', + \ ], 'Xscript') + let buf = RunVimInTerminal('-S Xscript', #{keep_t_u7: 1}) + call TermWait(buf) + call term_sendkeys(buf, "S\<C-R>=&ambiwidth\<CR>\<Esc>") + call WaitForAssert({-> assert_match('single', term_getline(buf, 1))}) + + call StopVimInTerminal(buf) + call delete('Xscript') +endfunc diff --git a/test/old/testdir/test_stat.vim b/test/old/testdir/test_stat.vim new file mode 100644 index 0000000000..d3059664e9 --- /dev/null +++ b/test/old/testdir/test_stat.vim @@ -0,0 +1,228 @@ +" Tests for stat functions and checktime + +source check.vim + +func CheckFileTime(doSleep) + let fnames = ['Xtest1.tmp', 'Xtest2.tmp', 'Xtest3.tmp'] + let times = [] + let result = 0 + + " Use three files instead of localtim(), with a network filesystem the file + " times may differ at bit + let fl = ['Hello World!'] + for fname in fnames + call writefile(fl, fname) + call add(times, fname->getftime()) + if a:doSleep + sleep 1 + endif + endfor + + let time_correct = (times[0] <= times[1] && times[1] <= times[2]) + if a:doSleep || time_correct + call assert_true(time_correct, printf('Expected %s <= %s <= %s', times[0], times[1], times[2])) + call assert_equal(strlen(fl[0] . "\n"), fnames[0]->getfsize()) + call assert_equal('file', fnames[0]->getftype()) + call assert_equal('rw-', getfperm(fnames[0])[0:2]) + let result = 1 + endif + + for fname in fnames + call delete(fname) + endfor + return result +endfunc + +func Test_existent_file() + " On some systems the file timestamp is rounded to a multiple of 2 seconds. + " We need to sleep to handle that, but that makes the test slow. First try + " without the sleep, and if it fails try again with the sleep. + if CheckFileTime(0) == 0 + call CheckFileTime(1) + endif +endfunc + +func Test_existent_directory() + let dname = '.' + + call assert_equal(0, getfsize(dname)) + call assert_equal('dir', getftype(dname)) + call assert_equal(has('win32') ? 'rw-' : 'rwx', getfperm(dname)[0:2]) +endfunc + +func SleepForTimestamp() + " FAT has a granularity of 2 seconds, otherwise it's usually 1 second + if has('win32') + sleep 2 + else + sleep 2 + endif +endfunc + +func Test_checktime() + let fname = 'Xtest.tmp' + + let fl = ['Hello World!'] + call writefile(fl, fname) + set autoread + exec 'e' fname + call SleepForTimestamp() + let fl = readfile(fname) + let fl[0] .= ' - checktime' + call writefile(fl, fname) + checktime + call assert_equal(fl[0], getline(1)) + + call delete(fname) +endfunc + +func Test_checktime_fast() + CheckFeature nanotime + + let fname = 'Xtest.tmp' + + let fl = ['Hello World!'] + call writefile(fl, fname) + set autoread + exec 'e' fname + let fl = readfile(fname) + let fl[0] .= ' - checktime' + sleep 10m " make test less flaky in Nvim + call writefile(fl, fname) + checktime + call assert_equal(fl[0], getline(1)) + + call delete(fname) +endfunc + +func Test_autoread_fast() + CheckFeature nanotime + + " this is timing sensitive + let g:test_is_flaky = 1 + + new Xautoread + setlocal autoread + call setline(1, 'foo') + w! + sleep 10m + call writefile(['bar'], 'Xautoread') + sleep 10m + checktime + call assert_equal('bar', trim(getline(1))) + + call delete('Xautoread') +endfunc + +func Test_autoread_file_deleted() + new Xautoread + set autoread + call setline(1, 'original') + w! + + call SleepForTimestamp() + if has('win32') + silent !echo changed > Xautoread + else + silent !echo 'changed' > Xautoread + endif + checktime + call assert_equal('changed', trim(getline(1))) + + call SleepForTimestamp() + messages clear + if has('win32') + silent !del Xautoread + else + silent !rm Xautoread + endif + checktime + call assert_match('E211:', execute('messages')) + call assert_equal('changed', trim(getline(1))) + + call SleepForTimestamp() + if has('win32') + silent !echo recreated > Xautoread + else + silent !echo 'recreated' > Xautoread + endif + checktime + call assert_equal('recreated', trim(getline(1))) + + call delete('Xautoread') + bwipe! +endfunc + + +func Test_nonexistent_file() + let fname = 'Xtest.tmp' + + call delete(fname) + call assert_equal(-1, getftime(fname)) + call assert_equal(-1, getfsize(fname)) + call assert_equal('', getftype(fname)) + call assert_equal('', getfperm(fname)) +endfunc + +func Test_getftype() + call assert_equal('file', getftype(v:progpath)) + call assert_equal('dir', getftype('.')) + + if !has('unix') + return + endif + + silent !ln -s Xfile Xlink + call assert_equal('link', getftype('Xlink')) + call delete('Xlink') + + if executable('mkfifo') + silent !mkfifo Xfifo + call assert_equal('fifo', getftype('Xfifo')) + call delete('Xfifo') + endif + + for cdevfile in systemlist('find /dev -type c -maxdepth 2 2>/dev/null') + " On Mac /def/fd/2 is found but the type is "fifo" + if cdevfile !~ '/dev/fd/' + let type = getftype(cdevfile) + " ignore empty result, can happen if the file disappeared + if type != '' + call assert_equal('cdev', type, 'for ' .. cdevfile) + endif + endif + endfor + + for bdevfile in systemlist('find /dev -type b -maxdepth 2 2>/dev/null') + let type = getftype(bdevfile) + " ignore empty result, can happen if the file disappeared + if type != '' + call assert_equal('bdev', type, 'for ' .. bdevfile) + endif + endfor + + " The /run/ directory typically contains socket files. + " If it does not, test won't fail but will not test socket files. + for socketfile in systemlist('find /run -type s -maxdepth 2 2>/dev/null') + let type = getftype(socketfile) + " ignore empty result, can happen if the file disappeared + if type != '' + call assert_equal('socket', type, 'for ' .. socketfile) + endif + endfor + + " TODO: file type 'other' is not tested. How can we test it? +endfunc + +func Test_win32_symlink_dir() + " On Windows, non-admin users cannot create symlinks. + " So we use an existing symlink for this test. + if has('win32') + " Check if 'C:\Users\All Users' is a symlink to a directory. + let res = system('dir C:\Users /a') + if match(res, '\C<SYMLINKD> *All Users') >= 0 + " Get the filetype of the symlink. + call assert_equal('link', getftype('C:\Users\All Users')) + endif + endif +endfunc diff --git a/test/old/testdir/test_statusline.vim b/test/old/testdir/test_statusline.vim new file mode 100644 index 0000000000..c48bac12b4 --- /dev/null +++ b/test/old/testdir/test_statusline.vim @@ -0,0 +1,641 @@ +" Test 'statusline' +" +" Not tested yet: +" %N + +source view_util.vim +source check.vim +source term_util.vim + +func SetUp() + set laststatus=2 +endfunc + +func TearDown() + set laststatus& +endfunc + +func s:get_statusline() + return ScreenLines(&lines - 1, &columns)[0] +endfunc + +func StatuslineWithCaughtError() + let s:func_in_statusline_called = 1 + try + call eval('unknown expression') + catch + endtry + return '' +endfunc + +func StatuslineWithError() + let s:func_in_statusline_called = 1 + call eval('unknown expression') + return '' +endfunc + +" Function used to display syntax group. +func SyntaxItem() + call assert_equal(s:expected_curbuf, g:actual_curbuf) + call assert_equal(s:expected_curwin, g:actual_curwin) + return synIDattr(synID(line("."), col("."),1), "name") +endfunc + +func Test_caught_error_in_statusline() + let s:func_in_statusline_called = 0 + let statusline = '%{StatuslineWithCaughtError()}' + let &statusline = statusline + redrawstatus + call assert_true(s:func_in_statusline_called) + call assert_equal(statusline, &statusline) + set statusline= +endfunc + +func Test_statusline_will_be_disabled_with_error() + let s:func_in_statusline_called = 0 + let statusline = '%{StatuslineWithError()}' + try + let &statusline = statusline + redrawstatus + catch + endtry + call assert_true(s:func_in_statusline_called) + call assert_equal('', &statusline) + set statusline= +endfunc + +func Test_statusline() + CheckFeature quickfix + + " %a: Argument list ({current} of {max}) + set statusline=%a + call assert_match('^\s*$', s:get_statusline()) + arglocal a1 a2 + rewind + call assert_match('^ (1 of 2)\s*$', s:get_statusline()) + next + call assert_match('^ (2 of 2)\s*$', s:get_statusline()) + e Xstatusline + call assert_match('^ ((2) of 2)\s*$', s:get_statusline()) + + only + set splitbelow + call setline(1, range(1, 10000)) + + " %b: Value of character under cursor. + " %B: As above, in hexadecimal. + call cursor(9000, 1) + set statusline=%b,%B + call assert_match('^57,39\s*$', s:get_statusline()) + + " %o: Byte number in file of byte under cursor, first byte is 1. + " %O: As above, in hexadecimal. + set statusline=%o,%O + set fileformat=dos + call assert_match('^52888,CE98\s*$', s:get_statusline()) + set fileformat=mac + call assert_match('^43889,AB71\s*$', s:get_statusline()) + set fileformat=unix + call assert_match('^43889,AB71\s*$', s:get_statusline()) + set fileformat& + + " %f: Path to the file in the buffer, as typed or relative to current dir. + set statusline=%f + call assert_match('^Xstatusline\s*$', s:get_statusline()) + + " %F: Full path to the file in the buffer. + set statusline=%F + call assert_match('/testdir/Xstatusline\s*$', s:get_statusline()) + + " Test for min and max width with %(. For some reason, if this test is moved + " after the below test for the help buffer flag, then the code to truncate + " the string is not executed. + set statusline=%015(%f%) + call assert_match('^ Xstatusline\s*$', s:get_statusline()) + set statusline=%.6(%f%) + call assert_match('^<sline\s*$', s:get_statusline()) + set statusline=%14f + call assert_match('^ Xstatusline\s*$', s:get_statusline()) + set statusline=%.4L + call assert_match('^10>3\s*$', s:get_statusline()) + + " %h: Help buffer flag, text is "[help]". + " %H: Help buffer flag, text is ",HLP". + set statusline=%h,%H + call assert_match('^,\s*$', s:get_statusline()) + help + call assert_match('^\[Help\],HLP\s*$', s:get_statusline()) + helpclose + + " %k: Value of "b:keymap_name" or 'keymap' + " when :lmap mappings are being used: <keymap>" + set statusline=%k + if has('keymap') + set keymap=esperanto + call assert_match('^<Eo>\s*$', s:get_statusline()) + set keymap& + else + call assert_match('^\s*$', s:get_statusline()) + endif + + " %l: Line number. + " %L: Number of line in buffer. + " %c: Column number. + set statusline=%l/%L,%c + call assert_match('^9000/10000,1\s*$', s:get_statusline()) + + " %m: Modified flag, text is "[+]", "[-]" if 'modifiable' is off. + " %M: Modified flag, text is ",+" or ",-". + set statusline=%m%M + call assert_match('^\[+\],+\s*$', s:get_statusline()) + set nomodifiable + call assert_match('^\[+-\],+-\s*$', s:get_statusline()) + write + call assert_match('^\[-\],-\s*$', s:get_statusline()) + set modifiable& + call assert_match('^\s*$', s:get_statusline()) + + " %n: Buffer number. + set statusline=%n + call assert_match('^'.bufnr('%').'\s*$', s:get_statusline()) + + " %p: Percentage through file in lines as in CTRL-G. + " %P: Percentage through file of displayed window. + set statusline=%p,%P + 0 + call assert_match('^0,Top\s*$', s:get_statusline()) + norm G + call assert_match('^100,Bot\s*$', s:get_statusline()) + 9000 + " Don't check the exact percentage as it depends on the window size + call assert_match('^90,\(Top\|Bot\|\d\+%\)\s*$', s:get_statusline()) + + " %q: "[Quickfix List]", "[Location List]" or empty. + set statusline=%q + call assert_match('^\s*$', s:get_statusline()) + copen + call assert_match('^\[Quickfix List\]\s*$', s:get_statusline()) + cclose + lexpr getline(1, 2) + lopen + call assert_match('^\[Location List\]\s*$', s:get_statusline()) + lclose + + " %r: Readonly flag, text is "[RO]". + " %R: Readonly flag, text is ",RO". + set statusline=%r,%R + call assert_match('^,\s*$', s:get_statusline()) + help + call assert_match('^\[RO\],RO\s*$', s:get_statusline()) + helpclose + + " %t: File name (tail) of file in the buffer. + set statusline=%t + call assert_match('^Xstatusline\s*$', s:get_statusline()) + + " %v: Virtual column number. + " %V: Virtual column number as -{num}. Not displayed if equal to 'c'. + call cursor(9000, 2) + set statusline=%v,%V + call assert_match('^2,\s*$', s:get_statusline()) + set virtualedit=all + norm 10| + call assert_match('^10,-10\s*$', s:get_statusline()) + set list + call assert_match('^10,-10\s*$', s:get_statusline()) + set virtualedit& + exe "norm A\<Tab>\<Tab>a\<Esc>" + " In list mode a <Tab> is shown as "^I", which is 2-wide. + call assert_match('^9,-9\s*$', s:get_statusline()) + set list& + " Now the second <Tab> ends at the 16th screen column. + call assert_match('^17,-17\s*$', s:get_statusline()) + undo + + " %w: Preview window flag, text is "[Preview]". + " %W: Preview window flag, text is ",PRV". + set statusline=%w%W + call assert_match('^\s*$', s:get_statusline()) + pedit + wincmd j + call assert_match('^\[Preview\],PRV\s*$', s:get_statusline()) + pclose + + " %y: Type of file in the buffer, e.g., "[vim]". See 'filetype'. + " %Y: Type of file in the buffer, e.g., ",VIM". See 'filetype'. + set statusline=%y\ %Y + call assert_match('^\s*$', s:get_statusline()) + setfiletype vim + call assert_match('^\[vim\] VIM\s*$', s:get_statusline()) + + " %=: Separation point between left and right aligned items. + set statusline=foo%=bar + call assert_match('^foo\s\+bar\s*$', s:get_statusline()) + set statusline=foo%=bar%=baz + call assert_match('^foo\s\+bar\s\+baz\s*$', s:get_statusline()) + set statusline=foo%=bar%=baz%=qux + call assert_match('^foo\s\+bar\s\+baz\s\+qux\s*$', s:get_statusline()) + + " Test min/max width, leading zeroes, left/right justify. + set statusline=%04B + call cursor(9000, 1) + call assert_match('^0039\s*$', s:get_statusline()) + set statusline=#%4B# + call assert_match('^# 39#\s*$', s:get_statusline()) + set statusline=#%-4B# + call assert_match('^#39 #\s*$', s:get_statusline()) + set statusline=%.6f + call assert_match('^<sline\s*$', s:get_statusline()) + + " %<: Where to truncate. + " First check with when %< should not truncate with many columns + exe 'set statusline=a%<b' . repeat('c', &columns - 3) . 'd' + call assert_match('^abc\+d$', s:get_statusline()) + exe 'set statusline=a' . repeat('b', &columns - 2) . '%<c' + call assert_match('^ab\+c$', s:get_statusline()) + " Then check when %< should truncate when there with too few columns. + exe 'set statusline=a%<b' . repeat('c', &columns - 2) . 'd' + call assert_match('^a<c\+d$', s:get_statusline()) + exe 'set statusline=a' . repeat('b', &columns - 1) . '%<c' + call assert_match('^ab\+>$', s:get_statusline()) + + "%{: Evaluate expression between '%{' and '}' and substitute result. + syntax on + let s:expected_curbuf = string(bufnr('')) + let s:expected_curwin = string(win_getid()) + set statusline=%{SyntaxItem()} + call assert_match('^vimNumber\s*$', s:get_statusline()) + s/^/"/ + call assert_match('^vimLineComment\s*$', s:get_statusline()) + syntax off + + "%{%expr%}: evaluates expressions present in result of expr + func! Inner_eval() + return '%n some other text' + endfunc + func! Outer_eval() + return 'some text %{%Inner_eval()%}' + endfunc + set statusline=%{%Outer_eval()%} + call assert_match('^some text ' . bufnr() . ' some other text\s*$', s:get_statusline()) + delfunc Inner_eval + delfunc Outer_eval + + "%{%expr%}: Doesn't get stuck in recursion + func! Recurse_eval() + return '%{%Recurse_eval()%}' + endfunc + set statusline=%{%Recurse_eval()%} + call assert_match('^%{%Recurse_eval()%}\s*$', s:get_statusline()) + delfunc Recurse_eval + + "%(: Start of item group. + set statusline=ab%(cd%q%)de + call assert_match('^abde\s*$', s:get_statusline()) + copen + call assert_match('^abcd\[Quickfix List]de\s*$', s:get_statusline()) + cclose + + " %#: Set highlight group. The name must follow and then a # again. + set statusline=ab%#Todo#cd%#Error#ef + call assert_match('^abcdef\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 3) + let sa3=screenattr(&lines - 1, 5) + call assert_notequal(sa1, sa2) + call assert_notequal(sa1, sa3) + call assert_notequal(sa2, sa3) + call assert_equal(sa1, screenattr(&lines - 1, 2)) + call assert_equal(sa2, screenattr(&lines - 1, 4)) + call assert_equal(sa3, screenattr(&lines - 1, 6)) + call assert_equal(sa3, screenattr(&lines - 1, 7)) + + " %*: Set highlight group to User{N} + set statusline=a%1*b%0*c + call assert_match('^abc\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 2) + let sa3=screenattr(&lines - 1, 3) + call assert_equal(sa1, sa3) + call assert_notequal(sa1, sa2) + + " An empty group that contains highlight changes + let g:a = '' + set statusline=ab%(cd%1*%{g:a}%*%)de + call assert_match('^abde\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 4) + call assert_equal(sa1, sa2) + let g:a = 'X' + call assert_match('^abcdXde\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 5) + let sa3=screenattr(&lines - 1, 7) + call assert_equal(sa1, sa3) + call assert_notequal(sa1, sa2) + + let g:a = '' + set statusline=ab%1*%(cd%*%{g:a}%1*%)de + call assert_match('^abde\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 4) + call assert_notequal(sa1, sa2) + let g:a = 'X' + call assert_match('^abcdXde\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 3) + let sa3=screenattr(&lines - 1, 5) + let sa4=screenattr(&lines - 1, 7) + call assert_notequal(sa1, sa2) + call assert_equal(sa1, sa3) + call assert_equal(sa2, sa4) + + " An empty group that contains highlight changes and doesn't reset them + let g:a = '' + set statusline=ab%(cd%1*%{g:a}%)de + call assert_match('^abcdde\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 5) + call assert_notequal(sa1, sa2) + let g:a = 'X' + call assert_match('^abcdXde\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 5) + let sa3=screenattr(&lines - 1, 7) + call assert_notequal(sa1, sa2) + call assert_equal(sa2, sa3) + + let g:a = '' + set statusline=ab%1*%(cd%*%{g:a}%)de + call assert_match('^abcdde\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 3) + let sa3=screenattr(&lines - 1, 5) + call assert_notequal(sa1, sa2) + call assert_equal(sa1, sa3) + let g:a = 'X' + call assert_match('^abcdXde\s*$', s:get_statusline()) + let sa1=screenattr(&lines - 1, 1) + let sa2=screenattr(&lines - 1, 3) + let sa3=screenattr(&lines - 1, 5) + let sa4=screenattr(&lines - 1, 7) + call assert_notequal(sa1, sa2) + call assert_equal(sa1, sa3) + call assert_equal(sa1, sa4) + + let g:a = '' + set statusline=%#Error#{%(\ %{g:a}\ %)} + call assert_match('^{}\s*$', s:get_statusline()) + let g:a = 'X' + call assert_match('^{ X }\s*$', s:get_statusline()) + + " %%: a percent sign. + set statusline=10%% + call assert_match('^10%\s*$', s:get_statusline()) + + " %!: evaluated expression is used as the option value + set statusline=%!2*3+1 + call assert_match('7\s*$', s:get_statusline()) + + func GetNested() + call assert_equal(string(win_getid()), g:actual_curwin) + call assert_equal(string(bufnr('')), g:actual_curbuf) + return 'nested' + endfunc + func GetStatusLine() + call assert_equal(win_getid(), g:statusline_winid) + return 'the %{GetNested()} line' + endfunc + set statusline=%!GetStatusLine() + call assert_match('the nested line', s:get_statusline()) + call assert_false(exists('g:actual_curwin')) + call assert_false(exists('g:actual_curbuf')) + call assert_false(exists('g:statusline_winid')) + delfunc GetNested + delfunc GetStatusLine + + " Test statusline works with 80+ items + function! StatusLabel() + redrawstatus + return '[label]' + endfunc + let statusline = '%{StatusLabel()}' + for i in range(150) + let statusline .= '%#TabLine' . (i % 2 == 0 ? 'Fill' : 'Sel') . '#' . string(i)[0] + endfor + let &statusline = statusline + redrawstatus + set statusline& + delfunc StatusLabel + + + " Check statusline in current and non-current window + " with the 'fillchars' option. + set fillchars=stl:^,stlnc:=,vert:\|,fold:-,diff:- + vsplit + set statusline=x%=y + call assert_match('^x^\+y^x=\+y$', s:get_statusline()) + set fillchars& + close + + %bw! + call delete('Xstatusline') + set statusline& + set splitbelow& +endfunc + +func Test_statusline_trailing_percent_zero() + " this was causing illegal memory access + set laststatus=2 stl=%!%0 + call assert_fails('redraw', 'E15: Invalid expression: "%0"') + set laststatus& stl& +endfunc + +func Test_statusline_visual() + func CallWordcount() + call wordcount() + endfunc + new x1 + setl statusline=count=%{CallWordcount()} + " buffer must not be empty + call setline(1, 'hello') + + " window with more lines than x1 + new x2 + call setline(1, range(10)) + $ + " Visual mode in line below liast line in x1 should not give ml_get error + call feedkeys("\<C-V>", "xt") + redraw + + delfunc CallWordcount + bwipe! x1 + bwipe! x2 +endfunc + +func Test_statusline_removed_group() + if !CanRunVimInTerminal() + throw 'Skipped: cannot make screendumps' + endif + + let lines =<< trim END + scriptencoding utf-8 + set laststatus=2 + let &statusline = '%#StatColorHi2#%(✓%#StatColorHi2#%) Q≡' + END + call writefile(lines, 'XTest_statusline') + + let buf = RunVimInTerminal('-S XTest_statusline', {'rows': 10, 'cols': 50}) + call VerifyScreenDump(buf, 'Test_statusline_1', {}) + + " clean up + call StopVimInTerminal(buf) + call delete('XTest_statusline') +endfunc + +func Test_statusline_using_mode() + CheckScreendump + + let lines =<< trim END + setlocal statusline=-%{mode()}- + split + setlocal statusline=+%{mode()}+ + END + call writefile(lines, 'XTest_statusline') + + let buf = RunVimInTerminal('-S XTest_statusline', {'rows': 7, 'cols': 50}) + call VerifyScreenDump(buf, 'Test_statusline_mode_1', {}) + + call term_sendkeys(buf, ":") + call VerifyScreenDump(buf, 'Test_statusline_mode_2', {}) + + " clean up + call term_sendkeys(buf, "close\<CR>") + call StopVimInTerminal(buf) + call delete('XTest_statusline') +endfunc + +func Test_statusline_after_split_vsplit() + only + + " Make the status line of each window show the window number. + set ls=2 stl=%{winnr()} + + split | redraw + vsplit | redraw + + " The status line of the third window should read '3' here. + call assert_equal('3', nr2char(screenchar(&lines - 1, 1))) + + only + set ls& stl& +endfunc + +" Test using a multibyte character for 'stl' and 'stlnc' items in 'fillchars' +" with a custom 'statusline' +func Test_statusline_mbyte_fillchar() + only + set fillchars=vert:\|,fold:-,stl:━,stlnc:═ + set statusline=a%=b + call assert_match('^a\+━\+b$', s:get_statusline()) + vnew + call assert_match('^a\+━\+b━a\+═\+b$', s:get_statusline()) + wincmd w + call assert_match('^a\+═\+b═a\+━\+b$', s:get_statusline()) + set statusline& fillchars& + %bw! +endfunc + +" Used to write beyond allocated memory. This assumes MAXPATHL is 4096 bytes. +func Test_statusline_verylong_filename() + let fname = repeat('x', 4090) + " Nvim's swap file creation fails on Windows (E303) due to fname's length + " exe "new " .. fname + exe "noswapfile new " .. fname + set buftype=help + set previewwindow + redraw + bwipe! +endfunc + +func Test_statusline_highlight_truncate() + CheckScreendump + + let lines =<< trim END + set laststatus=2 + hi! link User1 Directory + hi! link User2 ErrorMsg + set statusline=%.5(%1*ABC%2*DEF%1*GHI%) + END + call writefile(lines, 'XTest_statusline') + + let buf = RunVimInTerminal('-S XTest_statusline', {'rows': 6}) + call VerifyScreenDump(buf, 'Test_statusline_hl', {}) + + call StopVimInTerminal(buf) + call delete('XTest_statusline') +endfunc + +func Test_statusline_showcmd() + CheckScreendump + + let lines =<< trim END + func MyStatusLine() + return '%S' + endfunc + + set laststatus=2 + set statusline=%!MyStatusLine() + set showcmdloc=statusline + call setline(1, ['a', 'b', 'c']) + set foldopen+=jump + 1,2fold + 3 + END + call writefile(lines, 'XTest_statusline', 'D') + + let buf = RunVimInTerminal('-S XTest_statusline', {'rows': 6}) + + call term_sendkeys(buf, "g") + call VerifyScreenDump(buf, 'Test_statusline_showcmd_1', {}) + + " typing "gg" should open the fold + call term_sendkeys(buf, "g") + call VerifyScreenDump(buf, 'Test_statusline_showcmd_2', {}) + + call term_sendkeys(buf, "\<C-V>Gl") + call VerifyScreenDump(buf, 'Test_statusline_showcmd_3', {}) + + call term_sendkeys(buf, "\<Esc>1234") + call VerifyScreenDump(buf, 'Test_statusline_showcmd_4', {}) + + call term_sendkeys(buf, "\<Esc>:set statusline=\<CR>") + call term_sendkeys(buf, ":\<CR>") + call term_sendkeys(buf, "1234") + call VerifyScreenDump(buf, 'Test_statusline_showcmd_5', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_statusline_highlight_group_cleared() + CheckScreendump + + " the laststatus option is there to prevent + " the code-style test from complaining about + " trailing whitespace + let lines =<< trim END + set fillchars=stl:\ ,stlnc:\ laststatus=2 + split + hi clear StatusLine + hi clear StatusLineNC + END + call writefile(lines, 'XTest_statusline_stl', 'D') + + let buf = RunVimInTerminal('-S XTest_statusline_stl', {}) + + call VerifyScreenDump(buf, 'Test_statusline_stl_1', {}) + + call StopVimInTerminal(buf) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_substitute.vim b/test/old/testdir/test_substitute.vim new file mode 100644 index 0000000000..a9e317da02 --- /dev/null +++ b/test/old/testdir/test_substitute.vim @@ -0,0 +1,1502 @@ +" Tests for the substitute (:s) command + +source shared.vim +source check.vim +source screendump.vim + +" NOTE: This needs to be the first test to be +" run in the file, since it depends on +" that the previous substitution atom +" was not yet set. +" +" recursive call of :s and sub-replace special +" (did cause heap-use-after free in < v9.0.2121) +func Test_aaaa_substitute_expr_recursive_special() + func R() + " FIXME: leaving out the 'n' flag leaks memory, why? + %s/./\='.'/gn + endfunc + new Xfoobar_UAF + put ='abcdef' + let bufnr = bufnr('%') + try + silent! :s/./~\=R()/0 + "call assert_fails(':s/./~\=R()/0', 'E939:') + let @/='.' + ~g + catch /^Vim\%((\a\+)\)\=:E565:/ + endtry + delfunc R + exe bufnr .. "bw!" +endfunc + +func Test_multiline_subst() + enew! + call append(0, ["1 aa", + \ "bb", + \ "cc", + \ "2 dd", + \ "ee", + \ "3 ef", + \ "gh", + \ "4 ij", + \ "5 a8", + \ "8b c9", + \ "9d", + \ "6 e7", + \ "77f", + \ "xxxxx"]) + + 1 + " test if replacing a line break works with a back reference + /^1/,/^2/s/\n\(.\)/ \1/ + " test if inserting a line break works with a back reference + /^3/,/^4/s/\(.\)$/\r\1/ + " test if replacing a line break with another line break works + /^5/,/^6/s/\(\_d\{3}\)/x\1x/ + call assert_equal('1 aa bb cc 2 dd ee', getline(1)) + call assert_equal('3 e', getline(2)) + call assert_equal('f', getline(3)) + call assert_equal('g', getline(4)) + call assert_equal('h', getline(5)) + call assert_equal('4 i', getline(6)) + call assert_equal('j', getline(7)) + call assert_equal('5 ax8', getline(8)) + call assert_equal('8xb cx9', getline(9)) + call assert_equal('9xd', getline(10)) + call assert_equal('6 ex7', getline(11)) + call assert_equal('7x7f', getline(12)) + call assert_equal('xxxxx', getline(13)) + enew! +endfunc + +func Test_substitute_variants() + " Validate that all the 2-/3-letter variants which embed the flags into the + " command name actually work. + enew! + let ln = 'Testing string' + let variants = [ + \ { 'cmd': ':s/Test/test/c', 'exp': 'testing string', 'prompt': 'y' }, + \ { 'cmd': ':s/foo/bar/ce', 'exp': ln }, + \ { 'cmd': ':s/t/r/cg', 'exp': 'Tesring srring', 'prompt': 'a' }, + \ { 'cmd': ':s/t/r/ci', 'exp': 'resting string', 'prompt': 'y' }, + \ { 'cmd': ':s/t/r/cI', 'exp': 'Tesring string', 'prompt': 'y' }, + \ { 'cmd': ':s/t/r/c', 'exp': 'Testing string', 'prompt': 'n' }, + \ { 'cmd': ':s/t/r/cn', 'exp': ln }, + \ { 'cmd': ':s/t/r/cp', 'exp': 'Tesring string', 'prompt': 'y' }, + \ { 'cmd': ':s/t/r/cl', 'exp': 'Tesring string', 'prompt': 'y' }, + \ { 'cmd': ':s/t/r/gc', 'exp': 'Tesring srring', 'prompt': 'a' }, + \ { 'cmd': ':s/i/I/gc', 'exp': 'TestIng string', 'prompt': 'l' }, + \ { 'cmd': ':s/foo/bar/ge', 'exp': ln }, + \ { 'cmd': ':s/t/r/g', 'exp': 'Tesring srring' }, + \ { 'cmd': ':s/t/r/gi', 'exp': 'resring srring' }, + \ { 'cmd': ':s/t/r/gI', 'exp': 'Tesring srring' }, + \ { 'cmd': ':s/t/r/gn', 'exp': ln }, + \ { 'cmd': ':s/t/r/gp', 'exp': 'Tesring srring' }, + \ { 'cmd': ':s/t/r/gl', 'exp': 'Tesring srring' }, + \ { 'cmd': ':s//r/gr', 'exp': 'Testr strr' }, + \ { 'cmd': ':s/t/r/ic', 'exp': 'resting string', 'prompt': 'y' }, + \ { 'cmd': ':s/foo/bar/ie', 'exp': ln }, + \ { 'cmd': ':s/t/r/i', 'exp': 'resting string' }, + \ { 'cmd': ':s/t/r/iI', 'exp': 'Tesring string' }, + \ { 'cmd': ':s/t/r/in', 'exp': ln }, + \ { 'cmd': ':s/t/r/ip', 'exp': 'resting string' }, + \ { 'cmd': ':s//r/ir', 'exp': 'Testr string' }, + \ { 'cmd': ':s/t/r/Ic', 'exp': 'Tesring string', 'prompt': 'y' }, + \ { 'cmd': ':s/foo/bar/Ie', 'exp': ln }, + \ { 'cmd': ':s/t/r/Ig', 'exp': 'Tesring srring' }, + \ { 'cmd': ':s/t/r/Ii', 'exp': 'resting string' }, + \ { 'cmd': ':s/t/r/I', 'exp': 'Tesring string' }, + \ { 'cmd': ':s/t/r/Ip', 'exp': 'Tesring string' }, + \ { 'cmd': ':s/t/r/Il', 'exp': 'Tesring string' }, + \ { 'cmd': ':s//r/Ir', 'exp': 'Testr string' }, + \ { 'cmd': ':s//r/rc', 'exp': 'Testr string', 'prompt': 'y' }, + \ { 'cmd': ':s//r/rg', 'exp': 'Testr strr' }, + \ { 'cmd': ':s//r/ri', 'exp': 'Testr string' }, + \ { 'cmd': ':s//r/rI', 'exp': 'Testr string' }, + \ { 'cmd': ':s//r/rn', 'exp': 'Testing string' }, + \ { 'cmd': ':s//r/rp', 'exp': 'Testr string' }, + \ { 'cmd': ':s//r/rl', 'exp': 'Testr string' }, + \ { 'cmd': ':s//r/r', 'exp': 'Testr string' }, + \ { 'cmd': ':s/i/I/gc', 'exp': 'Testing string', 'prompt': 'q' }, + \] + + for var in variants + for run in [1, 2] + let cmd = var.cmd + if run == 2 && cmd =~ "/.*/.*/." + " Change :s/from/to/{flags} to :s{flags} + let cmd = substitute(cmd, '/.*/', '', '') + endif + call setline(1, [ln]) + let msg = printf('using "%s"', cmd) + let @/='ing' + let v:errmsg = '' + call feedkeys(cmd . "\<CR>" . get(var, 'prompt', ''), 'ntx') + " No error should exist (matters for testing e flag) + call assert_equal('', v:errmsg, msg) + call assert_equal(var.exp, getline('.'), msg) + endfor + endfor +endfunc + +" Test the l, p, # flags. +func Test_substitute_flags_lp() + new + call setline(1, "abc\tdef\<C-h>ghi") + + let a = execute('s/a/a/p') + call assert_equal("\nabc def^Hghi", a) + + let a = execute('s/a/a/l') + call assert_equal("\nabc^Idef^Hghi$", a) + + let a = execute('s/a/a/#') + call assert_equal("\n 1 abc def^Hghi", a) + + let a = execute('s/a/a/p#') + call assert_equal("\n 1 abc def^Hghi", a) + + let a = execute('s/a/a/l#') + call assert_equal("\n 1 abc^Idef^Hghi$", a) + + let a = execute('s/a/a/') + call assert_equal("", a) + + bwipe! +endfunc + +func Test_substitute_repeat() + " This caused an invalid memory access. + split Xfile + s/^/x + call feedkeys("Qsc\<CR>y", 'tx') + bwipe! +endfunc +" Test %s/\n// which is implemented as a special case to use a +" more efficient join rather than doing a regular substitution. +func Test_substitute_join() + new + + call setline(1, ["foo\tbar", "bar\<C-H>foo"]) + let a = execute('%s/\n//') + call assert_equal("", a) + call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$')) + call assert_equal('\n', histget("search", -1)) + + call setline(1, ["foo\tbar", "bar\<C-H>foo"]) + let a = execute('%s/\n//g') + call assert_equal("", a) + call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$')) + call assert_equal('\n', histget("search", -1)) + + call setline(1, ["foo\tbar", "bar\<C-H>foo"]) + let a = execute('%s/\n//p') + call assert_equal("\nfoo barbar^Hfoo", a) + call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$')) + call assert_equal('\n', histget("search", -1)) + + call setline(1, ["foo\tbar", "bar\<C-H>foo"]) + let a = execute('%s/\n//l') + call assert_equal("\nfoo^Ibarbar^Hfoo$", a) + call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$')) + call assert_equal('\n', histget("search", -1)) + + call setline(1, ["foo\tbar", "bar\<C-H>foo"]) + let a = execute('%s/\n//#') + call assert_equal("\n 1 foo barbar^Hfoo", a) + call assert_equal(["foo\tbarbar\<C-H>foo"], getline(1, '$')) + call assert_equal('\n', histget("search", -1)) + + call setline(1, ['foo', 'bar', 'baz', 'qux']) + call execute('1,2s/\n//') + call assert_equal(['foobarbaz', 'qux'], getline(1, '$')) + + bwipe! +endfunc + +func Test_substitute_count() + new + call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo']) + 2 + + s/foo/bar/3 + call assert_equal(['foo foo', 'bar foo', 'bar foo', 'bar foo', 'foo foo'], + \ getline(1, '$')) + + call assert_fails('s/foo/bar/0', 'E939:') + + call setline(1, ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo']) + 2,4s/foo/bar/ 10 + call assert_equal(['foo foo', 'foo foo', 'foo foo', 'bar foo', 'bar foo'], + \ getline(1, '$')) + + call assert_fails('s/./b/2147483647', 'E1510:') + bwipe! +endfunc + +" Test substitute 'n' flag (report number of matches, do not substitute). +func Test_substitute_flag_n() + new + let lines = ['foo foo', 'foo foo', 'foo foo', 'foo foo', 'foo foo'] + call setline(1, lines) + + call assert_equal("\n3 matches on 3 lines", execute('2,4s/foo/bar/n')) + call assert_equal("\n6 matches on 3 lines", execute('2,4s/foo/bar/gn')) + + " c flag (confirm) should be ignored when using n flag. + call assert_equal("\n3 matches on 3 lines", execute('2,4s/foo/bar/nc')) + + " No substitution should have been done. + call assert_equal(lines, getline(1, '$')) + + %delete _ + call setline(1, ['A', 'Bar', 'Baz']) + call assert_equal("\n1 match on 1 line", execute('s/\nB\@=//gn')) + + bwipe! +endfunc + +func Test_substitute_errors() + new + call setline(1, 'foobar') + + call assert_fails('s/FOO/bar/', 'E486:') + call assert_fails('s/foo/bar/@', 'E488:') + call assert_fails('s/\(/bar/', 'E54:') + call assert_fails('s afooabara', 'E146:') + call assert_fails('s\\a', 'E10:') + + setl nomodifiable + call assert_fails('s/foo/bar/', 'E21:') + + call assert_fails("let s=substitute([], 'a', 'A', 'g')", 'E730:') + call assert_fails("let s=substitute('abcda', [], 'A', 'g')", 'E730:') + call assert_fails("let s=substitute('abcda', 'a', [], 'g')", 'E730:') + call assert_fails("let s=substitute('abcda', 'a', 'A', [])", 'E730:') + call assert_fails("let s=substitute('abc', '\\%(', 'A', 'g')", 'E53:') + + bwipe! +endfunc + +" Test for *sub-replace-special* and *sub-replace-expression* on substitute(). +func Test_sub_replace_1() + " Run the tests with 'magic' on + set magic + set cpo& + call assert_equal('AA', substitute('A', 'A', '&&', '')) + call assert_equal('&', substitute('B', 'B', '\&', '')) + call assert_equal('C123456789987654321', substitute('C123456789', 'C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', '\0\9\8\7\6\5\4\3\2\1', '')) + call assert_equal('d', substitute('D', 'D', 'd', '')) + call assert_equal('~', substitute('E', 'E', '~', '')) + call assert_equal('~', substitute('F', 'F', '\~', '')) + call assert_equal('Gg', substitute('G', 'G', '\ugg', '')) + call assert_equal('Hh', substitute('H', 'H', '\Uh\Eh', '')) + call assert_equal('iI', substitute('I', 'I', '\lII', '')) + call assert_equal('jJ', substitute('J', 'J', '\LJ\EJ', '')) + call assert_equal('Kk', substitute('K', 'K', '\Uk\ek', '')) + call assert_equal("l\<C-V>\<C-M>l", + \ substitute('lLl', 'L', "\<C-V>\<C-M>", '')) + call assert_equal("m\<C-M>m", substitute('mMm', 'M', '\r', '')) + call assert_equal("n\<C-V>\<C-M>n", + \ substitute('nNn', 'N', "\\\<C-V>\<C-M>", '')) + call assert_equal("o\no", substitute('oOo', 'O', '\n', '')) + call assert_equal("p\<C-H>p", substitute('pPp', 'P', '\b', '')) + call assert_equal("q\tq", substitute('qQq', 'Q', '\t', '')) + call assert_equal('r\r', substitute('rRr', 'R', '\\', '')) + call assert_equal('scs', substitute('sSs', 'S', '\c', '')) + call assert_equal("u\nu", substitute('uUu', 'U', "\n", '')) + call assert_equal("v\<C-H>v", substitute('vVv', 'V', "\b", '')) + call assert_equal("w\\w", substitute('wWw', 'W', "\\", '')) + call assert_equal("x\<C-M>x", substitute('xXx', 'X', "\r", '')) + call assert_equal("YyyY", substitute('Y', 'Y', '\L\uyYy\l\EY', '')) + call assert_equal("zZZz", substitute('Z', 'Z', '\U\lZzZ\u\Ez', '')) + " \v or \V after $ + call assert_equal('abxx', substitute('abcd', 'xy$\v|cd$', 'xx', '')) + call assert_equal('abxx', substitute('abcd', 'xy$\V\|cd\$', 'xx', '')) +endfunc + +func Test_sub_replace_2() + " Run the tests with 'magic' off + set nomagic + set cpo& + call assert_equal('AA', substitute('A', 'A', '&&', '')) + call assert_equal('&', substitute('B', 'B', '\&', '')) + call assert_equal('C123456789987654321', substitute('C123456789', 'C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', '\0\9\8\7\6\5\4\3\2\1', '')) + call assert_equal('d', substitute('D', 'D', 'd', '')) + call assert_equal('~', substitute('E', 'E', '~', '')) + call assert_equal('~', substitute('F', 'F', '\~', '')) + call assert_equal('Gg', substitute('G', 'G', '\ugg', '')) + call assert_equal('Hh', substitute('H', 'H', '\Uh\Eh', '')) + call assert_equal('iI', substitute('I', 'I', '\lII', '')) + call assert_equal('jJ', substitute('J', 'J', '\LJ\EJ', '')) + call assert_equal('Kk', substitute('K', 'K', '\Uk\ek', '')) + call assert_equal("l\<C-V>\<C-M>l", + \ substitute('lLl', 'L', "\<C-V>\<C-M>", '')) + call assert_equal("m\<C-M>m", substitute('mMm', 'M', '\r', '')) + call assert_equal("n\<C-V>\<C-M>n", + \ substitute('nNn', 'N', "\\\<C-V>\<C-M>", '')) + call assert_equal("o\no", substitute('oOo', 'O', '\n', '')) + call assert_equal("p\<C-H>p", substitute('pPp', 'P', '\b', '')) + call assert_equal("q\tq", substitute('qQq', 'Q', '\t', '')) + call assert_equal('r\r', substitute('rRr', 'R', '\\', '')) + call assert_equal('scs', substitute('sSs', 'S', '\c', '')) + call assert_equal("t\<C-M>t", substitute('tTt', 'T', "\r", '')) + call assert_equal("u\nu", substitute('uUu', 'U', "\n", '')) + call assert_equal("v\<C-H>v", substitute('vVv', 'V', "\b", '')) + call assert_equal('w\w', substitute('wWw', 'W', "\\", '')) + call assert_equal('XxxX', substitute('X', 'X', '\L\uxXx\l\EX', '')) + call assert_equal('yYYy', substitute('Y', 'Y', '\U\lYyY\u\Ey', '')) +endfunc + +func Test_sub_replace_3() + set magic& + set cpo& + call assert_equal('a\a', substitute('aAa', 'A', '\="\\"', '')) + call assert_equal('b\\b', substitute('bBb', 'B', '\="\\\\"', '')) + call assert_equal("c\rc", substitute('cCc', 'C', "\\=\"\r\"", '')) + call assert_equal("d\\\rd", substitute('dDd', 'D', "\\=\"\\\\\r\"", '')) + call assert_equal("e\\\\\re", substitute('eEe', 'E', "\\=\"\\\\\\\\\r\"", '')) + call assert_equal('f\rf', substitute('fFf', 'F', '\="\\r"', '')) + call assert_equal('j\nj', substitute('jJj', 'J', '\="\\n"', '')) + call assert_equal("k\<C-M>k", substitute('kKk', 'K', '\="\r"', '')) + call assert_equal("l\nl", substitute('lLl', 'L', '\="\n"', '')) +endfunc + +" Test for submatch() on substitute(). +func Test_sub_replace_4() + set magic& + set cpo& + call assert_equal('a\a', substitute('aAa', 'A', + \ '\=substitute(submatch(0), ".", "\\", "")', '')) + call assert_equal('b\b', substitute('bBb', 'B', + \ '\=substitute(submatch(0), ".", "\\\\", "")', '')) + call assert_equal("c\<C-V>\<C-M>c", substitute('cCc', 'C', '\=substitute(submatch(0), ".", "\<C-V>\<C-M>", "")', '')) + call assert_equal("d\<C-V>\<C-M>d", substitute('dDd', 'D', '\=substitute(submatch(0), ".", "\\\<C-V>\<C-M>", "")', '')) + call assert_equal("e\\\<C-V>\<C-M>e", substitute('eEe', 'E', '\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-M>", "")', '')) + call assert_equal("f\<C-M>f", substitute('fFf', 'F', '\=substitute(submatch(0), ".", "\\r", "")', '')) + call assert_equal("j\nj", substitute('jJj', 'J', '\=substitute(submatch(0), ".", "\\n", "")', '')) + call assert_equal("k\rk", substitute('kKk', 'K', '\=substitute(submatch(0), ".", "\r", "")', '')) + call assert_equal("l\nl", substitute('lLl', 'L', '\=substitute(submatch(0), ".", "\n", "")', '')) +endfunc + +func Test_sub_replace_5() + set magic& + set cpo& + call assert_equal('A123456789987654321', substitute('A123456789', + \ 'A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', + \ '\=submatch(0) . submatch(9) . submatch(8) . ' . + \ 'submatch(7) . submatch(6) . submatch(5) . ' . + \ 'submatch(4) . submatch(3) . submatch(2) . submatch(1)', + \ '')) + call assert_equal("[['A123456789'], ['9'], ['8'], ['7'], ['6'], " . + \ "['5'], ['4'], ['3'], ['2'], ['1']]", + \ substitute('A123456789', + \ 'A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', + \ '\=string([submatch(0, 1), submatch(9, 1), ' . + \ 'submatch(8, 1), 7->submatch(1), submatch(6, 1), ' . + \ 'submatch(5, 1), submatch(4, 1), submatch(3, 1), ' . + \ 'submatch(2, 1), submatch(1, 1)])', + \ '')) +endfunc + +func Test_sub_replace_6() + set magic& + " Nvim: no "/" flag in 'cpoptions'. + " set cpo+=/ + call assert_equal('a', substitute('A', 'A', 'a', '')) + call assert_equal('%', substitute('B', 'B', '%', '')) + set cpo-=/ + call assert_equal('c', substitute('C', 'C', 'c', '')) + call assert_equal('%', substitute('D', 'D', '%', '')) +endfunc + +func Test_sub_replace_7() + set magic& + set cpo& + call assert_equal('AA', substitute('AA', 'A.', '\=submatch(0)', '')) + call assert_equal("B\nB", substitute("B\nB", 'B.', '\=submatch(0)', '')) + call assert_equal("['B\n']B", substitute("B\nB", 'B.', '\=string(submatch(0, 1))', '')) + call assert_equal('-abab', substitute('-bb', '\zeb', 'a', 'g')) + call assert_equal('c-cbcbc', substitute('-bb', '\ze', 'c', 'g')) +endfunc + +" Test for *:s%* on :substitute. +func Test_sub_replace_8() + new + set magic& + set cpo& + $put =',,X' + s/\(^\|,\)\ze\(,\|X\)/\1N/g + call assert_equal('N,,NX', getline("$")) + $put =',,Y' + let cmd = ':s/\(^\|,\)\ze\(,\|Y\)/\1N/gc' + call feedkeys(cmd . "\<CR>a", "xt") + call assert_equal('N,,NY', getline("$")) + :$put =',,Z' + let cmd = ':s/\(^\|,\)\ze\(,\|Z\)/\1N/gc' + call feedkeys(cmd . "\<CR>yy", "xt") + call assert_equal('N,,NZ', getline("$")) + enew! | close +endfunc + +func Test_sub_replace_9() + new + set magic& + set cpo& + $put ='xxx' + call feedkeys(":s/x/X/gc\<CR>yyq", "xt") + call assert_equal('XXx', getline("$")) + enew! | close +endfunc + +func Test_sub_replace_10() + set magic& + set cpo& + call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g')) + call assert_equal('aaa', substitute('123', '\zs.', 'a', 'g')) + call assert_equal('1a2a3a', substitute('123', '.\zs', 'a', 'g')) + call assert_equal('a1a2a3a', substitute('123', '\ze', 'a', 'g')) + call assert_equal('a1a2a3', substitute('123', '\ze.', 'a', 'g')) + call assert_equal('aaa', substitute('123', '.\ze', 'a', 'g')) + call assert_equal('aa2a3a', substitute('123', '1\|\ze', 'a', 'g')) + call assert_equal('1aaa', substitute('123', '1\zs\|[23]', 'a', 'g')) +endfunc + +func SubReplacer(text, submatches) + return a:text .. a:submatches[0] .. a:text +endfunc +func SubReplacerVar(text, ...) + return a:text .. a:1[0] .. a:text +endfunc +func SubReplacer20(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19, submatches) + return a:t3 .. a:submatches[0] .. a:t11 +endfunc + +func Test_substitute_partial() + call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacer', ['foo']), 'g')) + call assert_equal('1foo2foo3', substitute('123', '2', function('SubReplacerVar', ['foo']), 'g')) + + " 19 arguments plus one is just OK + let Replacer = function('SubReplacer20', repeat(['foo'], 19)) + call assert_equal('1foo2foo3', substitute('123', '2', Replacer, 'g')) + + " 20 arguments plus one is too many + let Replacer = function('SubReplacer20', repeat(['foo'], 20)) + call assert_fails("call substitute('123', '2', Replacer, 'g')", 'E118:') +endfunc + +func Test_substitute_float() + CheckFeature float + + call assert_equal('number 1.23', substitute('number ', '$', { -> 1.23 }, '')) + " vim9 assert_equal('number 1.23', substitute('number ', '$', () => 1.23, '')) +endfunc + +" Tests for *sub-replace-special* and *sub-replace-expression* on :substitute. + +" Execute a list of :substitute command tests +func Run_SubCmd_Tests(tests) + enew! + for t in a:tests + let start = line('.') + 1 + let end = start + len(t[2]) - 1 + exe "normal o" . t[0] + call cursor(start, 1) + exe t[1] + call assert_equal(t[2], getline(start, end), t[1]) + endfor + enew! +endfunc + +func Test_sub_cmd_1() + set magic + set cpo& + + " List entry format: [input, cmd, output] + let tests = [['A', 's/A/&&/', ['AA']], + \ ['B', 's/B/\&/', ['&']], + \ ['C123456789', 's/C\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']], + \ ['D', 's/D/d/', ['d']], + \ ['E', 's/E/~/', ['d']], + \ ['F', 's/F/\~/', ['~']], + \ ['G', 's/G/\ugg/', ['Gg']], + \ ['H', 's/H/\Uh\Eh/', ['Hh']], + \ ['I', 's/I/\lII/', ['iI']], + \ ['J', 's/J/\LJ\EJ/', ['jJ']], + \ ['K', 's/K/\Uk\ek/', ['Kk']], + \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']], + \ ['mMm', 's/M/\r/', ['m', 'm']], + \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']], + \ ['oOo', 's/O/\n/', ["o\no"]], + \ ['pPp', 's/P/\b/', ["p\<C-H>p"]], + \ ['qQq', 's/Q/\t/', ["q\tq"]], + \ ['rRr', 's/R/\\/', ['r\r']], + \ ['sSs', 's/S/\c/', ['scs']], + \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]], + \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']], + \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']], + \ ['\', 's/\\/\\\\/', ['\\']] + \ ] + call Run_SubCmd_Tests(tests) +endfunc + +func Test_sub_cmd_2() + set nomagic + set cpo& + + " List entry format: [input, cmd, output] + let tests = [['A', 's/A/&&/', ['&&']], + \ ['B', 's/B/\&/', ['B']], + \ ['C123456789', 's/\mC\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\0\9\8\7\6\5\4\3\2\1/', ['C123456789987654321']], + \ ['D', 's/D/d/', ['d']], + \ ['E', 's/E/~/', ['~']], + \ ['F', 's/F/\~/', ['~']], + \ ['G', 's/G/\ugg/', ['Gg']], + \ ['H', 's/H/\Uh\Eh/', ['Hh']], + \ ['I', 's/I/\lII/', ['iI']], + \ ['J', 's/J/\LJ\EJ/', ['jJ']], + \ ['K', 's/K/\Uk\ek/', ['Kk']], + \ ['lLl', "s/L/\<C-V>\<C-M>/", ["l\<C-V>", 'l']], + \ ['mMm', 's/M/\r/', ['m', 'm']], + \ ['nNn', "s/N/\\\<C-V>\<C-M>/", ["n\<C-V>", 'n']], + \ ['oOo', 's/O/\n/', ["o\no"]], + \ ['pPp', 's/P/\b/', ["p\<C-H>p"]], + \ ['qQq', 's/Q/\t/', ["q\tq"]], + \ ['rRr', 's/R/\\/', ['r\r']], + \ ['sSs', 's/S/\c/', ['scs']], + \ ['tTt', "s/T/\<C-V>\<C-J>/", ["t\<C-V>\<C-J>t"]], + \ ['U', 's/U/\L\uuUu\l\EU/', ['UuuU']], + \ ['V', 's/V/\U\lVvV\u\Ev/', ['vVVv']], + \ ['\', 's/\\/\\\\/', ['\\']] + \ ] + call Run_SubCmd_Tests(tests) +endfunc + +func Test_sub_cmd_3() + set nomagic + set cpo& + + " List entry format: [input, cmd, output] + let tests = [['aAa', "s/A/\\='\\'/", ['a\a']], + \ ['bBb', "s/B/\\='\\\\'/", ['b\\b']], + \ ['cCc', "s/C/\\='\<C-V>\<C-M>'/", ["c\<C-V>", 'c']], + \ ['dDd', "s/D/\\='\\\<C-V>\<C-M>'/", ["d\\\<C-V>", 'd']], + \ ['eEe', "s/E/\\='\\\\\<C-V>\<C-M>'/", ["e\\\\\<C-V>", 'e']], + \ ['fFf', "s/F/\\='\r'/", ['f', 'f']], + \ ['gGg', "s/G/\\='\<C-V>\<C-J>'/", ["g\<C-V>", 'g']], + \ ['hHh', "s/H/\\='\\\<C-V>\<C-J>'/", ["h\\\<C-V>", 'h']], + \ ['iIi', "s/I/\\='\\\\\<C-V>\<C-J>'/", ["i\\\\\<C-V>", 'i']], + \ ['jJj', "s/J/\\='\n'/", ['j', 'j']], + \ ['kKk', 's/K/\="\r"/', ['k', 'k']], + \ ['lLl', 's/L/\="\n"/', ['l', 'l']] + \ ] + call Run_SubCmd_Tests(tests) +endfunc + +" Test for submatch() on :substitute. +func Test_sub_cmd_4() + set magic& + set cpo& + + " List entry format: [input, cmd, output] + let tests = [ ['aAa', "s/A/\\=substitute(submatch(0), '.', '\\', '')/", + \ ['a\a']], + \ ['bBb', "s/B/\\=substitute(submatch(0), '.', '\\', '')/", + \ ['b\b']], + \ ['cCc', "s/C/\\=substitute(submatch(0), '.', '\<C-V>\<C-M>', '')/", + \ ["c\<C-V>", 'c']], + \ ['dDd', "s/D/\\=substitute(submatch(0), '.', '\\\<C-V>\<C-M>', '')/", + \ ["d\<C-V>", 'd']], + \ ['eEe', "s/E/\\=substitute(submatch(0), '.', '\\\\\<C-V>\<C-M>', '')/", + \ ["e\\\<C-V>", 'e']], + \ ['fFf', "s/F/\\=substitute(submatch(0), '.', '\\r', '')/", + \ ['f', 'f']], + \ ['gGg', 's/G/\=substitute(submatch(0), ".", "\<C-V>\<C-J>", "")/', + \ ["g\<C-V>", 'g']], + \ ['hHh', 's/H/\=substitute(submatch(0), ".", "\\\<C-V>\<C-J>", "")/', + \ ["h\<C-V>", 'h']], + \ ['iIi', 's/I/\=substitute(submatch(0), ".", "\\\\\<C-V>\<C-J>", "")/', + \ ["i\\\<C-V>", 'i']], + \ ['jJj', "s/J/\\=substitute(submatch(0), '.', '\\n', '')/", + \ ['j', 'j']], + \ ['kKk', "s/K/\\=substitute(submatch(0), '.', '\\r', '')/", + \ ['k', 'k']], + \ ['lLl', "s/L/\\=substitute(submatch(0), '.', '\\n', '')/", + \ ['l', 'l']], + \ ] + call Run_SubCmd_Tests(tests) +endfunc + +func Test_sub_cmd_5() + set magic& + set cpo& + + " List entry format: [input, cmd, output] + let tests = [ ['A123456789', 's/A\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\=submatch(0) . submatch(9) . submatch(8) . submatch(7) . submatch(6) . submatch(5) . submatch(4) . submatch(3) . submatch(2) . submatch(1)/', ['A123456789987654321']], + \ ['B123456789', 's/B\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)/\=string([submatch(0, 1), submatch(9, 1), submatch(8, 1), submatch(7, 1), submatch(6, 1), submatch(5, 1), submatch(4, 1), submatch(3, 1), submatch(2, 1), submatch(1, 1)])/', ["[['B123456789'], ['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'], ['2'], ['1']]"]], + \ ] + call Run_SubCmd_Tests(tests) +endfunc + +" Test for *:s%* on :substitute. +func Test_sub_cmd_6() + set magic& + " Nvim: no "/" flag in 'cpoptions'. + " set cpo+=/ + + " List entry format: [input, cmd, output] + let tests = [ ['A', 's/A/a/', ['a']], + \ ['B', 's/B/%/', ['a']], + \ ] + " call Run_SubCmd_Tests(tests) + + set cpo-=/ + let tests = [ ['C', 's/C/c/', ['c']], + \ ['D', 's/D/%/', ['%']], + \ ] + call Run_SubCmd_Tests(tests) + + set cpo& +endfunc + +" Test for :s replacing \n with line break. +func Test_sub_cmd_7() + set magic& + set cpo& + + " List entry format: [input, cmd, output] + let tests = [ ["A\<C-V>\<C-M>A", 's/A./\=submatch(0)/', ['A', 'A']], + \ ["B\<C-V>\<C-J>B", 's/B./\=submatch(0)/', ['B', 'B']], + \ ["C\<C-V>\<C-J>C", 's/C./\=strtrans(string(submatch(0, 1)))/', [strtrans("['C\<C-J>']C")]], + \ ["D\<C-V>\<C-J>\nD", 's/D.\nD/\=strtrans(string(submatch(0, 1)))/', [strtrans("['D\<C-J>', 'D']")]], + \ ["E\<C-V>\<C-J>\n\<C-V>\<C-J>\n\<C-V>\<C-J>\n\<C-V>\<C-J>\n\<C-V>\<C-J>E", 's/E\_.\{-}E/\=strtrans(string(submatch(0, 1)))/', [strtrans("['E\<C-J>', '\<C-J>', '\<C-J>', '\<C-J>', '\<C-J>E']")]], + \ ] + call Run_SubCmd_Tests(tests) + + exe "normal oQ\nQ\<Esc>k" + call assert_fails('s/Q[^\n]Q/\=submatch(0)."foobar"/', 'E486') + enew! +endfunc + +func TitleString() + let check = 'foo' =~ 'bar' + return "" +endfunc + +func Test_sub_cmd_8() + set titlestring=%{TitleString()} + + enew! + call append(0, ['', 'test_one', 'test_two']) + call cursor(1,1) + /^test_one/s/.*/\="foo\nbar"/ + call assert_equal('foo', getline(2)) + call assert_equal('bar', getline(3)) + call feedkeys(':/^test_two/s/.*/\="foo\nbar"/c', "t") + call feedkeys("\<CR>y", "xt") + call assert_equal('foo', getline(4)) + call assert_equal('bar', getline(5)) + + enew! + set titlestring& +endfunc + +func Test_sub_cmd_9() + new + let input = ['1 aaa', '2 aaa', '3 aaa'] + call setline(1, input) + func Foo() + return submatch(0) + endfunc + %s/aaa/\=Foo()/gn + call assert_equal(input, getline(1, '$')) + call assert_equal(1, &modifiable) + + delfunc Foo + bw! +endfunc + +func Test_sub_highlight_zero_match() + CheckRunVimInTerminal + + let lines =<< trim END + call setline(1, ['one', 'two', 'three']) + END + call writefile(lines, 'XscriptSubHighlight', 'D') + let buf = RunVimInTerminal('-S XscriptSubHighlight', #{rows: 8, cols: 60}) + call term_sendkeys(buf, ":%s/^/ /c\<CR>") + call VerifyScreenDump(buf, 'Test_sub_highlight_zer_match_1', {}) + + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) +endfunc + +func Test_nocatch_sub_failure_handling() + " normal error results in all replacements + func Foo() + foobar + endfunc + new + call setline(1, ['1 aaa', '2 aaa', '3 aaa']) + " need silent! to avoid a delay when entering Insert mode + silent! %s/aaa/\=Foo()/g + call assert_equal(['1 0', '2 0', '3 0'], getline(1, 3)) + + " Throw without try-catch causes abort after the first line. + " We cannot test this, since it would stop executing the test script. + + " try/catch does not result in any changes + func! Foo() + throw 'error' + endfunc + call setline(1, ['1 aaa', '2 aaa', '3 aaa']) + let error_caught = 0 + try + %s/aaa/\=Foo()/g + catch + let error_caught = 1 + endtry + call assert_equal(1, error_caught) + call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3)) + + " Same, but using "n" flag so that "sandbox" gets set + call setline(1, ['1 aaa', '2 aaa', '3 aaa']) + let error_caught = 0 + try + %s/aaa/\=Foo()/gn + catch + let error_caught = 1 + endtry + call assert_equal(1, error_caught) + call assert_equal(['1 aaa', '2 aaa', '3 aaa'], getline(1, 3)) + + delfunc Foo + bwipe! +endfunc + +" Test ":s/pat/sub/" with different ~s in sub. +func Test_replace_with_tilde() + new + " Set the last replace string to empty + s/^$// + call append(0, ['- Bug in "vPPPP" on this text:']) + normal gg + s/u/~u~/ + call assert_equal('- Bug in "vPPPP" on this text:', getline(1)) + s/i/~u~/ + call assert_equal('- Bug uuun "vPPPP" on this text:', getline(1)) + s/o/~~~/ + call assert_equal('- Bug uuun "vPPPP" uuuuuuuuun this text:', getline(1)) + close! +endfunc + +func Test_replace_keeppatterns() + new + a +foobar + +substitute foo asdf + +one two +. + + normal gg + /^substitute + s/foo/bar/ + call assert_equal('foo', @/) + call assert_equal('substitute bar asdf', getline('.')) + + /^substitute + keeppatterns s/asdf/xyz/ + call assert_equal('^substitute', @/) + call assert_equal('substitute bar xyz', getline('.')) + + exe "normal /bar /e\<CR>" + call assert_equal(15, col('.')) + normal - + keeppatterns /xyz + call assert_equal('bar ', @/) + call assert_equal('substitute bar xyz', getline('.')) + exe "normal 0dn" + call assert_equal('xyz', getline('.')) + + close! +endfunc + +func Test_sub_beyond_end() + new + call setline(1, '#') + let @/ = '^#\n\zs' + s///e + call assert_equal('#', getline(1)) + bwipe! +endfunc + +" Test for repeating last substitution using :~ and :&r +func Test_repeat_last_sub() + new + call setline(1, ['blue green yellow orange white']) + s/blue/red/ + let @/ = 'yellow' + ~ + let @/ = 'white' + :&r + let @/ = 'green' + s//gray + call assert_equal('red gray red orange red', getline(1)) + close! +endfunc + +" Test for Vi compatible substitution: +" \/{string}/, \?{string}? and \&{string}& +func Test_sub_vi_compatibility() + new + call setline(1, ['blue green yellow orange blue']) + let @/ = 'orange' + s\/white/ + let @/ = 'blue' + s\?amber? + let @/ = 'white' + s\&green& + call assert_equal('amber green yellow white green', getline(1)) + close! +endfunc + +" Test for substitute with the new text longer than the original text +func Test_sub_expand_text() + new + call setline(1, 'abcabcabcabcabcabcabcabc') + s/b/\=repeat('B', 10)/g + call assert_equal(repeat('aBBBBBBBBBBc', 8), getline(1)) + close! +endfunc + +" Test for command failures when the last substitute pattern is not set. +func Test_sub_with_no_last_pat() + let lines =<< trim [SCRIPT] + call assert_fails('~', 'E33:') + call assert_fails('s//abc/g', 'E35:') + call assert_fails('s\/bar', 'E35:') + call assert_fails('s\&bar&', 'E33:') + call writefile(v:errors, 'Xresult') + qall! + [SCRIPT] + call writefile(lines, 'Xscript') + if RunVim([], [], '--clean -S Xscript') + call assert_equal([], readfile('Xresult')) + endif + + let lines =<< trim [SCRIPT] + set cpo+=/ + call assert_fails('s/abc/%/', 'E33:') + call writefile(v:errors, 'Xresult') + qall! + [SCRIPT] + " Nvim: no "/" flag in 'cpoptions'. + " call writefile(lines, 'Xscript') + " if RunVim([], [], '--clean -S Xscript') + " call assert_equal([], readfile('Xresult')) + " endif + + call delete('Xscript') + call delete('Xresult') +endfunc + +func Test_substitute() + call assert_equal('a1a2a3a', substitute('123', '\zs', 'a', 'g')) + " Substitute with special keys + call assert_equal("a\<End>c", substitute('abc', "a.c", "a\<End>c", '')) +endfunc + +func Test_substitute_expr() + let g:val = 'XXX' + call assert_equal('XXX', substitute('yyy', 'y*', '\=g:val', '')) + call assert_equal('XXX', substitute('yyy', 'y*', {-> g:val}, '')) + call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)', + \ '\=nr2char("0x" . submatch(1))', 'g')) + call assert_equal("-\u1b \uf2-", substitute("-%1b %f2-", '%\(\x\x\)', + \ {-> nr2char("0x" . submatch(1))}, 'g')) + + call assert_equal('231', substitute('123', '\(.\)\(.\)\(.\)', + \ {-> submatch(2) . submatch(3) . submatch(1)}, '')) + + func Recurse() + return substitute('yyy', 'y\(.\)y', {-> submatch(1)}, '') + endfunc + " recursive call works + call assert_equal('-y-x-', substitute('xxx', 'x\(.\)x', {-> '-' . Recurse() . '-' . submatch(1) . '-'}, '')) + + call assert_fails("let s=submatch([])", 'E745:') + call assert_fails("let s=submatch(2, [])", 'E745:') +endfunc + +func Test_invalid_submatch() + " This was causing invalid memory access in Vim-7.4.2232 and older + call assert_fails("call substitute('x', '.', {-> submatch(10)}, '')", 'E935:') + call assert_fails('eval submatch(-1)', 'E935:') + call assert_equal('', submatch(0)) + call assert_equal('', submatch(1)) + call assert_equal([], submatch(0, 1)) + call assert_equal([], submatch(1, 1)) +endfunc + +func Test_submatch_list_concatenate() + let pat = 'A\(.\)' + let Rep = {-> string([submatch(0, 1)] + [[submatch(1)]])} + call substitute('A1', pat, Rep, '')->assert_equal("[['A1'], ['1']]") +endfunc + +func Test_substitute_expr_arg() + call assert_equal('123456789-123456789=', substitute('123456789', + \ '\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)\(.\)', + \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, '')) + + call assert_equal('123456-123456=789', substitute('123456789', + \ '\(.\)\(.\)\(.\)\(a*\)\(n*\)\(.\)\(.\)\(.\)\(x*\)', + \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, '')) + + call assert_equal('123456789-123456789x=', substitute('123456789', + \ '\(.\)\(.\)\(.*\)', + \ {m -> m[0] . '-' . m[1] . m[2] . m[3] . 'x' . m[4] . m[5] . m[6] . m[7] . m[8] . m[9] . '='}, '')) + + call assert_fails("call substitute('xxx', '.', {m -> string(add(m, 'x'))}, '')", 'E742:') + call assert_fails("call substitute('xxx', '.', {m -> string(insert(m, 'x'))}, '')", 'E742:') + call assert_fails("call substitute('xxx', '.', {m -> string(extend(m, ['x']))}, '')", 'E742:') + call assert_fails("call substitute('xxx', '.', {m -> string(remove(m, 1))}, '')", 'E742:') +endfunc + +" Test for using a function to supply the substitute string +func Test_substitute_using_func() + func Xfunc() + return '1234' + endfunc + call assert_equal('a1234f', substitute('abcdef', 'b..e', + \ function("Xfunc"), '')) + delfunc Xfunc +endfunc + +" Test for using submatch() with a multiline match +func Test_substitute_multiline_submatch() + new + call setline(1, ['line1', 'line2', 'line3', 'line4']) + %s/^line1\(\_.\+\)line4$/\=submatch(1)/ + call assert_equal(['', 'line2', 'line3', ''], getline(1, '$')) + close! +endfunc + +func Test_substitute_skipped_range() + new + if 0 + /1/5/2/2/\n + endif + call assert_equal([0, 1, 1, 0, 1], getcurpos()) + bwipe! +endfunc + +" Test using the 'gdefault' option (when on, flag 'g' is default on). +func Test_substitute_gdefault() + new + + " First check without 'gdefault' + call setline(1, 'foo bar foo') + s/foo/FOO/ + call assert_equal('FOO bar foo', getline(1)) + call setline(1, 'foo bar foo') + s/foo/FOO/g + call assert_equal('FOO bar FOO', getline(1)) + call setline(1, 'foo bar foo') + s/foo/FOO/gg + call assert_equal('FOO bar foo', getline(1)) + + " Then check with 'gdefault' + set gdefault + call setline(1, 'foo bar foo') + s/foo/FOO/ + call assert_equal('FOO bar FOO', getline(1)) + call setline(1, 'foo bar foo') + s/foo/FOO/g + call assert_equal('FOO bar foo', getline(1)) + call setline(1, 'foo bar foo') + s/foo/FOO/gg + call assert_equal('FOO bar FOO', getline(1)) + + " Setting 'compatible' should reset 'gdefault' + call assert_equal(1, &gdefault) + " set compatible + set nogdefault + call assert_equal(0, &gdefault) + set nocompatible + call assert_equal(0, &gdefault) + + bw! +endfunc + +" This was using "old_sub" after it was freed. +func Test_using_old_sub() + " set compatible maxfuncdepth=10 + set maxfuncdepth=10 + new + call setline(1, 'some text.') + func Repl() + ~ + s/ + endfunc + silent! s/\%')/\=Repl() + + delfunc Repl + bwipe! + set nocompatible +endfunc + +" This was switching windows in between computing the length and using it. +func Test_sub_change_window() + silent! lfile + sil! norm o0000000000000000000000000000000000000000000000000000 + func Repl() + lopen + endfunc + silent! s/\%')/\=Repl() + bwipe! + bwipe! + delfunc Repl +endfunc + +" This was undoign a change in between computing the length and using it. +func Do_Test_sub_undo_change() + new + norm o0000000000000000000000000000000000000000000000000000 + silent! s/\%')/\=Repl() + bwipe! +endfunc + +func Test_sub_undo_change() + func Repl() + silent! norm g- + endfunc + call Do_Test_sub_undo_change() + + func! Repl() + silent earlier + endfunc + call Do_Test_sub_undo_change() + + delfunc Repl +endfunc + +" This was opening a command line window from the expression +func Test_sub_open_cmdline_win() + " the error only happens in a very specific setup, run a new Vim instance to + " get a clean starting point. + let lines =<< trim [SCRIPT] + set vb t_vb= + norm o0000000000000000000000000000000000000000000000000000 + func Replace() + norm q/ + endfunc + s/\%')/\=Replace() + redir >Xresult + messages + redir END + qall! + [SCRIPT] + call writefile(lines, 'Xscript') + if RunVim([], [], '-u NONE -S Xscript') + call assert_match('E565: Not allowed to change text or change window', + \ readfile('Xresult')->join('XX')) + endif + + call delete('Xscript') + call delete('Xresult') +endfunc + +" This was editing a script file from the expression +func Test_sub_edit_scriptfile() + new + norm o0000000000000000000000000000000000000000000000000000 + func EditScript() + silent! scr! Xfile + endfunc + s/\%')/\=EditScript() + + delfunc EditScript + bwipe! +endfunc + +" This was editing another file from the expression. +func Test_sub_expr_goto_other_file() + call writefile([''], 'Xfileone', 'D') + enew! + call setline(1, ['a', 'b', 'c', 'd', + \ 'Xfileone zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz']) + + func g:SplitGotoFile() + exe "sil! norm 0\<C-W>gf" + return '' + endfunc + + $ + s/\%')/\=g:SplitGotoFile() + + delfunc g:SplitGotoFile + bwipe! +endfunc + +func Test_recursive_expr_substitute() + " this was reading invalid memory + let lines =<< trim END + func Repl(g, n) + s + r%:s000 + endfunc + next 0 + let caught = 0 + s/\%')/\=Repl(0, 0) + qall! + END + call writefile(lines, 'XexprSubst', 'D') + call RunVim([], [], '--clean -S XexprSubst') +endfunc + +" Test for the 2-letter and 3-letter :substitute commands +func Test_substitute_short_cmd() + new + call setline(1, ['one', 'one one one']) + s/one/two + call cursor(2, 1) + + " :sc + call feedkeys(":sc\<CR>y", 'xt') + call assert_equal('two one one', getline(2)) + + " :scg + call setline(2, 'one one one') + call feedkeys(":scg\<CR>nyq", 'xt') + call assert_equal('one two one', getline(2)) + + " :sci + call setline(2, 'ONE One onE') + call feedkeys(":sci\<CR>y", 'xt') + call assert_equal('two One onE', getline(2)) + + " :scI + set ignorecase + call setline(2, 'ONE One one') + call feedkeys(":scI\<CR>y", 'xt') + call assert_equal('ONE One two', getline(2)) + set ignorecase& + + " :scn + call setline(2, 'one one one') + let t = execute('scn')->split("\n") + call assert_equal(['1 match on 1 line'], t) + call assert_equal('one one one', getline(2)) + + " :scp + call setline(2, "\tone one one") + redir => output + call feedkeys(":scp\<CR>y", 'xt') + redir END + call assert_equal(' two one one', output->split("\n")[-1]) + call assert_equal("\ttwo one one", getline(2)) + + " :scl + call setline(2, "\tone one one") + redir => output + call feedkeys(":scl\<CR>y", 'xt') + redir END + call assert_equal("^Itwo one one$", output->split("\n")[-1]) + call assert_equal("\ttwo one one", getline(2)) + + " :sgc + call setline(2, 'one one one one one') + call feedkeys(":sgc\<CR>nyyq", 'xt') + call assert_equal('one two two one one', getline(2)) + + " :sg + call setline(2, 'one one one') + sg + call assert_equal('two two two', getline(2)) + + " :sgi + call setline(2, 'ONE One onE') + sgi + call assert_equal('two two two', getline(2)) + + " :sgI + set ignorecase + call setline(2, 'ONE One one') + sgI + call assert_equal('ONE One two', getline(2)) + set ignorecase& + + " :sgn + call setline(2, 'one one one') + let t = execute('sgn')->split("\n") + call assert_equal(['3 matches on 1 line'], t) + call assert_equal('one one one', getline(2)) + + " :sgp + call setline(2, "\tone one one") + redir => output + sgp + redir END + call assert_equal(' two two two', output->split("\n")[-1]) + call assert_equal("\ttwo two two", getline(2)) + + " :sgl + call setline(2, "\tone one one") + redir => output + sgl + redir END + call assert_equal("^Itwo two two$", output->split("\n")[-1]) + call assert_equal("\ttwo two two", getline(2)) + + " :sgr + call setline(2, "one one one") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + sgr + call assert_equal('xyz xyz xyz', getline(2)) + + " :sic + call cursor(1, 1) + s/one/two/e + call setline(2, "ONE One one") + call cursor(2, 1) + call feedkeys(":sic\<CR>y", 'xt') + call assert_equal('two One one', getline(2)) + + " :si + call setline(2, "ONE One one") + si + call assert_equal('two One one', getline(2)) + + " :siI + call setline(2, "ONE One one") + siI + call assert_equal('ONE One two', getline(2)) + + " :sin + call setline(2, 'ONE One onE') + let t = execute('sin')->split("\n") + call assert_equal(['1 match on 1 line'], t) + call assert_equal('ONE One onE', getline(2)) + + " :sip + call setline(2, "\tONE One onE") + redir => output + sip + redir END + call assert_equal(' two One onE', output->split("\n")[-1]) + call assert_equal("\ttwo One onE", getline(2)) + + " :sir + call setline(2, "ONE One onE") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + sir + call assert_equal('xyz One onE', getline(2)) + + " :sIc + call cursor(1, 1) + s/one/two/e + call setline(2, "ONE One one") + call cursor(2, 1) + call feedkeys(":sIc\<CR>y", 'xt') + call assert_equal('ONE One two', getline(2)) + + " :sIg + call setline(2, "ONE one onE one") + sIg + call assert_equal('ONE two onE two', getline(2)) + + " :sIi + call setline(2, "ONE One one") + sIi + call assert_equal('two One one', getline(2)) + + " :sI + call setline(2, "ONE One one") + sI + call assert_equal('ONE One two', getline(2)) + + " :sIn + call setline(2, 'ONE One one') + let t = execute('sIn')->split("\n") + call assert_equal(['1 match on 1 line'], t) + call assert_equal('ONE One one', getline(2)) + + " :sIp + call setline(2, "\tONE One one") + redir => output + sIp + redir END + call assert_equal(' ONE One two', output->split("\n")[-1]) + call assert_equal("\tONE One two", getline(2)) + + " :sIl + call setline(2, "\tONE onE one") + redir => output + sIl + redir END + call assert_equal("^IONE onE two$", output->split("\n")[-1]) + call assert_equal("\tONE onE two", getline(2)) + + " :sIr + call setline(2, "ONE one onE") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + sIr + call assert_equal('ONE xyz onE', getline(2)) + + " :src + call setline(2, "ONE one one") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + call feedkeys(":src\<CR>y", 'xt') + call assert_equal('ONE xyz one', getline(2)) + + " :srg + call setline(2, "one one one") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + srg + call assert_equal('xyz xyz xyz', getline(2)) + + " :sri + call setline(2, "ONE one onE") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + sri + call assert_equal('xyz one onE', getline(2)) + + " :srI + call setline(2, "ONE one onE") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + srI + call assert_equal('ONE xyz onE', getline(2)) + + " :srn + call setline(2, "ONE one onE") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + let t = execute('srn')->split("\n") + call assert_equal(['1 match on 1 line'], t) + call assert_equal('ONE one onE', getline(2)) + + " :srp + call setline(2, "\tONE one onE") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + redir => output + srp + redir END + call assert_equal(' ONE xyz onE', output->split("\n")[-1]) + call assert_equal("\tONE xyz onE", getline(2)) + + " :srl + call setline(2, "\tONE one onE") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + redir => output + srl + redir END + call assert_equal("^IONE xyz onE$", output->split("\n")[-1]) + call assert_equal("\tONE xyz onE", getline(2)) + + " :sr + call setline(2, "ONE one onE") + call cursor(2, 1) + s/abc/xyz/e + let @/ = 'one' + sr + call assert_equal('ONE xyz onE', getline(2)) + + " :sce + s/abc/xyz/e + call assert_fails("sc", 'E486:') + sce + " :sge + call assert_fails("sg", 'E486:') + sge + " :sie + call assert_fails("si", 'E486:') + sie + " :sIe + call assert_fails("sI", 'E486:') + sIe + + bw! +endfunc + +" Check handling expanding "~" resulting in extremely long text. +" FIXME: disabled, it takes too long to run on CI +"func Test_substitute_tilde_too_long() +" enew! +" +" s/.*/ixxx +" s//~~~~~~~~~AAAAAAA@( +" +" " Either fails with "out of memory" or "text too long". +" " This can take a long time. +" call assert_fails('sil! norm &&&&&&&&&', ['E1240:\|E342:']) +" +" bwipe! +"endfunc + +" This should be done last to reveal a memory leak when vim_regsub_both() is +" called to evaluate an expression but it is not used in a second call. +func Test_z_substitute_expr_leak() + func SubExpr() + ~n + endfunc + silent! s/\%')/\=SubExpr() + delfunc SubExpr +endfunc + +func Test_substitute_expr_switch_win() + func R() + wincmd x + return 'XXXX' + endfunc + new Xfoobar + let bufnr = bufnr('%') + put ='abcdef' + silent! s/\%')/\=R() + call assert_fails(':%s/./\=R()/g', 'E565:') + delfunc R + exe bufnr .. "bw!" +endfunc + +" recursive call of :s using test-replace special +func Test_substitute_expr_recursive() + func Q() + %s/./\='foobar'/gn + return "foobar" + endfunc + func R() + %s/./\=Q()/g + endfunc + new Xfoobar_UAF + let bufnr = bufnr('%') + put ='abcdef' + silent! s/./\=R()/g + call assert_fails(':%s/./\=R()/g', 'E565:') + delfunc R + delfunc Q + exe bufnr .. "bw!" +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_suspend.vim b/test/old/testdir/test_suspend.vim new file mode 100644 index 0000000000..aa6603be78 --- /dev/null +++ b/test/old/testdir/test_suspend.vim @@ -0,0 +1,63 @@ +" Test :suspend + +source shared.vim +source term_util.vim + +func CheckSuspended(buf, fileExists) + call WaitForAssert({-> assert_match('[$#] $', term_getline(a:buf, '.'))}) + + if a:fileExists + call assert_equal(['foo'], readfile('Xfoo')) + else + " Without 'autowrite', buffer should not be written. + call assert_equal(0, filereadable('Xfoo')) + endif + + call term_sendkeys(a:buf, "fg\<CR>\<C-L>") + call WaitForAssert({-> assert_equal(' 1 foo', term_getline(a:buf, '.'))}) +endfunc + +func Test_suspend() + if !has('terminal') || !executable('/bin/sh') + return + endif + + let buf = term_start('/bin/sh') + " Wait for shell prompt. + call WaitForAssert({-> assert_match('[$#] $', term_getline(buf, '.'))}) + + call term_sendkeys(buf, GetVimCommandClean() + \ . " -X" + \ . " -c 'set nu'" + \ . " -c 'call setline(1, \"foo\")'" + \ . " Xfoo\<CR>") + " Cursor in terminal buffer should be on first line in spawned vim. + call WaitForAssert({-> assert_equal(' 1 foo', term_getline(buf, '.'))}) + + for suspend_cmd in [":suspend\<CR>", + \ ":stop\<CR>", + \ ":suspend!\<CR>", + \ ":stop!\<CR>", + \ "\<C-Z>"] + " Suspend and wait for shell prompt. + call term_sendkeys(buf, suspend_cmd) + call CheckSuspended(buf, 0) + endfor + + " Test that :suspend! with 'autowrite' writes content of buffers if modified. + call term_sendkeys(buf, ":set autowrite\<CR>") + call assert_equal(0, filereadable('Xfoo')) + call term_sendkeys(buf, ":suspend\<CR>") + " Wait for shell prompt. + call CheckSuspended(buf, 1) + + " Quit gracefully to dump coverage information. + call term_sendkeys(buf, ":qall!\<CR>") + call TermWait(buf) + " Wait until Vim actually exited and shell shows a prompt + call WaitForAssert({-> assert_match('[$#] $', term_getline(buf, '.'))}) + call StopShellInTerminal(buf) + + exe buf . 'bwipe!' + call delete('Xfoo') +endfunc diff --git a/test/old/testdir/test_swap.vim b/test/old/testdir/test_swap.vim new file mode 100644 index 0000000000..65b6c57850 --- /dev/null +++ b/test/old/testdir/test_swap.vim @@ -0,0 +1,599 @@ +" Tests for the swap feature + +source check.vim +source shared.vim +source term_util.vim + +func s:swapname() + return trim(execute('swapname')) +endfunc + +" Tests for 'directory' option. +func Test_swap_directory() + if !has("unix") + return + endif + let content = ['start of testfile', + \ 'line 2 Abcdefghij', + \ 'line 3 Abcdefghij', + \ 'end of testfile'] + call writefile(content, 'Xtest1') + + " '.', swap file in the same directory as file + set dir=.,~ + + " Verify that the swap file doesn't exist in the current directory + call assert_equal([], glob(".Xtest1*.swp", 1, 1, 1)) + edit Xtest1 + let swfname = s:swapname() + call assert_equal([swfname], glob(swfname, 1, 1, 1)) + + " './dir', swap file in a directory relative to the file + set dir=./Xtest2,.,~ + + call mkdir("Xtest2") + edit Xtest1 + call assert_equal([], glob(swfname, 1, 1, 1)) + let swfname = "Xtest2/Xtest1.swp" + call assert_equal(swfname, s:swapname()) + call assert_equal([swfname], glob("Xtest2/*", 1, 1, 1)) + + " 'dir', swap file in directory relative to the current dir + set dir=Xtest.je,~ + + call mkdir("Xtest.je") + call writefile(content, 'Xtest2/Xtest3') + edit Xtest2/Xtest3 + call assert_equal(["Xtest2/Xtest3"], glob("Xtest2/*", 1, 1, 1)) + let swfname = "Xtest.je/Xtest3.swp" + call assert_equal(swfname, s:swapname()) + call assert_equal([swfname], glob("Xtest.je/*", 1, 1, 1)) + + set dir& + call delete("Xtest1") + call delete("Xtest2", "rf") + call delete("Xtest.je", "rf") +endfunc + +func Test_swap_group() + if !has("unix") + return + endif + let groups = split(system('groups')) + if len(groups) <= 1 + throw 'Skipped: need at least two groups, got ' . string(groups) + endif + + try + call delete('Xtest') + split Xtest + call setline(1, 'just some text') + wq + if system('ls -l Xtest') !~ ' ' . groups[0] . ' \d' + throw 'Skipped: test file does not have the first group' + else + silent !chmod 640 Xtest + call system('chgrp ' . groups[1] . ' Xtest') + if system('ls -l Xtest') !~ ' ' . groups[1] . ' \d' + throw 'Skipped: cannot set second group on test file' + else + split Xtest + let swapname = substitute(execute('swapname'), '[[:space:]]', '', 'g') + call assert_match('Xtest', swapname) + " Group of swapfile must now match original file. + call assert_match(' ' . groups[1] . ' \d', system('ls -l ' . swapname)) + + bwipe! + endif + endif + finally + call delete('Xtest') + endtry +endfunc + +func Test_missing_dir() + call mkdir('Xswapdir') + exe 'set directory=' . getcwd() . '/Xswapdir' + + call assert_equal('', glob('foo')) + call assert_equal('', glob('bar')) + edit foo/x.txt + " This should not give a warning for an existing swap file. + split bar/x.txt + only + + " Delete the buffer so that swap file is removed before we try to delete the + " directory. That fails on MS-Windows. + %bdelete! + set directory& + call delete('Xswapdir', 'rf') +endfunc + +func Test_swapinfo() + new Xswapinfo + call setline(1, ['one', 'two', 'three']) + w + let fname = s:swapname() + call assert_match('Xswapinfo', fname) + + " Check the tail appears in the list from swapfilelist(). The path depends + " on the system. + let tail = fnamemodify(fname, ":t")->fnameescape() + let nr = 0 + for name in swapfilelist() + if name =~ tail .. '$' + let nr += 1 + endif + endfor + call assert_equal(1, nr, 'not found in ' .. string(swapfilelist())) + + let info = fname->swapinfo() + let ver = printf('VIM %d.%d', v:version / 100, v:version % 100) + call assert_equal(ver, info.version) + + call assert_match('\w', info.user) + " host name is truncated to 39 bytes in the swap file + call assert_equal(hostname()[:38], info.host) + call assert_match('Xswapinfo', info.fname) + call assert_match(0, info.dirty) + call assert_equal(getpid(), info.pid) + call assert_match('^\d*$', info.mtime) + if has_key(info, 'inode') + call assert_match('\d', info.inode) + endif + bwipe! + call delete(fname) + call delete('Xswapinfo') + + let info = swapinfo('doesnotexist') + call assert_equal('Cannot open file', info.error) + + call writefile(['burp'], 'Xnotaswapfile') + let info = swapinfo('Xnotaswapfile') + call assert_equal('Cannot read file', info.error) + call delete('Xnotaswapfile') + + call writefile([repeat('x', 10000)], 'Xnotaswapfile') + let info = swapinfo('Xnotaswapfile') + call assert_equal('Not a swap file', info.error) + call delete('Xnotaswapfile') +endfunc + +func Test_swapname() + edit Xtest1 + let expected = s:swapname() + call assert_equal(expected, swapname('%')) + + new Xtest2 + let buf = bufnr('%') + let expected = s:swapname() + wincmd p + call assert_equal(expected, buf->swapname()) + + new Xtest3 + setlocal noswapfile + call assert_equal('', swapname('%')) + + bwipe! + call delete('Xtest1') + call delete('Xtest2') + call delete('Xtest3') +endfunc + +func Test_swapfile_delete() + autocmd! SwapExists + function s:swap_exists() + let v:swapchoice = s:swap_choice + let s:swapname = v:swapname + let s:filename = expand('<afile>') + endfunc + augroup test_swapfile_delete + autocmd! + autocmd SwapExists * call s:swap_exists() + augroup END + + + " Create a valid swapfile by editing a file. + split XswapfileText + call setline(1, ['one', 'two', 'three']) + write " file is written, not modified + " read the swapfile as a Blob + let swapfile_name = swapname('%') + let swapfile_bytes = readfile(swapfile_name, 'B') + + " Close the file and recreate the swap file. + " Now editing the file will run into the process still existing + quit + call writefile(swapfile_bytes, swapfile_name) + let s:swap_choice = 'e' + let s:swapname = '' + split XswapfileText + quit + call assert_equal(fnamemodify(swapfile_name, ':t'), fnamemodify(s:swapname, ':t')) + + " This test won't work as root because root can successfully run kill(1, 0) + if !IsRoot() + " Write the swapfile with a modified PID, now it will be automatically + " deleted. Process 0x3fffffff most likely does not exist. + let swapfile_bytes[24:27] = 0zffffff3f + call writefile(swapfile_bytes, swapfile_name) + let s:swapname = '' + split XswapfileText + quit + call assert_equal('', s:swapname) + endif + + " Now set the modified flag, the swap file will not be deleted + let swapfile_bytes[28 + 80 + 899] = 0x55 + call writefile(swapfile_bytes, swapfile_name) + let s:swapname = '' + split XswapfileText + quit + call assert_equal(fnamemodify(swapfile_name, ':t'), fnamemodify(s:swapname, ':t')) + + call delete('XswapfileText') + call delete(swapfile_name) + augroup test_swapfile_delete + autocmd! + augroup END + augroup! test_swapfile_delete +endfunc + +func Test_swap_recover() + autocmd! SwapExists + augroup test_swap_recover + autocmd! + autocmd SwapExists * let v:swapchoice = 'r' + augroup END + + call mkdir('Xswap') + let $Xswap = 'foo' " Check for issue #4369. + set dir=Xswap// + " Create a valid swapfile by editing a file. + split Xswap/text + call setline(1, ['one', 'two', 'three']) + write " file is written, not modified + " read the swapfile as a Blob + let swapfile_name = swapname('%') + let swapfile_bytes = readfile(swapfile_name, 'B') + + " Close the file and recreate the swap file. + quit + call writefile(swapfile_bytes, swapfile_name) + " Edit the file again. This triggers recovery. + try + split Xswap/text + catch + " E308 should be caught, not E305. + call assert_exception('E308:') " Original file may have been changed + endtry + " The file should be recovered. + call assert_equal(['one', 'two', 'three'], getline(1, 3)) + quit! + + call delete('Xswap/text') + call delete(swapfile_name) + call delete('Xswap', 'd') + unlet $Xswap + set dir& + augroup test_swap_recover + autocmd! + augroup END + augroup! test_swap_recover +endfunc + +func Test_swap_recover_ext() + autocmd! SwapExists + augroup test_swap_recover_ext + autocmd! + autocmd SwapExists * let v:swapchoice = 'r' + augroup END + + " Create a valid swapfile by editing a file with a special extension. + split Xtest.scr + call setline(1, ['one', 'two', 'three']) + write " file is written, not modified + write " write again to make sure the swapfile is created + " read the swapfile as a Blob + let swapfile_name = swapname('%') + let swapfile_bytes = readfile(swapfile_name, 'B') + + " Close and delete the file and recreate the swap file. + quit + call delete('Xtest.scr') + call writefile(swapfile_bytes, swapfile_name) + " Edit the file again. This triggers recovery. + try + split Xtest.scr + catch + " E308 should be caught, not E306. + call assert_exception('E308:') " Original file may have been changed + endtry + " The file should be recovered. + call assert_equal(['one', 'two', 'three'], getline(1, 3)) + quit! + + call delete('Xtest.scr') + call delete(swapfile_name) + augroup test_swap_recover_ext + autocmd! + augroup END + augroup! test_swap_recover_ext +endfunc + +" Test for closing a split window automatically when a swap file is detected +" and 'Q' is selected in the confirmation prompt. +func Test_swap_split_win() + autocmd! SwapExists + augroup test_swap_splitwin + autocmd! + autocmd SwapExists * let v:swapchoice = 'q' + augroup END + + " Create a valid swapfile by editing a file with a special extension. + split Xtest.scr + call setline(1, ['one', 'two', 'three']) + write " file is written, not modified + write " write again to make sure the swapfile is created + " read the swapfile as a Blob + let swapfile_name = swapname('%') + let swapfile_bytes = readfile(swapfile_name, 'B') + + " Close and delete the file and recreate the swap file. + quit + call delete('Xtest.scr') + call writefile(swapfile_bytes, swapfile_name) + " Split edit the file again. This should fail to open the window + try + split Xtest.scr + catch + " E308 should be caught, not E306. + call assert_exception('E308:') " Original file may have been changed + endtry + call assert_equal(1, winnr('$')) + + call delete('Xtest.scr') + call delete(swapfile_name) + + augroup test_swap_splitwin + autocmd! + augroup END + augroup! test_swap_splitwin +endfunc + +" Test for selecting 'q' in the attention prompt +func Test_swap_prompt_splitwin() + CheckRunVimInTerminal + + call writefile(['foo bar'], 'Xfile1') + edit Xfile1 + preserve " should help to make sure the swap file exists + + let buf = RunVimInTerminal('', {'rows': 20}) + call term_sendkeys(buf, ":set nomore\n") + call term_sendkeys(buf, ":set noruler\n") + + call term_sendkeys(buf, ":split Xfile1\n") + call TermWait(buf) + call WaitForAssert({-> assert_match('^\[O\]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort: $', term_getline(buf, 20))}) + call term_sendkeys(buf, "q") + call TermWait(buf) + call term_sendkeys(buf, ":\<CR>") + call WaitForAssert({-> assert_match('^:$', term_getline(buf, 20))}) + call term_sendkeys(buf, ":echomsg winnr('$')\<CR>") + call TermWait(buf) + call WaitForAssert({-> assert_match('^1$', term_getline(buf, 20))}) + call StopVimInTerminal(buf) + + " This caused Vim to crash when typing "q" at the swap file prompt. + let buf = RunVimInTerminal('-c "au bufadd * let foo_w = wincol()"', {'rows': 18}) + call term_sendkeys(buf, ":e Xfile1\<CR>") + call WaitForAssert({-> assert_match('More', term_getline(buf, 18))}) + call term_sendkeys(buf, " ") + call WaitForAssert({-> assert_match('^\[O\]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort:', term_getline(buf, 18))}) + call term_sendkeys(buf, "q") + call TermWait(buf) + " check that Vim is still running + call term_sendkeys(buf, ":echo 'hello'\<CR>") + call WaitForAssert({-> assert_match('^hello', term_getline(buf, 18))}) + call term_sendkeys(buf, ":%bwipe!\<CR>") + call StopVimInTerminal(buf) + + %bwipe! + call delete('Xfile1') +endfunc + +func Test_swap_symlink() + CheckUnix + + call writefile(['text'], 'Xtestfile') + silent !ln -s -f Xtestfile Xtestlink + + set dir=. + + " Test that swap file uses the name of the file when editing through a + " symbolic link (so that editing the file twice is detected) + edit Xtestlink + call assert_match('Xtestfile\.swp$', s:swapname()) + bwipe! + + call mkdir('Xswapdir') + exe 'set dir=' . getcwd() . '/Xswapdir//' + + " Check that this also works when 'directory' ends with '//' + edit Xtestlink + call assert_match('Xtestfile\.swp$', s:swapname()) + bwipe! + + set dir& + call delete('Xtestfile') + call delete('Xtestlink') + call delete('Xswapdir', 'rf') +endfunc + +func s:get_unused_pid(base) + if has('job') + " Execute 'echo' as a temporary job, and return its pid as an unused pid. + if has('win32') + let cmd = 'cmd /c echo' + else + let cmd = 'echo' + endif + let j = job_start(cmd) + while job_status(j) ==# 'run' + sleep 10m + endwhile + if job_status(j) ==# 'dead' + return job_info(j).process + endif + elseif has('nvim') + let j = jobstart('echo') + let pid = jobpid(j) + if jobwait([j])[0] >= 0 + return pid + endif + endif + " Must add four for MS-Windows to see it as a different one. + return a:base + 4 +endfunc + +func s:blob_to_pid(b) + return a:b[3] * 16777216 + a:b[2] * 65536 + a:b[1] * 256 + a:b[0] +endfunc + +func s:pid_to_blob(i) + let b = 0z + let b[0] = and(a:i, 0xff) + let b[1] = and(a:i / 256, 0xff) + let b[2] = and(a:i / 65536, 0xff) + let b[3] = and(a:i / 16777216, 0xff) + return b +endfunc + +func Test_swap_auto_delete() + " Create a valid swapfile by editing a file with a special extension. + split Xtest.scr + call setline(1, ['one', 'two', 'three']) + write " file is written, not modified + write " write again to make sure the swapfile is created + " read the swapfile as a Blob + let swapfile_name = swapname('%') + let swapfile_bytes = readfile(swapfile_name, 'B') + + " Forget about the file, recreate the swap file, then edit it again. The + " swap file should be automatically deleted. + bwipe! + " Change the process ID to avoid the "still running" warning. + let swapfile_bytes[24:27] = s:pid_to_blob(s:get_unused_pid( + \ s:blob_to_pid(swapfile_bytes[24:27]))) + call writefile(swapfile_bytes, swapfile_name) + edit Xtest.scr + " will end up using the same swap file after deleting the existing one + call assert_equal(swapfile_name, swapname('%')) + bwipe! + + " create the swap file again, but change the host name so that it won't be + " deleted + autocmd! SwapExists + augroup test_swap_recover_ext + autocmd! + autocmd SwapExists * let v:swapchoice = 'e' + augroup END + + " change the host name + let swapfile_bytes[28 + 40] = swapfile_bytes[28 + 40] + 2 + call writefile(swapfile_bytes, swapfile_name) + edit Xtest.scr + call assert_equal(1, filereadable(swapfile_name)) + " will use another same swap file name + call assert_notequal(swapfile_name, swapname('%')) + bwipe! + + call delete('Xtest.scr') + call delete(swapfile_name) + augroup test_swap_recover_ext + autocmd! + augroup END + augroup! test_swap_recover_ext +endfunc + +" Test for renaming a buffer when the swap file is deleted out-of-band +func Test_missing_swap_file() + CheckUnix + new Xfile2 + call delete(swapname('')) + call assert_fails('file Xfile3', 'E301:') + call assert_equal('Xfile3', bufname()) + call assert_true(bufexists('Xfile2')) + call assert_true(bufexists('Xfile3')) + %bw! +endfunc + +" Test for :preserve command +func Test_preserve() + new Xfile4 + setlocal noswapfile + call assert_fails('preserve', 'E313:') + bw! +endfunc + +" Test for the v:swapchoice variable +func Test_swapchoice() + call writefile(['aaa', 'bbb'], 'Xfile5') + edit Xfile5 + preserve + let swapfname = swapname('') + let b = readblob(swapfname) + bw! + call writefile(b, swapfname) + + autocmd! SwapExists + + " Test for v:swapchoice = 'o' (readonly) + augroup test_swapchoice + autocmd! + autocmd SwapExists * let v:swapchoice = 'o' + augroup END + edit Xfile5 + call assert_true(&readonly) + call assert_equal(['aaa', 'bbb'], getline(1, '$')) + %bw! + call assert_true(filereadable(swapfname)) + + " Test for v:swapchoice = 'a' (abort) + augroup test_swapchoice + autocmd! + autocmd SwapExists * let v:swapchoice = 'a' + augroup END + try + edit Xfile5 + catch /^Vim:Interrupt$/ + endtry + call assert_equal('', @%) + call assert_true(bufexists('Xfile5')) + %bw! + call assert_true(filereadable(swapfname)) + + " Test for v:swapchoice = 'd' (delete) + augroup test_swapchoice + autocmd! + autocmd SwapExists * let v:swapchoice = 'd' + augroup END + edit Xfile5 + call assert_equal('Xfile5', @%) + %bw! + call assert_false(filereadable(swapfname)) + + call delete('Xfile5') + call delete(swapfname) + augroup test_swapchoice + autocmd! + augroup END + augroup! test_swapchoice +endfunc + +func Test_no_swap_file() + call assert_equal("\nNo swap file", execute('swapname')) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_syn_attr.vim b/test/old/testdir/test_syn_attr.vim new file mode 100644 index 0000000000..88f9d0d84d --- /dev/null +++ b/test/old/testdir/test_syn_attr.vim @@ -0,0 +1,51 @@ +" Test syntax highlighting functions. + +func Test_missing_attr() + throw 'Skipped: use test/functional/legacy/syn_attr_spec.lua' + + hi Mine term=bold cterm=italic + call assert_equal('Mine', synIDattr(hlID("Mine"), "name")) + call assert_equal('', synIDattr("Mine"->hlID(), "bg", 'term')) + call assert_equal('', synIDattr("Mine"->hlID(), "fg", 'term')) + call assert_equal('', synIDattr("Mine"->hlID(), "sp", 'term')) + call assert_equal('1', synIDattr(hlID("Mine"), "bold", 'term')) + call assert_equal('1', synIDattr(hlID("Mine"), "italic", 'cterm')) + hi Mine term=reverse cterm=inverse + call assert_equal('1', synIDattr(hlID("Mine"), "reverse", 'term')) + call assert_equal('1', synIDattr(hlID("Mine"), "inverse", 'cterm')) + + hi Mine term=underline cterm=standout gui=undercurl + call assert_equal('1', synIDattr(hlID("Mine"), "underline", 'term')) + call assert_equal('1', synIDattr(hlID("Mine"), "standout", 'cterm')) + call assert_equal('1', synIDattr("Mine"->hlID(), "undercurl", 'gui')) + + hi Mine term=underdouble cterm=underdotted gui=underdashed + call assert_equal('1', synIDattr(hlID("Mine"), "underdouble", 'term')) + call assert_equal('1', synIDattr(hlID("Mine"), "underdotted", 'cterm')) + call assert_equal('1', synIDattr("Mine"->hlID(), "underdashed", 'gui')) + + hi Mine term=nocombine gui=strikethrough + call assert_equal('1', synIDattr(hlID("Mine"), "strikethrough", 'gui')) + call assert_equal('1', synIDattr(hlID("Mine"), "nocombine", 'term')) + call assert_equal('', synIDattr(hlID("Mine"), "nocombine", 'gui')) + hi Mine term=NONE cterm=NONE gui=NONE + call assert_equal('', synIDattr(hlID("Mine"), "bold", 'term')) + call assert_equal('', synIDattr(hlID("Mine"), "italic", 'cterm')) + call assert_equal('', synIDattr(hlID("Mine"), "reverse", 'term')) + call assert_equal('', synIDattr(hlID("Mine"), "inverse", 'cterm')) + call assert_equal('', synIDattr(hlID("Mine"), "underline", 'term')) + call assert_equal('', synIDattr(hlID("Mine"), "standout", 'cterm')) + call assert_equal('', synIDattr(hlID("Mine"), "undercurl", 'gui')) + call assert_equal('', synIDattr(hlID("Mine"), "strikethrough", 'gui')) + + if has('gui') + let fontname = getfontname() + if fontname == '' + let fontname = 'something' + endif + exe "hi Mine guifg=blue guibg=red font='" . fontname . "'" + call assert_equal('blue', synIDattr(hlID("Mine"), "fg", 'gui')) + call assert_equal('red', synIDattr(hlID("Mine"), "bg", 'gui')) + call assert_equal(fontname, synIDattr(hlID("Mine"), "font", 'gui')) + endif +endfunc diff --git a/test/old/testdir/test_syntax.vim b/test/old/testdir/test_syntax.vim new file mode 100644 index 0000000000..76a21adc57 --- /dev/null +++ b/test/old/testdir/test_syntax.vim @@ -0,0 +1,981 @@ +" Test for syntax and syntax iskeyword option + +source check.vim +CheckFeature syntax + +source view_util.vim +source screendump.vim + +func GetSyntaxItem(pat) + let c = '' + let a = ['a', getreg('a'), getregtype('a')] + 0 + redraw! + call search(a:pat, 'W') + let synid = synID(line('.'), col('.'), 1) + while synid == synID(line('.'), col('.'), 1) + norm! v"ay + " stop at whitespace + if @a =~# '\s' + break + endif + let c .= @a + norm! l + endw + call call('setreg', a) + 0 + return c +endfunc + +func AssertHighlightGroups(lnum, startcol, expected, trans = 1, msg = "") + " Assert that the characters starting at a given (line, col) + " sequentially match the expected highlight groups. + " If groups are provided as a string, each character is assumed to be a + " group and spaces represent no group, useful for visually describing tests. + let l:expectedGroups = type(a:expected) == v:t_string + \ ? a:expected->split('\zs')->map({_, v -> trim(v)}) + \ : a:expected + let l:errors = 0 + let l:msg = (a:msg->empty() ? "" : a:msg .. ": ") + \ .. "Wrong highlight group at " .. a:lnum .. "," + + for l:i in range(a:startcol, a:startcol + l:expectedGroups->len() - 1) + let l:errors += synID(a:lnum, l:i, a:trans) + \ ->synIDattr("name") + \ ->assert_equal(l:expectedGroups[l:i - 1], + \ l:msg .. l:i) + endfor +endfunc + +func Test_syn_iskeyword() + new + call setline(1, [ + \ 'CREATE TABLE FOOBAR(', + \ ' DLTD_BY VARCHAR2(100)', + \ ');', + \ '']) + + syntax on + set ft=sql + syn match SYN /C\k\+\>/ + hi link SYN ErrorMsg + call assert_equal('DLTD_BY', GetSyntaxItem('DLTD')) + /\<D\k\+\>/:norm! ygn + call assert_equal('DLTD_BY', @0) + redir @c + syn iskeyword + redir END + call assert_equal("\nsyntax iskeyword not set", @c) + + syn iskeyword @,48-57,_,192-255 + redir @c + syn iskeyword + redir END + call assert_equal("\nsyntax iskeyword @,48-57,_,192-255", @c) + + setlocal isk-=_ + call assert_equal('DLTD_BY', GetSyntaxItem('DLTD')) + /\<D\k\+\>/:norm! ygn + let b2 = @0 + call assert_equal('DLTD', @0) + + syn iskeyword clear + redir @c + syn iskeyword + redir END + call assert_equal("\nsyntax iskeyword not set", @c) + + quit! +endfunc + +func Test_syntax_after_reload() + split Xsomefile + call setline(1, ['hello', 'there']) + w! + only! + setl filetype=hello + au FileType hello let g:gotit = 1 + call assert_false(exists('g:gotit')) + edit other + buf Xsomefile + call assert_equal('hello', &filetype) + call assert_true(exists('g:gotit')) + call delete('Xsomefile') +endfunc + +func Test_syntime() + if !has('profile') + return + endif + + syntax on + syntime on + let a = execute('syntime report') + call assert_equal("\nNo Syntax items defined for this buffer", a) + + let a = execute('syntime clear') + call assert_equal("\nNo Syntax items defined for this buffer", a) + + view ../memfile_test.c + setfiletype cpp + redraw + let a = execute('syntime report') + call assert_match('^ TOTAL *COUNT *MATCH *SLOWEST *AVERAGE *NAME *PATTERN', a) + call assert_match(' \d*\.\d* \+[^0]\d* .* cppRawString ', a) + call assert_match(' \d*\.\d* \+[^0]\d* .* cppNumber ', a) + + syntime off + syntime clear + let a = execute('syntime report') + call assert_match('^ TOTAL *COUNT *MATCH *SLOWEST *AVERAGE *NAME *PATTERN', a) + call assert_notmatch('.* cppRawString *', a) + call assert_notmatch('.* cppNumber*', a) + call assert_notmatch('[1-9]', a) + + call assert_fails('syntime abc', 'E475') + + syntax clear + let a = execute('syntime report') + call assert_equal("\nNo Syntax items defined for this buffer", a) + + bd +endfunc + +func Test_syntime_completion() + if !has('profile') + return + endif + + call feedkeys(":syntime \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syntime clear off on report', @:) +endfunc + +func Test_syntax_list() + syntax on + let a = execute('syntax list') + call assert_equal("\nNo Syntax items defined for this buffer", a) + + view ../memfile_test.c + setfiletype c + + let a = execute('syntax list') + call assert_match('cInclude*', a) + call assert_match('cDefine', a) + + let a = execute('syntax list cDefine') + call assert_notmatch('cInclude*', a) + call assert_match('cDefine', a) + call assert_match(' links to Macro$', a) + + call assert_fails('syntax list ABCD', 'E28:') + call assert_fails('syntax list @ABCD', 'E392:') + + syntax clear + let a = execute('syntax list') + call assert_equal("\nNo Syntax items defined for this buffer", a) + + syntax keyword Type int containedin=g1 skipwhite skipempty skipnl nextgroup=Abc + let exp = "Type xxx containedin=g1 nextgroup=Abc skipnl skipwhite skipempty int" + call assert_equal(exp, split(execute("syntax list"), "\n")[1]) + + bd +endfunc + +func Test_syntax_completion() + call feedkeys(":syn \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syn case clear cluster conceal enable foldlevel include iskeyword keyword list manual match off on region reset spell sync', @:) + + call feedkeys(":syn case \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syn case ignore match', @:) + + call feedkeys(":syn spell \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syn spell default notoplevel toplevel', @:) + + call feedkeys(":syn sync \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"syn sync ccomment clear fromstart linebreaks= linecont lines= match maxlines= minlines= region', @:) + + " Check that clearing "Aap" avoids it showing up before Boolean. + hi @Aap ctermfg=blue + call feedkeys(":syn list \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_match('^"syn list @Aap @boolean @character ', @:) + hi clear @Aap + + call feedkeys(":syn list \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_match('^"syn list @boolean @character ', @:) + + call feedkeys(":syn match \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_match('^"syn match @boolean @character ', @:) + + syn cluster Aax contains=Aap + call feedkeys(":syn list @A\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_match('^"syn list @Aax', @:) +endfunc + +func Test_echohl_completion() + call feedkeys(":echohl no\<C-A>\<C-B>\"\<CR>", 'tx') + " call assert_equal('"echohl NonText Normal none', @:) + call assert_equal('"echohl NonText Normal NormalFloat none', @:) +endfunc + +func Test_syntax_arg_skipped() + syn clear + syntax case ignore + if 0 + syntax case match + endif + call assert_match('case ignore', execute('syntax case')) + + syn keyword Foo foo + call assert_match('Foo', execute('syntax')) + syn clear + call assert_match('case match', execute('syntax case')) + call assert_notmatch('Foo', execute('syntax')) + + if has('conceal') + syn clear + syntax conceal on + if 0 + syntax conceal off + endif + call assert_match('conceal on', execute('syntax conceal')) + syn clear + call assert_match('conceal off', execute('syntax conceal')) + endif + + syntax conceal on + syntax conceal off + call assert_match('conceal off', execute('syntax conceal')) + + syntax region Bar start=/</ end=/>/ + if 0 + syntax region NotTest start=/</ end=/>/ contains=@Spell + endif + call assert_match('Bar', execute('syntax')) + call assert_notmatch('NotTest', execute('syntax')) + call assert_notmatch('Spell', execute('syntax')) + + hi Foo ctermfg=blue + let a = execute('hi Foo') + if 0 + syntax rest + endif + call assert_equal(a, execute('hi Foo')) + hi clear Bar + hi clear Foo + + set ft=tags + syn off + if 0 + syntax enable + endif + call assert_match('No Syntax items defined', execute('syntax')) + syntax enable + call assert_match('tagComment', execute('syntax')) + set ft= + + syn clear + if 0 + syntax include @Spell nothing + endif + call assert_notmatch('Spell', execute('syntax')) + + syn clear + syn iskeyword 48-57,$,_ + call assert_match('48-57,$,_', execute('syntax iskeyword')) + if 0 + syn clear + syn iskeyword clear + endif + call assert_match('48-57,$,_', execute('syntax iskeyword')) + syn iskeyword clear + call assert_match('not set', execute('syntax iskeyword')) + syn iskeyword 48-57,$,_ + syn clear + call assert_match('not set', execute('syntax iskeyword')) + + syn clear + syn keyword Foo foo + if 0 + syn keyword NotAdded bar + endif + call assert_match('Foo', execute('syntax')) + call assert_notmatch('NotAdded', execute('highlight')) + + syn clear + syn keyword Foo foo + call assert_match('Foo', execute('syntax')) + call assert_match('Foo', execute('syntax list')) + call assert_notmatch('Foo', execute('if 0 | syntax | endif')) + call assert_notmatch('Foo', execute('if 0 | syntax list | endif')) + + syn clear + syn match Fopi /asdf/ + if 0 + syn match Fopx /asdf/ + endif + call assert_match('Fopi', execute('syntax')) + call assert_notmatch('Fopx', execute('syntax')) + + syn clear + syn spell toplevel + call assert_match('spell toplevel', execute('syntax spell')) + if 0 + syn spell notoplevel + endif + call assert_match('spell toplevel', execute('syntax spell')) + syn spell notoplevel + call assert_match('spell notoplevel', execute('syntax spell')) + syn spell default + call assert_match('spell default', execute('syntax spell')) + + syn clear + if 0 + syntax cluster Spell + endif + call assert_notmatch('Spell', execute('syntax')) + + syn clear + syn keyword Foo foo + syn sync ccomment + syn sync maxlines=5 + if 0 + syn sync maxlines=11 + endif + call assert_match('on C-style comments', execute('syntax sync')) + call assert_match('maximal 5 lines', execute('syntax sync')) + syn sync clear + if 0 + syn sync ccomment + endif + call assert_notmatch('on C-style comments', execute('syntax sync')) + syn sync fromstart + call assert_match('syncing starts at the first line', execute('syntax sync')) + + syn clear +endfunc + +" Check for an error. Used when multiple errors are thrown and we are checking +" for an earliest error. +func AssertFails(cmd, errcode) + let save_exception = '' + try + exe a:cmd + catch + let save_exception = v:exception + endtry + call assert_match(a:errcode, save_exception) +endfunc + +func Test_syntax_invalid_arg() + call assert_fails('syntax case asdf', 'E390:') + if has('conceal') + call assert_fails('syntax conceal asdf', 'E390:') + endif + call assert_fails('syntax spell asdf', 'E390:') + call assert_fails('syntax clear @ABCD', 'E391:') + call assert_fails('syntax include random_file', 'E484:') + call assert_fails('syntax include <afile>', 'E495:') + call assert_fails('syntax sync x', 'E404:') + call assert_fails('syntax keyword Abc a[', 'E789:') + call assert_fails('syntax keyword Abc a[bc]d', 'E890:') + call assert_fails('syntax cluster Abc add=A add=', 'E406:') + + " Test for too many \z\( and unmatched \z\( + " Not able to use assert_fails() here because both E50:/E879: and E475: + " messages are emitted. + set regexpengine=1 + call AssertFails("syntax region MyRegion start='\\z\\(' end='\\*/'", 'E52:') + + let cmd = "syntax region MyRegion start='" + let cmd ..= repeat("\\z\\(.\\)", 10) .. "' end='\*/'" + call AssertFails(cmd, 'E50:') + + set regexpengine=2 + call AssertFails("syntax region MyRegion start='\\z\\(' end='\\*/'", 'E54:') + + let cmd = "syntax region MyRegion start='" + let cmd ..= repeat("\\z\\(.\\)", 10) .. "' end='\*/'" + call AssertFails(cmd, 'E879:') + set regexpengine& + + call AssertFails('syntax keyword cMyItem grouphere G1', 'E393:') + call AssertFails('syntax sync match Abc grouphere MyItem "abc"', 'E394:') + call AssertFails('syn keyword Type contains int', 'E395:') + call assert_fails('syntax include @Xxx', 'E397:') + call AssertFails('syntax region X start', 'E398:') + call assert_fails('syntax region X start="{"', 'E399:') + call AssertFails('syntax cluster contains=Abc', 'E400:') + call AssertFails("syntax match Character /'.'", 'E401:') + call AssertFails("syntax match Character /'.'/a", 'E402:') + call assert_fails('syntax sync linecont /\%(/', 'E53:') + call assert_fails('syntax sync linecont /pat', 'E404:') + call assert_fails('syntax sync linecont', 'E404:') + call assert_fails('syntax sync linecont /pat1/ linecont /pat2/', 'E403:') + call assert_fails('syntax sync minlines=a', 'E404:') + call AssertFails('syntax match ABC /x/ contains=', 'E406:') + call AssertFails("syntax match Character contains /'.'/", 'E405:') + call AssertFails('syntax match ccFoo "Foo" nextgroup=ALLBUT,F', 'E407:') + call AssertFails('syntax region Block start="{" contains=F,ALLBUT', 'E408:') + call AssertFails("syntax match Characters contains=a.*x /'.'/", 'E409:') + call assert_fails('syntax match Search /abc/ contains=ALLBUT,/\%(/', 'E53:') +endfunc + +func Test_syn_sync() + syntax region HereGroup start=/this/ end=/that/ + syntax sync match SyncHere grouphere HereGroup "pattern" + call assert_match('SyncHere', execute('syntax sync')) + syn sync clear + call assert_notmatch('SyncHere', execute('syntax sync')) + syn clear +endfunc + +func Test_syn_clear() + syntax keyword Foo foo + syntax keyword Bar tar + call assert_match('Foo', execute('syntax')) + call assert_match('Bar', execute('syntax')) + call assert_equal('Foo', synIDattr(hlID("Foo"), "name")) + syn clear Foo + call assert_notmatch('Foo', execute('syntax')) + call assert_match('Bar', execute('syntax')) + call assert_equal('Foo', synIDattr(hlID("Foo"), "name")) + syn clear Foo Bar + call assert_notmatch('Foo', execute('syntax')) + call assert_notmatch('Bar', execute('syntax')) + hi clear Foo + call assert_equal('Foo', synIDattr(hlID("Foo"), "name")) + hi clear Bar + call assert_fails('syntax clear invalid_syngroup', 'E28:') +endfunc + +func Test_invalid_name() + syn clear + syn keyword Nop yes + call assert_fails("syntax keyword Wr\x17ong bar", 'E669:') + syntax keyword @Wrong bar + call assert_fails("syntax keyword @#Wrong bar", 'E5248:') + syn clear + hi clear Nop + hi clear @Wrong +endfunc + +func Test_ownsyntax() + new XfooOwnSyntax + call setline(1, '#define FOO') + syntax on + set filetype=c + + ownsyntax perl + " this should not crash + set + + call assert_equal('perlComment', synIDattr(synID(line('.'), col('.'), 1), 'name')) + call assert_equal('c', b:current_syntax) + call assert_equal('perl', w:current_syntax) + + " A new split window should have the original syntax. + split + call assert_equal('cDefine', synIDattr(synID(line('.'), col('.'), 1), 'name')) + call assert_equal('c', b:current_syntax) + call assert_equal(0, exists('w:current_syntax')) + + wincmd x + call assert_equal('perlComment', synIDattr(synID(line("."), col("."), 1), "name")) + + syntax off + set filetype& + %bw! +endfunc + +func Test_ownsyntax_completion() + call feedkeys(":ownsyntax java\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"ownsyntax java javacc javascript javascriptreact', @:) +endfunc + +func Test_highlight_invalid_arg() + if has('gui_running') + call assert_fails('hi XXX guifg=xxx', 'E254:') + endif + call assert_fails('hi DoesNotExist', 'E411:') + call assert_fails('hi link', 'E412:') + call assert_fails('hi link a', 'E412:') + call assert_fails('hi link a b c', 'E413:') + call assert_fails('hi XXX =', 'E415:') + call assert_fails('hi XXX cterm', 'E416:') + call assert_fails('hi XXX cterm=', 'E417:') + call assert_fails('hi XXX cterm=DoesNotExist', 'E418:') + call assert_fails('hi XXX ctermfg=DoesNotExist', 'E421:') + call assert_fails('hi XXX xxx=White', 'E423:') +endfunc + +func Test_conceal() + if !has('conceal') + return + endif + + new + call setline(1, ['', '123456']) + syn match test23 "23" conceal cchar=X + syn match test45 "45" conceal + + set conceallevel=0 + call assert_equal('123456 ', ScreenLines(2, 7)[0]) + call assert_equal([[0, '', 0], [0, '', 0], [0, '', 0], [0, '', 0], [0, '', 0], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)')) + + set conceallevel=1 + call assert_equal('1X 6 ', ScreenLines(2, 7)[0]) + call assert_equal([[0, '', 0], [1, 'X', 1], [1, 'X', 1], [1, ' ', 2], [1, ' ', 2], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)')) + + set conceallevel=1 + set listchars=conceal:Y + call assert_equal([[0, '', 0], [1, 'X', 1], [1, 'X', 1], [1, 'Y', 2], [1, 'Y', 2], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)')) + call assert_equal('1XY6 ', ScreenLines(2, 7)[0]) + + set conceallevel=2 + call assert_match('1X6 ', ScreenLines(2, 7)[0]) + call assert_equal([[0, '', 0], [1, 'X', 1], [1, 'X', 1], [1, '', 2], [1, '', 2], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)')) + + set conceallevel=3 + call assert_match('16 ', ScreenLines(2, 7)[0]) + call assert_equal([[0, '', 0], [1, '', 1], [1, '', 1], [1, '', 2], [1, '', 2], [0, '', 0]], map(range(1, 6), 'synconcealed(2, v:val)')) + + call AssertFails("syntax match Entity '&' conceal cchar=\<Tab>", 'E844:') + + syn clear + set conceallevel& + bw! +endfunc + +func Test_bg_detection() + CheckNotGui + + " auto-detection of &bg, make sure sure it isn't set anywhere before + " this test + hi Normal ctermbg=0 + call assert_equal('dark', &bg) + hi Normal ctermbg=4 + call assert_equal('dark', &bg) + hi Normal ctermbg=12 + call assert_equal('light', &bg) + hi Normal ctermbg=15 + call assert_equal('light', &bg) + + " manually-set &bg takes precedence over auto-detection + set bg=light + hi Normal ctermbg=4 + call assert_equal('light', &bg) + set bg=dark + hi Normal ctermbg=12 + call assert_equal('dark', &bg) + + hi Normal ctermbg=NONE +endfunc + +func Test_syntax_hangs() + if !has('reltime') || !has('float') || !has('syntax') + return + endif + + " This pattern takes a long time to match, it should timeout. + new + call setline(1, ['aaa', repeat('abc ', 1000), 'ccc']) + let start = reltime() + set nolazyredraw redrawtime=101 + syn match Error /\%#=1a*.*X\@<=b*/ + redraw + let elapsed = reltimefloat(reltime(start)) + call assert_true(elapsed > 0.1) + call assert_true(elapsed < 1.0) + + " second time syntax HL is disabled + let start = reltime() + redraw + let elapsed = reltimefloat(reltime(start)) + call assert_true(elapsed < 0.1) + + " after CTRL-L the timeout flag is reset + let start = reltime() + exe "normal \<C-L>" + redraw + let elapsed = reltimefloat(reltime(start)) + call assert_true(elapsed > 0.1) + call assert_true(elapsed < 1.0) + + set redrawtime& + bwipe! +endfunc + +func Test_synstack_synIDtrans() + new + setfiletype c + syntax on + call setline(1, ' /* A comment with a TODO */') + + call assert_equal([], synstack(1, 1)) + + norm f/ + eval synstack(line("."), col("."))->map('synIDattr(v:val, "name")')->assert_equal(['cComment', 'cCommentStart']) + eval synstack(line("."), col("."))->map('synIDattr(synIDtrans(v:val), "name")')->assert_equal(['Comment', 'Comment']) + + norm fA + call assert_equal(['cComment'], map(synstack(line("."), col(".")), 'synIDattr(v:val, "name")')) + call assert_equal(['Comment'], map(synstack(line("."), col(".")), 'synIDattr(synIDtrans(v:val), "name")')) + + norm fT + call assert_equal(['cComment', 'cTodo'], map(synstack(line("."), col(".")), 'synIDattr(v:val, "name")')) + call assert_equal(['Comment', 'Todo'], map(synstack(line("."), col(".")), 'synIDattr(synIDtrans(v:val), "name")')) + + call assert_fails("let n=synIDtrans([])", 'E745:') + + syn clear + bw! +endfunc + +" Check highlighting for a small piece of C code with a screen dump. +func Test_syntax_c() + CheckRunVimInTerminal + call writefile([ + \ '/* comment line at the top */', + \ 'int main(int argc, char **argv) { // another comment', + \ '#if 0', + \ ' int not_used;', + \ '#else', + \ ' int used;', + \ '#endif', + \ ' printf("Just an example piece of C code\n");', + \ ' return 0x0ff;', + \ '}', + \ ' static void', + \ 'myFunction(const double count, struct nothing, long there) {', + \ ' // 123: nothing to read here', + \ ' for (int i = 0; i < count; ++i) {', + \ ' break;', + \ ' }', + \ " Note: asdf", + \ '}', + \ ], 'Xtest.c') + + " This makes the default for 'background' use "dark", check that the + " response to t_RB corrects it to "light". + let $COLORFGBG = '15;0' + + let buf = RunVimInTerminal('Xtest.c', {}) + call term_sendkeys(buf, ":syn keyword Search Note\r") + call VerifyScreenDump(buf, 'Test_syntax_c_01', {}) + call StopVimInTerminal(buf) + + let $COLORFGBG = '' + call delete('Xtest.c') +endfun + +" Test \z(...) along with \z1 +func Test_syn_zsub() + new + syntax on + call setline(1, 'xxx start foo xxx not end foo xxx end foo xxx') + let l:expected = ' ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ' + + for l:re in [0, 1, 2] + " Example taken from :help :syn-ext-match + syntax region Z start="start \z(\I\i*\)" skip="not end \z1" end="end \z1" + eval AssertHighlightGroups(1, 1, l:expected, 1, 'regexp=' .. l:re) + syntax clear Z + endfor + + set re& + bw! +endfunc + +" Using \z() in a region with NFA failing should not crash. +func Test_syn_wrong_z_one() + new + call setline(1, ['just some text', 'with foo and bar to match with']) + syn region FooBar start="foo\z(.*\)bar" end="\z1" + " call test_override("nfa_fail", 1) + redraw! + redraw! + " call test_override("ALL", 0) + bwipe! +endfunc + +func Test_syntax_after_bufdo() + call writefile(['/* aaa comment */'], 'Xaaa.c') + call writefile(['/* bbb comment */'], 'Xbbb.c') + call writefile(['/* ccc comment */'], 'Xccc.c') + call writefile(['/* ddd comment */'], 'Xddd.c') + + let bnr = bufnr('%') + new Xaaa.c + badd Xbbb.c + badd Xccc.c + badd Xddd.c + exe "bwipe " . bnr + let l = [] + bufdo call add(l, bufnr('%')) + call assert_equal(4, len(l)) + + syntax on + + " This used to only enable syntax HL in the last buffer. + bufdo tab split + tabrewind + for tab in range(1, 4) + norm fm + call assert_equal(['cComment'], map(synstack(line("."), col(".")), 'synIDattr(v:val, "name")')) + tabnext + endfor + + bwipe! Xaaa.c + bwipe! Xbbb.c + bwipe! Xccc.c + bwipe! Xddd.c + syntax off + call delete('Xaaa.c') + call delete('Xbbb.c') + call delete('Xccc.c') + call delete('Xddd.c') +endfunc + +func Test_syntax_foldlevel() + new + call setline(1, [ + \ 'void f(int a)', + \ '{', + \ ' if (a == 1) {', + \ ' a = 0;', + \ ' } else if (a == 2) {', + \ ' a = 1;', + \ ' } else {', + \ ' a = 2;', + \ ' }', + \ ' if (a > 0) {', + \ ' if (a == 1) {', + \ ' a = 0;', + \ ' } /* missing newline */ } /* end of outer if */ else {', + \ ' a = 1;', + \ ' }', + \ ' if (a == 1)', + \ ' {', + \ ' a = 0;', + \ ' }', + \ ' else if (a == 2)', + \ ' {', + \ ' a = 1;', + \ ' }', + \ ' else', + \ ' {', + \ ' a = 2;', + \ ' }', + \ '}', + \ ]) + setfiletype c + syntax on + set foldmethod=syntax + + call assert_fails('syn foldlevel start start', 'E390') + call assert_fails('syn foldlevel not_an_option', 'E390') + + set foldlevel=1 + + syn foldlevel start + redir @c + syn foldlevel + redir END + call assert_equal("\nsyntax foldlevel start", @c) + syn sync fromstart + call assert_match('from the first line$', execute('syn sync')) + let a = map(range(3,9), 'foldclosed(v:val)') + call assert_equal([3,3,3,3,3,3,3], a) " attached cascade folds together + let a = map(range(10,15), 'foldclosed(v:val)') + call assert_equal([10,10,10,10,10,10], a) " over-attached 'else' hidden + let a = map(range(16,27), 'foldclosed(v:val)') + let unattached_results = [-1,17,17,17,-1,21,21,21,-1,25,25,25] + call assert_equal(unattached_results, a) " unattached cascade folds separately + + syn foldlevel minimum + redir @c + syn foldlevel + redir END + call assert_equal("\nsyntax foldlevel minimum", @c) + syn sync fromstart + let a = map(range(3,9), 'foldclosed(v:val)') + call assert_equal([3,3,5,5,7,7,7], a) " attached cascade folds separately + let a = map(range(10,15), 'foldclosed(v:val)') + call assert_equal([10,10,10,13,13,13], a) " over-attached 'else' visible + let a = map(range(16,27), 'foldclosed(v:val)') + call assert_equal(unattached_results, a) " unattached cascade folds separately + + set foldlevel=2 + + syn foldlevel start + syn sync fromstart + let a = map(range(11,14), 'foldclosed(v:val)') + call assert_equal([11,11,11,-1], a) " over-attached 'else' hidden + + syn foldlevel minimum + syn sync fromstart + let a = map(range(11,14), 'foldclosed(v:val)') + call assert_equal([11,11,-1,-1], a) " over-attached 'else' visible + + quit! +endfunc + +func Test_search_syntax_skip() + new + let lines =<< trim END + + /* This is VIM */ + Another Text for VIM + let a = "VIM" + END + call setline(1, lines) + syntax on + syntax match Comment "^/\*.*\*/" + syntax match String '".*"' + + " Skip argument using string evaluation. + 1 + call search('VIM', 'w', '', 0, 'synIDattr(synID(line("."), col("."), 1), "name") =~? "comment"') + call assert_equal('Another Text for VIM', getline('.')) + + 1 + call search('VIM', 'cw', '', 0, 'synIDattr(synID(line("."), col("."), 1), "name") !~? "string"') + call assert_equal(' let a = "VIM"', getline('.')) + + " Skip argument using Lambda. + 1 + call search('VIM', 'w', '', 0, { -> synIDattr(synID(line("."), col("."), 1), "name") =~? "comment"}) + call assert_equal('Another Text for VIM', getline('.')) + + 1 + call search('VIM', 'cw', '', 0, { -> synIDattr(synID(line("."), col("."), 1), "name") !~? "string"}) + call assert_equal(' let a = "VIM"', getline('.')) + + " Skip argument using funcref. + func InComment() + return synIDattr(synID(line("."), col("."), 1), "name") =~? "comment" + endfunc + func NotInString() + return synIDattr(synID(line("."), col("."), 1), "name") !~? "string" + endfunc + + 1 + call search('VIM', 'w', '', 0, function('InComment')) + call assert_equal('Another Text for VIM', getline('.')) + + 1 + call search('VIM', 'cw', '', 0, function('NotInString')) + call assert_equal(' let a = "VIM"', getline('.')) + + delfunc InComment + delfunc NotInString + bwipe! +endfunc + +func Test_syn_contained_transparent() + " Comments starting with "Regression:" show the result when the highlighting + " span of the containing item is assigned to the contained region. + syntax on + + let l:case = "Transparent region contained in region" + new + syntax region X start=/\[/ end=/\]/ contained transparent + syntax region Y start=/(/ end=/)/ contains=X + + call setline(1, "==(--[~~]--)==") + let l:expected = " YYYYYYYYYY " + eval AssertHighlightGroups(1, 1, l:expected, 1, l:case) + syntax clear Y X + bw! + + let l:case = "Transparent region extends region" + new + syntax region X start=/\[/ end=/\]/ contained transparent + syntax region Y start=/(/ end=/)/ end=/e/ contains=X + + call setline(1, "==(--[~~e~~]--)==") + let l:expected = " YYYYYYYYYYYYY " + " Regression: " YYYYYYY YYY " + eval AssertHighlightGroups(1, 1, l:expected, 1, l:case) + syntax clear Y X + bw! + + let l:case = "Nested transparent regions extend region" + new + syntax region X start=/\[/ end=/\]/ contained transparent + syntax region Y start=/(/ end=/)/ end=/e/ contains=X + + call setline(1, "==(--[~~e~~[~~e~~]~~e~~]--)==") + let l:expected = " YYYYYYYYYYYYYYYYYYYYYYYYY " + " Regression: " YYYYYYY YYYYYYYYY " + eval AssertHighlightGroups(1, 1, l:expected, 1, l:case) + syntax clear Y X + bw! + + let l:case = "Transparent region contained in match" + new + syntax region X start=/\[/ end=/\]/ contained transparent + syntax match Y /(.\{-})/ contains=X + + call setline(1, "==(--[~~]--)==") + let l:expected = " YYYYYYYYYY " + eval AssertHighlightGroups(1, 1, l:expected, 1, l:case) + syntax clear Y X + bw! + + let l:case = "Transparent region extends match" + new + syntax region X start=/\[/ end=/\]/ contained transparent + syntax match Y /(.\{-}[e)]/ contains=X + + call setline(1, "==(--[~~e~~]--)==") + let l:expected = " YYYYYYYYYY " + " Regression: " YYYYYYY " + eval AssertHighlightGroups(1, 1, l:expected, 1, l:case) + syntax clear Y X + bw! + + let l:case = "Nested transparent regions extend match" + new + syntax region X start=/\[/ end=/\]/ contained transparent + syntax match Y /(.\{-}[e)]/ contains=X + + call setline(1, "==(--[~~e~~[~~e~~]~~e~~]--)==") + let l:expected = " YYYYYYYYYYYYYYYYYYYYYY " + " Regression: " YYYYYYY YYYYYY " + eval AssertHighlightGroups(1, 1, l:expected, 1, l:case) + syntax clear Y X + bw! +endfunc + +func Test_syn_include_contains_TOP() + let l:case = "TOP in included syntax means its group list name" + new + syntax include @INCLUDED syntax/c.vim + syntax region FencedCodeBlockC start=/```c/ end=/```/ contains=@INCLUDED + + call setline(1, ['```c', '#if 0', 'int', '#else', 'int', '#endif', '```' ]) + let l:expected = ["cCppOutIf2"] + eval AssertHighlightGroups(3, 1, l:expected, 1) + " cCppOutElse has contains=TOP + let l:expected = ["cType"] + eval AssertHighlightGroups(5, 1, l:expected, 1, l:case) + syntax clear + bw! +endfunc + +" This was using freed memory +func Test_WinEnter_synstack_synID() + autocmd WinEnter * call synstack(line("."), col(".")) + autocmd WinEnter * call synID(line('.'), col('.') - 1, 1) + call setline(1, 'aaaaa') + normal! $ + new + close + + au! WinEnter + bw! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_system.vim b/test/old/testdir/test_system.vim new file mode 100644 index 0000000000..6c8373b335 --- /dev/null +++ b/test/old/testdir/test_system.vim @@ -0,0 +1,145 @@ +" Tests for system() and systemlist() + +source shared.vim +source check.vim + +func Test_System() + if !executable('echo') || !executable('cat') || !executable('wc') + return + endif + let out = 'echo 123'->system() + call assert_equal("123\n", out) + + let out = 'echo 123'->systemlist() + if &shell =~# 'cmd.exe$' + call assert_equal(["123\r"], out) + else + call assert_equal(['123'], out) + endif + + call assert_equal('123', system('cat', '123')) + call assert_equal(['123'], systemlist('cat', '123')) + call assert_equal(["as\<NL>df"], systemlist('cat', ["as\<NL>df"])) + + new Xdummy + call setline(1, ['asdf', "pw\<NL>er", 'xxxx']) + let out = system('wc -l', bufnr('%')) + " On OS/X we get leading spaces + let out = substitute(out, '^ *', '', '') + call assert_equal("3\n", out) + + let out = systemlist('wc -l', bufnr('%')) + " On Windows we may get a trailing CR. + if out != ["3\r"] + " On OS/X we get leading spaces + if type(out) == v:t_list + let out[0] = substitute(out[0], '^ *', '', '') + endif + call assert_equal(['3'], out) + endif + + let out = systemlist('cat', bufnr('%')) + " On Windows we may get a trailing CR. + if out != ["asdf\r", "pw\<NL>er\r", "xxxx\r"] + call assert_equal(['asdf', "pw\<NL>er", 'xxxx'], out) + endif + bwipe! + + call assert_fails('call system("wc -l", 99999)', 'E86:') +endfunc + +func Test_system_exmode() + if has('unix') " echo $? only works on Unix + let cmd = ' -es -c "source Xscript" +q; echo "result=$?"' + " Need to put this in a script, "catch" isn't found after an unknown + " function. + call writefile(['try', 'call doesnotexist()', 'catch', 'endtry'], 'Xscript') + let a = system(GetVimCommand() . cmd) + call assert_match('result=0', a) + call assert_equal(0, v:shell_error) + endif + + " Error before try does set error flag. + call writefile(['call nosuchfunction()', 'try', 'call doesnotexist()', 'catch', 'endtry'], 'Xscript') + if has('unix') " echo $? only works on Unix + let a = system(GetVimCommand() . cmd) + call assert_notequal('0', a[0]) + endif + + let cmd = ' -es -c "source Xscript" +q' + let a = system(GetVimCommand() . cmd) + call assert_notequal(0, v:shell_error) + call delete('Xscript') + + if has('unix') " echo $? only works on Unix + let cmd = ' -es -c "call doesnotexist()" +q; echo $?' + let a = system(GetVimCommand() . cmd) + call assert_notequal(0, a[0]) + endif + + let cmd = ' -es -c "call doesnotexist()" +q' + let a = system(GetVimCommand(). cmd) + call assert_notequal(0, v:shell_error) + + if has('unix') " echo $? only works on Unix + let cmd = ' -es -c "call doesnotexist()|let a=1" +q; echo $?' + let a = system(GetVimCommand() . cmd) + call assert_notequal(0, a[0]) + endif + + let cmd = ' -es -c "call doesnotexist()|let a=1" +q' + let a = system(GetVimCommand() . cmd) + call assert_notequal(0, v:shell_error) +endfunc + +func Test_system_with_shell_quote() + CheckMSWindows + + call mkdir('Xdir with spaces', 'p') + call system('copy "%COMSPEC%" "Xdir with spaces\cmd.exe"') + + let shell_save = &shell + let shellxquote_save = &shellxquote + try + " Set 'shell' always needs noshellslash. + let shellslash_save = &shellslash + set noshellslash + let shell_tests = [ + \ expand('$COMSPEC'), + \ '"' . fnamemodify('Xdir with spaces\cmd.exe', ':p') . '"', + \] + let &shellslash = shellslash_save + + let sxq_tests = ['', '(', '"'] + + " Matrix tests: 'shell' * 'shellxquote' + for shell in shell_tests + let &shell = shell + for sxq in sxq_tests + let &shellxquote = sxq + + let msg = printf('shell=%s shellxquote=%s', &shell, &shellxquote) + + try + let out = 'echo 123'->system() + catch + call assert_report(printf('%s: %s', msg, v:exception)) + continue + endtry + + " On Windows we may get a trailing space and CR. + if out != "123 \n" + call assert_equal("123\n", out, msg) + endif + + endfor + endfor + + finally + let &shell = shell_save + let &shellxquote = shellxquote_save + call delete('Xdir with spaces', 'rf') + endtry +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_tab.vim b/test/old/testdir/test_tab.vim new file mode 100644 index 0000000000..b8e8dfe062 --- /dev/null +++ b/test/old/testdir/test_tab.vim @@ -0,0 +1,90 @@ +" Various tests for inserting a Tab. + +" Tests for "r<Tab>" with 'smarttab' and 'expandtab' set/not set. +" Also test that dv_ works correctly +func Test_smarttab() + enew! + set smarttab expandtab ts=8 sw=4 + " make sure that backspace works, no matter what termcap is used + exe "set t_kD=\<C-V>x7f t_kb=\<C-V>x08" + call append(0, ['start text', + \ "\t\tsome test text", + \ 'test text', + \ "\t\tother test text", + \ ' a cde', + \ ' f ghi', + \ 'test text', + \ ' Second line beginning with whitespace' + \ ]) + call cursor(1, 1) + exe "normal /some\<CR>" + exe "normal r\t" + call assert_equal("\t\t ome test text", getline('.')) + set noexpandtab + exe "normal /other\<CR>" + exe "normal r\t" + call assert_equal("\t\t ther test text", getline('.')) + + " Test replacing with Tabs and then backspacing to undo it + exe "normal j0wR\t\t\t\<BS>\<BS>\<BS>" + call assert_equal(" a cde", getline('.')) + " Test replacing with Tabs + exe "normal j0wR\t\t\t" + call assert_equal(" \t\thi", getline('.')) + + " Test that copyindent works with expandtab set + set expandtab smartindent copyindent ts=8 sw=8 sts=8 + exe "normal jo{\<CR>x" + call assert_equal('{', getline(line('.') - 1)) + call assert_equal(' x', getline('.')) + set nosol + exe "normal /Second line/\<CR>" + exe "normal fwdv_" + call assert_equal(' with whitespace', getline('.')) + enew! + set expandtab& smartindent& copyindent& ts& sw& sts& +endfunc + +func Test_softtabstop() + new + set sts=0 sw=0 + exe "normal ix\<Tab>x\<Esc>" + call assert_equal("x\tx", getline(1)) + + call setline(1, '') + set sts=4 + exe "normal ix\<Tab>x\<Esc>" + call assert_equal("x x", getline(1)) + + call setline(1, '') + set sts=-1 sw=4 + exe "normal ix\<Tab>x\<Esc>" + call assert_equal("x x", getline(1)) + + call setline(1, 'x ') + set sts=0 sw=0 backspace=start + exe "normal A\<BS>x\<Esc>" + call assert_equal("x x", getline(1)) + + call setline(1, 'x ') + set sts=4 + exe "normal A\<BS>x\<Esc>" + call assert_equal("x x", getline(1)) + + call setline(1, 'x ') + set sts=-1 sw=4 + exe "normal A\<BS>x\<Esc>" + call assert_equal("x x", getline(1)) + + call setline(1, 'x') + set sts=-1 sw=0 smarttab + exe "normal I\<Tab>\<Esc>" + call assert_equal("\tx", getline(1)) + + call setline(1, 'x') + exe "normal I\<Tab>\<BS>\<Esc>" + call assert_equal("x", getline(1)) + + set sts=0 sw=0 backspace& nosmarttab + bwipe! +endfunc diff --git a/test/old/testdir/test_tabline.vim b/test/old/testdir/test_tabline.vim new file mode 100644 index 0000000000..d423f8a22c --- /dev/null +++ b/test/old/testdir/test_tabline.vim @@ -0,0 +1,231 @@ +" Test for tabline + +source shared.vim +source view_util.vim +source check.vim +source screendump.vim + +func TablineWithCaughtError() + let s:func_in_tabline_called = 1 + try + call eval('unknown expression') + catch + endtry + return '' +endfunc + +func TablineWithError() + let s:func_in_tabline_called = 1 + call eval('unknown expression') + return '' +endfunc + +func Test_caught_error_in_tabline() + if has('gui') + set guioptions-=e + endif + let showtabline_save = &showtabline + set showtabline=2 + let s:func_in_tabline_called = 0 + let tabline = '%{TablineWithCaughtError()}' + let &tabline = tabline + redraw! + call assert_true(s:func_in_tabline_called) + call assert_equal(tabline, &tabline) + set tabline= + let &showtabline = showtabline_save +endfunc + +func Test_tabline_will_be_disabled_with_error() + if has('gui') + set guioptions-=e + endif + let showtabline_save = &showtabline + set showtabline=2 + let s:func_in_tabline_called = 0 + let tabline = '%{TablineWithError()}' + try + let &tabline = tabline + redraw! + catch + endtry + call assert_true(s:func_in_tabline_called) + call assert_equal('', &tabline) + set tabline= + let &showtabline = showtabline_save +endfunc + +func Test_redrawtabline() + if has('gui') + set guioptions-=e + endif + let showtabline_save = &showtabline + set showtabline=2 + set tabline=%{bufnr('$')} + edit Xtabline1 + edit Xtabline2 + redraw + call assert_match(bufnr('$') . '', Screenline(1)) + au BufAdd * redrawtabline + badd Xtabline3 + call assert_match(bufnr('$') . '', Screenline(1)) + + set tabline= + let &showtabline = showtabline_save + au! Bufadd +endfunc + +" Test for the "%T" and "%X" flags in the 'tabline' option +func MyTabLine() + let s = '' + for i in range(tabpagenr('$')) + " set the tab page number (for mouse clicks) + let s .= '%' . (i + 1) . 'T' + + " the label is made by MyTabLabel() + let s .= ' %{MyTabLabel(' . (i + 1) . ')} ' + endfor + + " after the last tab fill with TabLineFill and reset tab page nr + let s .= '%T' + + " right-align the label to close the current tab page + if tabpagenr('$') > 1 + let s .= '%=%Xclose' + endif + + return s +endfunc + +func MyTabLabel(n) + let buflist = tabpagebuflist(a:n) + let winnr = tabpagewinnr(a:n) + return bufname(buflist[winnr - 1]) +endfunc + +func Test_tabline_flags() + if has('gui') + set guioptions-=e + endif + set tabline=%!MyTabLine() + edit Xtabline1 + tabnew Xtabline2 + redrawtabline + call assert_match('^ Xtabline1 Xtabline2\s\+close$', Screenline(1)) + set tabline= + %bw! +endfunc + +function EmptyTabname() + return "" +endfunction + +function MakeTabLine() abort + let titles = map(range(1, tabpagenr('$')), '"%( %" . v:val . "T%{EmptyTabname()}%T %)"') + let sep = 'あ' + let tabpages = join(titles, sep) + return tabpages .. sep .. '%=%999X X' +endfunction + +func Test_tabline_empty_group() + " this was reading invalid memory + set tabline=%!MakeTabLine() + tabnew + redraw! + + bw! + set tabline= +endfunc + +" When there are exactly 20 tabline format items (the exact size of the +" initial tabline items array), test that we don't write beyond the size +" of the array. +func Test_tabline_20_format_items_no_overrun() + set showtabline=2 + + let tabline = repeat('%#StatColorHi2#', 20) + let &tabline = tabline + redrawtabline + + set showtabline& tabline& +endfunc + +func Test_mouse_click_in_tab() + " This used to crash because TabPageIdxs[] was not initialized + let lines =<< trim END + tabnew + set mouse=a + exe "norm \<LeftMouse>" + END + call writefile(lines, 'Xclickscript') + call RunVim([], [], "-e -s -S Xclickscript -c qa") + + call delete('Xclickscript') +endfunc + +func Test_tabline_showcmd() + CheckScreendump + + let lines =<< trim END + func MyTabLine() + return '%S' + endfunc + + set showtabline=2 + set tabline=%!MyTabLine() + set showcmdloc=tabline + call setline(1, ['a', 'b', 'c']) + set foldopen+=jump + 1,2fold + 3 + END + call writefile(lines, 'XTest_tabline', 'D') + + let buf = RunVimInTerminal('-S XTest_tabline', {'rows': 6}) + + call term_sendkeys(buf, "g") + call VerifyScreenDump(buf, 'Test_tabline_showcmd_1', {}) + + " typing "gg" should open the fold + call term_sendkeys(buf, "g") + call VerifyScreenDump(buf, 'Test_tabline_showcmd_2', {}) + + call term_sendkeys(buf, "\<C-V>Gl") + call VerifyScreenDump(buf, 'Test_tabline_showcmd_3', {}) + + call term_sendkeys(buf, "\<Esc>1234") + call VerifyScreenDump(buf, 'Test_tabline_showcmd_4', {}) + + call term_sendkeys(buf, "\<Esc>:set tabline=\<CR>") + call term_sendkeys(buf, ":\<CR>") + call term_sendkeys(buf, "1234") + call VerifyScreenDump(buf, 'Test_tabline_showcmd_5', {}) + + call StopVimInTerminal(buf) +endfunc + +func TruncTabLine() + return '%1T口口%2Ta' .. repeat('b', &columns - 4) .. '%999X%#TabLine#c' +endfunc + +" Test 'tabline' with truncated double-width label at the start. +func Test_tabline_truncated_double_width() + tabnew + redraw + call assert_match('X$', Screenline(1)) + let attr_TabLineFill = screenattr(1, &columns - 1) + let attr_TabLine = screenattr(1, &columns) + call assert_notequal(attr_TabLine, attr_TabLineFill) + + set tabline=%!TruncTabLine() + redraw + call assert_equal('<a' .. repeat('b', &columns - 4) .. 'c', Screenline(1)) + call assert_equal(attr_TabLineFill, screenattr(1, &columns - 2)) + call assert_equal(attr_TabLine, screenattr(1, &columns - 1)) + call assert_equal(attr_TabLine, screenattr(1, &columns)) + + bw! + set tabline= +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_tabpage.vim b/test/old/testdir/test_tabpage.vim new file mode 100644 index 0000000000..4e7b09b9e7 --- /dev/null +++ b/test/old/testdir/test_tabpage.vim @@ -0,0 +1,908 @@ +" Tests for tabpage + +source screendump.vim +source check.vim + +function Test_tabpage() + CheckFeature quickfix + + bw! + " Simple test for opening and closing a tab page + tabnew + call assert_equal(2, tabpagenr()) + quit + + " Open three tab pages and use ":tabdo" + 0tabnew + 1tabnew + $tabnew + %del + tabdo call append(line('$'), tabpagenr()) + tabclose! 2 + tabrewind + let line1 = getline('$') + undo + q + tablast + let line2 = getline('$') + q! + call append(line('$'), line1) + call append(line('$'), line2) + unlet line1 line2 + call assert_equal(['', '3', '1', '4'], getline(1, '$')) + " + " Test for settabvar() and gettabvar() functions. Open a new tab page and + " set 3 variables to a number, string and a list. Verify that the variables + " are correctly set. + tabnew + tabfirst + call settabvar(2, 'val_num', 100) + eval 'SetTabVar test'->settabvar(2, 'val_str') + call settabvar(2, 'val_list', ['red', 'blue', 'green']) + " + call assert_true(gettabvar(2, 'val_num') == 100 && gettabvar(2, 'val_str') == 'SetTabVar test' && gettabvar(2, 'val_list') == ['red', 'blue', 'green']) + + tabnext 2 + call assert_true(t:val_num == 100 && t:val_str == 'SetTabVar test' && t:val_list == ['red', 'blue', 'green']) + tabclose + + " Test for ":tab drop exist-file" to keep current window. + sp test1 + tab drop test1 + call assert_true(tabpagenr('$') == 1 && winnr('$') == 2 && winnr() == 1) + close + " + " + " Test for ":tab drop new-file" to keep current window of tabpage 1. + split + tab drop newfile + call assert_true(tabpagenr('$') == 2 && tabpagewinnr(1, '$') == 2 && tabpagewinnr(1) == 1) + tabclose + q + " + " + " Test for ":tab drop multi-opened-file" to keep current tabpage and window. + new test1 + tabnew + new test1 + tab drop test1 + call assert_true(tabpagenr() == 2 && tabpagewinnr(2, '$') == 2 && tabpagewinnr(2) == 1) + tabclose + q + " + " + " Test for ":tab drop vertical-split-window" to jump test1 buffer + tabedit test1 + vnew + tabfirst + tab drop test1 + call assert_equal([2, 2, 2, 2], [tabpagenr('$'), tabpagenr(), tabpagewinnr(2, '$'), tabpagewinnr(2)]) + 1tabonly + " + " + for i in range(9) | tabnew | endfor + normal! 1gt + call assert_equal(1, tabpagenr()) + tabmove 5 + call assert_equal(5, tabpagenr()) + .tabmove + call assert_equal(5, tabpagenr()) + tabmove - + call assert_equal(4, tabpagenr()) + tabmove + + call assert_equal(5, tabpagenr()) + tabmove -2 + call assert_equal(3, tabpagenr()) + tabmove +4 + call assert_equal(7, tabpagenr()) + tabmove + call assert_equal(10, tabpagenr()) + 0tabmove + call assert_equal(1, tabpagenr()) + $tabmove + call assert_equal(10, tabpagenr()) + tabmove 0 + call assert_equal(1, tabpagenr()) + tabmove $ + call assert_equal(10, tabpagenr()) + 3tabmove + call assert_equal(4, tabpagenr()) + 7tabmove 5 + call assert_equal(5, tabpagenr()) + -tabmove + call assert_equal(4, tabpagenr()) + +tabmove + call assert_equal(5, tabpagenr()) + -2tabmove + call assert_equal(3, tabpagenr()) + +3tabmove + call assert_equal(6, tabpagenr()) + + " The following are a no-op + norm! 2gt + call assert_equal(2, tabpagenr()) + tabmove 2 + call assert_equal(2, tabpagenr()) + 2tabmove + call assert_equal(2, tabpagenr()) + tabmove 1 + call assert_equal(2, tabpagenr()) + 1tabmove + call assert_equal(2, tabpagenr()) + + call assert_fails('let t = tabpagenr("@")', 'E15:') + call assert_equal(0, tabpagewinnr(-1)) + call assert_fails("99tabmove", 'E16:') + call assert_fails("+99tabmove", 'E16:') + call assert_fails("-99tabmove", 'E16:') + call assert_fails("tabmove foo", 'E475:') + call assert_fails("tabmove 99", 'E475:') + call assert_fails("tabmove +99", 'E475:') + call assert_fails("tabmove -99", 'E475:') + call assert_fails("tabmove -3+", 'E475:') + call assert_fails("tabmove $3", 'E475:') + call assert_fails("%tabonly", 'E16:') + 1tabonly! + tabmove 1 + call assert_equal(1, tabpagenr()) + tabnew + call assert_fails("-2tabmove", 'E16:') + tabonly! +endfunc + +func Test_tabpage_drop() + edit f1 + tab split f2 + tab split f3 + normal! gt + call assert_equal(1, tabpagenr()) + + tab drop f3 + call assert_equal(3, tabpagenr()) + call assert_equal(1, tabpagenr('#')) + bwipe! + bwipe! + bwipe! + call assert_equal(1, tabpagenr('$')) +endfunc + +" Test autocommands +function Test_tabpage_with_autocmd() + command -nargs=1 -bar C :call add(s:li, '=== ' . <q-args> . ' ===')|<args> + augroup TestTabpageGroup + au! + autocmd TabEnter * call add(s:li, 'TabEnter') + autocmd WinEnter * call add(s:li, 'WinEnter') + autocmd BufEnter * call add(s:li, 'BufEnter') + autocmd TabLeave * call add(s:li, 'TabLeave') + autocmd WinLeave * call add(s:li, 'WinLeave') + autocmd BufLeave * call add(s:li, 'BufLeave') + augroup END + + let s:li = [] + let t:a='a' + C tab split + call assert_equal(['=== tab split ===', 'WinLeave', 'TabLeave', 'WinEnter', 'TabEnter'], s:li) + let s:li = [] + let t:a='b' + C tabnew + call assert_equal(['=== tabnew ===', 'WinLeave', 'TabLeave', 'WinEnter', 'TabEnter', 'BufLeave', 'BufEnter'], s:li) + let t:a='c' + let s:li = split(join(map(range(1, tabpagenr('$')), 'gettabvar(v:val, "a")')) , '\s\+') + call assert_equal(['a', 'b', 'c'], s:li) + + let s:li = [] + C call map(range(1, tabpagenr('$')), 'settabvar(v:val, ''a'', v:val*2)') + call assert_equal(["=== call map(range(1, tabpagenr('$')), 'settabvar(v:val, ''a'', v:val*2)') ==="], s:li) + let s:li = split(join(map(range(1, tabpagenr('$')), 'gettabvar(v:val, "a")')) , '\s\+') + call assert_equal(['2', '4', '6'], s:li) + + let s:li = [] + let w:a='a' + C vsplit + call assert_equal(['=== vsplit ===', 'WinLeave', 'WinEnter'], s:li) + let s:li = [] + let w:a='a' + let tabn=tabpagenr() + let winr=range(1, winnr('$')) + C tabnext 1 + call assert_equal(['=== tabnext 1 ===', 'BufLeave', 'WinLeave', 'TabLeave', 'WinEnter', 'TabEnter', 'BufEnter'], s:li) + let s:li = split(join(map(copy(winr), 'gettabwinvar('.tabn.', v:val, "a")')), '\s\+') + call assert_equal(['a', 'a'], s:li) + let s:li = [] + C call map(copy(winr), '(v:val*2)->settabwinvar(' .. tabn .. ', v:val, ''a'')') + let s:li = split(join(map(copy(winr), 'gettabwinvar('.tabn.', v:val, "a")')), '\s\+') + call assert_equal(['2', '4'], s:li) + + augroup TabDestructive + autocmd TabEnter * :C tabnext 2 | C tabclose 3 + augroup END + let s:li = [] + C tabnext 3 + call assert_equal(['=== tabnext 3 ===', 'BufLeave', 'WinLeave', 'TabLeave', 'WinEnter', 'TabEnter', '=== tabnext 2 ===', '=== tabclose 3 ==='], s:li) + call assert_equal(['2/2'], [tabpagenr().'/'.tabpagenr('$')]) + + autocmd! TabDestructive TabEnter + let s:li = [] + C tabnew + call assert_equal(['=== tabnew ===', 'WinLeave', 'TabLeave', 'WinEnter', 'TabEnter', 'BufLeave', 'BufEnter'], s:li) + let s:li = [] + C tabnext 1 + call assert_equal(['=== tabnext 1 ===', 'BufLeave', 'WinLeave', 'TabLeave', 'WinEnter', 'TabEnter', 'BufEnter'], s:li) + + autocmd TabDestructive TabEnter * nested :C tabnext 2 | C tabclose 3 + let s:li = [] + call assert_equal(3, tabpagenr('$')) + C tabnext 2 + call assert_equal(2, tabpagenr('$')) + call assert_equal(['=== tabnext 2 ===', 'WinLeave', 'TabLeave', 'WinEnter', 'TabEnter', '=== tabnext 2 ===', '=== tabclose 3 ==='], s:li) + call assert_equal(['2/2'], [tabpagenr().'/'.tabpagenr('$')]) + + delcommand C + autocmd! TabDestructive + augroup! TabDestructive + autocmd! TestTabpageGroup + augroup! TestTabpageGroup + 1tabonly! +endfunction + +" Test autocommands on tab drop +function Test_tabpage_with_autocmd_tab_drop() + augroup TestTabpageGroup + au! + autocmd TabEnter * call add(s:li, 'TabEnter') + autocmd WinEnter * call add(s:li, 'WinEnter') + autocmd BufEnter * call add(s:li, 'BufEnter') + autocmd TabLeave * call add(s:li, 'TabLeave') + autocmd WinLeave * call add(s:li, 'WinLeave') + autocmd BufLeave * call add(s:li, 'BufLeave') + augroup END + + let s:li = [] + tab drop test1 + call assert_equal(['BufLeave', 'BufEnter'], s:li) + + let s:li = [] + tab drop test2 test3 + call assert_equal([ + \ 'TabLeave', 'TabEnter', 'TabLeave', 'TabEnter', + \ 'TabLeave', 'WinEnter', 'TabEnter', 'BufEnter', + \ 'TabLeave', 'WinEnter', 'TabEnter', 'BufEnter'], s:li) + + autocmd! TestTabpageGroup + augroup! TestTabpageGroup + 1tabonly! +endfunction + +function Test_tabpage_with_tab_modifier() + CheckFeature quickfix + + for n in range(4) + tabedit + endfor + + function s:check_tab(pre_nr, cmd, post_nr) + exec 'tabnext ' . a:pre_nr + exec a:cmd + call assert_equal(a:post_nr, tabpagenr()) + call assert_equal('help', &buftype) + helpclose + endfunc + + call s:check_tab(1, 'tab help', 2) + call s:check_tab(1, '3tab help', 4) + call s:check_tab(1, '.tab help', 2) + call s:check_tab(1, '.+1tab help', 3) + call s:check_tab(1, '0tab help', 1) + call s:check_tab(2, '+tab help', 4) + call s:check_tab(2, '+2tab help', 5) + call s:check_tab(4, '-tab help', 4) + call s:check_tab(4, '-2tab help', 3) + call s:check_tab(3, '$tab help', 6) + call assert_fails('99tab help', 'E16:') + call assert_fails('+99tab help', 'E16:') + call assert_fails('-99tab help', 'E16:') + + delfunction s:check_tab + 1tabonly! +endfunction + +function Check_tab_count(pre_nr, cmd, post_nr) + exec 'tabnext' a:pre_nr + normal! G + exec a:cmd + call assert_equal(a:post_nr, tabpagenr(), a:cmd) +endfunc + +" Test for [count] of tabnext +function Test_tabpage_with_tabnext() + for n in range(4) + tabedit + call setline(1, ['', '', '3']) + endfor + + call Check_tab_count(1, 'tabnext', 2) + call Check_tab_count(1, '3tabnext', 3) + call Check_tab_count(1, '.tabnext', 1) + call Check_tab_count(1, '.+1tabnext', 2) + call Check_tab_count(2, '+tabnext', 3) + call Check_tab_count(2, '+2tabnext', 4) + call Check_tab_count(4, '-tabnext', 3) + call Check_tab_count(4, '-2tabnext', 2) + call Check_tab_count(3, '$tabnext', 5) + call assert_fails('0tabnext', 'E16:') + call assert_fails('99tabnext', 'E16:') + call assert_fails('+99tabnext', 'E16:') + call assert_fails('-99tabnext', 'E16:') + call Check_tab_count(1, 'tabnext 3', 3) + call Check_tab_count(2, 'tabnext +', 3) + call Check_tab_count(2, 'tabnext +2', 4) + call Check_tab_count(4, 'tabnext -', 3) + call Check_tab_count(4, 'tabnext -2', 2) + call Check_tab_count(3, 'tabnext $', 5) + call assert_fails('tabnext 0', 'E475:') + call assert_fails('tabnext .', 'E475:') + call assert_fails('tabnext -+', 'E475:') + call assert_fails('tabnext +2-', 'E475:') + call assert_fails('tabnext $3', 'E475:') + call assert_fails('tabnext 99', 'E475:') + call assert_fails('tabnext +99', 'E475:') + call assert_fails('tabnext -99', 'E475:') + + 1tabonly! +endfunction + +" Test for [count] of tabprevious +function Test_tabpage_with_tabprevious() + for n in range(5) + tabedit + call setline(1, ['', '', '3']) + endfor + + for cmd in ['tabNext', 'tabprevious'] + call Check_tab_count(6, cmd, 5) + call Check_tab_count(6, '3' . cmd, 3) + call Check_tab_count(6, '8' . cmd, 4) + call Check_tab_count(6, cmd . ' 3', 3) + call Check_tab_count(6, cmd . ' 8', 4) + for n in range(2) + for c in ['0', '.+3', '+', '+2' , '-', '-2' , '$', '+99', '-99'] + if n == 0 " pre count + let entire_cmd = c . cmd + let err_code = 'E16:' + else + let entire_cmd = cmd . ' ' . c + let err_code = 'E475:' + endif + call assert_fails(entire_cmd, err_code) + endfor + endfor + endfor + + 1tabonly! +endfunction + +function s:reconstruct_tabpage_for_test(nr) + let n = (a:nr > 2) ? a:nr - 2 : 1 + 1tabonly! + 0tabedit n0 + for n in range(1, n) + exec '$tabedit n' . n + if n == 1 + call setline(1, ['', '', '3']) + endif + endfor +endfunc + +func Test_tabpage_ctrl_pgup_pgdown() + enew! + tabnew tab1 + tabnew tab2 + + call assert_equal(3, tabpagenr()) + exe "norm! \<C-PageUp>" + call assert_equal(2, tabpagenr()) + exe "norm! \<C-PageDown>" + call assert_equal(3, tabpagenr()) + + " Check wrapping at last or first page. + exe "norm! \<C-PageDown>" + call assert_equal(1, tabpagenr()) + exe "norm! \<C-PageUp>" + call assert_equal(3, tabpagenr()) + + " With a count, <C-PageUp> and <C-PageDown> are not symmetrical somehow: + " - {count}<C-PageUp> goes {count} pages downward (relative count) + " - {count}<C-PageDown> goes to page number {count} (absolute count) + exe "norm! 2\<C-PageUp>" + call assert_equal(1, tabpagenr()) + exe "norm! 2\<C-PageDown>" + call assert_equal(2, tabpagenr()) + + 1tabonly! +endfunc + +" Test for [count] of tabclose +function Test_tabpage_with_tabclose() + + " pre count + call s:reconstruct_tabpage_for_test(6) + call Check_tab_count(3, 'tabclose!', 3) + call Check_tab_count(1, '3tabclose', 1) + call Check_tab_count(4, '4tabclose', 3) + call Check_tab_count(3, '1tabclose', 2) + call Check_tab_count(2, 'tabclose', 1) + call assert_equal(1, tabpagenr('$')) + call assert_equal('', bufname('')) + + call s:reconstruct_tabpage_for_test(6) + call Check_tab_count(2, '$tabclose', 2) + call Check_tab_count(4, '.tabclose', 4) + call Check_tab_count(3, '.+tabclose', 3) + call Check_tab_count(3, '.-2tabclose', 2) + call Check_tab_count(1, '.+1tabclose!', 1) + call assert_equal(1, tabpagenr('$')) + call assert_equal('', bufname('')) + + " post count + call s:reconstruct_tabpage_for_test(6) + call Check_tab_count(3, 'tabclose!', 3) + call Check_tab_count(1, 'tabclose 3', 1) + call Check_tab_count(4, 'tabclose 4', 3) + call Check_tab_count(3, 'tabclose 1', 2) + call Check_tab_count(2, 'tabclose', 1) + call assert_equal(1, tabpagenr('$')) + call assert_equal('', bufname('')) + + call s:reconstruct_tabpage_for_test(6) + call Check_tab_count(2, 'tabclose $', 2) + call Check_tab_count(4, 'tabclose', 4) + call Check_tab_count(3, 'tabclose +', 3) + call Check_tab_count(3, 'tabclose -2', 2) + call Check_tab_count(1, 'tabclose! +1', 1) + call assert_equal(1, tabpagenr('$')) + call assert_equal('', bufname('')) + + call s:reconstruct_tabpage_for_test(6) + for n in range(2) + for c in ['0', '$3', '99', '+99', '-99'] + if n == 0 " pre count + let entire_cmd = c . 'tabclose' + let err_code = 'E16:' + else + let entire_cmd = 'tabclose ' . c + let err_code = 'E475:' + endif + call assert_fails(entire_cmd, err_code) + call assert_equal(6, tabpagenr('$')) + endfor + endfor + + call assert_fails('3tabclose', 'E37:') + call assert_fails('tabclose 3', 'E37:') + call assert_fails('tabclose -+', 'E475:') + call assert_fails('tabclose +2-', 'E475:') + call assert_equal(6, tabpagenr('$')) + + 1tabonly! +endfunction + +" Test for [count] of tabonly +function Test_tabpage_with_tabonly() + + " Test for the normal behavior (pre count only) + let tc = [ [4, '.', '!'], [2, '.+', ''], [3, '.-2', '!'], [1, '.+1', '!'] ] + for c in tc + call s:reconstruct_tabpage_for_test(6) + let entire_cmd = c[1] . 'tabonly' . c[2] + call Check_tab_count(c[0], entire_cmd, 1) + call assert_equal(1, tabpagenr('$')) + endfor + + " Test for the normal behavior + let tc2 = [ [3, '', ''], [1, '3', ''], [4, '4', '!'], [3, '1', '!'], + \ [2, '', '!'], + \ [2, '$', '!'], [3, '+', '!'], [3, '-2', '!'], [3, '+1', '!'] + \ ] + for n in range(2) + for c in tc2 + call s:reconstruct_tabpage_for_test(6) + if n == 0 " pre count + let entire_cmd = c[1] . 'tabonly' . c[2] + else + let entire_cmd = 'tabonly' . c[2] . ' ' . c[1] + endif + call Check_tab_count(c[0], entire_cmd, 1) + call assert_equal(1, tabpagenr('$')) + endfor + endfor + + " Test for the error behavior + for n in range(2) + for c in ['0', '$3', '99', '+99', '-99'] + call s:reconstruct_tabpage_for_test(6) + if n == 0 " pre count + let entire_cmd = c . 'tabonly' + let err_code = 'E16:' + else + let entire_cmd = 'tabonly ' . c + let err_code = 'E475:' + endif + call assert_fails(entire_cmd, err_code) + call assert_equal(6, tabpagenr('$')) + endfor + endfor + + " Test for the error behavior (post count only) + for c in tc + call s:reconstruct_tabpage_for_test(6) + let entire_cmd = 'tabonly' . c[2] . ' ' . c[1] + let err_code = 'E475:' + call assert_fails(entire_cmd, err_code) + call assert_equal(6, tabpagenr('$')) + endfor + + call assert_fails('tabonly -+', 'E475:') + call assert_fails('tabonly +2-', 'E475:') + call assert_equal(6, tabpagenr('$')) + + 1tabonly! + new + only! +endfunction + +func Test_tabnext_on_buf_unload1() + " This once caused a crash + new + tabedit + tabfirst + au BufUnload <buffer> tabnext + q + + while tabpagenr('$') > 1 + bwipe! + endwhile +endfunc + +func Test_tabnext_on_buf_unload2() + " This once caused a crash + tabedit + autocmd BufUnload <buffer> tabnext + file x + edit y + + while tabpagenr('$') > 1 + bwipe! + endwhile +endfunc + +func Test_close_on_quitpre() + " This once caused a crash + edit Xtest + new + only + set bufhidden=delete + au QuitPre <buffer> close + tabnew tab1 + tabnew tab2 + 1tabn + q! + call assert_equal(1, tabpagenr()) + call assert_equal(2, tabpagenr('$')) + " clean up + while tabpagenr('$') > 1 + bwipe! + endwhile + buf Xtest +endfunc + +func Test_tabs() + enew! + tabnew tab1 + norm ixxx + let a=split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ '# [No Name]', + \ 'Tab page 2', + \ '> + tab1'], a) + + 1tabonly! + bw! +endfunc + +func Test_tabpage_cmdheight() + CheckRunVimInTerminal + call writefile([ + \ 'set laststatus=2', + \ 'set cmdheight=2', + \ 'tabnew', + \ 'set cmdheight=3', + \ 'tabnext', + \ 'redraw!', + \ 'echo "hello\nthere"', + \ 'tabnext', + \ 'redraw', + \ ], 'XTest_tabpage_cmdheight') + " Check that cursor line is concealed + let buf = RunVimInTerminal('-S XTest_tabpage_cmdheight', {'statusoff': 3}) + call VerifyScreenDump(buf, 'Test_tabpage_cmdheight', {}) + + call StopVimInTerminal(buf) + call delete('XTest_tabpage_cmdheight') +endfunc + +" Test for closing the tab page from a command window +func Test_tabpage_close_cmdwin() + tabnew + call feedkeys("q/:tabclose\<CR>\<Esc>", 'xt') + call assert_equal(2, tabpagenr('$')) + call feedkeys("q/:tabonly\<CR>\<Esc>", 'xt') + call assert_equal(2, tabpagenr('$')) + tabonly +endfunc + +" Pressing <C-PageUp> in insert mode should go to the previous tab page +" and <C-PageDown> should go to the next tab page +func Test_tabpage_Ctrl_Pageup() + tabnew + call feedkeys("i\<C-PageUp>", 'xt') + call assert_equal(1, tabpagenr()) + call feedkeys("i\<C-PageDown>", 'xt') + call assert_equal(2, tabpagenr()) + %bw! +endfunc + +" Return the terminal key code for selecting a tab page from the tabline. This +" sequence contains the following codes: a CSI (0x9b), KS_TABLINE (0xf0), +" KS_FILLER (0x58) and then the tab page number. +func TabLineSelectPageCode(tabnr) + return "\x9b\xf0\x58" .. nr2char(a:tabnr) +endfunc + +" Return the terminal key code for opening a new tabpage from the tabpage +" menu. This sequence consists of the following codes: a CSI (0x9b), +" KS_TABMENU (0xef), KS_FILLER (0x58), the tab page number and +" TABLINE_MENU_NEW (2). +func TabMenuNewItemCode(tabnr) + return "\x9b\xef\x58" .. nr2char(a:tabnr) .. nr2char(2) +endfunc + +" Return the terminal key code for closing a tabpage from the tabpage menu. +" This sequence consists of the following codes: a CSI (0x9b), KS_TABMENU +" (0xef), KS_FILLER (0x58), the tab page number and TABLINE_MENU_CLOSE (1). +func TabMenuCloseItemCode(tabnr) + return "\x9b\xef\x58" .. nr2char(a:tabnr) .. nr2char(1) +endfunc + +" Test for using the tabpage menu from the insert and normal modes +func Test_tabline_tabmenu() + " only works in GUI + CheckGui + + %bw! + tabnew + tabnew + call assert_equal(3, tabpagenr()) + + " go to tab page 2 in normal mode + call feedkeys(TabLineSelectPageCode(2), "Lx!") + call assert_equal(2, tabpagenr()) + + " close tab page 3 in normal mode + call feedkeys(TabMenuCloseItemCode(3), "Lx!") + call assert_equal(2, tabpagenr('$')) + call assert_equal(2, tabpagenr()) + + " open new tab page before tab page 1 in normal mode + call feedkeys(TabMenuNewItemCode(1), "Lx!") + call assert_equal(1, tabpagenr()) + call assert_equal(3, tabpagenr('$')) + + " go to tab page 2 in operator-pending mode (should beep) + call assert_beeps('call feedkeys("c" .. TabLineSelectPageCode(2), "Lx!")') + call assert_equal(2, tabpagenr()) + call assert_equal(3, tabpagenr('$')) + + " open new tab page before tab page 1 in operator-pending mode (should beep) + call assert_beeps('call feedkeys("c" .. TabMenuNewItemCode(1), "Lx!")') + call assert_equal(1, tabpagenr()) + call assert_equal(4, tabpagenr('$')) + + " open new tab page after tab page 3 in normal mode + call feedkeys(TabMenuNewItemCode(4), "Lx!") + call assert_equal(4, tabpagenr()) + call assert_equal(5, tabpagenr('$')) + + " go to tab page 2 in insert mode + call feedkeys("i" .. TabLineSelectPageCode(2) .. "\<C-C>", "Lx!") + call assert_equal(2, tabpagenr()) + + " close tab page 2 in insert mode + call feedkeys("i" .. TabMenuCloseItemCode(2) .. "\<C-C>", "Lx!") + call assert_equal(4, tabpagenr('$')) + + " open new tab page before tab page 3 in insert mode + call feedkeys("i" .. TabMenuNewItemCode(3) .. "\<C-C>", "Lx!") + call assert_equal(3, tabpagenr()) + call assert_equal(5, tabpagenr('$')) + + " open new tab page after tab page 4 in insert mode + call feedkeys("i" .. TabMenuNewItemCode(5) .. "\<C-C>", "Lx!") + call assert_equal(5, tabpagenr()) + call assert_equal(6, tabpagenr('$')) + + %bw! +endfunc + +" Test for changing the current tab page from an autocmd when closing a tab +" page. +func Test_tabpage_switchtab_on_close() + only + tabnew + tabnew + " Test for BufLeave + augroup T1 + au! + au BufLeave * tabfirst + augroup END + tabclose + call assert_equal(1, tabpagenr()) + augroup T1 + au! + augroup END + + " Test for WinLeave + $tabnew + augroup T1 + au! + au WinLeave * tabfirst + augroup END + tabclose + call assert_equal(1, tabpagenr()) + augroup T1 + au! + augroup END + + " Test for TabLeave + $tabnew + augroup T1 + au! + au TabLeave * tabfirst + augroup END + tabclose + call assert_equal(1, tabpagenr()) + augroup T1 + au! + augroup END + augroup! T1 + tabonly +endfunc + +" Test for closing the destination tabpage when jumping from one to another. +func Test_tabpage_close_on_switch() + tabnew + tabnew + edit Xfile + augroup T2 + au! + au BufLeave Xfile 1tabclose + augroup END + tabfirst + call assert_equal(2, tabpagenr()) + call assert_equal('Xfile', @%) + augroup T2 + au! + augroup END + augroup! T2 + %bw! +endfunc + +" Test for jumping to last accessed tabpage +func Test_lastused_tabpage() + tabonly! + call assert_equal(0, tabpagenr('#')) + call assert_beeps('call feedkeys("g\<Tab>", "xt")') + call assert_beeps('call feedkeys("\<C-Tab>", "xt")') + call assert_beeps('call feedkeys("\<C-W>g\<Tab>", "xt")') + call assert_fails('tabnext #', 'E475:') + + " open four tab pages + tabnew + tabnew + tabnew + + 2tabnext + + " Test for g<Tab> + call assert_equal(4, tabpagenr('#')) + call feedkeys("g\<Tab>", "xt") + call assert_equal(4, tabpagenr()) + call assert_equal(2, tabpagenr('#')) + + " Test for <C-Tab> + call feedkeys("\<C-Tab>", "xt") + call assert_equal(2, tabpagenr()) + call assert_equal(4, tabpagenr('#')) + + " Test for <C-W>g<Tab> + call feedkeys("\<C-W>g\<Tab>", "xt") + call assert_equal(4, tabpagenr()) + call assert_equal(2, tabpagenr('#')) + + " Test for :tabnext # + tabnext # + call assert_equal(2, tabpagenr()) + call assert_equal(4, tabpagenr('#')) + + " Try to jump to a closed tab page + tabclose # + call assert_equal(0, tabpagenr('#')) + call feedkeys("g\<Tab>", "xt") + call assert_equal(2, tabpagenr()) + call feedkeys("\<C-Tab>", "xt") + call assert_equal(2, tabpagenr()) + call feedkeys("\<C-W>g\<Tab>", "xt") + call assert_equal(2, tabpagenr()) + call assert_fails('tabnext #', 'E475:') + call assert_equal(2, tabpagenr()) + + " Test for :tabonly # + let wnum = win_getid() + $tabnew + tabonly # + call assert_equal(wnum, win_getid()) + call assert_equal(1, tabpagenr('$')) + + " Test for :tabmove # + tabnew + let wnum = win_getid() + tabnew + tabnew + tabnext 2 + tabmove # + call assert_equal(4, tabpagenr()) + call assert_equal(wnum, win_getid()) + + tabonly! +endfunc + +" Test for tabpage allocation failure +func Test_tabpage_alloc_failure() + CheckFunction test_alloc_fail + call test_alloc_fail(GetAllocId('newtabpage_tvars'), 0, 0) + call assert_fails('tabnew', 'E342:') + + call test_alloc_fail(GetAllocId('newtabpage_tvars'), 0, 0) + edit Xfile1 + call assert_fails('tabedit Xfile2', 'E342:') + call assert_equal(1, winnr('$')) + call assert_equal(1, tabpagenr('$')) + call assert_equal('Xfile1', @%) + + new + call test_alloc_fail(GetAllocId('newtabpage_tvars'), 0, 0) + call assert_fails('wincmd T', 'E342:') + bw! + + call test_alloc_fail(GetAllocId('newtabpage_tvars'), 0, 0) + call assert_fails('tab split', 'E342:') + call assert_equal(2, winnr('$')) + call assert_equal(1, tabpagenr('$')) +endfunc + +" this was giving ml_get errors +func Test_tabpage_last_line() + enew + call setline(1, repeat(['a'], &lines + 5)) + $ + tabnew + call setline(1, repeat(['b'], &lines + 20)) + $ + tabNext + call assert_equal('a', getline('.')) + + bwipe! + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_tagcase.vim b/test/old/testdir/test_tagcase.vim new file mode 100644 index 0000000000..53c08ccf1e --- /dev/null +++ b/test/old/testdir/test_tagcase.vim @@ -0,0 +1,74 @@ +" test 'tagcase' option + +func Test_tagcase() + call writefile(["Bar\tXtext\t3", "Foo\tXtext\t2", "foo\tXtext\t4"], 'Xtags') + set tags=Xtags + e Xtext + + for &ic in [0, 1] + for &scs in [0, 1] + for &g:tc in ["followic", "ignore", "match", "followscs", "smart"] + for &l:tc in ["", "followic", "ignore", "match", "followscs", "smart"] + let smart = 0 + if &l:tc != '' + let tc = &l:tc + else + let tc = &g:tc + endif + if tc == 'followic' + let ic = &ic + elseif tc == 'ignore' + let ic = 1 + elseif tc == 'followscs' + let ic = &ic + let smart = &scs + elseif tc == 'smart' + let ic = 1 + let smart = 1 + else + let ic = 0 + endif + if ic && smart + call assert_equal(['foo', 'Foo'], map(taglist("^foo$"), {i, v -> v.name})) + call assert_equal(['Foo'], map(taglist("^Foo$"), {i, v -> v.name})) + elseif ic + call assert_equal(['foo', 'Foo'], map(taglist("^foo$"), {i, v -> v.name})) + call assert_equal(['Foo', 'foo'], map(taglist("^Foo$"), {i, v -> v.name})) + else + call assert_equal(['foo'], map(taglist("^foo$"), {i, v -> v.name})) + call assert_equal(['Foo'], map(taglist("^Foo$"), {i, v -> v.name})) + endif + endfor + endfor + endfor + endfor + + call delete('Xtags') + set tags& + set ic& + setg tc& + setl tc& + set scs& +endfunc + +func Test_set_tagcase() + " Verify default values. + set ic& + setg tc& + setl tc& + call assert_equal(0, &ic) + call assert_equal('followic', &g:tc) + call assert_equal('followic', &l:tc) + call assert_equal('followic', &tc) + + " Verify that the local setting accepts <empty> but that the global setting + " does not. The first of these (setting the local value to <empty>) should + " succeed; the other two should fail. + setl tc= + call assert_fails('setg tc=', 'E474:') + call assert_fails('set tc=', 'E474:') + + set ic& + setg tc& + setl tc& +endfunc diff --git a/test/old/testdir/test_tagfunc.vim b/test/old/testdir/test_tagfunc.vim new file mode 100644 index 0000000000..44916f2fc9 --- /dev/null +++ b/test/old/testdir/test_tagfunc.vim @@ -0,0 +1,417 @@ +" Test 'tagfunc' + +source vim9.vim +source check.vim +source screendump.vim + +func TagFunc(pat, flag, info) + let g:tagfunc_args = [a:pat, a:flag, a:info] + let tags = [] + for num in range(1,10) + let tags += [{ + \ 'cmd': '2', 'name': 'nothing'.num, 'kind': 'm', + \ 'filename': 'Xfile1', 'user_data': 'somedata'.num, + \}] + endfor + return tags +endfunc + +func Test_tagfunc() + set tagfunc=TagFunc + new Xfile1 + call setline(1, ['empty', 'one()', 'empty']) + write + + call assert_equal({'cmd': '2', 'static': 0, + \ 'name': 'nothing2', 'user_data': 'somedata2', + \ 'kind': 'm', 'filename': 'Xfile1'}, taglist('.')[1]) + + call settagstack(win_getid(), {'items': []}) + + tag arbitrary + call assert_equal('arbitrary', g:tagfunc_args[0]) + call assert_equal('', g:tagfunc_args[1]) + call assert_equal('somedata1', gettagstack().items[0].user_data) + 5tag arbitrary + call assert_equal('arbitrary', g:tagfunc_args[0]) + call assert_equal('', g:tagfunc_args[1]) + call assert_equal('somedata5', gettagstack().items[1].user_data) + pop + tag + call assert_equal('arbitrary', g:tagfunc_args[0]) + call assert_equal('', g:tagfunc_args[1]) + call assert_equal('somedata5', gettagstack().items[1].user_data) + + let g:tagfunc_args=[] + execute "normal! \<c-]>" + call assert_equal('one', g:tagfunc_args[0]) + call assert_equal('c', g:tagfunc_args[1]) + + let g:tagfunc_args=[] + execute "tag /foo$" + call assert_equal('foo$', g:tagfunc_args[0]) + call assert_equal('r', g:tagfunc_args[1]) + + set cpt=t + let g:tagfunc_args=[] + execute "normal! i\<c-n>\<c-y>" + call assert_equal('\<\k\k', g:tagfunc_args[0]) + call assert_equal('cir', g:tagfunc_args[1]) + call assert_equal('nothing1', getline('.')[0:7]) + + let g:tagfunc_args=[] + execute "normal! ono\<c-n>\<c-n>\<c-y>" + call assert_equal('\<no', g:tagfunc_args[0]) + call assert_equal('cir', g:tagfunc_args[1]) + call assert_equal('nothing2', getline('.')[0:7]) + + func BadTagFunc1(...) + return 0 + endfunc + func BadTagFunc2(...) + return [1] + endfunc + func BadTagFunc3(...) + return [{'name': 'foo'}] + endfunc + + for &tagfunc in ['BadTagFunc1', 'BadTagFunc2', 'BadTagFunc3'] + try + tag nothing + call assert_false(1, 'tag command should have failed') + catch + call assert_exception('E987:') + endtry + exe 'delf' &tagfunc + endfor + + func NullTagFunc(...) + return v:null + endfunc + set tags= tfu=NullTagFunc + call assert_fails('tag nothing', 'E433') + delf NullTagFunc + + bwipe! + set tags& tfu& cpt& + call delete('Xfile1') +endfunc + +" Test for modifying the tag stack from a tag function and jumping to a tag +" from a tag function +func Test_tagfunc_settagstack() + func Mytagfunc1(pat, flags, info) + call settagstack(1, {'tagname' : 'mytag', 'from' : [0, 10, 1, 0]}) + return [{'name' : 'mytag', 'filename' : 'Xtest', 'cmd' : '1'}] + endfunc + set tagfunc=Mytagfunc1 + call writefile([''], 'Xtest') + call assert_fails('tag xyz', 'E986:') + + func Mytagfunc2(pat, flags, info) + tag test_tag + return [{'name' : 'mytag', 'filename' : 'Xtest', 'cmd' : '1'}] + endfunc + set tagfunc=Mytagfunc2 + call assert_fails('tag xyz', 'E986:') + + call delete('Xtest') + set tagfunc& + delfunc Mytagfunc1 + delfunc Mytagfunc2 +endfunc + +" Script local tagfunc callback function +func s:ScriptLocalTagFunc(pat, flags, info) + let g:ScriptLocalFuncArgs = [a:pat, a:flags, a:info] + return v:null +endfunc + +" Test for different ways of setting the 'tagfunc' option +func Test_tagfunc_callback() + func TagFunc1(callnr, pat, flags, info) + let g:TagFunc1Args = [a:callnr, a:pat, a:flags, a:info] + return v:null + endfunc + func TagFunc2(pat, flags, info) + let g:TagFunc2Args = [a:pat, a:flags, a:info] + return v:null + endfunc + + let lines =<< trim END + #" Test for using a function name + LET &tagfunc = 'g:TagFunc2' + new + LET g:TagFunc2Args = [] + call assert_fails('tag a10', 'E433:') + call assert_equal(['a10', '', {}], g:TagFunc2Args) + bw! + + #" Test for using a function() + set tagfunc=function('g:TagFunc1',\ [10]) + new + LET g:TagFunc1Args = [] + call assert_fails('tag a11', 'E433:') + call assert_equal([10, 'a11', '', {}], g:TagFunc1Args) + bw! + + #" Using a funcref variable to set 'tagfunc' + VAR Fn = function('g:TagFunc1', [11]) + LET &tagfunc = Fn + new + LET g:TagFunc1Args = [] + call assert_fails('tag a12', 'E433:') + call assert_equal([11, 'a12', '', {}], g:TagFunc1Args) + bw! + + #" Using a string(funcref_variable) to set 'tagfunc' + LET Fn = function('g:TagFunc1', [12]) + LET &tagfunc = string(Fn) + new + LET g:TagFunc1Args = [] + call assert_fails('tag a12', 'E433:') + call assert_equal([12, 'a12', '', {}], g:TagFunc1Args) + bw! + + #" Test for using a funcref() + set tagfunc=funcref('g:TagFunc1',\ [13]) + new + LET g:TagFunc1Args = [] + call assert_fails('tag a13', 'E433:') + call assert_equal([13, 'a13', '', {}], g:TagFunc1Args) + bw! + + #" Using a funcref variable to set 'tagfunc' + LET Fn = funcref('g:TagFunc1', [14]) + LET &tagfunc = Fn + new + LET g:TagFunc1Args = [] + call assert_fails('tag a14', 'E433:') + call assert_equal([14, 'a14', '', {}], g:TagFunc1Args) + bw! + + #" Using a string(funcref_variable) to set 'tagfunc' + LET Fn = funcref('g:TagFunc1', [15]) + LET &tagfunc = string(Fn) + new + LET g:TagFunc1Args = [] + call assert_fails('tag a14', 'E433:') + call assert_equal([15, 'a14', '', {}], g:TagFunc1Args) + bw! + + #" Test for using a lambda function + VAR optval = "LSTART a, b, c LMIDDLE TagFunc1(16, a, b, c) LEND" + LET optval = substitute(optval, ' ', '\\ ', 'g') + exe "set tagfunc=" .. optval + new + LET g:TagFunc1Args = [] + call assert_fails('tag a17', 'E433:') + call assert_equal([16, 'a17', '', {}], g:TagFunc1Args) + bw! + + #" Set 'tagfunc' to a lambda expression + LET &tagfunc = LSTART a, b, c LMIDDLE TagFunc1(17, a, b, c) LEND + new + LET g:TagFunc1Args = [] + call assert_fails('tag a18', 'E433:') + call assert_equal([17, 'a18', '', {}], g:TagFunc1Args) + bw! + + #" Set 'tagfunc' to a string(lambda expression) + LET &tagfunc = 'LSTART a, b, c LMIDDLE TagFunc1(18, a, b, c) LEND' + new + LET g:TagFunc1Args = [] + call assert_fails('tag a18', 'E433:') + call assert_equal([18, 'a18', '', {}], g:TagFunc1Args) + bw! + + #" Set 'tagfunc' to a variable with a lambda expression + VAR Lambda = LSTART a, b, c LMIDDLE TagFunc1(19, a, b, c) LEND + LET &tagfunc = Lambda + new + LET g:TagFunc1Args = [] + call assert_fails("tag a19", "E433:") + call assert_equal([19, 'a19', '', {}], g:TagFunc1Args) + bw! + + #" Set 'tagfunc' to a string(variable with a lambda expression) + LET Lambda = LSTART a, b, c LMIDDLE TagFunc1(20, a, b, c) LEND + LET &tagfunc = string(Lambda) + new + LET g:TagFunc1Args = [] + call assert_fails("tag a19", "E433:") + call assert_equal([20, 'a19', '', {}], g:TagFunc1Args) + bw! + + #" Test for using a lambda function with incorrect return value + LET Lambda = LSTART a, b, c LMIDDLE strlen(a) LEND + LET &tagfunc = string(Lambda) + new + call assert_fails("tag a20", "E987:") + bw! + + #" Test for clearing the 'tagfunc' option + set tagfunc='' + set tagfunc& + call assert_fails("set tagfunc=function('abc')", "E700:") + call assert_fails("set tagfunc=funcref('abc')", "E700:") + + #" set 'tagfunc' to a non-existing function + LET &tagfunc = function('g:TagFunc2', [21]) + LET g:TagFunc2Args = [] + call assert_fails("set tagfunc=function('NonExistingFunc')", 'E700:') + call assert_fails("LET &tagfunc = function('NonExistingFunc')", 'E700:') + call assert_fails("tag axb123", 'E426:') + call assert_equal([], g:TagFunc2Args) + bw! + END + call CheckLegacyAndVim9Success(lines) + + " Test for using a script-local function name + func s:TagFunc3(pat, flags, info) + let g:TagFunc3Args = [a:pat, a:flags, a:info] + return v:null + endfunc + set tagfunc=s:TagFunc3 + new + let g:TagFunc3Args = [] + call assert_fails('tag a21', 'E433:') + call assert_equal(['a21', '', {}], g:TagFunc3Args) + bw! + let &tagfunc = 's:TagFunc3' + new + let g:TagFunc3Args = [] + call assert_fails('tag a22', 'E433:') + call assert_equal(['a22', '', {}], g:TagFunc3Args) + bw! + delfunc s:TagFunc3 + + " invalid return value + let &tagfunc = "{a -> 'abc'}" + call assert_fails("echo taglist('a')", "E987:") + + " Using Vim9 lambda expression in legacy context should fail + " set tagfunc=(a,\ b,\ c)\ =>\ g:TagFunc1(21,\ a,\ b,\ c) + new + let g:TagFunc1Args = [] + " call assert_fails("tag a17", "E117:") + call assert_equal([], g:TagFunc1Args) + bw! + + " Test for using a script local function + set tagfunc=<SID>ScriptLocalTagFunc + new + let g:ScriptLocalFuncArgs = [] + call assert_fails('tag a15', 'E433:') + call assert_equal(['a15', '', {}], g:ScriptLocalFuncArgs) + bw! + + " Test for using a script local funcref variable + let Fn = function("s:ScriptLocalTagFunc") + let &tagfunc= Fn + new + let g:ScriptLocalFuncArgs = [] + call assert_fails('tag a16', 'E433:') + call assert_equal(['a16', '', {}], g:ScriptLocalFuncArgs) + bw! + + " Test for using a string(script local funcref variable) + let Fn = function("s:ScriptLocalTagFunc") + let &tagfunc= string(Fn) + new + let g:ScriptLocalFuncArgs = [] + call assert_fails('tag a16', 'E433:') + call assert_equal(['a16', '', {}], g:ScriptLocalFuncArgs) + bw! + + " set 'tagfunc' to a partial with dict. This used to cause a crash. + func SetTagFunc() + let params = {'tagfn': function('g:DictTagFunc')} + let &tagfunc = params.tagfn + endfunc + func g:DictTagFunc(_) dict + endfunc + call SetTagFunc() + new + call SetTagFunc() + bw + call test_garbagecollect_now() + new + set tagfunc= + wincmd w + set tagfunc= + :%bw! + delfunc g:DictTagFunc + delfunc SetTagFunc + + " Vim9 tests + let lines =<< trim END + vim9script + + def Vim9tagFunc(callnr: number, pat: string, flags: string, info: dict<any>): any + g:Vim9tagFuncArgs = [callnr, pat, flags, info] + return null + enddef + + # Test for using a def function with completefunc + set tagfunc=function('Vim9tagFunc',\ [60]) + new + g:Vim9tagFuncArgs = [] + assert_fails('tag a10', 'E433:') + assert_equal([60, 'a10', '', {}], g:Vim9tagFuncArgs) + + # Test for using a global function name + &tagfunc = g:TagFunc2 + new + g:TagFunc2Args = [] + assert_fails('tag a11', 'E433:') + assert_equal(['a11', '', {}], g:TagFunc2Args) + bw! + + # Test for using a script-local function name + def LocalTagFunc(pat: string, flags: string, info: dict<any> ): any + g:LocalTagFuncArgs = [pat, flags, info] + return null + enddef + &tagfunc = LocalTagFunc + new + g:LocalTagFuncArgs = [] + assert_fails('tag a12', 'E433:') + assert_equal(['a12', '', {}], g:LocalTagFuncArgs) + bw! + END + call CheckScriptSuccess(lines) + + " cleanup + delfunc TagFunc1 + delfunc TagFunc2 + set tagfunc& + %bw! +endfunc + +func Test_tagfunc_wipes_buffer() + func g:Tag0unc0(t,f,o) + bwipe + endfunc + set tagfunc=g:Tag0unc0 + new + cal assert_fails('tag 0', 'E987:') + + delfunc g:Tag0unc0 + set tagfunc= +endfunc + +func Test_tagfunc_closes_window() + split any + func MytagfuncClose(pat, flags, info) + close + return [{'name' : 'mytag', 'filename' : 'Xtest', 'cmd' : '1'}] + endfunc + set tagfunc=MytagfuncClose + call assert_fails('tag xyz', 'E1299:') + + set tagfunc= +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_tagjump.vim b/test/old/testdir/test_tagjump.vim new file mode 100644 index 0000000000..2ef5bd720b --- /dev/null +++ b/test/old/testdir/test_tagjump.vim @@ -0,0 +1,1615 @@ +" Tests for tagjump (tags and special searches) + +source check.vim +source screendump.vim + +" SEGV occurs in older versions. (At least 7.4.1748 or older) +func Test_ptag_with_notagstack() + CheckFeature quickfix + + set notagstack + call assert_fails('ptag does_not_exist_tag_name', 'E433') + set tagstack&vim +endfunc + +func Test_ptjump() + CheckFeature quickfix + + set tags=Xtags + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "one\tXfile\t1", + \ "three\tXfile\t3", + \ "two\tXfile\t2"], + \ 'Xtags') + call writefile(['one', 'two', 'three'], 'Xfile') + + %bw! + ptjump two + call assert_equal(2, winnr()) + wincmd p + call assert_equal(1, &previewwindow) + call assert_equal('Xfile', expand("%:p:t")) + call assert_equal(2, line('.')) + call assert_equal(2, winnr('$')) + call assert_equal(1, winnr()) + close + call setline(1, ['one', 'two', 'three']) + exe "normal 3G\<C-W>g}" + call assert_equal(2, winnr()) + wincmd p + call assert_equal(1, &previewwindow) + call assert_equal('Xfile', expand("%:p:t")) + call assert_equal(3, line('.')) + call assert_equal(2, winnr('$')) + call assert_equal(1, winnr()) + close + exe "normal 3G5\<C-W>\<C-G>}" + wincmd p + call assert_equal(5, winheight(0)) + close + + call delete('Xtags') + call delete('Xfile') + set tags& +endfunc + +func Test_cancel_ptjump() + CheckFeature quickfix + + set tags=Xtags + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "word\tfile1\tcmd1", + \ "word\tfile2\tcmd2"], + \ 'Xtags') + + only! + call feedkeys(":ptjump word\<CR>\<CR>", "xt") + help + call assert_equal(2, winnr('$')) + + call delete('Xtags') + set tags& + quit +endfunc + +func Test_static_tagjump() + set tags=Xtags + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "one\tXfile1\t/^one/;\"\tf\tfile:\tsignature:(void)", + \ "word\tXfile2\tcmd2"], + \ 'Xtags') + new Xfile1 + call setline(1, ['empty', 'one()', 'empty']) + write + tag one + call assert_equal(2, line('.')) + + bwipe! + set tags& + call delete('Xtags') + call delete('Xfile1') +endfunc + +func Test_duplicate_tagjump() + set tags=Xtags + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "thesame\tXfile1\t1;\"\td\tfile:", + \ "thesame\tXfile1\t2;\"\td\tfile:", + \ "thesame\tXfile1\t3;\"\td\tfile:", + \ ], + \ 'Xtags') + new Xfile1 + call setline(1, ['thesame one', 'thesame two', 'thesame three']) + write + tag thesame + call assert_equal(1, line('.')) + tnext + call assert_equal(2, line('.')) + tnext + call assert_equal(3, line('.')) + + bwipe! + set tags& + call delete('Xtags') + call delete('Xfile1') +endfunc + +func Test_tagjump_switchbuf() + CheckFeature quickfix + + set tags=Xtags + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "second\tXfile1\t2", + \ "third\tXfile1\t3",], + \ 'Xtags') + call writefile(['first', 'second', 'third'], 'Xfile1') + + enew | only + set switchbuf= + stag second + call assert_equal(2, winnr('$')) + call assert_equal(2, line('.')) + stag third + call assert_equal(3, winnr('$')) + call assert_equal(3, line('.')) + + enew | only + set switchbuf=useopen + stag second + call assert_equal(2, winnr('$')) + call assert_equal(2, line('.')) + stag third + call assert_equal(2, winnr('$')) + call assert_equal(3, line('.')) + + enew | only + set switchbuf=usetab + tab stag second + call assert_equal(2, tabpagenr('$')) + call assert_equal(2, line('.')) + 1tabnext | stag third + call assert_equal(2, tabpagenr('$')) + call assert_equal(3, line('.')) + + tabclose! + enew | only + call delete('Xfile1') + call delete('Xtags') + set tags& + set switchbuf&vim +endfunc + +" Tests for [ CTRL-I and CTRL-W CTRL-I commands +function Test_keyword_jump() + call writefile(["#include Xinclude", "", + \ "", + \ "/* test text test tex start here", + \ " some text", + \ " test text", + \ " start OK if found this line", + \ " start found wrong line", + \ "test text"], 'Xtestfile') + call writefile(["/* test text test tex start here", + \ " some text", + \ " test text", + \ " start OK if found this line", + \ " start found wrong line", + \ "test text"], 'Xinclude') + new Xtestfile + call cursor(1,1) + call search("start") + exe "normal! 5[\<C-I>" + call assert_equal(" start OK if found this line", getline('.')) + call cursor(1,1) + call search("start") + exe "normal! 5\<C-W>\<C-I>" + call assert_equal(" start OK if found this line", getline('.')) + + " invalid tag search pattern + call assert_fails('tag /\%(/', 'E426:') + + enew! | only + call delete('Xtestfile') + call delete('Xinclude') +endfunction + +" Test for jumping to a tag with 'hidden' set, with symbolic link in path of +" tag. This only works for Unix, because of the symbolic link. +func Test_tag_symbolic() + if !has('unix') + return + endif + set hidden + call delete("Xtest.dir", "rf") + call system("ln -s . Xtest.dir") + " Create a tags file with the current directory name inserted. + call writefile([ + \ "SECTION_OFF " . getcwd() . "/Xtest.dir/Xtest.c /^#define SECTION_OFF 3$/", + \ '', + \ ], 'Xtags') + call writefile(['#define SECTION_OFF 3', + \ '#define NUM_SECTIONS 3'], 'Xtest.c') + + " Try jumping to a tag, but with a path that contains a symbolic link. When + " wrong, this will give the ATTENTION message. The next space will then be + " eaten by hit-return, instead of moving the cursor to 'd'. + set tags=Xtags + enew! + call append(0, 'SECTION_OFF') + call cursor(1,1) + exe "normal \<C-]> " + call assert_equal('Xtest.c', expand('%:t')) + call assert_equal(2, col('.')) + + set nohidden + set tags& + enew! + call delete('Xtags') + call delete('Xtest.c') + call delete("Xtest.dir", "rf") + %bwipe! +endfunc + +" Tests for tag search with !_TAG_FILE_ENCODING. +func Test_tag_file_encoding() + if has('vms') + throw 'Skipped: does not work on VMS' + endif + + if !has('iconv') || iconv("\x82\x60", "cp932", "utf-8") != "\uff21" + throw 'Skipped: iconv does not work' + endif + + let save_enc = &encoding + set encoding=utf8 + + let content = ['text for tags1', 'abcdefghijklmnopqrs'] + call writefile(content, 'Xtags1.txt') + let content = ['text for tags2', 'ABC'] + call writefile(content, 'Xtags2.txt') + let content = ['text for tags3', 'ABC'] + call writefile(content, 'Xtags3.txt') + let content = ['!_TAG_FILE_ENCODING utf-8 //', 'abcdefghijklmnopqrs Xtags1.txt /abcdefghijklmnopqrs'] + call writefile(content, 'Xtags1') + + " case1: + new + set tags=Xtags1 + tag abcdefghijklmnopqrs + call assert_equal('Xtags1.txt', expand('%:t')) + call assert_equal('abcdefghijklmnopqrs', getline('.')) + close + + " case2: + new + let content = ['!_TAG_FILE_ENCODING cp932 //', + \ "\x82`\x82a\x82b Xtags2.txt /\x82`\x82a\x82b"] + call writefile(content, 'Xtags') + set tags=Xtags + tag /.BC + call assert_equal('Xtags2.txt', expand('%:t')) + call assert_equal('ABC', getline('.')) + call delete('Xtags') + close + + " case3: + new + let contents = [ + \ "!_TAG_FILE_SORTED 1 //", + \ "!_TAG_FILE_ENCODING cp932 //"] + for i in range(1, 100) + call add(contents, 'abc' .. i + \ .. " Xtags3.txt /\x82`\x82a\x82b") + endfor + call writefile(contents, 'Xtags') + set tags=Xtags + tag abc50 + call assert_equal('Xtags3.txt', expand('%:t')) + call assert_equal('ABC', getline('.')) + call delete('Xtags') + close + + set tags& + let &encoding = save_enc + call delete('Xtags1.txt') + call delete('Xtags2.txt') + call delete('Xtags3.txt') + call delete('Xtags1') +endfunc + +" Test for emacs-style tags file (TAGS) +func Test_tagjump_etags() + if !has('emacs_tags') + return + endif + call writefile([ + \ "void foo() {}", + \ "int main(int argc, char **argv)", + \ "{", + \ "\tfoo();", + \ "\treturn 0;", + \ "}", + \ ], 'Xmain.c') + + call writefile([ + \ "\x0c", + \ "Xmain.c,64", + \ "void foo() {}\x7ffoo\x011,0", + \ "int main(int argc, char **argv)\x7fmain\x012,14", + \ ], 'Xtags') + set tags=Xtags + ta foo + call assert_equal('void foo() {}', getline('.')) + + " Test for including another tags file + call writefile([ + \ "\x0c", + \ "Xmain.c,64", + \ "void foo() {}\x7ffoo\x011,0", + \ "\x0c", + \ "Xnonexisting,include", + \ "\x0c", + \ "Xtags2,include" + \ ], 'Xtags') + call writefile([ + \ "\x0c", + \ "Xmain.c,64", + \ "int main(int argc, char **argv)\x7fmain\x012,14", + \ ], 'Xtags2') + tag main + call assert_equal(2, line('.')) + call assert_fails('tag bar', 'E426:') + + " corrupted tag line + call writefile([ + \ "\x0c", + \ "Xmain.c,8", + \ "int main" + \ ], 'Xtags', 'b') + call assert_fails('tag foo', 'E426:') + + " invalid line number + call writefile([ + \ "\x0c", + \ "Xmain.c,64", + \ "void foo() {}\x7ffoo\x0abc,0", + \ ], 'Xtags') + call assert_fails('tag foo', 'E426:') + + " invalid tag name + call writefile([ + \ "\x0c", + \ "Xmain.c,64", + \ ";;;;\x7f1,0", + \ ], 'Xtags') + call assert_fails('tag foo', 'E431:') + + " end of file after a CTRL-L line + call writefile([ + \ "\x0c", + \ "Xmain.c,64", + \ "void foo() {}\x7ffoo\x011,0", + \ "\x0c", + \ ], 'Xtags') + call assert_fails('tag main', 'E426:') + + " error in an included tags file + call writefile([ + \ "\x0c", + \ "Xtags2,include" + \ ], 'Xtags') + call writefile([ + \ "\x0c", + \ "Xmain.c,64", + \ "void foo() {}", + \ ], 'Xtags2') + call assert_fails('tag foo', 'E431:') + + call delete('Xtags') + call delete('Xtags2') + call delete('Xmain.c') + set tags& + bwipe! +endfunc + +" Test for getting and modifying the tag stack +func Test_getsettagstack() + call writefile(['line1', 'line2', 'line3'], 'Xfile1') + call writefile(['line1', 'line2', 'line3'], 'Xfile2') + call writefile(['line1', 'line2', 'line3'], 'Xfile3') + + enew | only + call settagstack(1, {'items' : []}) + call assert_equal(0, gettagstack(1).length) + call assert_equal([], 1->gettagstack().items) + " Error cases + call assert_equal({}, gettagstack(100)) + call assert_equal(-1, settagstack(100, {'items' : []})) + call assert_fails('call settagstack(1, [1, 10])', 'E1206:') + call assert_fails("call settagstack(1, {'items' : 10})", 'E714:') + call assert_fails("call settagstack(1, {'items' : []}, 10)", 'E1174:') + call assert_fails("call settagstack(1, {'items' : []}, 'b')", 'E962:') + call assert_equal(-1, settagstack(0, v:_null_dict)) + + set tags=Xtags + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "one\tXfile1\t1", + \ "three\tXfile3\t3", + \ "two\tXfile2\t2"], + \ 'Xtags') + + let stk = [] + call add(stk, {'bufnr' : bufnr('%'), 'tagname' : 'one', + \ 'from' : [bufnr('%'), line('.'), col('.'), 0], 'matchnr' : 1}) + tag one + call add(stk, {'bufnr' : bufnr('%'), 'tagname' : 'two', + \ 'from' : [bufnr('%'), line('.'), col('.'), 0], 'matchnr' : 1}) + tag two + call add(stk, {'bufnr' : bufnr('%'), 'tagname' : 'three', + \ 'from' : [bufnr('%'), line('.'), col('.'), 0], 'matchnr' : 1}) + tag three + call assert_equal(3, gettagstack(1).length) + call assert_equal(stk, gettagstack(1).items) + " Check for default - current window + call assert_equal(3, gettagstack().length) + call assert_equal(stk, gettagstack().items) + + " Try to set current index to invalid values + call settagstack(1, {'curidx' : -1}) + call assert_equal(1, gettagstack().curidx) + eval {'curidx' : 50}->settagstack(1) + call assert_equal(4, gettagstack().curidx) + + " Try pushing invalid items onto the stack + call settagstack(1, {'items' : []}) + call settagstack(1, {'items' : ["plate"]}, 'a') + call assert_equal(0, gettagstack().length) + call assert_equal([], gettagstack().items) + call settagstack(1, {'items' : [{"tagname" : "abc"}]}, 'a') + call assert_equal(0, gettagstack().length) + call assert_equal([], gettagstack().items) + call settagstack(1, {'items' : [{"from" : 100}]}, 'a') + call assert_equal(0, gettagstack().length) + call assert_equal([], gettagstack().items) + call settagstack(1, {'items' : [{"from" : [2, 1, 0, 0]}]}, 'a') + call assert_equal(0, gettagstack().length) + call assert_equal([], gettagstack().items) + + " Push one item at a time to the stack + call settagstack(1, {'items' : []}) + call settagstack(1, {'items' : [stk[0]]}, 'a') + call settagstack(1, {'items' : [stk[1]]}, 'a') + call settagstack(1, {'items' : [stk[2]]}, 'a') + call settagstack(1, {'curidx' : 4}) + call assert_equal({'length' : 3, 'curidx' : 4, 'items' : stk}, + \ gettagstack(1)) + + " Try pushing items onto a full stack + for i in range(7) + call settagstack(1, {'items' : stk}, 'a') + endfor + call assert_equal(20, gettagstack().length) + call settagstack(1, + \ {'items' : [{'tagname' : 'abc', 'from' : [1, 10, 1, 0]}]}, 'a') + call assert_equal('abc', gettagstack().items[19].tagname) + + " truncate the tag stack + call settagstack(1, + \ {'curidx' : 9, + \ 'items' : [{'tagname' : 'abc', 'from' : [1, 10, 1, 0]}]}, 't') + let t = gettagstack() + call assert_equal(9, t.length) + call assert_equal(10, t.curidx) + + " truncate the tag stack without pushing any new items + call settagstack(1, {'curidx' : 5}, 't') + let t = gettagstack() + call assert_equal(4, t.length) + call assert_equal(5, t.curidx) + + " truncate an empty tag stack and push new items + call settagstack(1, {'items' : []}) + call settagstack(1, + \ {'items' : [{'tagname' : 'abc', 'from' : [1, 10, 1, 0]}]}, 't') + let t = gettagstack() + call assert_equal(1, t.length) + call assert_equal(2, t.curidx) + + " Tag with multiple matches + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "two\tXfile1\t1", + \ "two\tXfile2\t3", + \ "two\tXfile3\t2"], + \ 'Xtags') + call settagstack(1, {'items' : []}) + tag two + tnext + tnext + call assert_equal(1, gettagstack().length) + call assert_equal(3, gettagstack().items[0].matchnr) + + call settagstack(1, {'items' : []}) + call delete('Xfile1') + call delete('Xfile2') + call delete('Xfile3') + call delete('Xtags') + set tags& +endfunc + +func Test_tag_with_count() + call writefile([ + \ 'test Xtest.h /^void test();$/;" p typeref:typename:void signature:()', + \ ], 'Xtags') + call writefile([ + \ 'main Xtest.c /^int main()$/;" f typeref:typename:int signature:()', + \ 'test Xtest.c /^void test()$/;" f typeref:typename:void signature:()', + \ ], 'Ytags') + cal writefile([ + \ 'int main()', + \ 'void test()', + \ ], 'Xtest.c') + cal writefile([ + \ 'void test();', + \ ], 'Xtest.h') + set tags=Xtags,Ytags + + new Xtest.c + let tl = taglist('test', 'Xtest.c') + call assert_equal(tl[0].filename, 'Xtest.c') + call assert_equal(tl[1].filename, 'Xtest.h') + + tag test + call assert_equal(bufname('%'), 'Xtest.c') + 1tag test + call assert_equal(bufname('%'), 'Xtest.c') + 2tag test + call assert_equal(bufname('%'), 'Xtest.h') + + set tags& + call delete('Xtags') + call delete('Ytags') + bwipe Xtest.h + bwipe Xtest.c + call delete('Xtest.h') + call delete('Xtest.c') +endfunc + +func Test_tagnr_recall() + call writefile([ + \ 'test Xtest.h /^void test();$/;" p', + \ 'main Xtest.c /^int main()$/;" f', + \ 'test Xtest.c /^void test()$/;" f', + \ ], 'Xtags') + cal writefile([ + \ 'int main()', + \ 'void test()', + \ ], 'Xtest.c') + cal writefile([ + \ 'void test();', + \ ], 'Xtest.h') + set tags=Xtags + + new Xtest.c + let tl = taglist('test', 'Xtest.c') + call assert_equal(tl[0].filename, 'Xtest.c') + call assert_equal(tl[1].filename, 'Xtest.h') + + 2tag test + call assert_equal(bufname('%'), 'Xtest.h') + pop + call assert_equal(bufname('%'), 'Xtest.c') + tag + call assert_equal(bufname('%'), 'Xtest.h') + + set tags& + call delete('Xtags') + bwipe Xtest.h + bwipe Xtest.c + call delete('Xtest.h') + call delete('Xtest.c') +endfunc + +func Test_tag_line_toolong() + call writefile([ + \ '1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678 django/contrib/admin/templates/admin/edit_inline/stacked.html 16;" j line:16 language:HTML' + \ ], 'Xtags') + set tags=Xtags + let old_vbs = &verbose + set verbose=5 + " ":tjump" should give "tag not found" not "Format error in tags file" + call assert_fails('tj /foo', 'E426') + try + tj /foo + catch /^Vim\%((\a\+)\)\=:E431/ + call assert_report(v:exception) + catch /.*/ + endtry + call assert_equal('Searching tags file Xtags', split(execute('messages'), '\n')[-1]) + + call writefile([ + \ '123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567 django/contrib/admin/templates/admin/edit_inline/stacked.html 16;" j line:16 language:HTML' + \ ], 'Xtags') + call assert_fails('tj /foo', 'E426') + try + tj /foo + catch /^Vim\%((\a\+)\)\=:E431/ + call assert_report(v:exception) + catch /.*/ + endtry + call assert_equal('Searching tags file Xtags', split(execute('messages'), '\n')[-1]) + + " binary search works in file with long line + call writefile([ + \ 'asdfasfd nowhere 16', + \ 'foobar Xsomewhere 3; " 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567', + \ 'zasdfasfd nowhere 16', + \ ], 'Xtags') + call writefile([ + \ 'one', + \ 'two', + \ 'trhee', + \ 'four', + \ ], 'Xsomewhere') + tag foobar + call assert_equal('Xsomewhere', expand('%')) + call assert_equal(3, getcurpos()[1]) + + " expansion on command line works with long lines when &wildoptions contains + " 'tagfile' + set wildoptions=tagfile + call writefile([ + \ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa file /^pattern$/;" f' + \ ], 'Xtags') + call feedkeys(":tag \<Tab>", 'tx') + " Should not crash + call assert_true(v:true) + + call delete('Xtags') + call delete('Xsomewhere') + set tags& + let &verbose = old_vbs +endfunc + +" Check that using :tselect does not run into the hit-enter prompt. +" Requires a terminal to trigger that prompt. +func Test_tselect() + CheckScreendump + + call writefile([ + \ 'main Xtest.h /^void test();$/;" f', + \ 'main Xtest.c /^int main()$/;" f', + \ 'main Xtest.x /^void test()$/;" f', + \ ], 'Xtags') + cal writefile([ + \ 'int main()', + \ 'void test()', + \ ], 'Xtest.c') + + let lines =<< trim [SCRIPT] + set tags=Xtags + [SCRIPT] + call writefile(lines, 'XTest_tselect') + let buf = RunVimInTerminal('-S XTest_tselect', {'rows': 10, 'cols': 50}) + + call TermWait(buf, 50) + call term_sendkeys(buf, ":tselect main\<CR>2\<CR>") + call VerifyScreenDump(buf, 'Test_tselect_1', {}) + + call StopVimInTerminal(buf) + call delete('Xtags') + call delete('Xtest.c') + call delete('XTest_tselect') +endfunc + +func Test_tagline() + call writefile([ + \ 'provision Xtest.py /^ def provision(self, **kwargs):$/;" m line:1 language:Python class:Foo', + \ 'provision Xtest.py /^ def provision(self, **kwargs):$/;" m line:3 language:Python class:Bar', + \], 'Xtags') + call writefile([ + \ ' def provision(self, **kwargs):', + \ ' pass', + \ ' def provision(self, **kwargs):', + \ ' pass', + \], 'Xtest.py') + + set tags=Xtags + + 1tag provision + call assert_equal(line('.'), 1) + 2tag provision + call assert_equal(line('.'), 3) + + call delete('Xtags') + call delete('Xtest.py') + set tags& +endfunc + +" Test for expanding environment variable in a tag file name +func Test_tag_envvar() + call writefile(["Func1\t$FOO\t/^Func1/"], 'Xtags') + set tags=Xtags + + let $FOO='TagTestEnv' + + let caught_exception = v:false + try + tag Func1 + catch /E429:/ + call assert_match('E429:.*"TagTestEnv".*', v:exception) + let caught_exception = v:true + endtry + call assert_true(caught_exception) + + set tags& + call delete('Xtags') + unlet $FOO +endfunc + +" Test for :ptag +func Test_tag_preview() + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "second\tXfile1\t2", + \ "third\tXfile1\t3",], + \ 'Xtags') + set tags=Xtags + call writefile(['first', 'second', 'third'], 'Xfile1') + + enew | only + ptag third + call assert_equal(2, winnr()) + call assert_equal(2, winnr('$')) + call assert_equal(1, getwinvar(1, '&previewwindow')) + call assert_equal(0, getwinvar(2, '&previewwindow')) + wincmd P + call assert_equal(3, line('.')) + + " jump to the tag again + wincmd w + ptag third + wincmd P + call assert_equal(3, line('.')) + + " jump to the newer tag + wincmd w + ptag + wincmd P + call assert_equal(3, line('.')) + + " close the preview window + pclose + call assert_equal(1, winnr('$')) + + call delete('Xfile1') + call delete('Xtags') + set tags& +endfunc + +" Tests for guessing the tag location +func Test_tag_guess() + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "func1\tXfoo\t/^int func1(int x)/", + \ "func2\tXfoo\t/^int func2(int y)/", + \ "func3\tXfoo\t/^func3/", + \ "func4\tXfoo\t/^func4/"], + \ 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + + int FUNC1 (int x) { } + int + func2 (int y) { } + int * func3 () { } + + [CODE] + call writefile(code, 'Xfoo') + + let v:statusmsg = '' + ta func1 + call assert_match('E435:', v:statusmsg) + call assert_equal(2, line('.')) + let v:statusmsg = '' + ta func2 + call assert_match('E435:', v:statusmsg) + call assert_equal(4, line('.')) + let v:statusmsg = '' + ta func3 + call assert_match('E435:', v:statusmsg) + call assert_equal(5, line('.')) + call assert_fails('ta func4', 'E434:') + + call delete('Xtags') + call delete('Xfoo') + set tags& +endfunc + +" Test for an unsorted tags file +func Test_tag_sort() + let l = [ + \ "first\tXfoo\t1", + \ "ten\tXfoo\t3", + \ "six\tXfoo\t2"] + call writefile(l, 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + int first() {} + int six() {} + int ten() {} + [CODE] + call writefile(code, 'Xfoo') + + call assert_fails('tag first', 'E432:') + + " When multiple tag files are not sorted, then message should be displayed + " multiple times + call writefile(l, 'Xtags2') + set tags=Xtags,Xtags2 + call assert_fails('tag first', ['E432:', 'E432:']) + + call delete('Xtags') + call delete('Xtags2') + call delete('Xfoo') + set tags& + %bwipe +endfunc + +" Test for an unsorted tags file +func Test_tag_fold() + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "!_TAG_FILE_SORTED\t2\t/0=unsorted, 1=sorted, 2=foldcase/", + \ "first\tXfoo\t1", + \ "second\tXfoo\t2", + \ "third\tXfoo\t3"], + \ 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + int first() {} + int second() {} + int third() {} + [CODE] + call writefile(code, 'Xfoo') + + enew + tag second + call assert_equal('Xfoo', bufname('')) + call assert_equal(2, line('.')) + + call delete('Xtags') + call delete('Xfoo') + set tags& + %bwipe +endfunc + +" Test for the :ltag command +func Test_ltag() + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "first\tXfoo\t1", + \ "second\tXfoo\t/^int second() {}$/", + \ "third\tXfoo\t3"], + \ 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + int first() {} + int second() {} + int third() {} + [CODE] + call writefile(code, 'Xfoo') + + enew + call setloclist(0, [], 'f') + ltag third + call assert_equal('Xfoo', bufname('')) + call assert_equal(3, line('.')) + call assert_equal([{'lnum': 3, 'end_lnum': 0, 'bufnr': bufnr('Xfoo'), + \ 'col': 0, 'end_col': 0, 'pattern': '', 'valid': 1, 'vcol': 0, + \ 'nr': 0, 'type': '', 'module': '', 'text': 'third'}], getloclist(0)) + + ltag second + call assert_equal(2, line('.')) + call assert_equal([{'lnum': 0, 'end_lnum': 0, 'bufnr': bufnr('Xfoo'), + \ 'col': 0, 'end_col': 0, 'pattern': '^\Vint second() {}\$', + \ 'valid': 1, 'vcol': 0, 'nr': 0, 'type': '', 'module': '', + \ 'text': 'second'}], getloclist(0)) + + call delete('Xtags') + call delete('Xfoo') + set tags& + %bwipe +endfunc + +" Test for setting the last search pattern to the tag search pattern +" when cpoptions has 't' +func Test_tag_last_search_pat() + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "first\tXfoo\t/^int first() {}/", + \ "second\tXfoo\t/^int second() {}/", + \ "third\tXfoo\t/^int third() {}/"], + \ 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + int first() {} + int second() {} + int third() {} + [CODE] + call writefile(code, 'Xfoo') + + enew + let save_cpo = &cpo + set cpo+=t + let @/ = '' + tag second + call assert_equal('^int second() {}', @/) + let &cpo = save_cpo + + call delete('Xtags') + call delete('Xfoo') + set tags& + %bwipe +endfunc + +" Tag stack tests +func Test_tag_stack() + let l = [] + for i in range(10, 31) + let l += ["var" .. i .. "\tXfoo\t/^int var" .. i .. ";$/"] + endfor + call writefile(l, 'Xtags') + set tags=Xtags + + let l = [] + for i in range(10, 31) + let l += ["int var" .. i .. ";"] + endfor + call writefile(l, 'Xfoo') + + " Jump to a tag when the tag stack is full. Oldest entry should be removed. + enew + for i in range(10, 30) + exe "tag var" .. i + endfor + let l = gettagstack() + call assert_equal(20, l.length) + call assert_equal('var11', l.items[0].tagname) + tag var31 + let l = gettagstack() + call assert_equal('var12', l.items[0].tagname) + call assert_equal('var31', l.items[19].tagname) + + " Use tnext with a single match + call assert_fails('tnext', 'E427:') + + " Jump to newest entry from the top of the stack + call assert_fails('tag', 'E556:') + + " Pop with zero count from the top of the stack + call assert_fails('0pop', 'E556:') + + " Pop from an unsaved buffer + enew! + call append(1, "sample text") + call assert_fails('pop', 'E37:') + call assert_equal(21, gettagstack().curidx) + enew! + + " Pop all the entries in the tag stack + call assert_fails('30pop', 'E555:') + + " Pop with a count when already at the bottom of the stack + call assert_fails('exe "normal 4\<C-T>"', 'E555:') + call assert_equal(1, gettagstack().curidx) + + " Jump to newest entry from the bottom of the stack with zero count + call assert_fails('0tag', 'E555:') + + " Pop the tag stack when it is empty + call settagstack(1, {'items' : []}) + call assert_fails('pop', 'E73:') + + call delete('Xtags') + call delete('Xfoo') + set tags& + %bwipe +endfunc + +" Test for browsing multiple matching tags +func Test_tag_multimatch() + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "first\tXfoo\t1", + \ "first\tXfoo\t2", + \ "first\tXfoo\t3"], + \ 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + int first() {} + int first() {} + int first() {} + [CODE] + call writefile(code, 'Xfoo') + + call settagstack(1, {'items' : []}) + tag first + tlast + call assert_equal(3, line('.')) + call assert_fails('tnext', 'E428:') + tfirst + call assert_equal(1, line('.')) + call assert_fails('tprev', 'E425:') + + tlast + call feedkeys("5\<CR>", 't') + tselect first + call assert_equal(2, gettagstack().curidx) + + set ignorecase + tag FIRST + tnext + call assert_equal(2, line('.')) + tlast + tprev + call assert_equal(2, line('.')) + tNext + call assert_equal(1, line('.')) + set ignorecase& + + call delete('Xtags') + call delete('Xfoo') + set tags& + %bwipe +endfunc + +" Test for previewing multiple matching tags +func Test_preview_tag_multimatch() + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "first\tXfoo\t1", + \ "first\tXfoo\t2", + \ "first\tXfoo\t3"], + \ 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + int first() {} + int first() {} + int first() {} + [CODE] + call writefile(code, 'Xfoo') + + enew | only + ptag first + ptlast + wincmd P + call assert_equal(3, line('.')) + wincmd w + call assert_fails('ptnext', 'E428:') + ptprev + wincmd P + call assert_equal(2, line('.')) + wincmd w + ptfirst + wincmd P + call assert_equal(1, line('.')) + wincmd w + call assert_fails('ptprev', 'E425:') + ptnext + wincmd P + call assert_equal(2, line('.')) + wincmd w + ptlast + call feedkeys("5\<CR>", 't') + ptselect first + wincmd P + call assert_equal(3, line('.')) + + pclose + + call delete('Xtags') + call delete('Xfoo') + set tags& + %bwipe +endfunc + +" Test for jumping to multiple matching tags across multiple :tags commands +func Test_tnext_multimatch() + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "first\tXfoo1\t1", + \ "first\tXfoo2\t1", + \ "first\tXfoo3\t1"], + \ 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + int first() {} + [CODE] + call writefile(code, 'Xfoo1') + call writefile(code, 'Xfoo2') + call writefile(code, 'Xfoo3') + + tag first + tag first + pop + tnext + tnext + call assert_fails('tnext', 'E428:') + + call delete('Xtags') + call delete('Xfoo1') + call delete('Xfoo2') + call delete('Xfoo3') + set tags& + %bwipe +endfunc + +" Test for jumping to multiple matching tags in non-existing files +func Test_multimatch_non_existing_files() + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "first\tXfoo1\t1", + \ "first\tXfoo2\t1", + \ "first\tXfoo3\t1"], + \ 'Xtags') + set tags=Xtags + + call settagstack(1, {'items' : []}) + call assert_fails('tag first', 'E429:') + call assert_equal(3, gettagstack().items[0].matchnr) + + call delete('Xtags') + set tags& + %bwipe +endfunc + +func Test_tselect_listing() + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "first\tXfoo\t1" .. ';"' .. "\tv\ttyperef:typename:int\tfile:", + \ "first\tXfoo\t2" .. ';"' .. "\tkind:v\ttyperef:typename:char\tfile:"], + \ 'Xtags') + set tags=Xtags + + let code =<< trim [CODE] + static int first; + static char first; + [CODE] + call writefile(code, 'Xfoo') + + call feedkeys("\<CR>", "t") + let l = split(execute("tselect first"), "\n") + let expected =<< [DATA] + # pri kind tag file + 1 FS v first Xfoo + typeref:typename:int + 1 + 2 FS v first Xfoo + typeref:typename:char + 2 +Type number and <Enter> (q or empty cancels): +[DATA] + call assert_equal(expected, l) + + call delete('Xtags') + call delete('Xfoo') + set tags& + %bwipe +endfunc + +" Test for :isearch, :ilist, :ijump and :isplit commands +" Test for [i, ]i, [I, ]I, [ CTRL-I, ] CTRL-I and CTRL-W i commands +func Test_inc_search() + new + call setline(1, ['1:foo', '2:foo', 'foo', '3:foo', '4:foo', '===']) + call cursor(3, 1) + + " Test for [i and ]i + call assert_equal('1:foo', execute('normal [i')) + call assert_equal('2:foo', execute('normal 2[i')) + call assert_fails('normal 3[i', 'E387:') + call assert_equal('3:foo', execute('normal ]i')) + call assert_equal('4:foo', execute('normal 2]i')) + call assert_fails('normal 3]i', 'E389:') + call assert_fails('normal G]i', 'E349:') + call assert_fails('normal [i', 'E349:') + call cursor(3, 1) + + " Test for :isearch + call assert_equal('1:foo', execute('isearch foo')) + call assert_equal('3:foo', execute('isearch 4 /foo/')) + call assert_fails('isearch 3 foo', 'E387:') + call assert_equal('3:foo', execute('+1,$isearch foo')) + call assert_fails('1,.-1isearch 3 foo', 'E389:') + call assert_fails('isearch bar', 'E389:') + call assert_fails('isearch /foo/3', 'E488:') + + " Test for [I and ]I + call assert_equal([ + \ ' 1: 1 1:foo', + \ ' 2: 2 2:foo', + \ ' 3: 3 foo', + \ ' 4: 4 3:foo', + \ ' 5: 5 4:foo'], split(execute('normal [I'), "\n")) + call assert_equal([ + \ ' 1: 4 3:foo', + \ ' 2: 5 4:foo'], split(execute('normal ]I'), "\n")) + call assert_fails('normal G]I', 'E349:') + call assert_fails('normal [I', 'E349:') + call cursor(3, 1) + + " Test for :ilist + call assert_equal([ + \ ' 1: 1 1:foo', + \ ' 2: 2 2:foo', + \ ' 3: 3 foo', + \ ' 4: 4 3:foo', + \ ' 5: 5 4:foo'], split(execute('ilist foo'), "\n")) + call assert_equal([ + \ ' 1: 4 3:foo', + \ ' 2: 5 4:foo'], split(execute('+1,$ilist /foo/'), "\n")) + call assert_fails('ilist bar', 'E389:') + + " Test for [ CTRL-I and ] CTRL-I + exe "normal [\t" + call assert_equal([1, 3], [line('.'), col('.')]) + exe "normal 2j4[\t" + call assert_equal([4, 3], [line('.'), col('.')]) + call assert_fails("normal k3[\t", 'E387:') + call assert_fails("normal 6[\t", 'E389:') + exe "normal ]\t" + call assert_equal([4, 3], [line('.'), col('.')]) + exe "normal k2]\t" + call assert_equal([5, 3], [line('.'), col('.')]) + call assert_fails("normal 2k3]\t", 'E389:') + call assert_fails("normal G[\t", 'E349:') + call assert_fails("normal ]\t", 'E349:') + call cursor(3, 1) + + " Test for :ijump + call cursor(3, 1) + ijump foo + call assert_equal([1, 3], [line('.'), col('.')]) + call cursor(3, 1) + ijump 4 /foo/ + call assert_equal([4, 3], [line('.'), col('.')]) + call cursor(3, 1) + call assert_fails('ijump 3 foo', 'E387:') + +,$ijump 2 foo + call assert_equal([5, 3], [line('.'), col('.')]) + call assert_fails('ijump bar', 'E389:') + + " Test for CTRL-W i + call cursor(3, 1) + wincmd i + call assert_equal([1, 3, 3], [line('.'), col('.'), winnr('$')]) + close + 5wincmd i + call assert_equal([5, 3, 3], [line('.'), col('.'), winnr('$')]) + close + call assert_fails('3wincmd i', 'E387:') + call assert_fails('6wincmd i', 'E389:') + call assert_fails("normal G\<C-W>i", 'E349:') + call cursor(3, 1) + + " Test for :isplit + isplit foo + call assert_equal([1, 3, 3], [line('.'), col('.'), winnr('$')]) + close + isplit 5 /foo/ + call assert_equal([5, 3, 3], [line('.'), col('.'), winnr('$')]) + close + call assert_fails('isplit 3 foo', 'E387:') + call assert_fails('isplit 6 foo', 'E389:') + call assert_fails('isplit bar', 'E389:') + + close! +endfunc + +" this was using a line from ml_get() freed by the regexp +func Test_isearch_copy_line() + new + norm o + norm 0 + 0norm o + sil! norm bc0 + sil! isearch \%') + bwipe! +endfunc + +" Test for :dsearch, :dlist, :djump and :dsplit commands +" Test for [d, ]d, [D, ]D, [ CTRL-D, ] CTRL-D and CTRL-W d commands +func Test_macro_search() + new + call setline(1, ['#define FOO 1', '#define FOO 2', '#define FOO 3', + \ '#define FOO 4', '#define FOO 5']) + call cursor(3, 9) + + " Test for [d and ]d + call assert_equal('#define FOO 1', execute('normal [d')) + call assert_equal('#define FOO 2', execute('normal 2[d')) + call assert_fails('normal 3[d', 'E387:') + call assert_equal('#define FOO 4', execute('normal ]d')) + call assert_equal('#define FOO 5', execute('normal 2]d')) + call assert_fails('normal 3]d', 'E388:') + + " Test for :dsearch + call assert_equal('#define FOO 1', execute('dsearch FOO')) + call assert_equal('#define FOO 5', execute('dsearch 5 /FOO/')) + call assert_fails('dsearch 3 FOO', 'E387:') + call assert_equal('#define FOO 4', execute('+1,$dsearch FOO')) + call assert_fails('1,.-1dsearch 3 FOO', 'E388:') + call assert_fails('dsearch BAR', 'E388:') + + " Test for [D and ]D + call assert_equal([ + \ ' 1: 1 #define FOO 1', + \ ' 2: 2 #define FOO 2', + \ ' 3: 3 #define FOO 3', + \ ' 4: 4 #define FOO 4', + \ ' 5: 5 #define FOO 5'], split(execute('normal [D'), "\n")) + call assert_equal([ + \ ' 1: 4 #define FOO 4', + \ ' 2: 5 #define FOO 5'], split(execute('normal ]D'), "\n")) + + " Test for :dlist + call assert_equal([ + \ ' 1: 1 #define FOO 1', + \ ' 2: 2 #define FOO 2', + \ ' 3: 3 #define FOO 3', + \ ' 4: 4 #define FOO 4', + \ ' 5: 5 #define FOO 5'], split(execute('dlist FOO'), "\n")) + call assert_equal([ + \ ' 1: 4 #define FOO 4', + \ ' 2: 5 #define FOO 5'], split(execute('+1,$dlist /FOO/'), "\n")) + call assert_fails('dlist BAR', 'E388:') + + " Test for [ CTRL-D and ] CTRL-D + exe "normal [\<C-D>" + call assert_equal([1, 9], [line('.'), col('.')]) + exe "normal 2j4[\<C-D>" + call assert_equal([4, 9], [line('.'), col('.')]) + call assert_fails("normal k3[\<C-D>", 'E387:') + call assert_fails("normal 6[\<C-D>", 'E388:') + exe "normal ]\<C-D>" + call assert_equal([4, 9], [line('.'), col('.')]) + exe "normal k2]\<C-D>" + call assert_equal([5, 9], [line('.'), col('.')]) + call assert_fails("normal 2k3]\<C-D>", 'E388:') + + " Test for :djump + call cursor(3, 9) + djump FOO + call assert_equal([1, 9], [line('.'), col('.')]) + call cursor(3, 9) + djump 4 /FOO/ + call assert_equal([4, 9], [line('.'), col('.')]) + call cursor(3, 9) + call assert_fails('djump 3 FOO', 'E387:') + +,$djump 2 FOO + call assert_equal([5, 9], [line('.'), col('.')]) + call assert_fails('djump BAR', 'E388:') + + " Test for CTRL-W d + call cursor(3, 9) + wincmd d + call assert_equal([1, 9, 3], [line('.'), col('.'), winnr('$')]) + close + 5wincmd d + call assert_equal([5, 9, 3], [line('.'), col('.'), winnr('$')]) + close + call assert_fails('3wincmd d', 'E387:') + call assert_fails('6wincmd d', 'E388:') + new + call assert_fails("normal \<C-W>d", 'E349:') + call assert_fails("normal \<C-W>\<C-D>", 'E349:') + close + + " Test for :dsplit + dsplit FOO + call assert_equal([1, 9, 3], [line('.'), col('.'), winnr('$')]) + close + dsplit 5 /FOO/ + call assert_equal([5, 9, 3], [line('.'), col('.'), winnr('$')]) + close + call assert_fails('dsplit 3 FOO', 'E387:') + call assert_fails('dsplit 6 FOO', 'E388:') + call assert_fails('dsplit BAR', 'E388:') + + close! +endfunc + +func Test_define_search() + " this was accessing freed memory + new + call setline(1, ['first line', '', '#define something 0']) + sil norm o0 + sil! norm + bwipe! + + new somefile + call setline(1, ['first line', '', '#define something 0']) + sil norm 0o0 + sil! norm ]d + bwipe! +endfunc + +" Test for [*, [/, ]* and ]/ +func Test_comment_search() + new + call setline(1, ['', '/*', ' *', ' *', ' */']) + normal! 4gg[/ + call assert_equal([2, 1], [line('.'), col('.')]) + normal! 3gg[* + call assert_equal([2, 1], [line('.'), col('.')]) + normal! 3gg]/ + call assert_equal([5, 3], [line('.'), col('.')]) + normal! 3gg]* + call assert_equal([5, 3], [line('.'), col('.')]) + %d + call setline(1, ['', '/*', ' *', ' *']) + call assert_beeps('normal! 3gg]/') + %d + call setline(1, ['', ' *', ' *', ' */']) + call assert_beeps('normal! 4gg[/') + %d + call setline(1, ' /* comment */') + normal! 15|[/ + call assert_equal(9, col('.')) + normal! 15|]/ + call assert_equal(21, col('.')) + call setline(1, ' comment */') + call assert_beeps('normal! 15|[/') + call setline(1, ' /* comment') + call assert_beeps('normal! 15|]/') + close! +endfunc + +" Test for the 'taglength' option +func Test_tag_length() + set tags=Xtags + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "tame\tXfile1\t1;", + \ "tape\tXfile2\t1;"], 'Xtags') + call writefile(['tame'], 'Xfile1') + call writefile(['tape'], 'Xfile2') + + " Jumping to the tag 'tape', should instead jump to 'tame' + new + set taglength=2 + tag tape + call assert_equal('Xfile1', @%) + " Tag search should jump to the right tag + enew + tag /^tape$ + call assert_equal('Xfile2', @%) + + call delete('Xtags') + call delete('Xfile1') + call delete('Xfile2') + set tags& taglength& +endfunc + +" Tests for errors in a tags file +func Test_tagfile_errors() + set tags=Xtags + + " missing search pattern or line number for a tag + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "foo\tXfile\t"], 'Xtags', 'b') + call writefile(['foo'], 'Xfile') + + enew + tag foo + call assert_equal('', @%) + let caught_431 = v:false + try + eval taglist('.*') + catch /:E431:/ + let caught_431 = v:true + endtry + call assert_equal(v:true, caught_431) + + " tag name and file name are not separated by a tab + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "foo Xfile 1"], 'Xtags') + call assert_fails('tag foo', 'E431:') + + " file name and search pattern are not separated by a tab + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "foo\tXfile 1;"], 'Xtags') + call assert_fails('tag foo', 'E431:') + + call delete('Xtags') + call delete('Xfile') + set tags& +endfunc + +" When :stag fails to open the file, should close the new window +func Test_stag_close_window_on_error() + new | only + set tags=Xtags + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "foo\tXfile\t1"], 'Xtags') + call writefile(['foo'], 'Xfile') + call writefile([], '.Xfile.swp') + " Remove the catch-all that runtest.vim adds + au! SwapExists + augroup StagTest + au! + autocmd SwapExists Xfile let v:swapchoice='q' + augroup END + + stag foo + call assert_equal(1, winnr('$')) + call assert_equal('', @%) + + augroup StagTest + au! + augroup END + call delete('Xfile') + call delete('.Xfile.swp') + set tags& +endfunc + +" Test for 'tagbsearch' (binary search) +func Test_tagbsearch() + " If a tags file header says the tags are sorted, but the tags are actually + " unsorted, then binary search should fail and linear search should work. + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "!_TAG_FILE_SORTED\t1\t/0=unsorted, 1=sorted, 2=foldcase/", + \ "third\tXfoo\t3", + \ "second\tXfoo\t2", + \ "first\tXfoo\t1"], + \ 'Xtags') + set tags=Xtags + let code =<< trim [CODE] + int first() {} + int second() {} + int third() {} + [CODE] + call writefile(code, 'Xfoo') + + enew + set tagbsearch + call assert_fails('tag first', 'E426:') + call assert_equal('', bufname()) + call assert_fails('tag second', 'E426:') + call assert_equal('', bufname()) + tag third + call assert_equal('Xfoo', bufname()) + call assert_equal(3, line('.')) + %bw! + + set notagbsearch + tag first + call assert_equal('Xfoo', bufname()) + call assert_equal(1, line('.')) + enew + tag second + call assert_equal('Xfoo', bufname()) + call assert_equal(2, line('.')) + enew + tag third + call assert_equal('Xfoo', bufname()) + call assert_equal(3, line('.')) + %bw! + + " If a tags file header says the tags are unsorted, but the tags are + " actually sorted, then binary search should work. + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "!_TAG_FILE_SORTED\t0\t/0=unsorted, 1=sorted, 2=foldcase/", + \ "first\tXfoo\t1", + \ "second\tXfoo\t2", + \ "third\tXfoo\t3"], + \ 'Xtags') + + set tagbsearch + tag first + call assert_equal('Xfoo', bufname()) + call assert_equal(1, line('.')) + enew + tag second + call assert_equal('Xfoo', bufname()) + call assert_equal(2, line('.')) + enew + tag third + call assert_equal('Xfoo', bufname()) + call assert_equal(3, line('.')) + %bw! + + " Binary search fails on EOF + call writefile([ + \ "!_TAG_FILE_ENCODING\tutf-8\t//", + \ "!_TAG_FILE_SORTED\t1\t/0=unsorted, 1=sorted, 2=foldcase/", + \ "bar\tXfoo\t1", + \ "foo\tXfoo\t2"], + \ 'Xtags') + call assert_fails('tag bbb', 'E426:') + + call delete('Xtags') + call delete('Xfoo') + set tags& tagbsearch& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_taglist.vim b/test/old/testdir/test_taglist.vim new file mode 100644 index 0000000000..75d28c3ec4 --- /dev/null +++ b/test/old/testdir/test_taglist.vim @@ -0,0 +1,281 @@ +" test taglist(), tagfiles() functions and :tags command + +source view_util.vim + +func Test_taglist() + call writefile([ + \ "FFoo\tXfoo\t1", + \ "FBar\tXfoo\t2", + \ "BFoo\tXbar\t1", + \ "BBar\tXbar\t2", + \ "Kindly\tXbar\t3;\"\tv\tfile:", + \ "Lambda\tXbar\t3;\"\tλ\tfile:", + \ "Command\tXbar\tcall cursor(3, 4)|;\"\td", + \ ], 'Xtags') + set tags=Xtags + split Xtext + + call assert_equal(['FFoo', 'BFoo'], map(taglist("Foo"), {i, v -> v.name})) + call assert_equal(['FFoo', 'BFoo'], map("Foo"->taglist("Xtext"), {i, v -> v.name})) + call assert_equal(['FFoo', 'BFoo'], map(taglist("Foo", "Xfoo"), {i, v -> v.name})) + call assert_equal(['BFoo', 'FFoo'], map(taglist("Foo", "Xbar"), {i, v -> v.name})) + + let kindly = taglist("Kindly") + call assert_equal(1, len(kindly)) + call assert_equal('v', kindly[0]['kind']) + call assert_equal('3', kindly[0]['cmd']) + call assert_equal(1, kindly[0]['static']) + call assert_equal('Xbar', kindly[0]['filename']) + + let lambda = taglist("Lambda") + call assert_equal(1, len(lambda)) + call assert_equal('λ', lambda[0]['kind']) + + let cmd = taglist("Command") + call assert_equal(1, len(cmd)) + call assert_equal('d', cmd[0]['kind']) + call assert_equal('call cursor(3, 4)', cmd[0]['cmd']) + + " Use characters with value > 127 in the tag extra field. + call writefile([ + \ "vFoo\tXfoo\t4" .. ';"' .. "\ttypename:int\ta£££\tv", + \ ], 'Xtags') + call assert_equal('v', taglist('vFoo')[0].kind) + + call assert_fails("let l=taglist([])", 'E730:') + + call delete('Xtags') + set tags& + bwipe +endfunc + +func Test_taglist_native_etags() + if !has('emacs_tags') + return + endif + call writefile([ + \ "\x0c", + \ "src/os_unix.c,13491", + \ "set_signals(\x7f1335,32699", + \ "reset_signals(\x7f1407,34136", + \ ], 'Xtags') + + set tags=Xtags + + call assert_equal([['set_signals', '1335,32699'], ['reset_signals', '1407,34136']], + \ map(taglist('set_signals'), {i, v -> [v.name, v.cmd]})) + + call delete('Xtags') + set tags& +endfunc + +func Test_taglist_ctags_etags() + if !has('emacs_tags') + return + endif + call writefile([ + \ "\x0c", + \ "src/os_unix.c,13491", + \ "set_signals(void)\x7fset_signals\x011335,32699", + \ "reset_signals(void)\x7freset_signals\x011407,34136", + \ ], 'Xtags') + + set tags=Xtags + + call assert_equal([['set_signals', '1335,32699'], ['reset_signals', '1407,34136']], + \ map(taglist('set_signals'), {i, v -> [v.name, v.cmd]})) + + call delete('Xtags') + set tags& +endfunc + +func Test_tags_too_long() + call assert_fails('tag ' . repeat('x', 1020), ['E433', 'E426']) + tags +endfunc + +func Test_tagfiles() + call assert_equal([], tagfiles()) + + call writefile(["FFoo\tXfoo\t1"], 'Xtags1') + call writefile(["FBar\tXbar\t1"], 'Xtags2') + set tags=Xtags1,Xtags2 + call assert_equal(['Xtags1', 'Xtags2'], tagfiles()) + + help + let tf = tagfiles() + " Nvim: expectation(s) based on tags in build dir (added to &rtp). + " Filter out the '../../../runtime/doc/tags'. + call filter(tf, 'v:val != "../../../runtime/doc/tags"') + call assert_equal(1, len(tf)) + call assert_equal(fnamemodify(expand('$BUILD_DIR/runtime/doc/tags'), ':p:gs?\\?/?'), + \ fnamemodify(tf[0], ':p:gs?\\?/?')) + helpclose + call assert_equal(['Xtags1', 'Xtags2'], tagfiles()) + " Nvim: defaults to "./tags;,tags", which might cause false positives. + set tags=./tags,tags + call assert_equal([], tagfiles()) + + call delete('Xtags1') + call delete('Xtags2') + bd +endfunc + +" For historical reasons we support a tags file where the last line is missing +" the newline. +func Test_tagsfile_without_trailing_newline() + call writefile(["Foo\tfoo\t1"], 'Xtags', 'b') + set tags=Xtags + + let tl = taglist('.*') + call assert_equal(1, len(tl)) + call assert_equal('Foo', tl[0].name) + + call delete('Xtags') + set tags& +endfunc + +" Test for ignoring comments in a tags file +func Test_tagfile_ignore_comments() + call writefile([ + \ "!_TAG_PROGRAM_NAME /Test tags generator/", + \ "FBar\tXfoo\t2" .. ';"' .. "\textrafield\tf", + \ "!_TAG_FILE_FORMAT 2 /extended format/", + \ ], 'Xtags') + set tags=Xtags + + let l = taglist('.*') + call assert_equal(1, len(l)) + call assert_equal('FBar', l[0].name) + + set tags& + call delete('Xtags') +endfunc + +" Test for using an excmd in a tags file to position the cursor (instead of a +" search pattern or a line number) +func Test_tagfile_excmd() + call writefile([ + \ "vFoo\tXfoo\tcall cursor(3, 4)" .. '|;"' .. "\tv", + \ ], 'Xtags') + set tags=Xtags + + let l = taglist('.*') + call assert_equal([{ + \ 'cmd' : 'call cursor(3, 4)', + \ 'static' : 0, + \ 'name' : 'vFoo', + \ 'kind' : 'v', + \ 'filename' : 'Xfoo'}], l) + + set tags& + call delete('Xtags') +endfunc + +" Test for duplicate fields in a tag in a tags file +func Test_duplicate_field() + call writefile([ + \ "vFoo\tXfoo\t4" .. ';"' .. "\ttypename:int\ttypename:int\tv", + \ ], 'Xtags') + set tags=Xtags + + let l = taglist('.*') + call assert_equal([{ + \ 'cmd' : '4', + \ 'static' : 0, + \ 'name' : 'vFoo', + \ 'kind' : 'v', + \ 'typename' : 'int', + \ 'filename' : 'Xfoo'}], l) + + set tags& + call delete('Xtags') +endfunc + +" Test for tag address with ; +func Test_tag_addr_with_semicolon() + call writefile([ + \ "Func1\tXfoo\t6;/^Func1/" .. ';"' .. "\tf" + \ ], 'Xtags') + set tags=Xtags + + let l = taglist('.*') + call assert_equal([{ + \ 'cmd' : '6;/^Func1/', + \ 'static' : 0, + \ 'name' : 'Func1', + \ 'kind' : 'f', + \ 'filename' : 'Xfoo'}], l) + + set tags& + call delete('Xtags') +endfunc + +" Test for format error in a tags file +func Test_format_error() + call writefile(['vFoo-Xfoo-4'], 'Xtags') + set tags=Xtags + + let caught_exception = v:false + try + let l = taglist('.*') + catch /E431:/ + " test succeeded + let caught_exception = v:true + catch + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + call assert_true(caught_exception) + + " no field after the filename for a tag + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "foo\tXfile"], 'Xtags') + call assert_fails("echo taglist('foo')", 'E431:') + + set tags& + call delete('Xtags') +endfunc + +" Test for :tag command completion with 'wildoptions' set to 'tagfile' +func Test_tag_complete_wildoptions() + call writefile(["foo\ta.c\t10;\"\tf", "bar\tb.c\t20;\"\td"], 'Xtags') + set tags=Xtags + set wildoptions=tagfile + + call feedkeys(":tag \<C-D>\<C-R>=Screenline(&lines - 1)\<CR> : " + \ .. "\<C-R>=Screenline(&lines - 2)\<CR>\<C-B>\"\<CR>", 'xt') + + call assert_equal('"tag bar d b.c : foo f a.c', @:) + + call delete('Xtags') + set wildoptions& + set tags& +endfunc + +func Test_tag_complete_with_overlong_line() + let tagslines =<< trim END + !_TAG_FILE_FORMAT 2 // + !_TAG_FILE_SORTED 1 // + !_TAG_FILE_ENCODING utf-8 // + inboundGSV a 1;" r + inboundGovernor a 2;" kind:⊢ type:forall (muxMode :: MuxMode) socket peerAddr versionNumber m a b. (MonadAsync m, MonadCatch m, MonadEvaluate m, MonadThrow m, MonadThrow (STM m), MonadTime m, MonadTimer m, MonadMask m, Ord peerAddr, HasResponder muxMode ~ True) => Tracer m (RemoteTransitionTrace peerAddr) -> Tracer m (InboundGovernorTrace peerAddr) -> ServerControlChannel muxMode peerAddr ByteString m a b -> DiffTime -> MuxConnectionManager muxMode socket peerAddr versionNumber ByteString m a b -> StrictTVar m InboundGovernorObservableState -> m Void + inboundGovernorCounters a 3;" kind:⊢ type:InboundGovernorState muxMode peerAddr m a b -> InboundGovernorCounters + END + call writefile(tagslines, 'Xtags') + set tags=Xtags + + " try with binary search + set tagbsearch + call feedkeys(":tag inbou\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"tag inboundGSV inboundGovernor inboundGovernorCounters', @:) + " try with linear search + set notagbsearch + call feedkeys(":tag inbou\<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"tag inboundGSV inboundGovernor inboundGovernorCounters', @:) + set tagbsearch& + + call delete('Xtags') + set tags& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_termcodes.vim b/test/old/testdir/test_termcodes.vim new file mode 100644 index 0000000000..a00ea02286 --- /dev/null +++ b/test/old/testdir/test_termcodes.vim @@ -0,0 +1,1062 @@ + +source check.vim +" CheckNotGui +" CheckUnix + +source shared.vim +source mouse.vim +source view_util.vim +source term_util.vim + +func Test_term_mouse_left_click() + new + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " set mouse=a term=xterm + set mouse=a + call setline(1, ['line 1', 'line 2', 'line 3 is a bit longer']) + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + g:Ttymouse_netterm + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + go + call assert_equal([0, 1, 1, 0], getpos('.'), msg) + let row = 2 + let col = 6 + call MouseLeftClick(row, col) + call MouseLeftRelease(row, col) + call assert_equal([0, 2, 6, 0], getpos('.'), msg) + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) + bwipe! +endfunc + +func Test_xterm_mouse_right_click_extends_visual() + if has('mac') + " throw "Skipped: test right click in visual mode does not work on macOs (why?)" + endif + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " set mouse=a term=xterm + set mouse=a + + for visual_mode in ["v", "V", "\<C-V>"] + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'visual=' .. visual_mode .. ' ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + + call setline(1, repeat([repeat('-', 7)], 7)) + call MouseLeftClick(4, 4) + call MouseLeftRelease(4, 4) + exe "norm! " .. visual_mode + + " Right click extends top left of visual area. + call MouseRightClick(2, 2) + call MouseRightRelease(2, 2) + + " Right click extends bottom right of visual area. + call MouseRightClick(6, 6) + call MouseRightRelease(6, 6) + norm! r1gv + + " Right click shrinks top left of visual area. + call MouseRightClick(3, 3) + call MouseRightRelease(3, 3) + + " Right click shrinks bottom right of visual area. + call MouseRightClick(5, 5) + call MouseRightRelease(5, 5) + norm! r2 + + if visual_mode ==# 'v' + call assert_equal(['-------', + \ '-111111', + \ '1122222', + \ '2222222', + \ '2222211', + \ '111111-', + \ '-------'], getline(1, '$'), msg) + elseif visual_mode ==# 'V' + call assert_equal(['-------', + \ '1111111', + \ '2222222', + \ '2222222', + \ '2222222', + \ '1111111', + \ '-------'], getline(1, '$'), msg) + else + call assert_equal(['-------', + \ '-11111-', + \ '-12221-', + \ '-12221-', + \ '-12221-', + \ '-11111-', + \ '-------'], getline(1, '$'), msg) + endif + endfor + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) + bwipe! +endfunc + +" Test that <C-LeftMouse> jumps to help tag and <C-RightMouse> jumps back. +func Test_xterm_mouse_ctrl_click() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " set mouse=a term=xterm + set mouse=a + + for ttymouse_val in g:Ttymouse_values + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + " help + help usr_toc.txt + /usr_02.txt + norm! zt + let row = 1 + let col = 1 + call MouseCtrlLeftClick(row, col) + call MouseLeftRelease(row, col) + call assert_match('usr_02.txt$', bufname('%'), msg) + call assert_equal('*usr_02.txt*', expand('<cWORD>'), msg) + + call MouseCtrlRightClick(row, col) + call MouseRightRelease(row, col) + " call assert_match('help.txt$', bufname('%'), msg) + call assert_match('usr_toc.txt$', bufname('%'), msg) + call assert_equal('|usr_02.txt|', expand('<cWORD>'), msg) + + helpclose + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse +endfunc + +func Test_term_mouse_middle_click() + CheckFeature clipboard_working + + new + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + let save_quotestar = @* + let @* = 'abc' + " set mouse=a term=xterm + set mouse=a + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + call setline(1, ['123456789', '123456789']) + + " Middle-click in the middle of the line pastes text where clicked. + let row = 1 + let col = 6 + call MouseMiddleClick(row, col) + call MouseMiddleRelease(row, col) + call assert_equal(['12345abc6789', '123456789'], getline(1, '$'), msg) + + " Middle-click beyond end of the line pastes text at the end of the line. + let col = 20 + call MouseMiddleClick(row, col) + call MouseMiddleRelease(row, col) + call assert_equal(['12345abc6789abc', '123456789'], getline(1, '$'), msg) + + " Middle-click beyond the last line pastes in the last line. + let row = 5 + let col = 3 + call MouseMiddleClick(row, col) + call MouseMiddleRelease(row, col) + call assert_equal(['12345abc6789abc', '12abc3456789'], getline(1, '$'), msg) + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) + let @* = save_quotestar + bwipe! +endfunc + +" TODO: for unclear reasons this test fails if it comes after +" Test_xterm_mouse_ctrl_click() +func Test_1xterm_mouse_wheel() + new + let save_mouse = &mouse + let save_term = &term + let save_wrap = &wrap + " let save_ttymouse = &ttymouse + " set mouse=a term=xterm nowrap + set mouse=a nowrap + call setline(1, range(100000000000000, 100000000000100)) + + for ttymouse_val in g:Ttymouse_values + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + go + call assert_equal(1, line('w0'), msg) + call assert_equal([0, 1, 1, 0], getpos('.'), msg) + + call MouseWheelDown(1, 1) + call assert_equal(4, line('w0'), msg) + call assert_equal([0, 4, 1, 0], getpos('.'), msg) + + call MouseWheelDown(1, 1) + call assert_equal(7, line('w0'), msg) + call assert_equal([0, 7, 1, 0], getpos('.'), msg) + + call MouseWheelUp(1, 1) + call assert_equal(4, line('w0'), msg) + call assert_equal([0, 7, 1, 0], getpos('.'), msg) + + call MouseWheelUp(1, 1) + call assert_equal(1, line('w0'), msg) + call assert_equal([0, 7, 1, 0], getpos('.'), msg) + + call MouseWheelRight(1, 1) + call assert_equal(7, 1 + virtcol(".") - wincol(), msg) + call assert_equal([0, 7, 7, 0], getpos('.'), msg) + + call MouseWheelRight(1, 1) + call assert_equal(13, 1 + virtcol(".") - wincol(), msg) + call assert_equal([0, 7, 13, 0], getpos('.'), msg) + + call MouseWheelLeft(1, 1) + call assert_equal(7, 1 + virtcol(".") - wincol(), msg) + call assert_equal([0, 7, 13, 0], getpos('.'), msg) + + call MouseWheelLeft(1, 1) + call assert_equal(1, 1 + virtcol(".") - wincol(), msg) + call assert_equal([0, 7, 13, 0], getpos('.'), msg) + + endfor + + let &mouse = save_mouse + " let &term = save_term + let &wrap = save_wrap + " let &ttymouse = save_ttymouse + bwipe! +endfunc + +" Test that dragging beyond the window (at the bottom and at the top) +" scrolls window content by the number of lines beyond the window. +func Test_term_mouse_drag_beyond_window() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " set mouse=a term=xterm + set mouse=a + let col = 1 + call setline(1, range(1, 100)) + + " Split into 3 windows, and go into the middle window + " so we test dragging mouse below and above the window. + 2split + wincmd j + 2split + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + + " Line #10 at the top. + norm! 10zt + redraw + call assert_equal(10, winsaveview().topline, msg) + call assert_equal(2, winheight(0), msg) + + let row = 4 + call MouseLeftClick(row, col) + call assert_equal(10, winsaveview().topline, msg) + + " Drag downwards. We're still in the window so topline should + " not change yet. + let row += 1 + call MouseLeftDrag(row, col) + call assert_equal(10, winsaveview().topline, msg) + + " We now leave the window at the bottom, so the window content should + " scroll by 1 line, then 2 lines (etc) as we drag further away. + let row += 1 + call MouseLeftDrag(row, col) + call assert_equal(11, winsaveview().topline, msg) + + let row += 1 + call MouseLeftDrag(row, col) + call assert_equal(13, winsaveview().topline, msg) + + " Now drag upwards. + let row -= 1 + call MouseLeftDrag(row, col) + call assert_equal(14, winsaveview().topline, msg) + + " We're now back in the window so the topline should not change. + let row -= 1 + call MouseLeftDrag(row, col) + call assert_equal(14, winsaveview().topline, msg) + + let row -= 1 + call MouseLeftDrag(row, col) + call assert_equal(14, winsaveview().topline, msg) + + " We now leave the window at the top so the window content should + " scroll by 1 line, then 2, then 3 (etc) in the opposite direction. + let row -= 1 + call MouseLeftDrag(row, col) + call assert_equal(13, winsaveview().topline, msg) + + let row -= 1 + call MouseLeftDrag(row, col) + call assert_equal(11, winsaveview().topline, msg) + + let row -= 1 + call MouseLeftDrag(row, col) + call assert_equal(8, winsaveview().topline, msg) + + call MouseLeftRelease(row, col) + call assert_equal(8, winsaveview().topline, msg) + call assert_equal(2, winheight(0), msg) + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) + bwipe! +endfunc + +func Test_term_mouse_drag_window_separator() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " set mouse=a term=xterm + set mouse=a + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + + " Split horizontally and test dragging the horizontal window separator. + split + let rowseparator = winheight(0) + 1 + let row = rowseparator + let col = 1 + + " When 'ttymouse' is 'xterm2', row/col bigger than 223 are not supported. + if ttymouse_val !=# 'xterm2' || row <= 223 + call MouseLeftClick(row, col) + let row -= 1 + call MouseLeftDrag(row, col) + call assert_equal(rowseparator - 1, winheight(0) + 1, msg) + let row += 1 + call MouseLeftDrag(row, col) + call assert_equal(rowseparator, winheight(0) + 1, msg) + call MouseLeftRelease(row, col) + call assert_equal(rowseparator, winheight(0) + 1, msg) + endif + bwipe! + + " Split vertically and test dragging the vertical window separator. + vsplit + let colseparator = winwidth(0) + 1 + let row = 1 + let col = colseparator + + " When 'ttymouse' is 'xterm2', row/col bigger than 223 are not supported. + if ttymouse_val !=# 'xterm2' || col <= 223 + call MouseLeftClick(row, col) + let col -= 1 + call MouseLeftDrag(row, col) + call assert_equal(colseparator - 1, winwidth(0) + 1, msg) + let col += 1 + call MouseLeftDrag(row, col) + call assert_equal(colseparator, winwidth(0) + 1, msg) + call MouseLeftRelease(row, col) + call assert_equal(colseparator, winwidth(0) + 1, msg) + endif + bwipe! + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) +endfunc + +func Test_term_mouse_drag_statusline() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + let save_laststatus = &laststatus + " set mouse=a term=xterm laststatus=2 + set mouse=a laststatus=2 + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + + call assert_equal(1, &cmdheight, msg) + let rowstatusline = winheight(0) + 1 + let row = rowstatusline + let col = 1 + + if ttymouse_val ==# 'xterm2' && row > 223 + " When 'ttymouse' is 'xterm2', row/col bigger than 223 are not supported. + continue + endif + + call MouseLeftClick(row, col) + let row -= 1 + call MouseLeftDrag(row, col) + call assert_equal(2, &cmdheight, msg) + call assert_equal(rowstatusline - 1, winheight(0) + 1, msg) + let row += 1 + call MouseLeftDrag(row, col) + call assert_equal(1, &cmdheight, msg) + call assert_equal(rowstatusline, winheight(0) + 1, msg) + call MouseLeftRelease(row, col) + call assert_equal(1, &cmdheight, msg) + call assert_equal(rowstatusline, winheight(0) + 1, msg) + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) + let &laststatus = save_laststatus +endfunc + +func Test_term_mouse_click_tab() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " set mouse=a term=xterm + set mouse=a + let row = 1 + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + g:Ttymouse_netterm + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + e Xfoo + tabnew Xbar + + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ '# Xfoo', + \ 'Tab page 2', + \ '> Xbar'], a, msg) + + " Test clicking on tab names in the tabline at the top. + let col = 2 + redraw + call MouseLeftClick(row, col) + call MouseLeftRelease(row, col) + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ '> Xfoo', + \ 'Tab page 2', + \ '# Xbar'], a, msg) + + let col = 9 + call MouseLeftClick(row, col) + call MouseLeftRelease(row, col) + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ '# Xfoo', + \ 'Tab page 2', + \ '> Xbar'], a, msg) + + %bwipe! + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) +endfunc + +func Test_term_mouse_click_X_to_close_tab() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " set mouse=a term=xterm + set mouse=a + let row = 1 + let col = &columns + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + g:Ttymouse_netterm + if ttymouse_val ==# 'xterm2' && col > 223 + " When 'ttymouse' is 'xterm2', row/col bigger than 223 are not supported. + continue + endif + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + e Xtab1 + tabnew Xtab2 + tabnew Xtab3 + tabn 2 + + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ ' Xtab1', + \ 'Tab page 2', + \ '> Xtab2', + \ 'Tab page 3', + \ '# Xtab3'], a, msg) + + " Click on "X" in tabline to close current tab i.e. Xtab2. + redraw + call MouseLeftClick(row, col) + call MouseLeftRelease(row, col) + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ ' Xtab1', + \ 'Tab page 2', + \ '> Xtab3'], a, msg) + + %bwipe! + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) +endfunc + +func Test_term_mouse_drag_to_move_tab() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " Set 'mousetime' to 1 to avoid recognizing a double-click in the loop + " set mouse=a term=xterm mousetime=1 + set mouse=a mousetime=0 + let row = 1 + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + e Xtab1 + tabnew Xtab2 + + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ '# Xtab1', + \ 'Tab page 2', + \ '> Xtab2'], a, msg) + redraw + + " Click in tab2 and drag it to tab1. + " Check getcharmod() to verify that click is not + " interpreted as a spurious double-click. + call MouseLeftClick(row, 10) + call assert_equal(0, getcharmod(), msg) + for col in [9, 8, 7, 6] + call MouseLeftDrag(row, col) + endfor + call MouseLeftRelease(row, col) + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ '> Xtab2', + \ 'Tab page 2', + \ '# Xtab1'], a, msg) + + " Switch to tab1 + tabnext + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ '# Xtab2', + \ 'Tab page 2', + \ '> Xtab1'], a, msg) + + " Click in tab2 and drag it to tab1. + " This time it is non-current tab. + call MouseLeftClick(row, 6) + call assert_equal(0, getcharmod(), msg) + for col in [7, 8, 9, 10] + call MouseLeftDrag(row, col) + endfor + call MouseLeftRelease(row, col) + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ '# Xtab1', + \ 'Tab page 2', + \ '> Xtab2'], a, msg) + + " Click elsewhere so that click in next iteration is not + " interpreted as unwanted double-click. + call MouseLeftClick(row, 11) + call MouseLeftRelease(row, 11) + + %bwipe! + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) + set mousetime& +endfunc + +func Test_term_mouse_double_click_to_create_tab() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " Set 'mousetime' to a small value, so that double-click works but we don't + " have to wait long to avoid a triple-click. + " set mouse=a term=xterm mousetime=200 + set mouse=a mousetime=200 + let row = 1 + let col = 10 + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + e Xtab1 + tabnew Xtab2 + + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ '# Xtab1', + \ 'Tab page 2', + \ '> Xtab2'], a, msg) + + redraw + call MouseLeftClick(row, col) + " Check getcharmod() to verify that first click is not + " interpreted as a spurious double-click. + call assert_equal(0, getcharmod(), msg) + call MouseLeftRelease(row, col) + call MouseLeftClick(row, col) + call assert_equal(32, getcharmod(), msg) " double-click + call MouseLeftRelease(row, col) + let a = split(execute(':tabs'), "\n") + call assert_equal(['Tab page 1', + \ ' Xtab1', + \ 'Tab page 2', + \ '> [No Name]', + \ 'Tab page 3', + \ '# Xtab2'], a, msg) + + " Click elsewhere so that click in next iteration is not + " interpreted as unwanted double click. + call MouseLeftClick(row, col + 1) + call MouseLeftRelease(row, col + 1) + + %bwipe! + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + " call test_override('no_query_mouse', 0) + set mousetime& +endfunc + +" Test double/triple/quadruple click in normal mode to visually select. +func Test_term_mouse_multiple_clicks_to_visually_select() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + + " 'mousetime' must be sufficiently large, or else the test is flaky when + " using a ssh connection with X forwarding; i.e. ssh -X (issue #7563). + " set mouse=a term=xterm mousetime=600 + set mouse=a mousetime=600 + new + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + call setline(1, ['foo [foo bar] foo', 'foo']) + + " Double-click on word should visually select the word. + call MouseLeftClick(1, 2) + call assert_equal(0, getcharmod(), msg) + call MouseLeftRelease(1, 2) + call MouseLeftClick(1, 2) + call assert_equal(32, getcharmod(), msg) " double-click + call MouseLeftRelease(1, 2) + call assert_equal('v', mode(), msg) + norm! r1 + call assert_equal(['111 [foo bar] foo', 'foo'], getline(1, '$'), msg) + + " Double-click on opening square bracket should visually + " select the whole [foo bar]. + call MouseLeftClick(1, 5) + call assert_equal(0, getcharmod(), msg) + call MouseLeftRelease(1, 5) + call MouseLeftClick(1, 5) + call assert_equal(32, getcharmod(), msg) " double-click + call MouseLeftRelease(1, 5) + call assert_equal('v', mode(), msg) + norm! r2 + call assert_equal(['111 222222222 foo', 'foo'], getline(1, '$'), msg) + + " Triple-click should visually select the whole line. + call MouseLeftClick(1, 3) + call assert_equal(0, getcharmod(), msg) + call MouseLeftRelease(1, 3) + call MouseLeftClick(1, 3) + call assert_equal(32, getcharmod(), msg) " double-click + call MouseLeftRelease(1, 3) + call MouseLeftClick(1, 3) + call assert_equal(64, getcharmod(), msg) " triple-click + call MouseLeftRelease(1, 3) + call assert_equal('V', mode(), msg) + norm! r3 + call assert_equal(['33333333333333333', 'foo'], getline(1, '$'), msg) + + " Quadruple-click should start visual block select. + call MouseLeftClick(1, 2) + call assert_equal(0, getcharmod(), msg) + call MouseLeftRelease(1, 2) + call MouseLeftClick(1, 2) + call assert_equal(32, getcharmod(), msg) " double-click + call MouseLeftRelease(1, 2) + call MouseLeftClick(1, 2) + call assert_equal(64, getcharmod(), msg) " triple-click + call MouseLeftRelease(1, 2) + call MouseLeftClick(1, 2) + call assert_equal(96, getcharmod(), msg) " quadruple-click + call MouseLeftRelease(1, 2) + call assert_equal("\<c-v>", mode(), msg) + norm! r4 + call assert_equal(['34333333333333333', 'foo'], getline(1, '$'), msg) + + " Double-click on a space character should visually select all the + " consecutive space characters. + %d + call setline(1, ' one two') + call MouseLeftClick(1, 2) + call MouseLeftRelease(1, 2) + call MouseLeftClick(1, 2) + call MouseLeftRelease(1, 2) + call assert_equal('v', mode(), msg) + norm! r1 + call assert_equal(['1111one two'], getline(1, '$'), msg) + + " Double-click on a word with exclusive selection + set selection=exclusive + let @" = '' + call MouseLeftClick(1, 10) + call MouseLeftRelease(1, 10) + call MouseLeftClick(1, 10) + call MouseLeftRelease(1, 10) + norm! y + call assert_equal('two', @", msg) + + " Double click to select a block of text with exclusive selection + %d + call setline(1, 'one (two) three') + call MouseLeftClick(1, 5) + call MouseLeftRelease(1, 5) + call MouseLeftClick(1, 5) + call MouseLeftRelease(1, 5) + norm! y + call assert_equal(5, col("'<"), msg) + call assert_equal(10, col("'>"), msg) + + call MouseLeftClick(1, 9) + call MouseLeftRelease(1, 9) + call MouseLeftClick(1, 9) + call MouseLeftRelease(1, 9) + norm! y + call assert_equal(5, col("'<"), msg) + call assert_equal(10, col("'>"), msg) + set selection& + + " Click somewhere else so that the clicks above is not combined with the + " clicks in the next iteration. + call MouseRightClick(3, 10) + call MouseRightRelease(3, 10) + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + set mousetime& + " call test_override('no_query_mouse', 0) + bwipe! +endfunc + +" Test for selecting text in visual blockwise mode using Alt-LeftClick +func Test_mouse_alt_leftclick() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " set mouse=a term=xterm mousetime=200 + set mouse=a mousetime=200 + set mousemodel=popup + new + call setline(1, 'one (two) three') + + for ttymouse_val in g:Ttymouse_values + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + + " Left click with the Alt modifier key should extend the selection in + " blockwise visual mode. + let @" = '' + call MouseLeftClick(1, 3) + call MouseLeftRelease(1, 3) + call MouseAltLeftClick(1, 11) + call MouseLeftRelease(1, 11) + call assert_equal("\<C-V>", mode(), msg) + normal! y + call assert_equal('e (two) t', @") + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + set mousetime& mousemodel& + " call test_override('no_query_mouse', 0) + close! +endfunc + +func Test_xterm_mouse_click_in_fold_columns() + new + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + let save_foldcolumn = &foldcolumn + " set mouse=a term=xterm foldcolumn=3 ttymouse=xterm2 + set mouse=a foldcolumn=3 + + " Create 2 nested folds. + call setline(1, range(1, 7)) + 2,6fold + norm! zR + 4,5fold + call assert_equal([-1, -1, -1, 4, 4, -1, -1], + \ map(range(1, 7), 'foldclosed(v:val)')) + + " Click in "+" of inner fold in foldcolumn should open it. + redraw + let row = 4 + let col = 2 + call MouseLeftClick(row, col) + call MouseLeftRelease(row, col) + call assert_equal([-1, -1, -1, -1, -1, -1, -1], + \ map(range(1, 7), 'foldclosed(v:val)')) + + " Click in "-" of outer fold in foldcolumn should close it. + redraw + let row = 2 + let col = 1 + call MouseLeftClick(row, col) + call MouseLeftRelease(row, col) + call assert_equal([-1, 2, 2, 2, 2, 2, -1], + \ map(range(1, 7), 'foldclosed(v:val)')) + norm! zR + + " Click in "|" of inner fold in foldcolumn should close it. + redraw + let row = 5 + let col = 2 + call MouseLeftClick(row, col) + call MouseLeftRelease(row, col) + call assert_equal([-1, -1, -1, 4, 4, -1, -1], + \ map(range(1, 7), 'foldclosed(v:val)')) + + let &foldcolumn = save_foldcolumn + " Redraw at the end of the test to avoid interfering with other tests. + defer execute('redraw') + " let &ttymouse = save_ttymouse + " let &term = save_term + let &mouse = save_mouse + bwipe! +endfunc + +" Test for the 'h' flag in the 'mouse' option. Using mouse in the help window. +func Test_term_mouse_help_window() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " set mouse=h term=xterm mousetime=200 + set mouse=h mousetime=200 + + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + help + let @" = '' + call MouseLeftClick(2, 5) + call MouseLeftRelease(2, 5) + call MouseLeftClick(1, 1) + call MouseLeftDrag(1, 10) + call MouseLeftRelease(1, 10) + norm! y + call assert_equal('*help.txt*', @", msg) + helpclose + + " Click somewhere else to make sure the left click above is not combined + " with the next left click and treated as a double click + call MouseRightClick(5, 10) + call MouseRightRelease(5, 10) + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + set mousetime& + " call test_override('no_query_mouse', 0) + %bw! +endfunc + +" Test for the translation of various mouse terminal codes +func Test_mouse_termcodes() + let save_mouse = &mouse + let save_term = &term + " let save_ttymouse = &ttymouse + " call test_override('no_query_mouse', 1) + " set mouse=a term=xterm mousetime=200 + + new + for ttymouse_val in g:Ttymouse_values + g:Ttymouse_dec + g:Ttymouse_netterm + let msg = 'ttymouse=' .. ttymouse_val + " exe 'set ttymouse=' .. ttymouse_val + + let mouse_codes = [ + \ ["\<LeftMouse>", "<LeftMouse>"], + \ ["\<MiddleMouse>", "<MiddleMouse>"], + \ ["\<RightMouse>", "<RightMouse>"], + \ ["\<S-LeftMouse>", "<S-LeftMouse>"], + \ ["\<S-MiddleMouse>", "<S-MiddleMouse>"], + \ ["\<S-RightMouse>", "<S-RightMouse>"], + \ ["\<C-LeftMouse>", "<C-LeftMouse>"], + \ ["\<C-MiddleMouse>", "<C-MiddleMouse>"], + \ ["\<C-RightMouse>", "<C-RightMouse>"], + \ ["\<M-LeftMouse>", "<M-LeftMouse>"], + \ ["\<M-MiddleMouse>", "<M-MiddleMouse>"], + \ ["\<M-RightMouse>", "<M-RightMouse>"], + \ ["\<2-LeftMouse>", "<2-LeftMouse>"], + \ ["\<2-MiddleMouse>", "<2-MiddleMouse>"], + \ ["\<2-RightMouse>", "<2-RightMouse>"], + \ ["\<3-LeftMouse>", "<3-LeftMouse>"], + \ ["\<3-MiddleMouse>", "<3-MiddleMouse>"], + \ ["\<3-RightMouse>", "<3-RightMouse>"], + \ ["\<4-LeftMouse>", "<4-LeftMouse>"], + \ ["\<4-MiddleMouse>", "<4-MiddleMouse>"], + \ ["\<4-RightMouse>", "<4-RightMouse>"], + \ ["\<LeftDrag>", "<LeftDrag>"], + \ ["\<MiddleDrag>", "<MiddleDrag>"], + \ ["\<RightDrag>", "<RightDrag>"], + \ ["\<LeftRelease>", "<LeftRelease>"], + \ ["\<MiddleRelease>", "<MiddleRelease>"], + \ ["\<RightRelease>", "<RightRelease>"], + \ ["\<ScrollWheelUp>", "<ScrollWheelUp>"], + \ ["\<S-ScrollWheelUp>", "<S-ScrollWheelUp>"], + \ ["\<C-ScrollWheelUp>", "<C-ScrollWheelUp>"], + \ ["\<ScrollWheelDown>", "<ScrollWheelDown>"], + \ ["\<S-ScrollWheelDown>", "<S-ScrollWheelDown>"], + \ ["\<C-ScrollWheelDown>", "<C-ScrollWheelDown>"], + \ ["\<ScrollWheelLeft>", "<ScrollWheelLeft>"], + \ ["\<S-ScrollWheelLeft>", "<S-ScrollWheelLeft>"], + \ ["\<C-ScrollWheelLeft>", "<C-ScrollWheelLeft>"], + \ ["\<ScrollWheelRight>", "<ScrollWheelRight>"], + \ ["\<S-ScrollWheelRight>", "<S-ScrollWheelRight>"], + \ ["\<C-ScrollWheelRight>", "<C-ScrollWheelRight>"] + \ ] + + for [code, outstr] in mouse_codes + exe "normal ggC\<C-K>" . code + call assert_equal(outstr, getline(1), msg) + endfor + endfor + + let &mouse = save_mouse + " let &term = save_term + " let &ttymouse = save_ttymouse + set mousetime& + " call test_override('no_query_mouse', 0) + %bw! +endfunc + +" Test for translation of special key codes (<xF1>, <xF2>, etc.) +func Test_Keycode_Translation() + let keycodes = [ + \ ["<xUp>", "<Up>"], + \ ["<xDown>", "<Down>"], + \ ["<xLeft>", "<Left>"], + \ ["<xRight>", "<Right>"], + \ ["<xHome>", "<Home>"], + \ ["<xEnd>", "<End>"], + \ ["<zHome>", "<Home>"], + \ ["<zEnd>", "<End>"], + \ ["<xF1>", "<F1>"], + \ ["<xF2>", "<F2>"], + \ ["<xF3>", "<F3>"], + \ ["<xF4>", "<F4>"], + \ ["<S-xF1>", "<S-F1>"], + \ ["<S-xF2>", "<S-F2>"], + \ ["<S-xF3>", "<S-F3>"], + \ ["<S-xF4>", "<S-F4>"]] + for [k1, k2] in keycodes + exe "nnoremap " .. k1 .. " 2wx" + call assert_true(maparg(k1, 'n', 0, 1).lhs == k2) + exe "nunmap " .. k1 + endfor +endfunc + +" Test for terminal keycodes that doesn't have termcap entries +func Test_special_term_keycodes() + new + " Test for <xHome>, <S-xHome> and <C-xHome> + " send <K_SPECIAL> <KS_EXTRA> keycode + call feedkeys("i\<C-K>\x80\xfd\x3f\n", 'xt') + " send <K_SPECIAL> <KS_MODIFIER> bitmap <K_SPECIAL> <KS_EXTRA> keycode + call feedkeys("i\<C-K>\x80\xfc\x2\x80\xfd\x3f\n", 'xt') + call feedkeys("i\<C-K>\x80\xfc\x4\x80\xfd\x3f\n", 'xt') + " Test for <xEnd>, <S-xEnd> and <C-xEnd> + call feedkeys("i\<C-K>\x80\xfd\x3d\n", 'xt') + call feedkeys("i\<C-K>\x80\xfc\x2\x80\xfd\x3d\n", 'xt') + call feedkeys("i\<C-K>\x80\xfc\x4\x80\xfd\x3d\n", 'xt') + " Test for <zHome>, <S-zHome> and <C-zHome> + call feedkeys("i\<C-K>\x80\xfd\x40\n", 'xt') + call feedkeys("i\<C-K>\x80\xfc\x2\x80\xfd\x40\n", 'xt') + call feedkeys("i\<C-K>\x80\xfc\x4\x80\xfd\x40\n", 'xt') + " Test for <zEnd>, <S-zEnd> and <C-zEnd> + call feedkeys("i\<C-K>\x80\xfd\x3e\n", 'xt') + call feedkeys("i\<C-K>\x80\xfc\x2\x80\xfd\x3e\n", 'xt') + call feedkeys("i\<C-K>\x80\xfc\x4\x80\xfd\x3e\n", 'xt') + " Test for <xUp>, <xDown>, <xLeft> and <xRight> + call feedkeys("i\<C-K>\x80\xfd\x41\n", 'xt') + call feedkeys("i\<C-K>\x80\xfd\x42\n", 'xt') + call feedkeys("i\<C-K>\x80\xfd\x43\n", 'xt') + call feedkeys("i\<C-K>\x80\xfd\x44\n", 'xt') + call assert_equal(['<Home>', '<S-Home>', '<C-Home>', + \ '<End>', '<S-End>', '<C-End>', + \ '<Home>', '<S-Home>', '<C-Home>', + \ '<End>', '<S-End>', '<C-End>', + \ '<Up>', '<Down>', '<Left>', '<Right>', ''], getline(1, '$')) + bw! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_termdebug.vim b/test/old/testdir/test_termdebug.vim new file mode 100644 index 0000000000..98a4bd3215 --- /dev/null +++ b/test/old/testdir/test_termdebug.vim @@ -0,0 +1,228 @@ +" Test for the termdebug plugin + +source shared.vim +source check.vim + +CheckUnix +" CheckFeature terminal +CheckExecutable gdb +CheckExecutable gcc + +let g:GDB = exepath('gdb') +if g:GDB->empty() + throw 'Skipped: gdb is not found in $PATH' +endif + +let g:GCC = exepath('gcc') +if g:GCC->empty() + throw 'Skipped: gcc is not found in $PATH' +endif + +packadd termdebug + +func Test_termdebug_basic() + let lines =<< trim END + #include <stdio.h> + #include <stdlib.h> + + int isprime(int n) + { + if (n <= 1) + return 0; + + for (int i = 2; i <= n / 2; i++) + if (n % i == 0) + return 0; + + return 1; + } + + int main(int argc, char *argv[]) + { + int n = 7; + + printf("%d is %s prime\n", n, isprime(n) ? "a" : "not a"); + + return 0; + } + END + call writefile(lines, 'XTD_basic.c', 'D') + call system($'{g:GCC} -g -o XTD_basic XTD_basic.c') + + edit XTD_basic.c + Termdebug ./XTD_basic + call WaitForAssert({-> assert_equal(3, winnr('$'))}) + let gdb_buf = winbufnr(1) + wincmd b + Break 9 + call Nterm_wait(gdb_buf) + redraw! + call assert_equal([ + \ {'lnum': 9, 'id': 1014, 'name': 'debugBreakpoint1.0', + \ 'priority': 110, 'group': 'TermDebug'}], + \ sign_getplaced('', #{group: 'TermDebug'})[0].signs) + Run + call Nterm_wait(gdb_buf, 400) + redraw! + call WaitForAssert({-> assert_equal([ + \ {'lnum': 9, 'id': 12, 'name': 'debugPC', 'priority': 110, + \ 'group': 'TermDebug'}, + \ {'lnum': 9, 'id': 1014, 'name': 'debugBreakpoint1.0', + \ 'priority': 110, 'group': 'TermDebug'}], + "\ sign_getplaced('', #{group: 'TermDebug'})[0].signs)}) + \ sign_getplaced('', #{group: 'TermDebug'})[0].signs->reverse())}) + Finish + call Nterm_wait(gdb_buf) + redraw! + call WaitForAssert({-> assert_equal([ + \ {'lnum': 9, 'id': 1014, 'name': 'debugBreakpoint1.0', + \ 'priority': 110, 'group': 'TermDebug'}, + \ {'lnum': 20, 'id': 12, 'name': 'debugPC', + \ 'priority': 110, 'group': 'TermDebug'}], + \ sign_getplaced('', #{group: 'TermDebug'})[0].signs)}) + Continue + call Nterm_wait(gdb_buf) + + let i = 2 + while i <= 258 + Break + call Nterm_wait(gdb_buf) + if i == 2 + call WaitForAssert({-> assert_equal(sign_getdefined('debugBreakpoint2.0')[0].text, '02')}) + endif + if i == 10 + call WaitForAssert({-> assert_equal(sign_getdefined('debugBreakpoint10.0')[0].text, '0A')}) + endif + if i == 168 + call WaitForAssert({-> assert_equal(sign_getdefined('debugBreakpoint168.0')[0].text, 'A8')}) + endif + if i == 255 + call WaitForAssert({-> assert_equal(sign_getdefined('debugBreakpoint255.0')[0].text, 'FF')}) + endif + if i == 256 + call WaitForAssert({-> assert_equal(sign_getdefined('debugBreakpoint256.0')[0].text, 'F+')}) + endif + if i == 258 + call WaitForAssert({-> assert_equal(sign_getdefined('debugBreakpoint258.0')[0].text, 'F+')}) + endif + let i += 1 + endwhile + + let cn = 0 + " 60 is approx spaceBuffer * 3 + if winwidth(0) <= 78 + 60 + Var + call assert_equal(winnr(), winnr('$')) + call assert_equal(winlayout(), ['col', [['leaf', 1002], ['leaf', 1001], ['leaf', 1000], ['leaf', 1003 + cn]]]) + let cn += 1 + bw! + Asm + call assert_equal(winnr(), winnr('$')) + call assert_equal(winlayout(), ['col', [['leaf', 1002], ['leaf', 1001], ['leaf', 1000], ['leaf', 1003 + cn]]]) + let cn += 1 + bw! + endif + set columns=160 + call Nterm_wait(gdb_buf) + let winw = winwidth(0) + Var + if winwidth(0) < winw + call assert_equal(winnr(), winnr('$') - 1) + call assert_equal(winlayout(), ['col', [['leaf', 1002], ['leaf', 1001], ['row', [['leaf', 1003 + cn], ['leaf', 1000]]]]]) + let cn += 1 + bw! + endif + let winw = winwidth(0) + Asm + if winwidth(0) < winw + call assert_equal(winnr(), winnr('$') - 1) + call assert_equal(winlayout(), ['col', [['leaf', 1002], ['leaf', 1001], ['row', [['leaf', 1003 + cn], ['leaf', 1000]]]]]) + let cn += 1 + bw! + endif + set columns& + call Nterm_wait(gdb_buf) + + wincmd t + quit! + redraw! + call WaitForAssert({-> assert_equal(1, winnr('$'))}) + call assert_equal([], sign_getplaced('', #{group: 'TermDebug'})[0].signs) + + call delete('XTD_basic') + %bw! +endfunc + +func Test_termdebug_mapping() + %bw! + call assert_equal(maparg('K', 'n', 0, 1)->empty(), 1) + call assert_equal(maparg('-', 'n', 0, 1)->empty(), 1) + call assert_equal(maparg('+', 'n', 0, 1)->empty(), 1) + Termdebug + call WaitForAssert({-> assert_equal(3, winnr('$'))}) + wincmd b + call assert_equal(maparg('K', 'n', 0, 1)->empty(), 0) + call assert_equal(maparg('-', 'n', 0, 1)->empty(), 0) + call assert_equal(maparg('+', 'n', 0, 1)->empty(), 0) + call assert_equal(maparg('K', 'n', 0, 1).buffer, 0) + call assert_equal(maparg('-', 'n', 0, 1).buffer, 0) + call assert_equal(maparg('+', 'n', 0, 1).buffer, 0) + call assert_equal(maparg('K', 'n', 0, 1).rhs, ':Evaluate<CR>') + wincmd t + quit! + redraw! + call WaitForAssert({-> assert_equal(1, winnr('$'))}) + call assert_equal(maparg('K', 'n', 0, 1)->empty(), 1) + call assert_equal(maparg('-', 'n', 0, 1)->empty(), 1) + call assert_equal(maparg('+', 'n', 0, 1)->empty(), 1) + + %bw! + nnoremap K :echom "K"<cr> + nnoremap - :echom "-"<cr> + nnoremap + :echom "+"<cr> + Termdebug + call WaitForAssert({-> assert_equal(3, winnr('$'))}) + wincmd b + call assert_equal(maparg('K', 'n', 0, 1)->empty(), 0) + call assert_equal(maparg('-', 'n', 0, 1)->empty(), 0) + call assert_equal(maparg('+', 'n', 0, 1)->empty(), 0) + call assert_equal(maparg('K', 'n', 0, 1).buffer, 0) + call assert_equal(maparg('-', 'n', 0, 1).buffer, 0) + call assert_equal(maparg('+', 'n', 0, 1).buffer, 0) + call assert_equal(maparg('K', 'n', 0, 1).rhs, ':Evaluate<CR>') + wincmd t + quit! + redraw! + call WaitForAssert({-> assert_equal(1, winnr('$'))}) + call assert_equal(maparg('K', 'n', 0, 1)->empty(), 0) + call assert_equal(maparg('-', 'n', 0, 1)->empty(), 0) + call assert_equal(maparg('+', 'n', 0, 1)->empty(), 0) + call assert_equal(maparg('K', 'n', 0, 1).buffer, 0) + call assert_equal(maparg('-', 'n', 0, 1).buffer, 0) + call assert_equal(maparg('+', 'n', 0, 1).buffer, 0) + call assert_equal(maparg('K', 'n', 0, 1).rhs, ':echom "K"<cr>') + + %bw! + nnoremap <buffer> K :echom "bK"<cr> + nnoremap <buffer> - :echom "b-"<cr> + nnoremap <buffer> + :echom "b+"<cr> + Termdebug + call WaitForAssert({-> assert_equal(3, winnr('$'))}) + wincmd b + call assert_equal(maparg('K', 'n', 0, 1).buffer, 1) + call assert_equal(maparg('-', 'n', 0, 1).buffer, 1) + call assert_equal(maparg('+', 'n', 0, 1).buffer, 1) + call assert_equal(maparg('K', 'n', 0, 1).rhs, ':echom "bK"<cr>') + wincmd t + quit! + redraw! + call WaitForAssert({-> assert_equal(1, winnr('$'))}) + call assert_equal(maparg('K', 'n', 0, 1).buffer, 1) + call assert_equal(maparg('-', 'n', 0, 1).buffer, 1) + call assert_equal(maparg('+', 'n', 0, 1).buffer, 1) + call assert_equal(maparg('K', 'n', 0, 1).rhs, ':echom "bK"<cr>') + + %bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_textformat.vim b/test/old/testdir/test_textformat.vim new file mode 100644 index 0000000000..7a13de12f4 --- /dev/null +++ b/test/old/testdir/test_textformat.vim @@ -0,0 +1,1307 @@ +" Tests for the various 'formatoptions' settings + +source check.vim + +func Test_text_format() + enew! + + setl noai tw=2 fo=t + call append('$', [ + \ '{', + \ ' ', + \ '', + \ '}']) + exe "normal /^{/+1\n0" + normal gRa b + let lnum = line('.') + call assert_equal([ + \ 'a', + \ 'b'], getline(lnum - 1, lnum)) + + normal ggdG + setl ai tw=2 fo=tw + call append('$', [ + \ '{', + \ 'a b ', + \ '', + \ 'a ', + \ '}']) + exe "normal /^{/+1\n0" + normal gqgqjjllab + let lnum = line('.') + call assert_equal([ + \ 'a ', + \ 'b ', + \ '', + \ 'a ', + \ 'b'], getline(lnum - 4, lnum)) + + normal ggdG + setl tw=3 fo=t + call append('$', [ + \ '{', + \ "a \<C-A>", + \ '}']) + exe "normal /^{/+1\n0" + exe "normal gqgqo\na \<C-V>\<C-A>" + let lnum = line('.') + call assert_equal([ + \ 'a', + \ "\<C-A>", + \ '', + \ 'a', + \ "\<C-A>"], getline(lnum - 4, lnum)) + + normal ggdG + setl tw=2 fo=tcq1 comments=:# + call append('$', [ + \ '{', + \ 'a b', + \ '#a b', + \ '}']) + exe "normal /^{/+1\n0" + exe "normal gqgqjgqgqo\na b\n#a b" + let lnum = line('.') + call assert_equal([ + \ 'a b', + \ '#a b', + \ '', + \ 'a b', + \ '#a b'], getline(lnum - 4, lnum)) + + normal ggdG + setl tw=5 fo=tcn comments=:# + call append('$', [ + \ '{', + \ ' 1 a', + \ '# 1 a', + \ '}']) + exe "normal /^{/+1\n0" + exe "normal A b\<Esc>jA b" + let lnum = line('.') + call assert_equal([ + \ ' 1 a', + \ ' b', + \ '# 1 a', + \ '# b'], getline(lnum - 3, lnum)) + + normal ggdG + setl tw=5 fo=t2a si + call append('$', [ + \ '{', + \ '', + \ ' x a', + \ ' b', + \ ' c', + \ '', + \ '}']) + exe "normal /^{/+3\n0" + exe "normal i \<Esc>A_" + let lnum = line('.') + call assert_equal([ + \ '', + \ ' x a', + \ ' b_', + \ ' c', + \ ''], getline(lnum - 2, lnum + 2)) + + normal ggdG + setl tw=5 fo=qn comments=:# + call append('$', [ + \ '{', + \ '# 1 a b', + \ '}']) + exe "normal /^{/+1\n5|" + normal gwap + call assert_equal(5, col('.')) + let lnum = line('.') + call assert_equal([ + \ '# 1 a', + \ '# b'], getline(lnum, lnum + 1)) + + normal ggdG + setl tw=5 fo=q2 comments=:# + call append('$', [ + \ '{', + \ '# x', + \ '# a b', + \ '}']) + exe "normal /^{/+1\n0" + normal gwap + let lnum = line('.') + call assert_equal([ + \ '# x a', + \ '# b'], getline(lnum, lnum + 1)) + + normal ggdG + setl tw& fo=a + call append('$', [ + \ '{', + \ ' 1aa', + \ ' 2bb', + \ '}']) + exe "normal /^{/+2\n0" + normal I^^ + call assert_equal('{ 1aa ^^2bb }', getline('.')) + + normal ggdG + setl tw=20 fo=an12wcq comments=s1:/*,mb:*,ex:*/ + call append('$', [ + \ '/* abc def ghi jkl ', + \ ' * mno pqr stu', + \ ' */']) + exe "normal /mno pqr/\n" + normal A vwx yz + let lnum = line('.') + call assert_equal([ + \ ' * mno pqr stu ', + \ ' * vwx yz', + \ ' */'], getline(lnum - 1, lnum + 1)) + + normal ggdG + setl tw=12 fo=tqnc comments=:# + call setline('.', '# 1 xxxxx') + normal A foobar + call assert_equal([ + \ '# 1 xxxxx', + \ '# foobar'], getline(1, 2)) + + " Test the 'p' flag for 'formatoptions' + " First test without the flag: that it will break "Mr. Feynman" at the space + normal ggdG + setl tw=28 fo=tcq + call setline('.', 'Surely you''re joking, Mr. Feynman!') + normal gqq + call assert_equal([ + \ 'Surely you''re joking, Mr.', + \ 'Feynman!'], getline(1, 2)) + " Now test with the flag: that it will push the name with the title onto the + " next line + normal ggdG + setl fo+=p + call setline('.', 'Surely you''re joking, Mr. Feynman!') + normal gqq + call assert_equal([ + \ 'Surely you''re joking,', + \ 'Mr. Feynman!'], getline(1, 2)) + " Ensure that it will still break if two spaces are entered + normal ggdG + call setline('.', 'Surely you''re joking, Mr. Feynman!') + normal gqq + call assert_equal([ + \ 'Surely you''re joking, Mr.', + \ 'Feynman!'], getline(1, 2)) + + setl ai& tw& fo& si& comments& + enew! +endfunc + +func Test_format_c_comment() + new + setl ai cindent tw=40 et fo=croql + let text =<< trim END + var = 2345; // asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf + END + call setline(1, text) + normal gql + let expected =<< trim END + var = 2345; // asdf asdf asdf asdf asdf + // asdf asdf asdf asdf asdf + END + call assert_equal(expected, getline(1, '$')) + + %del + let text =<< trim END + var = 2345; // asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf + END + call setline(1, text) + normal gql + let expected =<< trim END + var = 2345; // asdf asdf asdf asdf asdf + // asdf asdf asdf asdf asdf + // asdf asdf + END + call assert_equal(expected, getline(1, '$')) + + %del + let text =<< trim END + #if 0 // This is another long end of + // line comment that + // wraps. + END + call setline(1, text) + normal gq2j + let expected =<< trim END + #if 0 // This is another long + // end of line comment + // that wraps. + END + call assert_equal(expected, getline(1, '$')) + + " Using either "o" or "O" repeats a line comment occupying a whole line. + %del + let text =<< trim END + nop; + // This is a comment + val = val; + END + call setline(1, text) + normal 2Go + let expected =<< trim END + nop; + // This is a comment + // + val = val; + END + call assert_equal(expected, getline(1, '$')) + normal 2GO + let expected =<< trim END + nop; + // + // This is a comment + // + val = val; + END + call assert_equal(expected, getline(1, '$')) + + " Using "o" repeats a line comment after a statement, "O" does not. + %del + let text =<< trim END + nop; + val = val; // This is a comment + END + call setline(1, text) + normal 2Go + let expected =<< trim END + nop; + val = val; // This is a comment + // + END + call assert_equal(expected, getline(1, '$')) + 3delete + + " No comment repeated with a slash in 'formatoptions' + set fo+=/ + normal 2Gox + let expected =<< trim END + nop; + val = val; // This is a comment + x + END + call assert_equal(expected, getline(1, '$')) + + " Comment is formatted when it wraps + normal 2GA with some more text added + let expected =<< trim END + nop; + val = val; // This is a comment + // with some more text + // added + x + END + call assert_equal(expected, getline(1, '$')) + + set fo-=/ + + " using 'indentexpr' instead of 'cindent' does not repeat a comment + setl nocindent indentexpr=2 + %del + let text =<< trim END + nop; + val = val; // This is a comment + END + call setline(1, text) + normal 2Gox + let expected =<< trim END + nop; + val = val; // This is a comment + x + END + call assert_equal(expected, getline(1, '$')) + setl cindent indentexpr= + 3delete + + normal 2GO + let expected =<< trim END + nop; + + val = val; // This is a comment + END + call assert_equal(expected, getline(1, '$')) + + " Using "o" does not repeat a comment in a string + %del + let text =<< trim END + nop; + val = " // This is not a comment"; + END + call setline(1, text) + normal 2Gox + let expected =<< trim END + nop; + val = " // This is not a comment"; + x + END + call assert_equal(expected, getline(1, '$')) + + " Using CTRL-U after "o" fixes the indent + %del + let text =<< trim END + { + val = val; // This is a comment + END + call setline(1, text) + exe "normal! 2Go\<C-U>x\<Esc>" + let expected =<< trim END + { + val = val; // This is a comment + x + END + call assert_equal(expected, getline(1, '$')) + + " typing comment text auto-wraps + %del + call setline(1, text) + exe "normal! 2GA blah more text blah.\<Esc>" + let expected =<< trim END + { + val = val; // This is a comment + // blah more text + // blah. + END + call assert_equal(expected, getline(1, '$')) + + bwipe! +endfunc + +" Tests for :right, :center and :left on text with embedded TAB. +func Test_format_align() + enew! + set tw=65 + + " :left alignment + call append(0, [ + \ " test for :left", + \ " a a", + \ " fa a", + \ " dfa a", + \ " sdfa a", + \ " asdfa a", + \ " xasdfa a", + \ "asxxdfa a", + \ ]) + %left + call assert_equal([ + \ "test for :left", + \ "a a", + \ "fa a", + \ "dfa a", + \ "sdfa a", + \ "asdfa a", + \ "xasdfa a", + \ "asxxdfa a", + \ "" + \ ], getline(1, '$')) + enew! + + " :center alignment + call append(0, [ + \ " test for :center", + \ " a a", + \ " fa afd asdf", + \ " dfa a", + \ " sdfa afd asdf", + \ " asdfa a", + \ " xasdfa asdfasdfasdfasdfasdf", + \ "asxxdfa a" + \ ]) + %center + call assert_equal([ + \ " test for :center", + \ " a a", + \ " fa afd asdf", + \ " dfa a", + \ " sdfa afd asdf", + \ " asdfa a", + \ " xasdfa asdfasdfasdfasdfasdf", + \ " asxxdfa a", + \ "" + \ ], getline(1, '$')) + enew! + + " :right alignment + call append(0, [ + \ " test for :right", + \ " a a", + \ " fa a", + \ " dfa a", + \ " sdfa a", + \ " asdfa a", + \ " xasdfa a", + \ " asxxdfa a", + \ " asxa;ofa a", + \ " asdfaqwer a", + \ " a ax", + \ " fa ax", + \ " dfa ax", + \ " sdfa ax", + \ " asdfa ax", + \ " xasdfa ax", + \ " asxxdfa ax", + \ " asxa;ofa ax", + \ " asdfaqwer ax", + \ " a axx", + \ " fa axx", + \ " dfa axx", + \ " sdfa axx", + \ " asdfa axx", + \ " xasdfa axx", + \ " asxxdfa axx", + \ " asxa;ofa axx", + \ " asdfaqwer axx", + \ " a axxx", + \ " fa axxx", + \ " dfa axxx", + \ " sdfa axxx", + \ " asdfa axxx", + \ " xasdfa axxx", + \ " asxxdfa axxx", + \ " asxa;ofa axxx", + \ " asdfaqwer axxx", + \ " a axxxo", + \ " fa axxxo", + \ " dfa axxxo", + \ " sdfa axxxo", + \ " asdfa axxxo", + \ " xasdfa axxxo", + \ " asxxdfa axxxo", + \ " asxa;ofa axxxo", + \ " asdfaqwer axxxo", + \ " a axxxoi", + \ " fa axxxoi", + \ " dfa axxxoi", + \ " sdfa axxxoi", + \ " asdfa axxxoi", + \ " xasdfa axxxoi", + \ " asxxdfa axxxoi", + \ " asxa;ofa axxxoi", + \ " asdfaqwer axxxoi", + \ " a axxxoik", + \ " fa axxxoik", + \ " dfa axxxoik", + \ " sdfa axxxoik", + \ " asdfa axxxoik", + \ " xasdfa axxxoik", + \ " asxxdfa axxxoik", + \ " asxa;ofa axxxoik", + \ " asdfaqwer axxxoik", + \ " a axxxoike", + \ " fa axxxoike", + \ " dfa axxxoike", + \ " sdfa axxxoike", + \ " asdfa axxxoike", + \ " xasdfa axxxoike", + \ " asxxdfa axxxoike", + \ " asxa;ofa axxxoike", + \ " asdfaqwer axxxoike", + \ " a axxxoikey", + \ " fa axxxoikey", + \ " dfa axxxoikey", + \ " sdfa axxxoikey", + \ " asdfa axxxoikey", + \ " xasdfa axxxoikey", + \ " asxxdfa axxxoikey", + \ " asxa;ofa axxxoikey", + \ " asdfaqwer axxxoikey", + \ ]) + %right + call assert_equal([ + \ "\t\t\t\t test for :right", + \ "\t\t\t\t a a", + \ "\t\t\t\t fa a", + \ "\t\t\t\t dfa a", + \ "\t\t\t\t sdfa a", + \ "\t\t\t\t asdfa a", + \ "\t\t\t\t xasdfa a", + \ "\t\t\t\t asxxdfa a", + \ "\t\t\t\t asxa;ofa a", + \ "\t\t\t\t asdfaqwer a", + \ "\t\t\t\t a ax", + \ "\t\t\t\t fa ax", + \ "\t\t\t\t dfa ax", + \ "\t\t\t\t sdfa ax", + \ "\t\t\t\t asdfa ax", + \ "\t\t\t\t xasdfa ax", + \ "\t\t\t\t asxxdfa ax", + \ "\t\t\t\t asxa;ofa ax", + \ "\t\t\t\t asdfaqwer ax", + \ "\t\t\t\t a axx", + \ "\t\t\t\t fa axx", + \ "\t\t\t\t dfa axx", + \ "\t\t\t\t sdfa axx", + \ "\t\t\t\t asdfa axx", + \ "\t\t\t\t xasdfa axx", + \ "\t\t\t\t asxxdfa axx", + \ "\t\t\t\t asxa;ofa axx", + \ "\t\t\t\t asdfaqwer axx", + \ "\t\t\t\t a axxx", + \ "\t\t\t\t fa axxx", + \ "\t\t\t\t dfa axxx", + \ "\t\t\t\t sdfa axxx", + \ "\t\t\t\t asdfa axxx", + \ "\t\t\t\t xasdfa axxx", + \ "\t\t\t\t asxxdfa axxx", + \ "\t\t\t\t asxa;ofa axxx", + \ "\t\t\t\t asdfaqwer axxx", + \ "\t\t\t\t a axxxo", + \ "\t\t\t\t fa axxxo", + \ "\t\t\t\t dfa axxxo", + \ "\t\t\t\t sdfa axxxo", + \ "\t\t\t\t asdfa axxxo", + \ "\t\t\t\t xasdfa axxxo", + \ "\t\t\t\t asxxdfa axxxo", + \ "\t\t\t\t asxa;ofa axxxo", + \ "\t\t\t\t asdfaqwer axxxo", + \ "\t\t\t\t a axxxoi", + \ "\t\t\t\t fa axxxoi", + \ "\t\t\t\t dfa axxxoi", + \ "\t\t\t\t sdfa axxxoi", + \ "\t\t\t\t asdfa axxxoi", + \ "\t\t\t\t xasdfa axxxoi", + \ "\t\t\t\t asxxdfa axxxoi", + \ "\t\t\t\t asxa;ofa axxxoi", + \ "\t\t\t\t asdfaqwer axxxoi", + \ "\t\t\t\t a axxxoik", + \ "\t\t\t\t fa axxxoik", + \ "\t\t\t\t dfa axxxoik", + \ "\t\t\t\t sdfa axxxoik", + \ "\t\t\t\t asdfa axxxoik", + \ "\t\t\t\t xasdfa axxxoik", + \ "\t\t\t\t asxxdfa axxxoik", + \ "\t\t\t\t asxa;ofa axxxoik", + \ "\t\t\t\t asdfaqwer axxxoik", + \ "\t\t\t\t a axxxoike", + \ "\t\t\t\t fa axxxoike", + \ "\t\t\t\t dfa axxxoike", + \ "\t\t\t\t sdfa axxxoike", + \ "\t\t\t\t asdfa axxxoike", + \ "\t\t\t\t xasdfa axxxoike", + \ "\t\t\t\t asxxdfa axxxoike", + \ "\t\t\t\t asxa;ofa axxxoike", + \ "\t\t\t\t asdfaqwer axxxoike", + \ "\t\t\t\t a axxxoikey", + \ "\t\t\t\t fa axxxoikey", + \ "\t\t\t\t dfa axxxoikey", + \ "\t\t\t\t sdfa axxxoikey", + \ "\t\t\t\t asdfa axxxoikey", + \ "\t\t\t\t xasdfa axxxoikey", + \ "\t\t\t\t asxxdfa axxxoikey", + \ "\t\t\t\t asxa;ofa axxxoikey", + \ "\t\t\t\t asdfaqwer axxxoikey", + \ "" + \ ], getline(1, '$')) + enew! + + " align text with 'wrapmargin' + 50vnew + call setline(1, ['Vim']) + setl textwidth=0 + setl wrapmargin=30 + right + call assert_equal("\t\t Vim", getline(1)) + q! + + " align text with 'rightleft' + if has('rightleft') + new + call setline(1, 'Vim') + setlocal rightleft + left 20 + setlocal norightleft + call assert_equal("\t\t Vim", getline(1)) + setlocal rightleft + right + setlocal norightleft + call assert_equal("Vim", getline(1)) + close! + endif + + set tw& +endfunc + +" Test formatting a paragraph. +func Test_format_para() + enew! + set fo+=tcroql tw=72 + + call append(0, [ + \ "xxxxx xx xxxxxx ", + \ "xxxxxxx xxxxxxxxx xxx xxxx xxxxx xxxxx xxx xx", + \ "xxxxxxxxxxxxxxxxxx xxxxx xxxx, xxxx xxxx xxxx xxxx xxx xx xx", + \ "xx xxxxxxx. xxxx xxxx.", + \ "", + \ "> xx xx, xxxx xxxx xxx xxxx xxx xxxxx xxx xxx xxxxxxx xxx xxxxx", + \ "> xxxxxx xxxxxxx: xxxx xxxxxxx, xx xxxxxx xxxx xxxxxxxxxx" + \ ]) + exe "normal /xxxxxxxx$\<CR>" + normal 0gq6kk + call assert_equal([ + \ "xxxxx xx xxxxxx xxxxxxx xxxxxxxxx xxx xxxx xxxxx xxxxx xxx xx", + \ "xxxxxxxxxxxxxxxxxx xxxxx xxxx, xxxx xxxx xxxx xxxx xxx xx xx xx xxxxxxx.", + \ "xxxx xxxx.", + \ "", + \ "> xx xx, xxxx xxxx xxx xxxx xxx xxxxx xxx xxx xxxxxxx xxx xxxxx xxxxxx", + \ "> xxxxxxx: xxxx xxxxxxx, xx xxxxxx xxxx xxxxxxxxxx", + \ "" + \ ], getline(1, '$')) + + set fo& tw& + enew! +endfunc + +" Test undo after ":%s" and formatting. +func Test_format_undo() + enew! + map gg :.,.+2s/^/x/<CR>kk:set tw=3<CR>gqq + + call append(0, [ + \ "aa aa aa aa", + \ "bb bb bb bb", + \ "cc cc cc cc" + \ ]) + " undo/redo here to make the next undo only work on the following changes + exe "normal i\<C-G>u" + call cursor(1,1) + normal ggu + call assert_equal([ + \ "aa aa aa aa", + \ "bb bb bb bb", + \ "cc cc cc cc", + \ "" + \ ], getline(1, '$')) + + unmap gg + set tw& + enew! +endfunc + +func Test_format_list_auto() + new + call setline(1, ['1. abc', '2. def', '3. ghi']) + set fo=tan ai bs=2 + call feedkeys("3G0lli\<BS>\<BS>x\<Esc>", 'tx') + call assert_equal('2. defx ghi', getline(2)) + bwipe! + set fo& ai& bs& +endfunc + +func Test_crash_github_issue_5095() + CheckFeature autocmd + + " This used to segfault, see https://github.com/vim/vim/issues/5095 + augroup testing + au BufNew x center + augroup END + + next! x + + bw + augroup testing + au! + augroup END + augroup! testing +endfunc + +" Test for formatting multi-byte text with 'fo=t' +func Test_tw_2_fo_t() + new + let t =<< trim END + { + XYZ + abc XYZ + } + END + call setline(1, t) + call cursor(2, 1) + + set tw=2 fo=t + let t =<< trim END + XYZ + abc XYZ + END + exe "normal gqgqjgqgq" + exe "normal o\n" . join(t, "\n") + + let expected =<< trim END + { + XYZ + abc + XYZ + + XYZ + abc + XYZ + } + END + call assert_equal(expected, getline(1, '$')) + + set tw& fo& + bwipe! +endfunc + +" Test for formatting multi-byte text with 'fo=tm' and 'tw=1' +func Test_tw_1_fo_tm() + new + let t =<< trim END + { + X + Xa + X a + XY + X Y + } + END + call setline(1, t) + call cursor(2, 1) + + set tw=1 fo=tm + let t =<< trim END + X + Xa + X a + XY + X Y + END + exe "normal gqgqjgqgqjgqgqjgqgqjgqgq" + exe "normal o\n" . join(t, "\n") + + let expected =<< trim END + { + X + X + a + X + a + X + Y + X + Y + + X + X + a + X + a + X + Y + X + Y + } + END + call assert_equal(expected, getline(1, '$')) + + set tw& fo& + bwipe! +endfunc + +" Test for formatting multi-byte text with 'fo=tm' and 'tw=2' +func Test_tw_2_fo_tm() + new + let t =<< trim END + { + X + Xa + X a + XY + X Y + aX + abX + abcX + abX c + abXY + } + END + call setline(1, t) + call cursor(2, 1) + + set tw=2 fo=tm + let t =<< trim END + X + Xa + X a + XY + X Y + aX + abX + abcX + abX c + abXY + END + exe "normal gqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgqjgqgq" + exe "normal o\n" . join(t, "\n") + + let expected =<< trim END + { + X + X + a + X + a + X + Y + X + Y + a + X + ab + X + abc + X + ab + X + c + ab + X + Y + + X + X + a + X + a + X + Y + X + Y + a + X + ab + X + abc + X + ab + X + c + ab + X + Y + } + END + call assert_equal(expected, getline(1, '$')) + + set tw& fo& + bwipe! +endfunc + +" Test for formatting multi-byte text with 'fo=tm', 'tw=2' and 'autoindent'. +func Test_tw_2_fo_tm_ai() + new + let t =<< trim END + { + X + Xa + } + END + call setline(1, t) + call cursor(2, 1) + + set ai tw=2 fo=tm + let t =<< trim END + X + Xa + END + exe "normal gqgqjgqgq" + exe "normal o\n" . join(t, "\n") + + let expected =<< trim END + { + X + X + a + + X + X + a + } + END + call assert_equal(expected, getline(1, '$')) + + set tw& fo& ai& + bwipe! +endfunc + +" Test for formatting multi-byte text with 'fo=tm', 'tw=2' and 'noai'. +func Test_tw_2_fo_tm_noai() + new + let t =<< trim END + { + X + Xa + } + END + call setline(1, t) + call cursor(2, 1) + + set noai tw=2 fo=tm + exe "normal gqgqjgqgqo\n X\n Xa" + + let expected =<< trim END + { + X + X + a + + X + X + a + } + END + call assert_equal(expected, getline(1, '$')) + + set tw& fo& ai& + bwipe! +endfunc + +func Test_tw_2_fo_tm_replace() + new + let t =<< trim END + { + + } + END + call setline(1, t) + call cursor(2, 1) + + set tw=2 fo=tm + exe "normal RXa" + + let expected =<< trim END + { + X + a + } + END + call assert_equal(expected, getline(1, '$')) + + set tw& fo& + bwipe! +endfunc + +" Test for 'matchpairs' with multibyte chars +func Test_mps_multibyte() + new + let t =<< trim END + { + ‘ two three ’ four + } + END + call setline(1, t) + call cursor(2, 1) + + exe "set mps+=\u2018:\u2019" + normal d% + + let expected =<< trim END + { + four + } + END + call assert_equal(expected, getline(1, '$')) + + set mps& + bwipe! +endfunc + +" Test for 'matchpairs' in latin1 encoding +func Test_mps_latin1() + new + let save_enc = &encoding + " set encoding=latin1 + call setline(1, 'abc(def)ghi') + normal % + call assert_equal(8, col('.')) + normal % + call assert_equal(4, col('.')) + call cursor(1, 6) + normal [( + call assert_equal(4, col('.')) + normal % + call assert_equal(8, col('.')) + call cursor(1, 6) + normal ]) + call assert_equal(8, col('.')) + normal % + call assert_equal(4, col('.')) + let &encoding = save_enc + close! +endfunc + +func Test_empty_matchpairs() + split + set matchpairs= showmatch + call assert_nobeep('call feedkeys("ax\tx\t\<Esc>", "xt")') + set matchpairs& noshowmatch + bwipe! +endfunc + +func Test_mps_error() + let encoding_save = &encoding + + " for e in ['utf-8', 'latin1'] + for e in ['utf-8'] + exe 'set encoding=' .. e + + call assert_fails('set mps=<:', 'E474:', e) + call assert_fails('set mps=:>', 'E474:', e) + call assert_fails('set mps=<>', 'E474:', e) + call assert_fails('set mps=<:>_', 'E474:', e) + endfor + + let &encoding = encoding_save +endfunc + +" Test for ra on multi-byte characters +func Test_ra_multibyte() + new + let t =<< trim END + ra test + abba + aab + END + call setline(1, t) + call cursor(1, 1) + + normal jVjra + + let expected =<< trim END + ra test + aaaa + aaa + END + call assert_equal(expected, getline(1, '$')) + + bwipe! +endfunc + +" Test for 'whichwrap' with multi-byte character +func Test_whichwrap_multi_byte() + new + let t =<< trim END + á + x + END + call setline(1, t) + call cursor(2, 1) + + set whichwrap+=h + normal dh + set whichwrap& + + let expected =<< trim END + áx + END + call assert_equal(expected, getline(1, '$')) + + bwipe! +endfunc + +" Test for 'a' and 'w' flags in 'formatoptions' +func Test_fo_a_w() + new + setlocal fo+=aw tw=10 + call feedkeys("iabc abc a abc\<Esc>k0weade", 'xt') + call assert_equal(['abc abcde ', 'a abc'], getline(1, '$')) + + " when a line ends with space, it is not broken up. + %d + call feedkeys("ione two to ", 'xt') + call assert_equal('one two to ', getline(1)) + + " when a line ends with spaces and backspace is used in the next line, the + " last space in the previous line should be removed. + %d + set backspace=indent,eol,start + call setline(1, ['one ', 'two']) + exe "normal 2Gi\<BS>" + call assert_equal(['one two'], getline(1, '$')) + set backspace& + + " Test for 'a', 'w' and '1' options. + setlocal textwidth=0 + setlocal fo=1aw + %d + call setline(1, '. foo') + normal 72ig + call feedkeys('a uu uu uu', 'xt') + call assert_equal('g uu uu ', getline(1)[-8:]) + call assert_equal(['uu. foo'], getline(2, '$')) + + " using backspace or "x" triggers reformat + call setline(1, ['1 2 3 4 5 ', '6 7 8 9']) + set tw=10 + set fo=taw + set bs=indent,eol,start + exe "normal 1G4la\<BS>\<BS>\<Esc>" + call assert_equal(['1 2 4 5 6 ', '7 8 9'], getline(1, 2)) + exe "normal f4xx" + call assert_equal(['1 2 5 6 7 ', '8 9'], getline(1, 2)) + + " using "cw" leaves cursor in right spot + call setline(1, ['Now we g whether that nation, or', + \ 'any nation so conceived and,']) + set fo=tcqa tw=35 + exe "normal 2G0cwx\<Esc>" + call assert_equal(['Now we g whether that nation, or x', 'nation so conceived and,'], getline(1, 2)) + + set tw=0 + set fo& + %bw! +endfunc + +" Test for formatting lines using gq in visual mode +func Test_visual_gq_format() + new + call setline(1, ['one two three four', 'five six', 'one two']) + setl textwidth=10 + call feedkeys('ggv$jj', 'xt') + redraw! + normal gq + %d + call setline(1, ['one two three four', 'five six', 'one two']) + normal G$ + call feedkeys('v0kk', 'xt') + redraw! + normal gq + setl textwidth& + close! +endfunc + +" Test for 'n' flag in 'formatoptions' to format numbered lists +func Test_fo_n() + new + setlocal autoindent + setlocal textwidth=12 + setlocal fo=n + call setline(1, [' 1) one two three four', ' 2) two']) + normal gggqG + call assert_equal([' 1) one two', ' three', ' four', ' 2) two'], + \ getline(1, '$')) + close! +endfunc + +" Test for 'formatlistpat' option +func Test_formatlistpat() + new + setlocal autoindent + setlocal textwidth=10 + setlocal fo=n + setlocal formatlistpat=^\\s*-\\s* + call setline(1, [' - one two three', ' - two']) + normal gggqG + call assert_equal([' - one', ' two', ' three', ' - two'], + \ getline(1, '$')) + close! +endfunc + +" Test for the 'b' and 'v' flags in 'formatoptions' +" Text should wrap only if a space character is inserted at or before +" 'textwidth' +func Test_fo_b() + new + setlocal textwidth=20 + + setlocal formatoptions=t + call setline(1, 'one two three four') + call feedkeys('Amore', 'xt') + call assert_equal(['one two three', 'fourmore'], getline(1, '$')) + + setlocal formatoptions=bt + %d + call setline(1, 'one two three four') + call feedkeys('Amore five', 'xt') + call assert_equal(['one two three fourmore five'], getline(1, '$')) + + setlocal formatoptions=bt + %d + call setline(1, 'one two three four') + call feedkeys('A five', 'xt') + call assert_equal(['one two three four', 'five'], getline(1, '$')) + + setlocal formatoptions=vt + %d + call setline(1, 'one two three four') + call feedkeys('Amore five', 'xt') + call assert_equal(['one two three fourmore', 'five'], getline(1, '$')) + + close! +endfunc + +" Test for the '1' flag in 'formatoptions'. Don't wrap text after a one letter +" word. +func Test_fo_1() + new + setlocal textwidth=20 + + setlocal formatoptions=t + call setline(1, 'one two three four') + call feedkeys('A a bird', 'xt') + call assert_equal(['one two three four a', 'bird'], getline(1, '$')) + + %d + setlocal formatoptions=t1 + call setline(1, 'one two three four') + call feedkeys('A a bird', 'xt') + call assert_equal(['one two three four', 'a bird'], getline(1, '$')) + + close! +endfunc + +" Test for 'l' flag in 'formatoptions'. When starting insert mode, if a line +" is longer than 'textwidth', then it is not broken. +func Test_fo_l() + new + setlocal textwidth=20 + + setlocal formatoptions=t + call setline(1, 'one two three four five') + call feedkeys('A six', 'xt') + call assert_equal(['one two three four', 'five six'], getline(1, '$')) + + %d + setlocal formatoptions=tl + call setline(1, 'one two three four five') + call feedkeys('A six', 'xt') + call assert_equal(['one two three four five six'], getline(1, '$')) + + close! +endfunc + +" Test for the '2' flag in 'formatoptions' +func Test_fo_2() + new + setlocal autoindent + setlocal formatoptions=t2 + setlocal textwidth=30 + call setline(1, ["\tfirst line of a paragraph.", + \ "second line of the same paragraph.", + \ "third line."]) + normal gggqG + call assert_equal(["\tfirst line of a", + \ "paragraph. second line of the", + \ "same paragraph. third line."], getline(1, '$')) + close! +endfunc + +" This was leaving the cursor after the end of a line. Complicated way to +" have the problem show up with valgrind. +func Test_correct_cursor_position() + " set encoding=iso8859 + new + norm a0000 + sil! norm gggg0i0gw0gg + + bwipe! + set encoding=utf8 +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_textobjects.vim b/test/old/testdir/test_textobjects.vim new file mode 100644 index 0000000000..f21d6fcb99 --- /dev/null +++ b/test/old/testdir/test_textobjects.vim @@ -0,0 +1,646 @@ +" Test for textobjects + +source check.vim + +func CpoM(line, useM, expected) + new + + if a:useM + set cpoptions+=M + else + set cpoptions-=M + endif + + call setline(1, a:line) + + call setreg('"', '') + normal! ggfrmavi)y + call assert_equal(getreg('"'), a:expected[0]) + + call setreg('"', '') + normal! `afbmavi)y + call assert_equal(getreg('"'), a:expected[1]) + + call setreg('"', '') + normal! `afgmavi)y + call assert_equal(getreg('"'), a:expected[2]) + + q! +endfunc + +func Test_inner_block_without_cpo_M() + call CpoM('(red \(blue) green)', 0, ['red \(blue', 'red \(blue', '']) +endfunc + +func Test_inner_block_with_cpo_M_left_backslash() + call CpoM('(red \(blue) green)', 1, ['red \(blue) green', 'blue', 'red \(blue) green']) +endfunc + +func Test_inner_block_with_cpo_M_right_backslash() + call CpoM('(red (blue\) green)', 1, ['red (blue\) green', 'blue\', 'red (blue\) green']) +endfunc + +func Test_inner_block_single_char() + new + call setline(1, "(a)") + + set selection=inclusive + let @" = '' + call assert_nobeep('norm! 0faviby') + call assert_equal('a', @") + + set selection=exclusive + let @" = '' + call assert_nobeep('norm! 0faviby') + call assert_equal('a', @") + + set selection& + bwipe! +endfunc + +func Test_quote_selection_selection_exclusive() + new + call setline(1, "a 'bcde' f") + set selection=exclusive + + exe "norm! fdvhi'y" + call assert_equal('bcde', @") + + let @" = 'dummy' + exe "norm! $gevi'y" + call assert_equal('bcde', @") + + let @" = 'dummy' + exe "norm! 0fbhvi'y" + call assert_equal('bcde', @") + + set selection&vim + bw! +endfunc + +func Test_quote_selection_selection_exclusive_abort() + new + set selection=exclusive + call setline(1, "'abzzc'") + let exp_curs = [0, 1, 6, 0] + call cursor(1,1) + exe 'norm! fcdvi"' + " make sure to end visual mode to have a clear state + exe "norm! \<esc>" + call assert_equal(exp_curs, getpos('.')) + call cursor(1,1) + exe 'norm! fcvi"' + exe "norm! \<esc>" + call assert_equal(exp_curs, getpos('.')) + call cursor(1,2) + exe 'norm! vfcoi"' + exe "norm! \<esc>" + let exp_curs = [0, 1, 2, 0] + let exp_visu = [0, 1, 7, 0] + call assert_equal(exp_curs, getpos('.')) + call assert_equal(exp_visu, getpos("'>")) + set selection&vim + bw! +endfunc + +" Tests for string and html text objects +func Test_string_html_objects() + + " Nvim only supports set encoding=utf-8 + " for e in ['utf-8', 'latin1', 'cp932'] + for e in ['utf-8'] + enew! + exe 'set enc=' .. e + + let t = '"wo\"rd\\" foo' + put =t + normal! da" + call assert_equal('foo', getline('.'), e) + + let t = "'foo' 'bar' 'piep'" + put =t + normal! 0va'a'rx + call assert_equal("xxxxxxxxxxxx'piep'", getline('.'), e) + + let t = "bla bla `quote` blah" + put =t + normal! 02f`da` + call assert_equal("bla bla blah", getline('.'), e) + + let t = 'out " in "noXno"' + put =t + normal! 0fXdi" + call assert_equal('out " in ""', getline('.'), e) + + let t = "\"'\" 'blah' rep 'buh'" + put =t + normal! 03f'vi'ry + call assert_equal("\"'\" 'blah'yyyyy'buh'", getline('.'), e) + + set quoteescape=+*- + let t = "bla `s*`d-`+++`l**` b`la" + put =t + normal! di` + call assert_equal("bla `` b`la", getline('.'), e) + + let t = 'voo "nah" sdf " asdf" sdf " sdf" sd' + put =t + normal! $F"va"oha"i"rz + call assert_equal('voo "zzzzzzzzzzzzzzzzzzzzzzzzzzzzsd', getline('.'), e) + + let t = "-<b>asdf<i>Xasdf</i>asdf</b>-" + put =t + normal! fXdit + call assert_equal('-<b>asdf<i></i>asdf</b>-', getline('.'), e) + + let t = "-<b>asdX<i>a<i />sdf</i>asdf</b>-" + put =t + normal! 0fXdit + call assert_equal('-<b></b>-', getline('.'), e) + + let t = "-<b>asdf<i>Xasdf</i>asdf</b>-" + put =t + normal! fXdat + call assert_equal('-<b>asdfasdf</b>-', getline('.'), e) + + let t = "-<b>asdX<i>as<b />df</i>asdf</b>-" + put =t + normal! 0fXdat + call assert_equal('--', getline('.'), e) + + let t = "-<b>\ninnertext object\n</b>" + put =t + normal! dit + call assert_equal('-<b></b>', getline('.'), e) + + " copy the tag block from leading indentation before the start tag + let t = " <b>\ntext\n</b>" + $put =t + normal! 2kvaty + call assert_equal("<b>\ntext\n</b>", @", e) + + " copy the tag block from the end tag + let t = "<title>\nwelcome\n</title>" + $put =t + normal! $vaty + call assert_equal("<title>\nwelcome\n</title>", @", e) + + " copy the outer tag block from a tag without an end tag + let t = "<html>\n<title>welcome\n</html>" + $put =t + normal! k$vaty + call assert_equal("<html>\n<title>welcome\n</html>", @", e) + + " nested tag that has < in a different line from > + let t = "<div><div\n></div></div>" + $put =t + normal! k0vaty + call assert_equal("<div><div\n></div></div>", @", e) + + " nested tag with attribute that has < in a different line from > + let t = "<div><div\nattr=\"attr\"\n></div></div>" + $put =t + normal! 2k0vaty + call assert_equal("<div><div\nattr=\"attr\"\n></div></div>", @", e) + + set quoteescape& + + " this was going beyond the end of the line + %del + sil! norm i"\ + sil! norm i"\ + sil! norm i"\ + call assert_equal('"\', getline(1)) + + bwipe! + endfor + + set enc=utf-8 +endfunc + +func Test_empty_html_tag() + new + call setline(1, '<div></div>') + normal 0citxxx + call assert_equal('<div>xxx</div>', getline(1)) + + call setline(1, '<div></div>') + normal 0f<cityyy + call assert_equal('<div>yyy</div>', getline(1)) + + call setline(1, '<div></div>') + normal 0f<vitsaaa + call assert_equal('aaa', getline(1)) + + " selecting a tag block in an non-empty blank line should fail + call setline(1, ' ') + call assert_beeps('normal $vaty') + + bwipe! +endfunc + +" Tests for match() and matchstr() +func Test_match() + call assert_equal("b", matchstr("abcd", ".", 0, 2)) + call assert_equal("bc", matchstr("abcd", "..", 0, 2)) + call assert_equal("c", matchstr("abcd", ".", 2, 0)) + call assert_equal("a", matchstr("abcd", ".", 0, -1)) + call assert_equal(-1, match("abcd", ".", 0, 5)) + call assert_equal(0 , match("abcd", ".", 0, -1)) + call assert_equal(0 , match('abc', '.', 0, 1)) + call assert_equal(1 , match('abc', '.', 0, 2)) + call assert_equal(2 , match('abc', '.', 0, 3)) + call assert_equal(-1, match('abc', '.', 0, 4)) + call assert_equal(1 , match('abc', '.', 1, 1)) + call assert_equal(2 , match('abc', '.', 2, 1)) + call assert_equal(-1, match('abc', '.', 3, 1)) + call assert_equal(3 , match('abc', '$', 0, 1)) + call assert_equal(-1, match('abc', '$', 0, 2)) + call assert_equal(3 , match('abc', '$', 1, 1)) + call assert_equal(3 , match('abc', '$', 2, 1)) + call assert_equal(3 , match('abc', '$', 3, 1)) + call assert_equal(-1, match('abc', '$', 4, 1)) + call assert_equal(0 , match('abc', '\zs', 0, 1)) + call assert_equal(1 , match('abc', '\zs', 0, 2)) + call assert_equal(2 , match('abc', '\zs', 0, 3)) + call assert_equal(3 , match('abc', '\zs', 0, 4)) + call assert_equal(-1, match('abc', '\zs', 0, 5)) + call assert_equal(1 , match('abc', '\zs', 1, 1)) + call assert_equal(2 , match('abc', '\zs', 2, 1)) + call assert_equal(3 , match('abc', '\zs', 3, 1)) + call assert_equal(-1, match('abc', '\zs', 4, 1)) +endfunc + +" This was causing an illegal memory access +func Test_inner_tag() + new + norm ixxx + call feedkeys("v", 'xt') + insert +x +x +. + norm it + q! +endfunc + +func Test_sentence() + enew! + call setline(1, 'A sentence. A sentence? A sentence!') + + normal yis + call assert_equal('A sentence.', @") + normal yas + call assert_equal('A sentence. ', @") + + normal ) + + normal yis + call assert_equal('A sentence?', @") + normal yas + call assert_equal('A sentence? ', @") + + normal ) + + normal yis + call assert_equal('A sentence!', @") + normal yas + call assert_equal(' A sentence!', @") + + normal 0 + normal 2yis + call assert_equal('A sentence. ', @") + normal 3yis + call assert_equal('A sentence. A sentence?', @") + normal 2yas + call assert_equal('A sentence. A sentence? ', @") + + %delete _ +endfunc + +func Test_sentence_with_quotes() + enew! + call setline(1, 'A "sentence." A sentence.') + + normal yis + call assert_equal('A "sentence."', @") + normal yas + call assert_equal('A "sentence." ', @") + + normal ) + + normal yis + call assert_equal('A sentence.', @") + normal yas + call assert_equal(' A sentence.', @") + + %delete _ +endfunc + +func Test_sentence_with_cursor_on_delimiter() + enew! + call setline(1, "A '([sentence.])' A sentence.") + + normal! 15|yis + call assert_equal("A '([sentence.])'", @") + normal! 15|yas + call assert_equal("A '([sentence.])' ", @") + + normal! 16|yis + call assert_equal("A '([sentence.])'", @") + normal! 16|yas + call assert_equal("A '([sentence.])' ", @") + + normal! 17|yis + call assert_equal("A '([sentence.])'", @") + normal! 17|yas + call assert_equal("A '([sentence.])' ", @") + + " don't get stuck on a quote at the start of a sentence + %delete _ + call setline(1, ['A sentence.', '"A sentence"?', 'A sentence!']) + normal gg)) + call assert_equal(3, getcurpos()[1]) + + %delete _ + call setline(1, ['A sentence.', "'A sentence'?", 'A sentence!']) + normal gg)) + call assert_equal(3, getcurpos()[1]) + + %delete _ +endfunc + +" Test for the paragraph (ap) text object +func Test_paragraph() + new + call setline(1, ['First line.', 'Second line.', 'Third line.']) + call cursor(2, 1) + normal vapy + call assert_equal("First line.\nSecond line.\nThird line.\n", @") + + call cursor(2, 1) + call assert_beeps('normal vapapy') + + call setline(1, ['First line.', 'Second line.', ' ', '']) + call cursor(1, 1) + normal vapy + call assert_equal("First line.\nSecond line.\n \n\n", @") + + call setline(1, ['', '', '', 'First line.', 'Second line.']) + call cursor(2, 1) + normal yap + call assert_equal("\n\n\nFirst line.\nSecond line.\n", @") + call assert_beeps('normal 3yap') + exe "normal \<C-C>" + + %d + call setline(1, [' ', ' ', ' ']) + call cursor(2, 1) + normal Vipy + call assert_equal(" \n \n \n", @") + call cursor(2, 1) + call assert_beeps("normal Vipip") + exe "normal \<C-C>" + + close! +endfunc + +" Tests for text object aw +func Test_textobj_a_word() + new + call append(0, ['foobar,eins,foobar', 'foo,zwei,foo ']) + " diw + norm! 1gg0diw + call assert_equal([',eins,foobar', 'foo,zwei,foo ', ''], getline(1,'$')) + " daw + norm! 2ggEdaw + call assert_equal([',eins,foobar', 'foo,zwei,', ''], getline(1, '$')) + " daw the last word in a line + call setline(1, ['foo bar', 'foo bar', '']) + call cursor(1, 5) + normal daw + call assert_equal('foo', getline(1)) + " aw in visual mode + call cursor(2, 5) + normal! vawx + call assert_equal('foo', getline(2)) + %d + call append(0, ["foo\teins\tfoobar", "foo\tzwei\tfoo "]) + " diW + norm! 2ggwd2iW + call assert_equal(['foo eins foobar', 'foo foo ', ''], getline(1,'$')) + " daW + norm! 1ggd2aW + call assert_equal(['foobar', 'foo foo ', ''], getline(1,'$')) + + %d + call append(0, ["foo\teins\tfoobar", "foo\tzwei\tfoo "]) + " aw in visual line mode switches to characterwise mode + norm! 2gg$Vawd + call assert_equal(['foo eins foobar', 'foo zwei foo'], getline(1,'$')) + norm! 1gg$Viwd + call assert_equal(['foo eins ', 'foo zwei foo'], getline(1,'$')) + + " visually selecting a tab before a word with 'selection' set to 'exclusive' + set selection=exclusive + normal gg3lvlawy + call assert_equal("\teins", @") + " visually selecting a tab before a word with 'selection' set to 'inclusive' + set selection=inclusive + normal gg3lvlawy + call assert_equal("\teins\t", @") + set selection& + + " selecting a word with no non-space characters in a buffer fails + %d + call setline(1, ' ') + call assert_beeps('normal 3lyaw') + + " visually selecting words backwards with no more words to select + call setline(1, 'one two') + call assert_beeps('normal 2lvh2aw') + exe "normal \<C-C>" + call assert_beeps('normal $vh3aw') + exe "normal \<C-C>" + call setline(1, ['', 'one two']) + call assert_beeps('normal 2G2lvh3aw') + exe "normal \<C-C>" + + " selecting words forward with no more words to select + %d + call setline(1, 'one a') + call assert_beeps('normal 0y3aw') + call setline(1, 'one two ') + call assert_beeps('normal 0y3aw') + call assert_beeps('normal 03ly2aw') + + " clean up + bw! +endfunc + +" Test for is and as text objects +func Test_textobj_sentence() + new + call append(0, ['This is a test. With some sentences!', '', + \ 'Even with a question? And one more. And no sentence here']) + " Test for dis - does not remove trailing whitespace + norm! 1gg0dis + call assert_equal([' With some sentences!', '', + \ 'Even with a question? And one more. And no sentence here', ''], + \ getline(1,'$')) + " Test for das - removes leading whitespace + norm! 3ggf?ldas + call assert_equal([' With some sentences!', '', + \ 'Even with a question? And no sentence here', ''], getline(1,'$')) + " when used in visual mode, is made characterwise + norm! 3gg$Visy + call assert_equal('v', visualmode()) + " reset visualmode() + norm! 3ggVy + norm! 3gg$Vasy + call assert_equal('v', visualmode()) + " basic testing for textobjects a< and at + %d + call setline(1, ['<div> ','<a href="foobar" class="foo">xyz</a>',' </div>', ' ']) + " a< + norm! 1gg0da< + call assert_equal([' ', '<a href="foobar" class="foo">xyz</a>', ' </div>', ' '], getline(1,'$')) + norm! 1pj + call assert_equal([' <div>', '<a href="foobar" class="foo">xyz</a>', ' </div>', ' '], getline(1,'$')) + " at + norm! d2at + call assert_equal([' '], getline(1,'$')) + %d + call setline(1, ['<div> ','<a href="foobar" class="foo">xyz</a>',' </div>', ' ']) + " i< + norm! 1gg0di< + call assert_equal(['<> ', '<a href="foobar" class="foo">xyz</a>', ' </div>', ' '], getline(1,'$')) + norm! 1Pj + call assert_equal(['<div> ', '<a href="foobar" class="foo">xyz</a>', ' </div>', ' '], getline(1,'$')) + norm! d2it + call assert_equal(['<div></div>',' '], getline(1,'$')) + " basic testing for a[ and i[ text object + %d + call setline(1, [' ', '[', 'one [two]', 'thre', ']']) + norm! 3gg0di[ + call assert_equal([' ', '[', ']'], getline(1,'$')) + call setline(1, [' ', '[', 'one [two]', 'thre', ']']) + norm! 3gg0ftd2a[ + call assert_equal([' '], getline(1,'$')) + + " clean up + bw! +endfunc + +" Test for quote (', " and `) textobjects +func Test_textobj_quote() + new + + " Test for i" when cursor is in front of a quoted object + call append(0, 'foo "bar"') + norm! 1gg0di" + call assert_equal(['foo ""', ''], getline(1,'$')) + + " Test for visually selecting an inner quote + %d + " extend visual selection from one quote to the next + call setline(1, 'color "red" color "blue"') + call cursor(1, 7) + normal v4li"y + call assert_equal('"red" color "blue', @") + + " try to extend visual selection from one quote to a non-existing quote + call setline(1, 'color "red" color blue') + call cursor(1, 7) + call feedkeys('v4li"y', 'xt') + call assert_equal('"red"', @") + + " try to extend visual selection from one quote to a next partial quote + call setline(1, 'color "red" color "blue') + call cursor(1, 7) + normal v4li"y + call assert_equal('"red" color ', @") + + " select a quote backwards in visual mode + call cursor(1, 12) + normal vhi"y + call assert_equal('red" ', @") + call assert_equal(8, col('.')) + + " select a quote backwards in visual mode from outside the quote + call cursor(1, 17) + normal v2hi"y + call assert_equal('red', @") + call assert_equal(8, col('.')) + + " visually selecting a quote with 'selection' set to 'exclusive' + call setline(1, 'He said "How are you?"') + set selection=exclusive + normal 012lv2li"y + call assert_equal('How are you?', @") + set selection& + + " try copy a quote object with a single quote in the line + call setline(1, "Smith's car") + call cursor(1, 6) + call assert_beeps("normal yi'") + call assert_beeps("normal 2lyi'") + + " selecting space before and after a quoted string + call setline(1, "some 'special' string") + normal 0ya' + call assert_equal("'special' ", @") + call setline(1, "some 'special'string") + normal 0ya' + call assert_equal(" 'special'", @") + + " quoted string with odd or even number of backslashes. + call setline(1, 'char *s = "foo\"bar"') + normal $hhyi" + call assert_equal('foo\"bar', @") + call setline(1, 'char *s = "foo\\"bar"') + normal $hhyi" + call assert_equal('bar', @") + call setline(1, 'char *s = "foo\\\"bar"') + normal $hhyi" + call assert_equal('foo\\\"bar', @") + call setline(1, 'char *s = "foo\\\\"bar"') + normal $hhyi" + call assert_equal('bar', @") + + close! +endfunc + +" Test for i(, i<, etc. when cursor is in front of a block +func Test_textobj_find_paren_forward() + new + + " i< and a> when cursor is in front of a block + call setline(1, '#include <foo.h>') + normal 0yi< + call assert_equal('foo.h', @") + normal 0ya> + call assert_equal('<foo.h>', @") + + " 2i(, 3i( in front of a block enters second/third nested '(' + call setline(1, 'foo (bar (baz (quux)))') + normal 0yi) + call assert_equal('bar (baz (quux))', @") + normal 02yi) + call assert_equal('baz (quux)', @") + normal 03yi) + call assert_equal('quux', @") + + " 3i( in front of a block doesn't enter third but un-nested '(' + call setline(1, 'foo (bar (baz) (quux))') + normal 03di) + call assert_equal('foo (bar (baz) (quux))', getline(1)) + normal 02di) + call assert_equal('foo (bar () (quux))', getline(1)) + normal 0di) + call assert_equal('foo ()', getline(1)) + + close! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_timers.vim b/test/old/testdir/test_timers.vim new file mode 100644 index 0000000000..42114618fb --- /dev/null +++ b/test/old/testdir/test_timers.vim @@ -0,0 +1,471 @@ +" Test for timers + +source check.vim +CheckFeature timers + +source screendump.vim +source shared.vim +source term_util.vim +source load.vim + +func SetUp() + call timer_stopall() +endfunc + +func MyHandler(timer) + let g:val += 1 +endfunc + +func MyHandlerWithLists(lists, timer) + let x = string(a:lists) +endfunc + +func Test_timer_oneshot() + let g:test_is_flaky = 1 + let g:val = 0 + let timer = timer_start(50, 'MyHandler') + let slept = WaitFor('g:val == 1') + call assert_equal(1, g:val) + if has('reltime') + call assert_inrange(40, LoadAdjust(120), slept) + else + call assert_inrange(20, 120, slept) + endif +endfunc + +func Test_timer_repeat_three() + let g:test_is_flaky = 1 + let g:val = 0 + let timer = timer_start(50, 'MyHandler', {'repeat': 3}) + let slept = WaitFor('g:val == 3') + call assert_equal(3, g:val) + if has('reltime') + call assert_inrange(120, LoadAdjust(250), slept) + else + call assert_inrange(80, 200, slept) + endif +endfunc + +func Test_timer_repeat_many() + let g:test_is_flaky = 1 + let g:val = 0 + let timer = timer_start(50, 'MyHandler', {'repeat': -1}) + sleep 200m + call timer_stop(timer) + call assert_inrange((has('mac') ? 1 : 2), LoadAdjust(5), g:val) +endfunc + +func Test_timer_with_partial_callback() + let g:test_is_flaky = 1 + let g:val = 0 + let meow = {'one': 1} + function meow.bite(...) + let g:val += self.one + endfunction + + call timer_start(50, meow.bite) + let slept = WaitFor('g:val == 1') + call assert_equal(1, g:val) + if has('reltime') + call assert_inrange(40, LoadAdjust(130), slept) + else + call assert_inrange(20, 100, slept) + endif +endfunc + +func Test_timer_retain_partial() + call timer_start(50, function('MyHandlerWithLists', [['a']])) + call test_garbagecollect_now() + sleep 100m +endfunc + +func Test_timer_info() + let id = timer_start(1000, 'MyHandler') + let info = id->timer_info() + call assert_equal(id, info[0]['id']) + call assert_equal(1000, info[0]['time']) + call assert_equal("function('MyHandler')", string(info[0]['callback'])) + + let found = 0 + for info in timer_info() + if info['id'] == id + let found += 1 + endif + endfor + call assert_equal(1, found) + + call timer_stop(id) + call assert_equal([], timer_info(id)) + + call assert_fails('call timer_info("abc")', 'E1210:') + + " check repeat count inside the callback + let g:timer_repeat = [] + let tid = timer_start(10, {tid -> execute("call add(g:timer_repeat, timer_info(tid)[0].repeat)")}, #{repeat: 3}) + call WaitForAssert({-> assert_equal([2, 1, 0], g:timer_repeat)}) + unlet g:timer_repeat +endfunc + +func Test_timer_stopall() + let id1 = timer_start(1000, 'MyHandler') + let id2 = timer_start(2000, 'MyHandler') + let info = timer_info() + call assert_equal(2, len(info)) + + call timer_stopall() + let info = timer_info() + call assert_equal(0, len(info)) +endfunc + +func Test_timer_paused() + let g:test_is_flaky = 1 + let g:val = 0 + + let id = timer_start(50, 'MyHandler') + let info = timer_info(id) + call assert_equal(0, info[0]['paused']) + + eval id->timer_pause(1) + let info = timer_info(id) + call assert_equal(1, info[0]['paused']) + sleep 200m + call assert_equal(0, g:val) + + call timer_pause(id, 0) + let info = timer_info(id) + call assert_equal(0, info[0]['paused']) + + let slept = WaitFor('g:val == 1') + call assert_equal(1, g:val) + if has('reltime') + call assert_inrange(0, LoadAdjust(140), slept) + else + call assert_inrange(0, 10, slept) + endif + + call assert_fails('call timer_pause("abc", 1)', 'E39:') +endfunc + +func StopMyself(timer) + let g:called += 1 + if g:called == 2 + call timer_stop(a:timer) + endif +endfunc + +func Test_timer_delete_myself() + let g:called = 0 + let t = timer_start(10, 'StopMyself', {'repeat': -1}) + call WaitForAssert({-> assert_equal(2, g:called)}) + call assert_equal(2, g:called) + call assert_equal([], timer_info(t)) +endfunc + +func StopTimer1(timer) + let g:timer2 = 10->timer_start('StopTimer2') + " avoid maxfuncdepth error + call timer_pause(g:timer1, 1) + sleep 20m +endfunc + +func StopTimer2(timer) + call timer_stop(g:timer1) +endfunc + +func Test_timer_stop_in_callback() + let g:test_is_flaky = 1 + call assert_equal(0, len(timer_info())) + let g:timer1 = timer_start(10, 'StopTimer1') + let slept = 0 + for i in range(10) + if len(timer_info()) == 0 + break + endif + sleep 10m + let slept += 10 + endfor + " This should take only 30 msec, but on Mac it's often longer + call assert_inrange(0, 50, slept) +endfunc + +func StopTimerAll(timer) + call timer_stopall() +endfunc + +func Test_timer_stop_all_in_callback() + let g:test_is_flaky = 1 + call assert_equal(0, len(timer_info())) + call timer_start(10, 'StopTimerAll') + call assert_equal(1, len(timer_info())) + let slept = 0 + for i in range(10) + if len(timer_info()) == 0 + break + endif + sleep 10m + let slept += 10 + endfor + call assert_inrange(0, 30, slept) +endfunc + +func FeedkeysCb(timer) + call feedkeys("hello\<CR>", 'nt') +endfunc + +func InputCb(timer) + call timer_start(10, 'FeedkeysCb') + let g:val = input('?') + call Resume() +endfunc + +func Test_timer_input_in_timer() + let g:val = '' + call timer_start(10, 'InputCb') + call Standby(1000) + call assert_equal('hello', g:val) +endfunc + +func FuncWithError(timer) + let g:call_count += 1 + if g:call_count == 4 + return + endif + doesnotexist +endfunc + +func Test_timer_errors() + let g:call_count = 0 + let timer = timer_start(10, 'FuncWithError', {'repeat': -1}) + " Timer will be stopped after failing 3 out of 3 times. + call WaitForAssert({-> assert_equal(3, g:call_count)}) + sleep 50m + call assert_equal(3, g:call_count) + + call assert_fails('call timer_start(100, "MyHandler", "abc")', 'E1206:') + call assert_fails('call timer_start(100, [])', 'E921:') + call assert_fails('call timer_stop("abc")', 'E1210:') +endfunc + +func FuncWithCaughtError(timer) + let g:call_count += 1 + try + doesnotexist + catch + " nop + endtry +endfunc + +func Test_timer_catch_error() + let g:call_count = 0 + let timer = timer_start(10, 'FuncWithCaughtError', {'repeat': 4}) + " Timer will not be stopped. + call WaitForAssert({-> assert_equal(4, g:call_count)}) + sleep 50m + call assert_equal(4, g:call_count) +endfunc + +func FeedAndPeek(timer) + " call test_feedinput('a') + call nvim_input('a') + call getchar(1) +endfunc + +func Interrupt(timer) + " eval "\<C-C>"->test_feedinput() + call nvim_input("\<C-C>") +endfunc + +func Test_timer_peek_and_get_char() + if !has('unix') && !has('gui_running') + throw 'Skipped: cannot feed low-level input' + endif + + call timer_start(0, 'FeedAndPeek') + let intr = timer_start(100, 'Interrupt') + let c = getchar() + call assert_equal(char2nr('a'), c) + eval intr->timer_stop() +endfunc + +func Test_timer_getchar_zero() + if has('win32') && !has('gui_running') + throw 'Skipped: cannot feed low-level input' + endif + CheckFunction reltimefloat + + " Measure the elapsed time to avoid a hang when it fails. + let start = reltime() + let id = timer_start(20, {-> feedkeys('x', 'L')}) + let c = 0 + while c == 0 && reltimefloat(reltime(start)) < 0.2 + let c = getchar(0) + sleep 10m + endwhile + call assert_equal('x', nr2char(c)) + call timer_stop(id) +endfunc + +func Test_timer_ex_mode() + " Function with an empty line. + func Foo(...) + + endfunc + let timer = timer_start(40, function('g:Foo'), {'repeat':-1}) + " This used to throw error E749. + exe "normal Qsleep 100m\rvi\r" + call timer_stop(timer) +endfunc + +func Test_timer_restore_count() + CheckRunVimInTerminal + " Check that v:count is saved and restored, not changed by a timer. + call writefile([ + \ 'nnoremap <expr><silent> L v:count ? v:count . "l" : "l"', + \ 'func Doit(id)', + \ ' normal 3j', + \ 'endfunc', + \ 'call timer_start(100, "Doit")', + \ ], 'Xtrcscript') + call writefile([ + \ '1-1234', + \ '2-1234', + \ '3-1234', + \ ], 'Xtrctext') + let buf = RunVimInTerminal('-S Xtrcscript Xtrctext', {}) + + " Wait for the timer to move the cursor to the third line. + call WaitForAssert({-> assert_equal(3, term_getcursor(buf)[0])}) + call assert_equal(1, term_getcursor(buf)[1]) + " Now check that v:count has not been set to 3 + call term_sendkeys(buf, 'L') + call WaitForAssert({-> assert_equal(2, term_getcursor(buf)[1])}) + + call StopVimInTerminal(buf) + call delete('Xtrcscript') + call delete('Xtrctext') +endfunc + +" Test that the garbage collector isn't triggered if a timer callback invokes +" vgetc(). +func Test_nocatch_timer_garbage_collect() + " skipped: Nvim does not support test_garbagecollect_soon(), test_override() + return + " 'uptimetime. must be bigger than the timer timeout + set ut=200 + call test_garbagecollect_soon() + call test_override('no_wait_return', 0) + func CauseAnError(id) + " This will show an error and wait for Enter. + let a = {'foo', 'bar'} + endfunc + func FeedChar(id) + call feedkeys(":\<CR>", 't') + endfunc + call timer_start(300, 'FeedChar') + call timer_start(100, 'CauseAnError') + let x = getchar() " wait for error in timer + let x = getchar(0) " read any remaining chars + let x = getchar(0) + + set ut& + call test_override('no_wait_return', 1) + delfunc CauseAnError + delfunc FeedChar +endfunc + +func Test_timer_error_in_timer_callback() + if !has('terminal') || (has('win32') && has('gui_running')) + throw 'Skipped: cannot run Vim in a terminal window' + endif + + let lines =<< trim [CODE] + func Func(timer) + " fail to create list + let x = [ + endfunc + set updatetime=50 + call timer_start(1, 'Func') + [CODE] + call writefile(lines, 'Xtest.vim') + + let buf = term_start(GetVimCommandCleanTerm() .. ' -S Xtest.vim', {'term_rows': 8}) + let job = term_getjob(buf) + call WaitForAssert({-> assert_notequal('', term_getline(buf, 8))}) + + " GC must not run during timer callback, which can make Vim crash. + call TermWait(buf, 50) + call term_sendkeys(buf, "\<CR>") + call TermWait(buf, 50) + call assert_equal('run', job_status(job)) + + call term_sendkeys(buf, ":qall!\<CR>") + call WaitFor({-> job_status(job) ==# 'dead'}) + if has('unix') + call assert_equal('', job_info(job).termsig) + endif + + call delete('Xtest.vim') + exe buf .. 'bwipe!' +endfunc + +" Test for garbage collection when a timer is still running +func Test_timer_garbage_collect() + let timer = timer_start(1000, function('MyHandler'), {'repeat' : 10}) + call test_garbagecollect_now() + let l = timer_info(timer) + call assert_equal(function('MyHandler'), l[0].callback) + call timer_stop(timer) +endfunc + +func Test_timer_invalid_callback() + call assert_fails('call timer_start(0, "0")', 'E921') +endfunc + +func Test_timer_changing_function_list() + CheckRunVimInTerminal + + " Create a large number of functions. Should get the "more" prompt. + " The typing "G" triggers the timer, which changes the function table. + let lines =<< trim END + for func in map(range(1,99), "'Func' .. v:val") + exe "func " .. func .. "()" + endfunc + endfor + au CmdlineLeave : call timer_start(0, {-> 0}) + END + call writefile(lines, 'XTest_timerchange') + let buf = RunVimInTerminal('-S XTest_timerchange', #{rows: 10}) + call term_sendkeys(buf, ":fu\<CR>") + call WaitForAssert({-> assert_match('-- More --', term_getline(buf, 10))}) + call term_sendkeys(buf, "G") + call WaitForAssert({-> assert_match('E454', term_getline(buf, 9))}) + call term_sendkeys(buf, "\<Esc>") + + call StopVimInTerminal(buf) + call delete('XTest_timerchange') +endfunc + +func Test_timer_using_win_execute_undo_sync() + let bufnr1 = bufnr() + new + let g:bufnr2 = bufnr() + let g:winid = win_getid() + exe "buffer " .. bufnr1 + wincmd w + call setline(1, ['test']) + autocmd InsertEnter * call timer_start(100, { -> win_execute(g:winid, 'buffer ' .. g:bufnr2) }) + call timer_start(200, { -> feedkeys("\<CR>bbbb\<Esc>") }) + call feedkeys("Oaaaa", 'x!t') + " will hang here until the second timer fires + call assert_equal(['aaaa', 'bbbb', 'test'], getline(1, '$')) + undo + call assert_equal(['test'], getline(1, '$')) + + bwipe! + bwipe! + unlet g:winid + unlet g:bufnr2 + au! InsertEnter +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_true_false.vim b/test/old/testdir/test_true_false.vim new file mode 100644 index 0000000000..f3c7fff4a6 --- /dev/null +++ b/test/old/testdir/test_true_false.vim @@ -0,0 +1,155 @@ +" Test behavior of boolean-like values. + +source check.vim + +" Test what is explained at ":help TRUE" and ":help FALSE". +func Test_if() + if v:false + call assert_true(false, 'v:false is false') + endif + if 0 + call assert_true(false, 'zero is false') + endif + if "0" + call assert_true(false, 'zero string is false') + endif + if "foo" + call assert_true(false, 'foo is false') + endif + if " " + call assert_true(false, 'space is false') + endif + if empty("foo") + call assert_true(false, 'foo is not empty') + endif + + if v:true + else + call assert_true(false, 'v:true is true') + endif + if 1 + else + call assert_true(false, 'one is true') + endif + if "1" + else + call assert_true(false, 'one string is true') + endif + if "1foo" + else + call assert_true(false, 'one in string is true') + endif + + call assert_fails('if [1]', 'E745') + call assert_fails('if {1: 1}', 'E728') + call assert_fails('if function("string")', 'E703') + if has('float') + call assert_fails('if 1.3")', 'E805') + endif +endfunc + +function Try_arg_true_false(expr, false_val, true_val) + for v in ['v:false', '0', '"0"', '"foo"', '" "'] + let r = eval(substitute(a:expr, '%v%', v, '')) + call assert_equal(a:false_val, r, 'result for ' . v . ' is not ' . string(a:false_val) . ' but ' . string(r)) + endfor + for v in ['v:true', '1', '"1"', '"1foo"'] + let r = eval(substitute(a:expr, '%v%', v, '')) + call assert_equal(a:true_val, r, 'result for ' . v . ' is not ' . string(a:true_val) . ' but ' . string(r)) + endfor +endfunc + +" Test using TRUE or FALSE values for an argument. +func Test_true_false_arg() + call Try_arg_true_false('count(["a", "A"], "a", %v%)', 1, 2) + + set wildignore=*.swp + call Try_arg_true_false('expand("foo.swp", %v%)', "", "foo.swp") + call Try_arg_true_false('expand("foo.vim", 0, %v%)', "foo.vim", ["foo.vim"]) + + call setreg('a', ['x', 'y']) + call Try_arg_true_false('getreg("a", 1, %v%)', "x\ny\n", ['x', 'y']) + + set wildignore=*.vim + call Try_arg_true_false('glob("runtest.vim", %v%)', "", "runtest.vim") + set wildignore=*.swp + call Try_arg_true_false('glob("runtest.vim", 0, %v%)', "runtest.vim", ["runtest.vim"]) + if has('unix') + silent !ln -s doesntexit Xlink + call Try_arg_true_false('glob("Xlink", 0, 0, %v%)', "", "Xlink") + silent !rm Xlink + endif + + set wildignore=*.vim + call Try_arg_true_false('globpath(".", "runtest.vim", %v%)', "", "./runtest.vim") + set wildignore=*.swp + call Try_arg_true_false('globpath(".", "runtest.vim", 0, %v%)', "./runtest.vim", ["./runtest.vim"]) + if has('unix') + silent !ln -s doesntexit Xlink + call Try_arg_true_false('globpath(".", "Xlink", 0, 0, %v%)', "", "./Xlink") + silent !rm Xlink + endif + + abbr asdf asdff + call Try_arg_true_false('hasmapto("asdff", "i", %v%)', 0, 1) + + call Try_arg_true_false('index(["a", "A"], "A", 0, %v%)', 1, 0) + + function FilterMapArg(d) + if type(a:d) == type({}) + return filter(a:d, 'v:key == "rhs"') + endif + return a:d + endfunction + call Try_arg_true_false('maparg("asdf", "i", %v%)', "", "asdff") + call Try_arg_true_false('FilterMapArg(maparg("asdf", "i", 1, %v%))', "asdff", {'rhs': 'asdff'}) + + call Try_arg_true_false('"asdf"->hasmapto("i", %v%)', 0, 1) + + new colored + call setline(1, '<here>') + syn match brackets "<.*>" + syn match here "here" transparent + let brackets_id = synID(1, 1, 0) + let here_id = synID(1, 3, 0) + call Try_arg_true_false('synID(1, 3, %v%)', here_id, brackets_id) + bwipe! +endfunc + +function Try_arg_non_zero(expr, false_val, true_val) + CheckFeature float + for v in ['v:false', '0', '[1]', '{2:3}', '3.4'] + let r = eval(substitute(a:expr, '%v%', v, '')) + call assert_equal(a:false_val, r, 'result for ' . v . ' is not ' . a:false_val . ' but ' . r) + endfor + for v in ['v:true', '1', '" "', '"0"'] + let r = eval(substitute(a:expr, '%v%', v, '')) + call assert_equal(a:true_val, r, 'result for ' . v . ' is not ' . a:true_val . ' but ' . r) + endfor +endfunc + + +" Test using non-zero-arg for an argument. +func Test_non_zero_arg() + " call test_settime(93784) + " call Try_arg_non_zero("mode(%v%)", 'x', 'x!') + " call test_settime(0) + + call Try_arg_non_zero("shellescape('foo%', %v%)", "'foo%'", "'foo\\%'") + + " visualmode() needs to be called twice to check + for v in [v:false, 0, [1], {2:3}, 3.4] + normal vv + let r = visualmode(v) + call assert_equal('v', r, 'result for ' . string(v) . ' is not "v" but ' . r) + let r = visualmode(v) + call assert_equal('v', r, 'result for ' . string(v) . ' is not "v" but ' . r) + endfor + for v in [v:true, 1, " ", "0"] + normal vv + let r = visualmode(v) + call assert_equal('v', r, 'result for ' . v . ' is not "v" but ' . r) + let r = visualmode(v) + call assert_equal('', r, 'result for ' . v . ' is not "" but ' . r) + endfor +endfunc diff --git a/test/old/testdir/test_trycatch.vim b/test/old/testdir/test_trycatch.vim new file mode 100644 index 0000000000..d60b793f1b --- /dev/null +++ b/test/old/testdir/test_trycatch.vim @@ -0,0 +1,2389 @@ +" Test try-catch-finally exception handling +" Most of this was formerly in test49. + +source check.vim +source shared.vim +source vim9.vim + +"------------------------------------------------------------------------------- +" Test environment {{{1 +"------------------------------------------------------------------------------- + +com! XpathINIT let g:Xpath = '' +com! -nargs=1 -bar Xpath let g:Xpath = g:Xpath . <args> + +" Test 25: Executing :finally clauses on normal control flow {{{1 +" +" Control flow in a :try conditional should always fall through to its +" :finally clause. A :finally clause of a :try conditional inside an +" inactive conditional should never be executed. +"------------------------------------------------------------------------------- + +func T25_F() + let loops = 3 + while loops > 0 + Xpath 'a' . loops + if loops >= 2 + try + Xpath 'b' . loops + if loops == 2 + try + Xpath 'c' . loops + finally + Xpath 'd' . loops + endtry + endif + finally + Xpath 'e' . loops + if loops == 2 + try + Xpath 'f' . loops + final + Xpath 'g' . loops + endtry + endif + endtry + endif + Xpath 'h' . loops + let loops = loops - 1 + endwhile + Xpath 'i' +endfunc + +" Also try using "fina" and "final" and "finall" as abbraviations. +func T25_G() + if 1 + try + Xpath 'A' + call T25_F() + Xpath 'B' + fina + Xpath 'C' + endtry + else + try + Xpath 'D' + finall + Xpath 'E' + endtry + endif +endfunc + +func Test_finally() + XpathINIT + call T25_G() + call assert_equal('Aa3b3e3h3a2b2c2d2e2f2g2h2a1h1iBC', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 26: Executing :finally clauses after :continue or :break {{{1 +" +" For a :continue or :break dynamically enclosed in a :try/:endtry +" region inside the next surrounding :while/:endwhile, if the +" :continue/:break is before the :finally, the :finally clause is +" executed first. If the :continue/:break is after the :finally, the +" :finally clause is broken (like an :if/:endif region). +"------------------------------------------------------------------------------- + +func T26_F() + try + let loops = 3 + while loops > 0 + try + try + if loops == 2 + Xpath 'a' . loops + let loops = loops - 1 + continue + elseif loops == 1 + Xpath 'b' . loops + break + finish + endif + Xpath 'c' . loops + endtry + finally + Xpath 'd' . loops + endtry + Xpath 'e' . loops + let loops = loops - 1 + endwhile + Xpath 'f' + finally + Xpath 'g' + let loops = 3 + while loops > 0 + try + finally + try + if loops == 2 + Xpath 'h' . loops + let loops = loops - 1 + continue + elseif loops == 1 + Xpath 'i' . loops + break + finish + endif + endtry + Xpath 'j' . loops + endtry + Xpath 'k' . loops + let loops = loops - 1 + endwhile + Xpath 'l' + endtry + Xpath 'm' +endfunc + +func Test_finally_after_continue() + XpathINIT + call T26_F() + call assert_equal('c3d3e3a2d1b1d1fgj3k3h2i1lm', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 32: Remembering the :return value on :finally {{{1 +" +" If a :finally clause is executed due to a :return specifying +" a value, this is the value visible to the caller if not overwritten +" by a new :return in the :finally clause. A :return without a value +" in the :finally clause overwrites with value 0. +"------------------------------------------------------------------------------- + +func T32_F() + try + Xpath 'a' + try + Xpath 'b' + return "ABCD" + Xpath 'c' + finally + Xpath 'd' + endtry + Xpath 'e' + finally + Xpath 'f' + endtry + Xpath 'g' +endfunc + +func T32_G() + try + Xpath 'h' + return 8 + Xpath 'i' + finally + Xpath 'j' + return 16 + strlen(T32_F()) + Xpath 'k' + endtry + Xpath 'l' +endfunc + +func T32_H() + try + Xpath 'm' + return 32 + Xpath 'n' + finally + Xpath 'o' + return + Xpath 'p' + endtry + Xpath 'q' +endfunc + +func T32_I() + try + Xpath 'r' + finally + Xpath 's' + return T32_G() + T32_H() + 64 + Xpath 't' + endtry + Xpath 'u' +endfunc + +func Test_finally_return() + XpathINIT + call assert_equal(84, T32_I()) + call assert_equal('rshjabdfmo', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 33: :return under :execute or user command and :finally {{{1 +" +" A :return command may be executed under an ":execute" or from +" a user command. Executing of :finally clauses and passing through +" the return code works also then. +"------------------------------------------------------------------------------- + +func T33_F() + try + RETURN 10 + Xpath 'a' + finally + Xpath 'b' + endtry + Xpath 'c' +endfunc + +func T33_G() + try + RETURN 20 + Xpath 'd' + finally + Xpath 'e' + RETURN 30 + Xpath 'f' + endtry + Xpath 'g' +endfunc + +func T33_H() + try + execute "try | return 40 | finally | return 50 | endtry" + Xpath 'h' + finally + Xpath 'i' + endtry + Xpath 'j' +endfunc + +func T33_I() + try + execute "try | return 60 | finally | return 70 | endtry" + Xpath 'k' + finally + Xpath 'l' + execute "try | return 80 | finally | return 90 | endtry" + Xpath 'm' + endtry + Xpath 'n' +endfunc + +func T33_J() + try + RETURN 100 + Xpath 'o' + finally + Xpath 'p' + return + Xpath 'q' + endtry + Xpath 'r' +endfunc + +func T33_K() + try + execute "try | return 110 | finally | return 120 | endtry" + Xpath 's' + finally + Xpath 't' + execute "try | return 130 | finally | return | endtry" + Xpath 'u' + endtry + Xpath 'v' +endfunc + +func T33_L() + try + return + Xpath 'w' + finally + Xpath 'x' + RETURN 140 + Xpath 'y' + endtry + Xpath 'z' +endfunc + +func T33_M() + try + return + Xpath 'A' + finally + Xpath 'B' + execute "try | return 150 | finally | return 160 | endtry" + Xpath 'C' + endtry + Xpath 'D' +endfunc + +func T33_N() + RETURN 170 +endfunc + +func T33_O() + execute "try | return 180 | finally | return 190 | endtry" +endfunc + +func Test_finally_cmd_return() + command! -nargs=? RETURN + \ try | return <args> | finally | return <args> * 2 | endtry + XpathINIT + call assert_equal(20, T33_F()) + call assert_equal(60, T33_G()) + call assert_equal(50, T33_H()) + call assert_equal(90, T33_I()) + call assert_equal(0, T33_J()) + call assert_equal(0, T33_K()) + call assert_equal(280, T33_L()) + call assert_equal(160, T33_M()) + call assert_equal(340, T33_N()) + call assert_equal(190, T33_O()) + call assert_equal('beilptxB', g:Xpath) + delcommand RETURN +endfunc + + +"------------------------------------------------------------------------------- +" Test 41: Skipped :throw finding next command {{{1 +" +" A :throw in an inactive conditional must not hide a following +" command. +"------------------------------------------------------------------------------- + +func T41_F() + Xpath 'a' + if 0 | throw 'never' | endif | Xpath 'b' + Xpath 'c' +endfunc + +func T41_G() + Xpath 'd' + while 0 | throw 'never' | endwhile | Xpath 'e' + Xpath 'f' +endfunc + +func T41_H() + Xpath 'g' + if 0 | try | throw 'never' | endtry | endif | Xpath 'h' + Xpath 'i' +endfunc + +func Test_throw_inactive_cond() + XpathINIT + try + Xpath 'j' + call T41_F() + Xpath 'k' + catch /.*/ + Xpath 'l' + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + + try + Xpath 'm' + call T41_G() + Xpath 'n' + catch /.*/ + Xpath 'o' + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + + try + Xpath 'p' + call T41_H() + Xpath 'q' + catch /.*/ + Xpath 'r' + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + + call assert_equal('jabckmdefnpghiq', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 42: Catching number and string exceptions {{{1 +" +" When a number is thrown, it is converted to a string exception. +" Numbers and strings may be caught by specifying a regular exception +" as argument to the :catch command. +"------------------------------------------------------------------------------- + + +func T42_F() + try + + try + Xpath 'a' + throw 4711 + Xpath 'b' + catch /4711/ + Xpath 'c' + endtry + + try + Xpath 'd' + throw 4711 + Xpath 'e' + catch /^4711$/ + Xpath 'f' + endtry + + try + Xpath 'g' + throw 4711 + Xpath 'h' + catch /\d/ + Xpath 'i' + endtry + + try + Xpath 'j' + throw 4711 + Xpath 'k' + catch /^\d\+$/ + Xpath 'l' + endtry + + try + Xpath 'm' + throw "arrgh" + Xpath 'n' + catch /arrgh/ + Xpath 'o' + endtry + + try + Xpath 'p' + throw "arrgh" + Xpath 'q' + catch /^arrgh$/ + Xpath 'r' + endtry + + try + Xpath 's' + throw "arrgh" + Xpath 't' + catch /\l/ + Xpath 'u' + endtry + + try + Xpath 'v' + throw "arrgh" + Xpath 'w' + catch /^\l\+$/ + Xpath 'x' + endtry + + try + try + Xpath 'y' + throw "ARRGH" + Xpath 'z' + catch /^arrgh$/ + Xpath 'A' + endtry + catch /^\carrgh$/ + Xpath 'B' + endtry + + try + Xpath 'C' + throw "" + Xpath 'D' + catch /^$/ + Xpath 'E' + endtry + + catch /.*/ + Xpath 'F' + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry +endfunc + +func Test_catch_number_string() + XpathINIT + call T42_F() + call assert_equal('acdfgijlmoprsuvxyBCE', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 43: Selecting the correct :catch clause {{{1 +" +" When an exception is thrown and there are multiple :catch clauses, +" the first matching one is taken. +"------------------------------------------------------------------------------- + +func T43_F() + let loops = 3 + while loops > 0 + try + if loops == 3 + Xpath 'a' . loops + throw "a" + Xpath 'b' . loops + elseif loops == 2 + Xpath 'c' . loops + throw "ab" + Xpath 'd' . loops + elseif loops == 1 + Xpath 'e' . loops + throw "abc" + Xpath 'f' . loops + endif + catch /abc/ + Xpath 'g' . loops + catch /ab/ + Xpath 'h' . loops + catch /.*/ + Xpath 'i' . loops + catch /a/ + Xpath 'j' . loops + endtry + + let loops = loops - 1 + endwhile + Xpath 'k' +endfunc + +func Test_multi_catch() + XpathINIT + call T43_F() + call assert_equal('a3i3c2h2e1g1k', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 44: Missing or empty :catch patterns {{{1 +" +" A missing or empty :catch pattern means the same as /.*/, that is, +" catches everything. To catch only empty exceptions, /^$/ must be +" used. A :catch with missing, empty, or /.*/ argument also works +" when followed by another command separated by a bar on the same +" line. :catch patterns cannot be specified between ||. But other +" pattern separators can be used instead of //. +"------------------------------------------------------------------------------- + +func T44_F() + try + try + Xpath 'a' + throw "" + catch /^$/ + Xpath 'b' + endtry + + try + Xpath 'c' + throw "" + catch /.*/ + Xpath 'd' + endtry + + try + Xpath 'e' + throw "" + catch // + Xpath 'f' + endtry + + try + Xpath 'g' + throw "" + catch + Xpath 'h' + endtry + + try + Xpath 'i' + throw "oops" + catch /^$/ + Xpath 'j' + catch /.*/ + Xpath 'k' + endtry + + try + Xpath 'l' + throw "arrgh" + catch /^$/ + Xpath 'm' + catch // + Xpath 'n' + endtry + + try + Xpath 'o' + throw "brrr" + catch /^$/ + Xpath 'p' + catch + Xpath 'q' + endtry + + try | Xpath 'r' | throw "x" | catch /.*/ | Xpath 's' | endtry + + try | Xpath 't' | throw "y" | catch // | Xpath 'u' | endtry + + while 1 + try + let caught = 0 + let v:errmsg = "" + " Extra try level: if ":catch" without arguments below raises + " a syntax error because it misinterprets the "Xpath" as a pattern, + " let it be caught by the ":catch /.*/" below. + try + try | Xpath 'v' | throw "z" | catch | Xpath 'w' | : + endtry + endtry + catch /.*/ + let caught = 1 + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + finally + if $VIMNOERRTHROW && v:errmsg != "" + call assert_report(v:errmsg) + endif + if caught || $VIMNOERRTHROW && v:errmsg != "" + Xpath 'x' + endif + break " discard error for $VIMNOERRTHROW + endtry + endwhile + + let cologne = 4711 + try + try + Xpath 'y' + throw "throw cologne" + " Next lines catches all and throws 4711: + catch |throw cologne| + Xpath 'z' + endtry + catch /4711/ + Xpath 'A' + endtry + + try + Xpath 'B' + throw "plus" + catch +plus+ + Xpath 'C' + endtry + + Xpath 'D' + catch /.*/ + Xpath 'E' + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry +endfunc + +func Test_empty_catch() + XpathINIT + call T44_F() + call assert_equal('abcdefghiklnoqrstuvwyABCD', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 45: Catching exceptions from nested :try blocks {{{1 +" +" When :try blocks are nested, an exception is caught by the innermost +" try conditional that has a matching :catch clause. +"------------------------------------------------------------------------------- + +func T45_F() + let loops = 3 + while loops > 0 + try + try + try + try + if loops == 3 + Xpath 'a' . loops + throw "a" + Xpath 'b' . loops + elseif loops == 2 + Xpath 'c' . loops + throw "ab" + Xpath 'd' . loops + elseif loops == 1 + Xpath 'e' . loops + throw "abc" + Xpath 'f' . loops + endif + catch /abc/ + Xpath 'g' . loops + endtry + catch /ab/ + Xpath 'h' . loops + endtry + catch /.*/ + Xpath 'i' . loops + endtry + catch /a/ + Xpath 'j' . loops + endtry + + let loops = loops - 1 + endwhile + Xpath 'k' +endfunc + +func Test_catch_from_nested_try() + XpathINIT + call T45_F() + call assert_equal('a3i3c2h2e1g1k', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 46: Executing :finally after a :throw in nested :try {{{1 +" +" When an exception is thrown from within nested :try blocks, the +" :finally clauses of the non-catching try conditionals should be +" executed before the matching :catch of the next surrounding :try +" gets the control. If this also has a :finally clause, it is +" executed afterwards. +"------------------------------------------------------------------------------- + +func T46_F() + let sum = 0 + + try + Xpath 'a' + try + Xpath 'b' + try + Xpath 'c' + try + Xpath 'd' + throw "ABC" + Xpath 'e' + catch /xyz/ + Xpath 'f' + finally + Xpath 'g' + if sum != 0 + Xpath 'h' + endif + let sum = sum + 1 + endtry + Xpath 'i' + catch /123/ + Xpath 'j' + catch /321/ + Xpath 'k' + finally + Xpath 'l' + if sum != 1 + Xpath 'm' + endif + let sum = sum + 2 + endtry + Xpath 'n' + finally + Xpath 'o' + if sum != 3 + Xpath 'p' + endif + let sum = sum + 4 + endtry + Xpath 'q' + catch /ABC/ + Xpath 'r' + if sum != 7 + Xpath 's' + endif + let sum = sum + 8 + finally + Xpath 't' + if sum != 15 + Xpath 'u' + endif + let sum = sum + 16 + endtry + Xpath 'v' + if sum != 31 + Xpath 'w' + endif +endfunc + +func Test_finally_after_throw() + XpathINIT + call T46_F() + call assert_equal('abcdglortv', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 47: Throwing exceptions from a :catch clause {{{1 +" +" When an exception is thrown from a :catch clause, it should not be +" caught by a :catch of the same :try conditional. After executing +" the :finally clause (if present), surrounding try conditionals +" should be checked for a matching :catch. +"------------------------------------------------------------------------------- + +func T47_F() + Xpath 'a' + try + Xpath 'b' + try + Xpath 'c' + try + Xpath 'd' + throw "x1" + Xpath 'e' + catch /x1/ + Xpath 'f' + try + Xpath 'g' + throw "x2" + Xpath 'h' + catch /x1/ + Xpath 'i' + catch /x2/ + Xpath 'j' + try + Xpath 'k' + throw "x3" + Xpath 'l' + catch /x1/ + Xpath 'm' + catch /x2/ + Xpath 'n' + finally + Xpath 'o' + endtry + Xpath 'p' + catch /x3/ + Xpath 'q' + endtry + Xpath 'r' + catch /x1/ + Xpath 's' + catch /x2/ + Xpath 't' + catch /x3/ + Xpath 'u' + finally + Xpath 'v' + endtry + Xpath 'w' + catch /x1/ + Xpath 'x' + catch /x2/ + Xpath 'y' + catch /x3/ + Xpath 'z' + endtry + Xpath 'A' + catch /.*/ + Xpath 'B' + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + Xpath 'C' +endfunc + +func Test_throw_from_catch() + XpathINIT + call T47_F() + call assert_equal('abcdfgjkovzAC', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 48: Throwing exceptions from a :finally clause {{{1 +" +" When an exception is thrown from a :finally clause, it should not be +" caught by a :catch of the same :try conditional. Surrounding try +" conditionals should be checked for a matching :catch. A previously +" thrown exception is discarded. +"------------------------------------------------------------------------------- + +func T48_F() + try + + try + try + Xpath 'a' + catch /x1/ + Xpath 'b' + finally + Xpath 'c' + throw "x1" + Xpath 'd' + endtry + Xpath 'e' + catch /x1/ + Xpath 'f' + endtry + Xpath 'g' + + try + try + Xpath 'h' + throw "x2" + Xpath 'i' + catch /x2/ + Xpath 'j' + catch /x3/ + Xpath 'k' + finally + Xpath 'l' + throw "x3" + Xpath 'm' + endtry + Xpath 'n' + catch /x2/ + Xpath 'o' + catch /x3/ + Xpath 'p' + endtry + Xpath 'q' + + try + try + try + Xpath 'r' + throw "x4" + Xpath 's' + catch /x5/ + Xpath 't' + finally + Xpath 'u' + throw "x5" " discards 'x4' + Xpath 'v' + endtry + Xpath 'w' + catch /x4/ + Xpath 'x' + finally + Xpath 'y' + endtry + Xpath 'z' + catch /x5/ + Xpath 'A' + endtry + Xpath 'B' + + catch /.*/ + Xpath 'C' + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + Xpath 'D' +endfunc + +func Test_throw_from_finally() + XpathINIT + call T48_F() + call assert_equal('acfghjlpqruyABD', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 51: Throwing exceptions across :execute and user commands {{{1 +" +" A :throw command may be executed under an ":execute" or from +" a user command. +"------------------------------------------------------------------------------- + +func T51_F() + command! -nargs=? THROW1 throw <args> | throw 1 + command! -nargs=? THROW2 try | throw <args> | endtry | throw 2 + command! -nargs=? THROW3 try | throw 3 | catch /3/ | throw <args> | endtry + command! -nargs=? THROW4 try | throw 4 | finally | throw <args> | endtry + + try + + try + try + Xpath 'a' + THROW1 "A" + catch /A/ + Xpath 'b' + endtry + catch /1/ + Xpath 'c' + endtry + + try + try + Xpath 'd' + THROW2 "B" + catch /B/ + Xpath 'e' + endtry + catch /2/ + Xpath 'f' + endtry + + try + try + Xpath 'g' + THROW3 "C" + catch /C/ + Xpath 'h' + endtry + catch /3/ + Xpath 'i' + endtry + + try + try + Xpath 'j' + THROW4 "D" + catch /D/ + Xpath 'k' + endtry + catch /4/ + Xpath 'l' + endtry + + try + try + Xpath 'm' + execute 'throw "E" | throw 5' + catch /E/ + Xpath 'n' + endtry + catch /5/ + Xpath 'o' + endtry + + try + try + Xpath 'p' + execute 'try | throw "F" | endtry | throw 6' + catch /F/ + Xpath 'q' + endtry + catch /6/ + Xpath 'r' + endtry + + try + try + Xpath 's' + execute'try | throw 7 | catch /7/ | throw "G" | endtry' + catch /G/ + Xpath 't' + endtry + catch /7/ + Xpath 'u' + endtry + + try + try + Xpath 'v' + execute 'try | throw 8 | finally | throw "H" | endtry' + catch /H/ + Xpath 'w' + endtry + catch /8/ + Xpath 'x' + endtry + + catch /.*/ + Xpath 'y' + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + + Xpath 'z' + + delcommand THROW1 + delcommand THROW2 + delcommand THROW3 + delcommand THROW4 +endfunc + +func Test_throw_across_commands() + XpathINIT + call T51_F() + call assert_equal('abdeghjkmnpqstvwz', g:Xpath) +endfunc + + + +"------------------------------------------------------------------------------- +" Test 69: :throw across :if, :elseif, :while {{{1 +" +" On an :if, :elseif, or :while command, an exception might be thrown +" during evaluation of the expression to test. The exception can be +" caught by the script. +"------------------------------------------------------------------------------- + +func T69_throw(x) + Xpath 'x' + throw a:x +endfunc + +func Test_throw_ifelsewhile() + XpathINIT + + try + try + Xpath 'a' + if 111 == T69_throw("if") + 111 + Xpath 'b' + else + Xpath 'c' + endif + Xpath 'd' + catch /^if$/ + Xpath 'e' + catch /.*/ + Xpath 'f' + call assert_report("if: " . v:exception . " in " . v:throwpoint) + endtry + + try + Xpath 'g' + if v:false + Xpath 'h' + elseif 222 == T69_throw("elseif") + 222 + Xpath 'i' + else + Xpath 'j' + endif + Xpath 'k' + catch /^elseif$/ + Xpath 'l' + catch /.*/ + Xpath 'm' + call assert_report("elseif: " . v:exception . " in " . v:throwpoint) + endtry + + try + Xpath 'n' + while 333 == T69_throw("while") + 333 + Xpath 'o' + break + endwhile + Xpath 'p' + catch /^while$/ + Xpath 'q' + catch /.*/ + Xpath 'r' + call assert_report("while: " .. v:exception .. " in " .. v:throwpoint) + endtry + catch /^0$/ " default return value + Xpath 's' + call assert_report(v:throwpoint) + catch /.*/ + call assert_report(v:exception .. " in " .. v:throwpoint) + Xpath 't' + endtry + + call assert_equal('axegxlnxq', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 70: :throw across :return or :throw {{{1 +" +" On a :return or :throw command, an exception might be thrown during +" evaluation of the expression to return or throw, respectively. The +" exception can be caught by the script. +"------------------------------------------------------------------------------- + +let T70_taken = "" + +func T70_throw(x, n) + let g:T70_taken = g:T70_taken . "T" . a:n + throw a:x +endfunc + +func T70_F(x, y, n) + let g:T70_taken = g:T70_taken . "F" . a:n + return a:x + T70_throw(a:y, a:n) +endfunc + +func T70_G(x, y, n) + let g:T70_taken = g:T70_taken . "G" . a:n + throw a:x . T70_throw(a:y, a:n) + return a:x +endfunc + +func Test_throwreturn() + XpathINIT + + try + try + Xpath 'a' + call T70_F(4711, "return", 1) + Xpath 'b' + catch /^return$/ + Xpath 'c' + catch /.*/ + Xpath 'd' + call assert_report("return: " .. v:exception .. " in " .. v:throwpoint) + endtry + + try + Xpath 'e' + let var = T70_F(4712, "return-var", 2) + Xpath 'f' + catch /^return-var$/ + Xpath 'g' + catch /.*/ + Xpath 'h' + call assert_report("return-var: " . v:exception . " in " . v:throwpoint) + finally + unlet! var + endtry + + try + Xpath 'i' + throw "except1" . T70_throw("throw1", 3) + Xpath 'j' + catch /^except1/ + Xpath 'k' + catch /^throw1$/ + Xpath 'l' + catch /.*/ + Xpath 'm' + call assert_report("throw1: " .. v:exception .. " in " .. v:throwpoint) + endtry + + try + Xpath 'n' + call T70_G("except2", "throw2", 4) + Xpath 'o' + catch /^except2/ + Xpath 'p' + catch /^throw2$/ + Xpath 'q' + catch /.*/ + Xpath 'r' + call assert_report("throw2: " .. v:exception .. " in " .. v:throwpoint) + endtry + + try + Xpath 's' + let var = T70_G("except3", "throw3", 5) + Xpath 't' + catch /^except3/ + Xpath 'u' + catch /^throw3$/ + Xpath 'v' + catch /.*/ + Xpath 'w' + call assert_report("throw3: " .. v:exception .. " in " .. v:throwpoint) + finally + unlet! var + endtry + + call assert_equal('F1T1F2T2T3G4T4G5T5', g:T70_taken) + Xpath 'x' + catch /^0$/ " default return value + Xpath 'y' + call assert_report(v:throwpoint) + catch /.*/ + Xpath 'z' + call assert_report('Caught' .. v:exception .. ' in ' .. v:throwpoint) + endtry + + call assert_equal('acegilnqsvx', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 71: :throw across :echo variants and :execute {{{1 +" +" On an :echo, :echon, :echomsg, :echoerr, or :execute command, an +" exception might be thrown during evaluation of the arguments to +" be displayed or executed as a command, respectively. Any following +" arguments are not evaluated, then. The exception can be caught by +" the script. +"------------------------------------------------------------------------------- + +let T71_taken = "" + +func T71_throw(x, n) + let g:T71_taken = g:T71_taken . "T" . a:n + throw a:x +endfunc + +func T71_F(n) + let g:T71_taken = g:T71_taken . "F" . a:n + return "F" . a:n +endfunc + +func Test_throw_echo() + XpathINIT + + try + try + Xpath 'a' + echo 'echo ' . T71_throw("echo-except", 1) . T71_F(1) + Xpath 'b' + catch /^echo-except$/ + Xpath 'c' + catch /.*/ + Xpath 'd' + call assert_report("echo: " .. v:exception .. " in " .. v:throwpoint) + endtry + + try + Xpath 'e' + echon "echon " . T71_throw("echon-except", 2) . T71_F(2) + Xpath 'f' + catch /^echon-except$/ + Xpath 'g' + catch /.*/ + Xpath 'h' + call assert_report('echon: ' . v:exception . ' in ' . v:throwpoint) + endtry + + try + Xpath 'i' + echomsg "echomsg " . T71_throw("echomsg-except", 3) . T71_F(3) + Xpath 'j' + catch /^echomsg-except$/ + Xpath 'k' + catch /.*/ + Xpath 'l' + call assert_report('echomsg: ' . v:exception . ' in ' . v:throwpoint) + endtry + + try + Xpath 'm' + echoerr "echoerr " . T71_throw("echoerr-except", 4) . T71_F(4) + Xpath 'n' + catch /^echoerr-except$/ + Xpath 'o' + catch /Vim/ + Xpath 'p' + catch /echoerr/ + Xpath 'q' + catch /.*/ + Xpath 'r' + call assert_report('echoerr: ' . v:exception . ' in ' . v:throwpoint) + endtry + + try + Xpath 's' + execute "echo 'execute " . T71_throw("execute-except", 5) . T71_F(5) "'" + Xpath 't' + catch /^execute-except$/ + Xpath 'u' + catch /.*/ + Xpath 'v' + call assert_report('execute: ' . v:exception . ' in ' . v:throwpoint) + endtry + + call assert_equal('T1T2T3T4T5', g:T71_taken) + Xpath 'w' + catch /^0$/ " default return value + Xpath 'x' + call assert_report(v:throwpoint) + catch /.*/ + Xpath 'y' + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + + call assert_equal('acegikmosuw', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 72: :throw across :let or :unlet {{{1 +" +" On a :let command, an exception might be thrown during evaluation +" of the expression to assign. On an :let or :unlet command, the +" evaluation of the name of the variable to be assigned or list or +" deleted, respectively, may throw an exception. Any following +" arguments are not evaluated, then. The exception can be caught by +" the script. +"------------------------------------------------------------------------------- + +let throwcount = 0 + +func T72_throw(x) + let g:throwcount = g:throwcount + 1 + throw a:x +endfunc + +let T72_addpath = '' + +func T72_addpath(p) + let g:T72_addpath = g:T72_addpath . a:p +endfunc + +func Test_throw_let() + XpathINIT + + try + try + let $VAR = 'old_value' + Xpath 'a' + let $VAR = 'let(' . T72_throw('var') . ')' + Xpath 'b' + catch /^var$/ + Xpath 'c' + finally + call assert_equal('old_value', $VAR) + endtry + + try + let @a = 'old_value' + Xpath 'd' + let @a = 'let(' . T72_throw('reg') . ')' + Xpath 'e' + catch /^reg$/ + try + Xpath 'f' + let @A = 'let(' . T72_throw('REG') . ')' + Xpath 'g' + catch /^REG$/ + Xpath 'h' + endtry + finally + call assert_equal('old_value', @a) + call assert_equal('old_value', @A) + endtry + + try + let saved_gpath = &g:path + let saved_lpath = &l:path + Xpath 'i' + let &path = 'let(' . T72_throw('opt') . ')' + Xpath 'j' + catch /^opt$/ + try + Xpath 'k' + let &g:path = 'let(' . T72_throw('gopt') . ')' + Xpath 'l' + catch /^gopt$/ + try + Xpath 'm' + let &l:path = 'let(' . T72_throw('lopt') . ')' + Xpath 'n' + catch /^lopt$/ + Xpath 'o' + endtry + endtry + finally + call assert_equal(saved_gpath, &g:path) + call assert_equal(saved_lpath, &l:path) + let &g:path = saved_gpath + let &l:path = saved_lpath + endtry + + unlet! var1 var2 var3 + + try + Xpath 'p' + let var1 = 'let(' . T72_throw('var1') . ')' + Xpath 'q' + catch /^var1$/ + Xpath 'r' + finally + call assert_true(!exists('var1')) + endtry + + try + let var2 = 'old_value' + Xpath 's' + let var2 = 'let(' . T72_throw('var2'). ')' + Xpath 't' + catch /^var2$/ + Xpath 'u' + finally + call assert_equal('old_value', var2) + endtry + + try + Xpath 'v' + let var{T72_throw('var3')} = 4711 + Xpath 'w' + catch /^var3$/ + Xpath 'x' + endtry + + try + call T72_addpath('T1') + let var{T72_throw('var4')} var{T72_addpath('T2')} | call T72_addpath('T3') + call T72_addpath('T4') + catch /^var4$/ + call T72_addpath('T5') + endtry + + try + call T72_addpath('T6') + unlet var{T72_throw('var5')} var{T72_addpath('T7')} + \ | call T72_addpath('T8') + call T72_addpath('T9') + catch /^var5$/ + call T72_addpath('T10') + endtry + + call assert_equal('T1T5T6T10', g:T72_addpath) + call assert_equal(11, g:throwcount) + catch /.*/ + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + + call assert_equal('acdfhikmoprsuvx', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 73: :throw across :function, :delfunction {{{1 +" +" The :function and :delfunction commands may cause an expression +" specified in braces to be evaluated. During evaluation, an +" exception might be thrown. The exception can be caught by the +" script. +"------------------------------------------------------------------------------- + +let T73_taken = '' + +func T73_throw(x, n) + let g:T73_taken = g:T73_taken . 'T' . a:n + throw a:x +endfunc + +func T73_expr(x, n) + let g:T73_taken = g:T73_taken . 'E' . a:n + if a:n % 2 == 0 + call T73_throw(a:x, a:n) + endif + return 2 - a:n % 2 +endfunc + +func Test_throw_func() + XpathINIT + + try + try + " Define function. + Xpath 'a' + function! F0() + endfunction + Xpath 'b' + function! F{T73_expr('function-def-ok', 1)}() + endfunction + Xpath 'c' + function! F{T73_expr('function-def', 2)}() + endfunction + Xpath 'd' + catch /^function-def-ok$/ + Xpath 'e' + catch /^function-def$/ + Xpath 'f' + catch /.*/ + call assert_report('def: ' . v:exception . ' in ' . v:throwpoint) + endtry + + try + " List function. + Xpath 'g' + function F0 + Xpath 'h' + function F{T73_expr('function-lst-ok', 3)} + Xpath 'i' + function F{T73_expr('function-lst', 4)} + Xpath 'j' + catch /^function-lst-ok$/ + Xpath 'k' + catch /^function-lst$/ + Xpath 'l' + catch /.*/ + call assert_report('lst: ' . v:exception . ' in ' . v:throwpoint) + endtry + + try + " Delete function + Xpath 'm' + delfunction F0 + Xpath 'n' + delfunction F{T73_expr('function-del-ok', 5)} + Xpath 'o' + delfunction F{T73_expr('function-del', 6)} + Xpath 'p' + catch /^function-del-ok$/ + Xpath 'q' + catch /^function-del$/ + Xpath 'r' + catch /.*/ + call assert_report('del: ' . v:exception . ' in ' . v:throwpoint) + endtry + call assert_equal('E1E2T2E3E4T4E5E6T6', g:T73_taken) + catch /.*/ + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + + call assert_equal('abcfghilmnor', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 74: :throw across builtin functions and commands {{{1 +" +" Some functions like exists(), searchpair() take expression +" arguments, other functions or commands like substitute() or +" :substitute cause an expression (specified in the regular +" expression) to be evaluated. During evaluation an exception +" might be thrown. The exception can be caught by the script. +"------------------------------------------------------------------------------- + +let T74_taken = "" + +func T74_throw(x, n) + let g:T74_taken = g:T74_taken . "T" . a:n + throw a:x +endfunc + +func T74_expr(x, n) + let g:T74_taken = g:T74_taken . "E" . a:n + call T74_throw(a:x . a:n, a:n) + return "EXPR" +endfunc + +func T74_skip(x, n) + let g:T74_taken = g:T74_taken . "S" . a:n . "(" . line(".") + let theline = getline(".") + if theline =~ "skip" + let g:T74_taken = g:T74_taken . "s)" + return 1 + elseif theline =~ "throw" + let g:T74_taken = g:T74_taken . "t)" + call T74_throw(a:x . a:n, a:n) + else + let g:T74_taken = g:T74_taken . ")" + return 0 + endif +endfunc + +func T74_subst(x, n) + let g:T74_taken = g:T74_taken . "U" . a:n . "(" . line(".") + let theline = getline(".") + if theline =~ "not" " T74_subst() should not be called for this line + let g:T74_taken = g:T74_taken . "n)" + call T74_throw(a:x . a:n, a:n) + elseif theline =~ "throw" + let g:T74_taken = g:T74_taken . "t)" + call T74_throw(a:x . a:n, a:n) + else + let g:T74_taken = g:T74_taken . ")" + return "replaced" + endif +endfunc + +func Test_throw_builtin_func() + XpathINIT + + try + try + Xpath 'a' + let result = exists('*{T74_expr("exists", 1)}') + Xpath 'b' + catch /^exists1$/ + Xpath 'c' + try + let result = exists('{T74_expr("exists", 2)}') + Xpath 'd' + catch /^exists2$/ + Xpath 'e' + catch /.*/ + call assert_report('exists2: ' . v:exception . ' in ' . v:throwpoint) + endtry + catch /.*/ + call assert_report('exists1: ' . v:exception . ' in ' . v:throwpoint) + endtry + + try + let file = tempname() + exec "edit" file + call append(0, [ + \ 'begin', + \ 'xx', + \ 'middle 3', + \ 'xx', + \ 'middle 5 skip', + \ 'xx', + \ 'middle 7 throw', + \ 'xx', + \ 'end']) + normal! gg + Xpath 'f' + let result = searchpair("begin", "middle", "end", '', + \ 'T74_skip("searchpair", 3)') + Xpath 'g' + let result = searchpair("begin", "middle", "end", '', + \ 'T74_skip("searchpair", 4)') + Xpath 'h' + let result = searchpair("begin", "middle", "end", '', + \ 'T74_skip("searchpair", 5)') + Xpath 'i' + catch /^searchpair[35]$/ + Xpath 'j' + catch /^searchpair4$/ + Xpath 'k' + catch /.*/ + call assert_report('searchpair: ' . v:exception . ' in ' . v:throwpoint) + finally + bwipeout! + call delete(file) + endtry + + try + let file = tempname() + exec "edit" file + call append(0, [ + \ 'subst 1', + \ 'subst 2', + \ 'not', + \ 'subst 4', + \ 'subst throw', + \ 'subst 6']) + normal! gg + Xpath 'l' + 1,2substitute/subst/\=T74_subst("substitute", 6)/ + try + Xpath 'm' + try + let v:errmsg = "" + 3substitute/subst/\=T74_subst("substitute", 7)/ + finally + if v:errmsg != "" + " If exceptions are not thrown on errors, fake the error + " exception in order to get the same execution path. + throw "faked Vim(substitute)" + endif + endtry + catch /Vim(substitute)/ " Pattern not found ('e' flag missing) + Xpath 'n' + 3substitute/subst/\=T74_subst("substitute", 8)/e + Xpath 'o' + endtry + Xpath 'p' + 4,6substitute/subst/\=T74_subst("substitute", 9)/ + Xpath 'q' + catch /^substitute[678]/ + Xpath 'r' + catch /^substitute9/ + Xpath 's' + finally + bwipeout! + call delete(file) + endtry + + try + Xpath 't' + let var = substitute("sub", "sub", '\=T74_throw("substitute()y", 10)', '') + Xpath 'u' + catch /substitute()y/ + Xpath 'v' + catch /.*/ + call assert_report('substitute()y: ' . v:exception . ' in ' + \ . v:throwpoint) + endtry + + try + Xpath 'w' + let var = substitute("not", "sub", '\=T74_throw("substitute()n", 11)', '') + Xpath 'x' + catch /substitute()n/ + Xpath 'y' + catch /.*/ + call assert_report('substitute()n: ' . v:exception . ' in ' + \ . v:throwpoint) + endtry + + call assert_equal('E1T1E2T2S3(3)S4(5s)S4(7t)T4U6(1)U6(2)U9(4)U9(5t)T9T10', + \ g:T74_taken) + + catch /.*/ + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + endtry + + call assert_equal('acefgklmnopstvwx', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 75: Errors in builtin functions. {{{1 +" +" On an error in a builtin function called inside a :try/:endtry +" region, the evaluation of the expression calling that function and +" the command containing that expression are abandoned. The error can +" be caught as an exception. +" +" A simple :call of the builtin function is a trivial case. If the +" builtin function is called in the argument list of another function, +" no further arguments are evaluated, and the other function is not +" executed. If the builtin function is called from the argument of +" a :return command, the :return command is not executed. If the +" builtin function is called from the argument of a :throw command, +" the :throw command is not executed. The evaluation of the +" expression calling the builtin function is abandoned. +"------------------------------------------------------------------------------- + +func T75_F1(arg1) + Xpath 'a' +endfunc + +func T75_F2(arg1, arg2) + Xpath 'b' +endfunc + +func T75_G() + Xpath 'c' +endfunc + +func T75_H() + Xpath 'd' +endfunc + +func T75_R() + while 1 + try + let caught = 0 + let v:errmsg = "" + Xpath 'e' + return append(1, "s") + catch /E21/ + let caught = 1 + catch /.*/ + Xpath 'f' + finally + Xpath 'g' + if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' + Xpath 'h' + endif + break " discard error for $VIMNOERRTHROW + endtry + endwhile + Xpath 'i' +endfunc + +func Test_builtin_func_error() + XpathINIT + + try + set noma " let append() fail with "E21" + + while 1 + try + let caught = 0 + let v:errmsg = "" + Xpath 'j' + call append(1, "s") + catch /E21/ + let caught = 1 + catch /.*/ + Xpath 'k' + finally + Xpath 'l' + if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' + Xpath 'm' + endif + break " discard error for $VIMNOERRTHROW + endtry + endwhile + + while 1 + try + let caught = 0 + let v:errmsg = "" + Xpath 'n' + call T75_F1('x' . append(1, "s")) + catch /E21/ + let caught = 1 + catch /.*/ + Xpath 'o' + finally + Xpath 'p' + if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' + Xpath 'q' + endif + break " discard error for $VIMNOERRTHROW + endtry + endwhile + + while 1 + try + let caught = 0 + let v:errmsg = "" + Xpath 'r' + call T75_F2('x' . append(1, "s"), T75_G()) + catch /E21/ + let caught = 1 + catch /.*/ + Xpath 's' + finally + Xpath 't' + if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' + Xpath 'u' + endif + break " discard error for $VIMNOERRTHROW + endtry + endwhile + + call T75_R() + + while 1 + try + let caught = 0 + let v:errmsg = "" + Xpath 'v' + throw "T" . append(1, "s") + catch /E21/ + let caught = 1 + catch /^T.*/ + Xpath 'w' + catch /.*/ + Xpath 'x' + finally + Xpath 'y' + if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' + Xpath 'z' + endif + break " discard error for $VIMNOERRTHROW + endtry + endwhile + + while 1 + try + let caught = 0 + let v:errmsg = "" + Xpath 'A' + let x = "a" + let x = x . "b" . append(1, "s") . T75_H() + catch /E21/ + let caught = 1 + catch /.*/ + Xpath 'B' + finally + Xpath 'C' + if caught || $VIMNOERRTHROW && v:errmsg =~ 'E21' + Xpath 'D' + endif + call assert_equal('a', x) + break " discard error for $VIMNOERRTHROW + endtry + endwhile + catch /.*/ + call assert_report('Caught ' . v:exception . ' in ' . v:throwpoint) + finally + set ma& + endtry + + call assert_equal('jlmnpqrtueghivyzACD', g:Xpath) +endfunc + +func Test_reload_in_try_catch() + call writefile(['x'], 'Xreload') + set autoread + edit Xreload + tabnew + call writefile(['xx'], 'Xreload') + augroup ReLoad + au FileReadPost Xreload let x = doesnotexist + au BufReadPost Xreload let x = doesnotexist + augroup END + try + edit Xreload + catch + endtry + tabnew + + tabclose + tabclose + autocmd! ReLoad + set noautoread + bwipe! Xreload + call delete('Xreload') +endfunc + +" Test for errors with :catch, :throw, :finally {{{1 +func Test_try_catch_errors() + call assert_fails('throw |', 'E471:') + call assert_fails("throw \n ", 'E471:') + call assert_fails('catch abc', 'E654:') + call assert_fails('try | let i = 1| finally | catch | endtry', 'E604:') + call assert_fails('finally', 'E606:') + call assert_fails('try | finally | finally | endtry', 'E607:') + call assert_fails('try | for i in range(5) | endif | endtry', 'E580:') + call assert_fails('try | while v:true | endtry', 'E170:') + call assert_fails('try | if v:true | endtry', 'E171:') + + " this was using a negative index in cstack[] + let lines =<< trim END + try + for + if + endwhile + if + finally + END + call CheckScriptFailure(lines, 'E690:') + + let lines =<< trim END + try + for + if + endwhile + if + endtry + END + call CheckScriptFailure(lines, 'E690:') +endfunc + +" Test for verbose messages with :try :catch, and :finally {{{1 +func Test_try_catch_verbose() + " This test works only when the language is English + CheckEnglish + + set verbose=14 + + " Test for verbose messages displayed when an exception is caught + redir => msg + try + echo i + catch /E121:/ + finally + endtry + redir END + let expected = [ + \ 'Exception thrown: Vim(echo):E121: Undefined variable: i', '', + \ 'Exception caught: Vim(echo):E121: Undefined variable: i', '', + \ 'Exception finished: Vim(echo):E121: Undefined variable: i'] + call assert_equal(expected, split(msg, "\n")) + + " Test for verbose messages displayed when an exception is discarded + redir => msg + try + try + throw 'abc' + finally + throw 'xyz' + endtry + catch + endtry + redir END + let expected = [ + \ 'Exception thrown: abc', '', + \ 'Exception made pending: abc', '', + \ 'Exception thrown: xyz', '', + \ 'Exception discarded: abc', '', + \ 'Exception caught: xyz', '', + \ 'Exception finished: xyz'] + call assert_equal(expected, split(msg, "\n")) + + " Test for messages displayed when :throw is resumed after :finally + redir => msg + try + try + throw 'abc' + finally + endtry + catch + endtry + redir END + let expected = [ + \ 'Exception thrown: abc', '', + \ 'Exception made pending: abc', '', + \ 'Exception resumed: abc', '', + \ 'Exception caught: abc', '', + \ 'Exception finished: abc'] + call assert_equal(expected, split(msg, "\n")) + + " Test for messages displayed when :break is resumed after :finally + redir => msg + for i in range(1) + try + break + finally + endtry + endfor + redir END + let expected = [':break made pending', '', ':break resumed'] + call assert_equal(expected, split(msg, "\n")) + + " Test for messages displayed when :continue is resumed after :finally + redir => msg + for i in range(1) + try + continue + finally + endtry + endfor + redir END + let expected = [':continue made pending', '', ':continue resumed'] + call assert_equal(expected, split(msg, "\n")) + + " Test for messages displayed when :return is resumed after :finally + func Xtest() + try + return 'vim' + finally + endtry + endfunc + redir => msg + call Xtest() + redir END + let expected = [ + \ 'calling Xtest()', '', + \ ':return vim made pending', '', + \ ':return vim resumed', '', + \ 'Xtest returning ''vim''', '', + \ 'continuing in Test_try_catch_verbose'] + call assert_equal(expected, split(msg, "\n")) + delfunc Xtest + + " Test for messages displayed when :finish is resumed after :finally + call writefile(['try', 'finish', 'finally', 'endtry'], 'Xscript') + redir => msg + source Xscript + redir END + let expected = [ + \ ':finish made pending', '', + \ ':finish resumed', '', + \ 'finished sourcing Xscript', + \ 'continuing in Test_try_catch_verbose'] + call assert_equal(expected, split(msg, "\n")[1:]) + call delete('Xscript') + + " Test for messages displayed when a pending :continue is discarded by an + " exception in a finally handler + redir => msg + try + for i in range(1) + try + continue + finally + throw 'abc' + endtry + endfor + catch + endtry + redir END + let expected = [ + \ ':continue made pending', '', + \ 'Exception thrown: abc', '', + \ ':continue discarded', '', + \ 'Exception caught: abc', '', + \ 'Exception finished: abc'] + call assert_equal(expected, split(msg, "\n")) + + set verbose& +endfunc + +" Test for throwing an exception from a BufEnter autocmd {{{1 +func Test_BufEnter_exception() + augroup bufenter_exception + au! + autocmd BufEnter Xfile1 throw 'abc' + augroup END + + let caught_abc = 0 + try + sp Xfile1 + catch /^abc/ + let caught_abc = 1 + endtry + call assert_equal(1, caught_abc) + call assert_equal(1, winnr('$')) + + augroup bufenter_exception + au! + augroup END + augroup! bufenter_exception + %bwipe! + + " Test for recursively throwing exceptions in autocmds + augroup bufenter_exception + au! + autocmd BufEnter Xfile1 throw 'bufenter' + autocmd BufLeave Xfile1 throw 'bufleave' + augroup END + + let ex_count = 0 + try + try + sp Xfile1 + catch /^bufenter/ + let ex_count += 1 + endtry + catch /^bufleave/ + let ex_count += 10 + endtry + call assert_equal(10, ex_count) + call assert_equal(2, winnr('$')) + + augroup bufenter_exception + au! + augroup END + augroup! bufenter_exception + %bwipe! +endfunc + +" Test for using try/catch when lines are joined by "|" or "\n" {{{1 +func Test_try_catch_nextcmd() + func Throw() + throw "Failure" + endfunc + + let lines =<< trim END + try + let s:x = Throw() + catch + let g:caught = 1 + endtry + END + + let g:caught = 0 + call execute(lines) + call assert_equal(1, g:caught) + + let g:caught = 0 + call execute(join(lines, '|')) + call assert_equal(1, g:caught) + + let g:caught = 0 + call execute(join(lines, "\n")) + call assert_equal(1, g:caught) + + unlet g:caught + delfunc Throw +endfunc + +" Test for using try/catch in a user command with a failing expression {{{1 +func Test_user_command_try_catch() + let lines =<< trim END + function s:throw() abort + throw 'error' + endfunction + + command! Execute + \ try + \ | let s:x = s:throw() + \ | catch + \ | let g:caught = 'caught' + \ | endtry + + let g:caught = 'no' + Execute + call assert_equal('caught', g:caught) + END + call writefile(lines, 'XtestTryCatch') + source XtestTryCatch + + call delete('XtestTryCatch') + unlet g:caught +endfunc + +" Test for using throw in a called function with following error {{{1 +func Test_user_command_throw_in_function_call() + let lines =<< trim END + function s:get_dict() abort + throw 'my_error' + endfunction + + try + call s:get_dict().foo() + catch /my_error/ + let caught = 'yes' + catch + let caught = v:exception + endtry + call assert_equal('yes', caught) + END + call writefile(lines, 'XtestThrow') + source XtestThrow + + call delete('XtestThrow') + unlet g:caught +endfunc + +" Test that after reporting an uncaught exception there is no error for a +" missing :endif +func Test_after_exception_no_endif_error() + function Throw() + throw "Failure" + endfunction + + function Foo() + if 1 + call Throw() + endif + endfunction + call assert_fails('call Foo()', ['E605:', 'E605:']) + delfunc Throw + delfunc Foo +endfunc + +" Test for using throw in a called function with following endtry {{{1 +func Test_user_command_function_call_with_endtry() + let lines =<< trim END + funct s:throw(msg) abort + throw a:msg + endfunc + func s:main() abort + try + try + throw 'err1' + catch + call s:throw('err2') | endtry + catch + let s:caught = 'yes' + endtry + endfunc + + call s:main() + call assert_equal('yes', s:caught) + END + call writefile(lines, 'XtestThrow') + source XtestThrow + + call delete('XtestThrow') +endfunc + +func ThisWillFail() + +endfunc + +" This was crashing prior to the fix in 8.2.3478. +func Test_error_in_catch_and_finally() + let lines =<< trim END + try + echo x + catch + for l in [] + finally + END + call writefile(lines, 'XtestCatchAndFinally') + try + source XtestCatchAndFinally + catch /E600:/ + endtry + + call delete('XtestCatchAndFinally') +endfunc + +" This was causing an illegal memory access +func Test_leave_block_in_endtry_not_called() + let lines =<< trim END + " vim9script + " try # + try " + for x in [] + if + endwhile + if + endtry + END + call writefile(lines, 'XtestEndtry') + try + source XtestEndtry + catch /E171:/ + endtry + + call delete('XtestEndtry') +endfunc + +" Modeline {{{1 +" vim: ts=8 sw=2 sts=2 expandtab tw=80 fdm=marker diff --git a/test/old/testdir/test_undo.vim b/test/old/testdir/test_undo.vim new file mode 100644 index 0000000000..a06731cc96 --- /dev/null +++ b/test/old/testdir/test_undo.vim @@ -0,0 +1,885 @@ +" Tests for the undo tree. +" Since this script is sourced we need to explicitly break changes up in +" undo-able pieces. Do that by setting 'undolevels'. +" Also tests :earlier and :later. + +source check.vim +source screendump.vim + +func Test_undotree() + new + + normal! Aabc + set ul=100 + let d = undotree() + call assert_equal(1, d.seq_last) + call assert_equal(1, d.seq_cur) + call assert_equal(0, d.save_last) + call assert_equal(0, d.save_cur) + call assert_equal(1, len(d.entries)) + call assert_equal(1, d.entries[0].newhead) + call assert_equal(1, d.entries[0].seq) + call assert_true(d.entries[0].time <= d.time_cur) + + normal! Adef + set ul=100 + let d = undotree() + call assert_equal(2, d.seq_last) + call assert_equal(2, d.seq_cur) + call assert_equal(0, d.save_last) + call assert_equal(0, d.save_cur) + call assert_equal(2, len(d.entries)) + call assert_equal(1, d.entries[0].seq) + call assert_equal(1, d.entries[1].newhead) + call assert_equal(2, d.entries[1].seq) + call assert_true(d.entries[1].time <= d.time_cur) + + undo + set ul=100 + let d = undotree() + call assert_equal(2, d.seq_last) + call assert_equal(1, d.seq_cur) + call assert_equal(0, d.save_last) + call assert_equal(0, d.save_cur) + call assert_equal(2, len(d.entries)) + call assert_equal(1, d.entries[0].seq) + call assert_equal(1, d.entries[1].curhead) + call assert_equal(1, d.entries[1].newhead) + call assert_equal(2, d.entries[1].seq) + call assert_true(d.entries[1].time == d.time_cur) + + normal! Aghi + set ul=100 + let d = undotree() + call assert_equal(3, d.seq_last) + call assert_equal(3, d.seq_cur) + call assert_equal(0, d.save_last) + call assert_equal(0, d.save_cur) + call assert_equal(2, len(d.entries)) + call assert_equal(1, d.entries[0].seq) + call assert_equal(2, d.entries[1].alt[0].seq) + call assert_equal(1, d.entries[1].newhead) + call assert_equal(3, d.entries[1].seq) + call assert_true(d.entries[1].time <= d.time_cur) + + undo + set ul=100 + let d = undotree() + call assert_equal(3, d.seq_last) + call assert_equal(1, d.seq_cur) + call assert_equal(0, d.save_last) + call assert_equal(0, d.save_cur) + call assert_equal(2, len(d.entries)) + call assert_equal(1, d.entries[0].seq) + call assert_equal(2, d.entries[1].alt[0].seq) + call assert_equal(1, d.entries[1].curhead) + call assert_equal(1, d.entries[1].newhead) + call assert_equal(3, d.entries[1].seq) + call assert_true(d.entries[1].time == d.time_cur) + + w! Xtest + let d = undotree() + call assert_equal(1, d.save_cur) + call assert_equal(1, d.save_last) + call delete('Xtest') + bwipe! Xtest +endfunc + +func FillBuffer() + for i in range(1,13) + put=i + " Set 'undolevels' to split undo. + exe "setg ul=" . &g:ul + endfor +endfunc + +func Test_undotree_bufnr() + new + let buf1 = bufnr() + + normal! Aabc + set ul=100 + + " Save undo tree without bufnr as ground truth for buffer 1 + let d1 = undotree() + + new + let buf2 = bufnr() + + normal! Adef + set ul=100 + + normal! Aghi + set ul=100 + + " Save undo tree without bufnr as ground truth for buffer 2 + let d2 = undotree() + + " Check undotree() with bufnr argument + let d = undotree(buf1) + call assert_equal(d1, d) + call assert_notequal(d2, d) + + let d = undotree(buf2) + call assert_notequal(d1, d) + call assert_equal(d2, d) + + " Switch buffers and check again + wincmd p + + let d = undotree(buf1) + call assert_equal(d1, d) + + let d = undotree(buf2) + call assert_notequal(d1, d) + call assert_equal(d2, d) + + " error cases + call assert_fails('call undotree(-1)', 'E158:') + call assert_fails('call undotree("nosuchbuf")', 'E158:') + + " after creating a buffer nosuchbuf, undotree('nosuchbuf') should + " not error out + new nosuchbuf + let d = {'seq_last': 0, 'entries': [], 'time_cur': 0, 'save_last': 0, 'synced': 1, 'save_cur': 0, 'seq_cur': 0} + call assert_equal(d, undotree("nosuchbuf")) + " clean up + bw nosuchbuf + + " Drop created windows + set ul& + new + only! +endfunc + +func Test_global_local_undolevels() + new one + set undolevels=5 + call FillBuffer() + " will only undo the last 5 changes, end up with 13 - (5 + 1) = 7 lines + earlier 10 + call assert_equal(5, &g:undolevels) + call assert_equal(-123456, &l:undolevels) + call assert_equal('7', getline('$')) + + new two + setlocal undolevels=2 + call FillBuffer() + " will only undo the last 2 changes, end up with 13 - (2 + 1) = 10 lines + earlier 10 + call assert_equal(5, &g:undolevels) + call assert_equal(2, &l:undolevels) + call assert_equal('10', getline('$')) + + setlocal ul=10 + call assert_equal(5, &g:undolevels) + call assert_equal(10, &l:undolevels) + + " Setting local value in "two" must not change local value in "one" + wincmd p + call assert_equal(5, &g:undolevels) + call assert_equal(-123456, &l:undolevels) + + new three + setglobal ul=50 + call assert_equal(50, &g:undolevels) + call assert_equal(-123456, &l:undolevels) + + " Resetting the local 'undolevels' value to use the global value + setlocal undolevels=5 + setlocal undolevels< + call assert_equal(-123456, &l:undolevels) + + " Drop created windows + set ul& + new + only! +endfunc + +func BackOne(expected) + call feedkeys('g-', 'xt') + call assert_equal(a:expected, getline(1)) +endfunc + +func Test_undo_del_chars() + throw 'Skipped: Nvim does not support test_settime()' + " Setup a buffer without creating undo entries + new + set ul=-1 + call setline(1, ['123-456']) + set ul=100 + 1 + call test_settime(100) + + " Delete three characters and undo with g- + call feedkeys('x', 'xt') + call feedkeys('x', 'xt') + call feedkeys('x', 'xt') + call assert_equal('-456', getline(1)) + call BackOne('3-456') + call BackOne('23-456') + call BackOne('123-456') + call assert_fails("BackOne('123-456')") + + :" Delete three other characters and go back in time with g- + call feedkeys('$x', 'xt') + call feedkeys('x', 'xt') + call feedkeys('x', 'xt') + call assert_equal('123-', getline(1)) + call test_settime(101) + + call BackOne('123-4') + call BackOne('123-45') + " skips '123-456' because it's older + call BackOne('-456') + call BackOne('3-456') + call BackOne('23-456') + call BackOne('123-456') + call assert_fails("BackOne('123-456')") + normal 10g+ + call assert_equal('123-', getline(1)) + + :" Jump two seconds and go some seconds forward and backward + call test_settime(103) + call feedkeys("Aa\<Esc>", 'xt') + call feedkeys("Ab\<Esc>", 'xt') + call feedkeys("Ac\<Esc>", 'xt') + call assert_equal('123-abc', getline(1)) + earlier 1s + call assert_equal('123-', getline(1)) + earlier 3s + call assert_equal('123-456', getline(1)) + later 1s + call assert_equal('123-', getline(1)) + later 1h + call assert_equal('123-abc', getline(1)) + + close! +endfunc + +func Test_undolist() + new + set ul=100 + + let a = execute('undolist') + call assert_equal("\nNothing to undo", a) + + " 1 leaf (2 changes). + call feedkeys('achange1', 'xt') + call feedkeys('achange2', 'xt') + let a = execute('undolist') + call assert_match("^\nnumber changes when *saved\n *2 *2 .*$", a) + + " 2 leaves. + call feedkeys('u', 'xt') + call feedkeys('achange3\<Esc>', 'xt') + let a = execute('undolist') + call assert_match("^\nnumber changes when *saved\n *2 *2 *.*\n *3 *2 .*$", a) + close! +endfunc + +func Test_U_command() + new + set ul=100 + call feedkeys("achange1\<Esc>", 'xt') + call feedkeys("achange2\<Esc>", 'xt') + norm! U + call assert_equal('', getline(1)) + norm! U + call assert_equal('change1change2', getline(1)) + close! +endfunc + +func Test_undojoin() + new + call feedkeys("Goaaaa\<Esc>", 'xt') + call feedkeys("obbbb\<Esc>", 'xt') + call assert_equal(['aaaa', 'bbbb'], getline(2, '$')) + call feedkeys("u", 'xt') + call assert_equal(['aaaa'], getline(2, '$')) + call feedkeys("obbbb\<Esc>", 'xt') + undojoin + " Note: next change must not be as if typed + call feedkeys("occcc\<Esc>", 'x') + call assert_equal(['aaaa', 'bbbb', 'cccc'], getline(2, '$')) + call feedkeys("u", 'xt') + call assert_equal(['aaaa'], getline(2, '$')) + bwipe! +endfunc + +func Test_undojoin_redo() + new + call setline(1, ['first line', 'second line']) + call feedkeys("ixx\<Esc>", 'xt') + call feedkeys(":undojoin | redo\<CR>", 'xt') + call assert_equal('xxfirst line', getline(1)) + call assert_equal('second line', getline(2)) + bwipe! +endfunc + +" undojoin not allowed after undo +func Test_undojoin_after_undo() + new + call feedkeys("ixx\<Esc>u", 'xt') + call assert_fails(':undojoin', 'E790:') + bwipe! +endfunc + +" undojoin is a noop when no change yet, or when 'undolevels' is negative +func Test_undojoin_noop() + new + call feedkeys(":undojoin\<CR>", 'xt') + call assert_equal([''], getline(1, '$')) + setlocal undolevels=-1 + call feedkeys("ixx\<Esc>u", 'xt') + call feedkeys(":undojoin\<CR>", 'xt') + call assert_equal(['xx'], getline(1, '$')) + bwipe! +endfunc + +func Test_undo_write() + call delete('Xtest') + split Xtest + call feedkeys("ione one one\<Esc>", 'xt') + w! + call feedkeys("otwo\<Esc>", 'xt') + call feedkeys("otwo\<Esc>", 'xt') + w + call feedkeys("othree\<Esc>", 'xt') + call assert_equal(['one one one', 'two', 'two', 'three'], getline(1, '$')) + earlier 1f + call assert_equal(['one one one', 'two', 'two'], getline(1, '$')) + earlier 1f + call assert_equal(['one one one'], getline(1, '$')) + earlier 1f + call assert_equal([''], getline(1, '$')) + later 1f + call assert_equal(['one one one'], getline(1, '$')) + later 1f + call assert_equal(['one one one', 'two', 'two'], getline(1, '$')) + later 1f + call assert_equal(['one one one', 'two', 'two', 'three'], getline(1, '$')) + + close! + call delete('Xtest') + bwipe! Xtest + + call assert_fails('earlier xyz', 'E475:') +endfunc + +func Test_insert_expr() + new + " calling setline() triggers undo sync + call feedkeys("oa\<Esc>", 'xt') + call feedkeys("ob\<Esc>", 'xt') + set ul=100 + call feedkeys("o1\<Esc>a2\<C-R>=setline('.','1234')\<CR>\<CR>\<Esc>", 'x') + call assert_equal(['a', 'b', '120', '34'], getline(2, '$')) + call feedkeys("u", 'x') + call assert_equal(['a', 'b', '12'], getline(2, '$')) + call feedkeys("u", 'x') + call assert_equal(['a', 'b'], getline(2, '$')) + + call feedkeys("oc\<Esc>", 'xt') + set ul=100 + call feedkeys("o1\<Esc>a2\<C-R>=setline('.','1234')\<CR>\<CR>\<Esc>", 'x') + call assert_equal(['a', 'b', 'c', '120', '34'], getline(2, '$')) + call feedkeys("u", 'x') + call assert_equal(['a', 'b', 'c', '12'], getline(2, '$')) + + call feedkeys("od\<Esc>", 'xt') + set ul=100 + call feedkeys("o1\<Esc>a2\<C-R>=string(123)\<CR>\<Esc>", 'x') + call assert_equal(['a', 'b', 'c', '12', 'd', '12123'], getline(2, '$')) + call feedkeys("u", 'x') + call assert_equal(['a', 'b', 'c', '12', 'd'], getline(2, '$')) + + close! +endfunc + +func Test_undofile_earlier() + throw 'Skipped: Nvim does not support test_settime()' + if has('win32') + " FIXME: This test is flaky on MS-Windows. + let g:test_is_flaky = 1 + endif + + " Issue #1254 + " create undofile with timestamps older than Vim startup time. + let t0 = localtime() - 43200 + call test_settime(t0) + new XfileEarlier + call feedkeys("ione\<Esc>", 'xt') + set ul=100 + call test_settime(t0 + 1) + call feedkeys("otwo\<Esc>", 'xt') + set ul=100 + call test_settime(t0 + 2) + call feedkeys("othree\<Esc>", 'xt') + set ul=100 + w + wundo Xundofile + bwipe! + " restore normal timestamps. + call test_settime(0) + new XfileEarlier + rundo Xundofile + earlier 1d + call assert_equal('', getline(1)) + bwipe! + call delete('XfileEarlier') + call delete('Xundofile') +endfunc + +func Test_wundo_errors() + new + call setline(1, 'hello') + call assert_fails('wundo! Xdoesnotexist/Xundofile', 'E828:') + bwipe! +endfunc + +" Check that reading a truncated undo file doesn't hang. +func Test_undofile_truncated() + new + call setline(1, 'hello') + set ul=100 + wundo Xundofile + let contents = readfile('Xundofile', 'B') + + " try several sizes + for size in range(20, 500, 33) + call writefile(contents[0:size], 'Xundofile') + call assert_fails('rundo Xundofile', 'E825:') + endfor + + bwipe! + call delete('Xundofile') +endfunc + +func Test_rundo_errors() + call assert_fails('rundo XfileDoesNotExist', 'E822:') + + call writefile(['abc'], 'Xundofile') + call assert_fails('rundo Xundofile', 'E823:') + + call delete('Xundofile') +endfunc + +func Test_undofile_next() + set undofile + new Xfoo.txt + execute "norm ix\<c-g>uy\<c-g>uz\<Esc>" + write + bwipe + + next Xfoo.txt + call assert_equal('xyz', getline(1)) + silent undo + call assert_equal('xy', getline(1)) + silent undo + call assert_equal('x', getline(1)) + bwipe! + + call delete('Xfoo.txt') + call delete('.Xfoo.txt.un~') + set undofile& +endfunc + +" Test for undo working properly when executing commands from a register. +" Also test this in an empty buffer. +func Test_cmd_in_reg_undo() + enew! + let @a = "Ox\<Esc>jAy\<Esc>kdd" + edit +/^$ test_undo.vim + normal @au + call assert_equal(0, &modified) + return + new + normal @au + call assert_equal(0, &modified) + only! + let @a = '' +endfunc + +" This used to cause an illegal memory access +func Test_undo_append() + new + call feedkeys("axx\<Esc>v", 'xt') + undo + norm o + quit +endfunc + +func Test_undo_0() + new + set ul=100 + normal i1 + undo + normal i2 + undo + normal i3 + + undo 0 + let d = undotree() + call assert_equal('', getline(1)) + call assert_equal(0, d.seq_cur) + + redo + let d = undotree() + call assert_equal('3', getline(1)) + call assert_equal(3, d.seq_cur) + + undo 2 + undo 0 + let d = undotree() + call assert_equal('', getline(1)) + call assert_equal(0, d.seq_cur) + + redo + let d = undotree() + call assert_equal('2', getline(1)) + call assert_equal(2, d.seq_cur) + + undo 1 + undo 0 + let d = undotree() + call assert_equal('', getline(1)) + call assert_equal(0, d.seq_cur) + + redo + let d = undotree() + call assert_equal('1', getline(1)) + call assert_equal(1, d.seq_cur) + + bwipe! +endfunc + +" undo or redo are noop if there is nothing to undo or redo +func Test_undo_redo_noop() + new + call assert_fails('undo 2', 'E830:') + + message clear + undo + let messages = split(execute('message'), "\n") + call assert_equal('Already at oldest change', messages[-1]) + + message clear + redo + let messages = split(execute('message'), "\n") + call assert_equal('Already at newest change', messages[-1]) + + bwipe! +endfunc + +func Test_redo_empty_line() + new + exe "norm\x16r\x160" + exe "norm." + bwipe! +endfunc + +funct Test_undofile() + " Test undofile() without setting 'undodir'. + if has('persistent_undo') + call assert_equal(fnamemodify('.Xundofoo.un~', ':p'), undofile('Xundofoo')) + else + call assert_equal('', undofile('Xundofoo')) + endif + call assert_equal('', undofile('')) + + " Test undofile() with 'undodir' set to to an existing directory. + call mkdir('Xundodir') + set undodir=Xundodir + let cwd = getcwd() + if has('win32') + " Replace windows drive such as C:... into C%... + let cwd = substitute(cwd, '^\([a-zA-Z]\):', '\1%', 'g') + endif + let cwd = substitute(cwd . '/Xundofoo', '/', '%', 'g') + if has('persistent_undo') + call assert_equal('Xundodir/' . cwd, undofile('Xundofoo')) + else + call assert_equal('', undofile('Xundofoo')) + endif + call assert_equal('', undofile('')) + call delete('Xundodir', 'd') + + " Test undofile() with 'undodir' set to a non-existing directory. + " call assert_equal('', 'Xundofoo'->undofile()) + + if isdirectory('/tmp') + set undodir=/tmp + if has('osx') + call assert_equal('/tmp/%private%tmp%file', undofile('///tmp/file')) + else + call assert_equal('/tmp/%tmp%file', undofile('///tmp/file')) + endif + endif + + set undodir& +endfunc + +" Tests for the undo file +" Explicitly break changes up in undo-able pieces by setting 'undolevels'. +func Test_undofile_2() + set undolevels=100 undofile + edit Xtestfile + call append(0, 'this is one line') + call cursor(1, 1) + + " first a simple one-line change. + set undolevels=100 + s/one/ONE/ + set undolevels=100 + write + bwipe! + edit Xtestfile + undo + call assert_equal('this is one line', getline(1)) + + " change in original file fails check + set noundofile + edit! Xtestfile + s/line/Line/ + write + set undofile + bwipe! + edit Xtestfile + undo + call assert_equal('this is ONE Line', getline(1)) + + " add 10 lines, delete 6 lines, undo 3 + set undofile + call setbufline('%', 1, ['one', 'two', 'three', 'four', 'five', 'six', + \ 'seven', 'eight', 'nine', 'ten']) + set undolevels=100 + normal 3Gdd + set undolevels=100 + normal dd + set undolevels=100 + normal dd + set undolevels=100 + normal dd + set undolevels=100 + normal dd + set undolevels=100 + normal dd + set undolevels=100 + write + bwipe! + edit Xtestfile + normal uuu + call assert_equal(['one', 'two', 'six', 'seven', 'eight', 'nine', 'ten'], + \ getline(1, '$')) + + " Test that reading the undofiles when setting undofile works + set noundofile undolevels=0 + exe "normal i\n" + undo + edit! Xtestfile + set undofile undolevels=100 + normal uuuuuu + call assert_equal(['one', 'two', 'three', 'four', 'five', 'six', 'seven', + \ 'eight', 'nine', 'ten'], getline(1, '$')) + + bwipe! + call delete('Xtestfile') + let ufile = has('vms') ? '_un_Xtestfile' : '.Xtestfile.un~' + call delete(ufile) + set undofile& undolevels& +endfunc + +" Test 'undofile' using a file encrypted with 'zip' crypt method +func Test_undofile_cryptmethod_zip() + throw 'skipped: Nvim does not support cryptmethod' + edit Xtestfile + set undofile cryptmethod=zip + call append(0, ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']) + call cursor(5, 1) + + set undolevels=100 + normal kkkdd + set undolevels=100 + normal dd + set undolevels=100 + normal dd + set undolevels=100 + " encrypt the file using key 'foobar' + call feedkeys("foobar\nfoobar\n") + X + write! + bwipe! + + call feedkeys("foobar\n") + edit Xtestfile + set key= + normal uu + call assert_equal(['monday', 'wednesday', 'thursday', 'friday', ''], + \ getline(1, '$')) + + bwipe! + call delete('Xtestfile') + let ufile = has('vms') ? '_un_Xtestfile' : '.Xtestfile.un~' + call delete(ufile) + set undofile& undolevels& cryptmethod& +endfunc + +" Test 'undofile' using a file encrypted with 'blowfish' crypt method +func Test_undofile_cryptmethod_blowfish() + throw 'skipped: Nvim does not support cryptmethod' + edit Xtestfile + set undofile cryptmethod=blowfish + call append(0, ['jan', 'feb', 'mar', 'apr', 'jun']) + call cursor(5, 1) + + set undolevels=100 + exe 'normal kk0ifoo ' + set undolevels=100 + normal dd + set undolevels=100 + exe 'normal ibar ' + set undolevels=100 + " encrypt the file using key 'foobar' + call feedkeys("foobar\nfoobar\n") + X + write! + bwipe! + + call feedkeys("foobar\n") + edit Xtestfile + set key= + call search('bar') + call assert_equal('bar apr', getline('.')) + undo + call assert_equal('apr', getline('.')) + undo + call assert_equal('foo mar', getline('.')) + undo + call assert_equal('mar', getline('.')) + + bwipe! + call delete('Xtestfile') + let ufile = has('vms') ? '_un_Xtestfile' : '.Xtestfile.un~' + call delete(ufile) + set undofile& undolevels& cryptmethod& +endfunc + +" Test 'undofile' using a file encrypted with 'blowfish2' crypt method +func Test_undofile_cryptmethod_blowfish2() + throw 'skipped: Nvim does not support cryptmethod' + edit Xtestfile + set undofile cryptmethod=blowfish2 + call append(0, ['jan', 'feb', 'mar', 'apr', 'jun']) + call cursor(5, 1) + + set undolevels=100 + exe 'normal kk0ifoo ' + set undolevels=100 + normal dd + set undolevels=100 + exe 'normal ibar ' + set undolevels=100 + " encrypt the file using key 'foo2bar' + call feedkeys("foo2bar\nfoo2bar\n") + X + write! + bwipe! + + call feedkeys("foo2bar\n") + edit Xtestfile + set key= + call search('bar') + call assert_equal('bar apr', getline('.')) + normal u + call assert_equal('apr', getline('.')) + normal u + call assert_equal('foo mar', getline('.')) + normal u + call assert_equal('mar', getline('.')) + + bwipe! + call delete('Xtestfile') + let ufile = has('vms') ? '_un_Xtestfile' : '.Xtestfile.un~' + call delete(ufile) + set undofile& undolevels& cryptmethod& +endfunc + +" Test for redoing with incrementing numbered registers +func Test_redo_repeat_numbered_register() + new + for [i, v] in [[1, 'one'], [2, 'two'], [3, 'three'], + \ [4, 'four'], [5, 'five'], [6, 'six'], + \ [7, 'seven'], [8, 'eight'], [9, 'nine']] + exe 'let @' .. i .. '="' .. v .. '\n"' + endfor + call feedkeys('"1p.........', 'xt') + call assert_equal(['', 'one', 'two', 'three', 'four', 'five', 'six', + \ 'seven', 'eight', 'nine', 'nine'], getline(1, '$')) + bwipe! +endfunc + +" Test for redo in insert mode using CTRL-O with multibyte characters +func Test_redo_multibyte_in_insert_mode() + new + call feedkeys("a\<C-K>ft", 'xt') + call feedkeys("uiHe\<C-O>.llo", 'xt') + call assert_equal("He\ufb05llo", getline(1)) + bwipe! +endfunc + +func Test_undo_mark() + new + " The undo is applied to the only line. + call setline(1, 'hello') + call feedkeys("ggyiw$p", 'xt') + undo + call assert_equal([0, 1, 1, 0], getpos("'[")) + call assert_equal([0, 1, 1, 0], getpos("']")) + " The undo removes the last line. + call feedkeys("Goaaaa\<Esc>", 'xt') + call feedkeys("obbbb\<Esc>", 'xt') + undo + call assert_equal([0, 2, 1, 0], getpos("'[")) + call assert_equal([0, 2, 1, 0], getpos("']")) + bwipe! +endfunc + +func Test_undo_after_write() + " use a terminal to make undo work like when text is typed + CheckRunVimInTerminal + + let lines =<< trim END + edit Xtestfile.txt + set undolevels=100 undofile + imap . <Cmd>write<CR> + write + END + call writefile(lines, 'Xtest_undo_after_write', 'D') + let buf = RunVimInTerminal('-S Xtest_undo_after_write', #{rows: 6}) + + call term_sendkeys(buf, "Otest.\<CR>boo!!!\<Esc>") + sleep 100m + call term_sendkeys(buf, "u") + call VerifyScreenDump(buf, 'Test_undo_after_write_1', {}) + + call term_sendkeys(buf, "u") + call VerifyScreenDump(buf, 'Test_undo_after_write_2', {}) + + call StopVimInTerminal(buf) + call delete('Xtestfile.txt') + call delete('.Xtestfile.txt.un~') +endfunc + +func Test_undo_range_normal() + new + call setline(1, ['asa', 'bsb']) + let &l:undolevels = &l:undolevels + %normal dfs + call assert_equal(['a', 'b'], getline(1, '$')) + undo + call assert_equal(['asa', 'bsb'], getline(1, '$')) + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_unlet.vim b/test/old/testdir/test_unlet.vim new file mode 100644 index 0000000000..4779d17906 --- /dev/null +++ b/test/old/testdir/test_unlet.vim @@ -0,0 +1,67 @@ +" Tests for :unlet + +func Test_read_only() + " these caused a crash + call assert_fails('unlet v:count', 'E795:') + call assert_fails('unlet v:errmsg', 'E795:') +endfunc + +func Test_existing() + let does_exist = 1 + call assert_true(exists('does_exist')) + unlet does_exist + call assert_false(exists('does_exist')) +endfunc + +func Test_not_existing() + unlet! does_not_exist + call assert_fails('unlet does_not_exist', 'E108:') +endfunc + +func Test_unlet_fails() + call assert_fails('unlet v:["count"]', 'E46:') + call assert_fails('unlet $', 'E475:') + let v = {} + call assert_fails('unlet v[:]', 'E719:') + let l = [] + call assert_fails("unlet l['k'", 'E111:') + let d = {'k' : 1} + call assert_fails("unlet d.k2", 'E716:') + call assert_fails("unlet {a};", 'E488:') +endfunc + +func Test_unlet_env() + let envcmd = has('win32') ? 'set' : 'env' + + let $FOOBAR = 'test' + let found = 0 + for kv in split(system(envcmd), "\r*\n") + if kv == 'FOOBAR=test' + let found = 1 + endif + endfor + call assert_equal(1, found) + + unlet $FOOBAR + let found = 0 + for kv in split(system(envcmd), "\r*\n") + if kv == 'FOOBAR=test' + let found = 1 + endif + endfor + call assert_equal(0, found) + + unlet $MUST_NOT_BE_AN_ERROR +endfunc + +func Test_unlet_complete() + let g:FOOBAR = 1 + call feedkeys(":unlet g:FOO\t\n", 'tx') + call assert_true(!exists('g:FOOBAR')) + + let $FOOBAR = 1 + call feedkeys(":unlet $FOO\t\n", 'tx') + call assert_true(!exists('$FOOBAR') || empty($FOOBAR)) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_user_func.vim b/test/old/testdir/test_user_func.vim new file mode 100644 index 0000000000..fc7dcd62b8 --- /dev/null +++ b/test/old/testdir/test_user_func.vim @@ -0,0 +1,894 @@ +" Test for user functions. +" Also test an <expr> mapping calling a function. +" Also test that a builtin function cannot be replaced. +" Also test for regression when calling arbitrary expression. + +source check.vim +source shared.vim +source vim9.vim + +func Table(title, ...) + let ret = a:title + let idx = 1 + while idx <= a:0 + exe "let ret = ret . a:" . idx + let idx = idx + 1 + endwhile + return ret +endfunc + +func Compute(n1, n2, divname) + if a:n2 == 0 + return "fail" + endif + exe "let g:" . a:divname . " = ". a:n1 / a:n2 + return "ok" +endfunc + +func Expr1() + silent! normal! v + return "111" +endfunc + +func Expr2() + call search('XX', 'b') + return "222" +endfunc + +func ListItem() + let g:counter += 1 + return g:counter . '. ' +endfunc + +func ListReset() + let g:counter = 0 + return '' +endfunc + +func FuncWithRef(a) + unlet g:FuncRef + return a:a +endfunc + +func Test_user_func() + let g:FuncRef = function("FuncWithRef") + let g:counter = 0 + inoremap <expr> ( ListItem() + inoremap <expr> [ ListReset() + imap <expr> + Expr1() + imap <expr> * Expr2() + let g:retval = "nop" + + call assert_equal('xxx4asdf', Table("xxx", 4, "asdf")) + call assert_equal('fail', Compute(45, 0, "retval")) + call assert_equal('nop', g:retval) + call assert_equal('ok', Compute(45, 5, "retval")) + call assert_equal(9, g:retval) + call assert_equal(333, g:FuncRef(333)) + + let g:retval = "nop" + call assert_equal('xxx4asdf', "xxx"->Table(4, "asdf")) + call assert_equal('fail', 45->Compute(0, "retval")) + call assert_equal('nop', g:retval) + call assert_equal('ok', 45->Compute(5, "retval")) + call assert_equal(9, g:retval) + " call assert_equal(333, 333->g:FuncRef()) + + enew + + normal oXX+-XX + call assert_equal('XX111-XX', getline('.')) + normal o---*--- + call assert_equal('---222---', getline('.')) + normal o(one + call assert_equal('1. one', getline('.')) + normal o(two + call assert_equal('2. two', getline('.')) + normal o[(one again + call assert_equal('1. one again', getline('.')) + + " Try to overwrite a function in the global (g:) scope + call assert_equal(3, max([1, 2, 3])) + call assert_fails("call extend(g:, {'max': function('min')})", 'E704') + call assert_equal(3, max([1, 2, 3])) + + " Try to overwrite an user defined function with a function reference + call assert_fails("let Expr1 = function('min')", 'E705:') + + " Regression: the first line below used to throw ?E110: Missing ')'? + " Second is here just to prove that this line is correct when not skipping + " rhs of &&. + call assert_equal(0, (0 && (function('tr'))(1, 2, 3))) + call assert_equal(1, (1 && (function('tr'))(1, 2, 3))) + + delfunc Table + delfunc Compute + delfunc Expr1 + delfunc Expr2 + delfunc ListItem + delfunc ListReset + unlet g:retval g:counter + enew! +endfunc + +func Log(val, base = 10) + return log(a:val) / log(a:base) +endfunc + +func Args(mandatory, optional = v:null, ...) + return deepcopy(a:) +endfunc + +func Args2(a = 1, b = 2, c = 3) + return deepcopy(a:) +endfunc + +func MakeBadFunc() + func s:fcn(a, b=1, c) + endfunc +endfunc + +func Test_default_arg() + if has('float') + call assert_equal(1.0, Log(10)) + call assert_equal(log(10), Log(10, exp(1))) + call assert_fails("call Log(1,2,3)", 'E118') + endif + + let res = Args(1) + call assert_equal(res.mandatory, 1) + call assert_equal(res.optional, v:null) + call assert_equal(res['0'], 0) + + let res = Args(1,2) + call assert_equal(res.mandatory, 1) + call assert_equal(res.optional, 2) + call assert_equal(res['0'], 0) + + let res = Args(1,2,3) + call assert_equal(res.mandatory, 1) + call assert_equal(res.optional, 2) + call assert_equal(res['0'], 1) + + call assert_fails("call MakeBadFunc()", 'E989:') + call assert_fails("fu F(a=1 ,) | endf", 'E1068:') + + " Since neovim does not have v:none, the ability to use the default + " argument with the intermediate argument set to v:none has been omitted. + " Therefore, this test is not performed. + " let d = Args2(7, v:none, 9) + " call assert_equal([7, 2, 9], [d.a, d.b, d.c]) + + call assert_equal("\n" + \ .. " function Args2(a = 1, b = 2, c = 3)\n" + \ .. "1 return deepcopy(a:)\n" + \ .. " endfunction", + \ execute('func Args2')) + + " Error in default argument expression + let l =<< trim END + func F1(x = y) + return a:x * 2 + endfunc + echo F1() + END + let @a = l->join("\n") + call assert_fails("exe @a", 'E121:') +endfunc + +func s:addFoo(lead) + return a:lead .. 'foo' +endfunc + +func Test_user_method() + eval 'bar'->s:addFoo()->assert_equal('barfoo') +endfunc + +func Test_failed_call_in_try() + try | call UnknownFunc() | catch | endtry +endfunc + +" Test for listing user-defined functions +func Test_function_list() + call assert_fails("function Xabc", 'E123:') +endfunc + +" Test for <sfile>, <slnum> in a function +func Test_sfile_in_function() + func Xfunc() + call assert_match('..Test_sfile_in_function\[5]..Xfunc', expand('<sfile>')) + call assert_equal('2', expand('<slnum>')) + endfunc + call Xfunc() + delfunc Xfunc +endfunc + +" Test trailing text after :endfunction {{{1 +func Test_endfunction_trailing() + call assert_false(exists('*Xtest')) + + exe "func Xtest()\necho 'hello'\nendfunc\nlet done = 'yes'" + call assert_true(exists('*Xtest')) + call assert_equal('yes', done) + delfunc Xtest + unlet done + + exe "func Xtest()\necho 'hello'\nendfunc|let done = 'yes'" + call assert_true(exists('*Xtest')) + call assert_equal('yes', done) + delfunc Xtest + unlet done + + " trailing line break + exe "func Xtest()\necho 'hello'\nendfunc\n" + call assert_true(exists('*Xtest')) + delfunc Xtest + + set verbose=1 + exe "func Xtest()\necho 'hello'\nendfunc \" garbage" + call assert_notmatch('W22:', split(execute('1messages'), "\n")[0]) + call assert_true(exists('*Xtest')) + delfunc Xtest + + exe "func Xtest()\necho 'hello'\nendfunc garbage" + call assert_match('W22:', split(execute('1messages'), "\n")[0]) + call assert_true(exists('*Xtest')) + delfunc Xtest + set verbose=0 + + func Xtest(a1, a2) + echo a:a1 .. a:a2 + endfunc + set verbose=15 + redir @a + call Xtest(123, repeat('x', 100)) + redir END + call assert_match('calling Xtest(123, ''xxxxxxx.*x\.\.\.x.*xxxx'')', getreg('a')) + delfunc Xtest + set verbose=0 + + function Foo() + echo 'hello' + endfunction | echo 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + delfunc Foo +endfunc + +func Test_delfunction_force() + delfunc! Xtest + delfunc! Xtest + func Xtest() + echo 'nothing' + endfunc + delfunc! Xtest + delfunc! Xtest + + " Try deleting the current function + call assert_fails('delfunc Test_delfunction_force', 'E131:') +endfunc + +func Test_function_defined_line() + CheckNotGui + + let lines =<< trim [CODE] + " F1 + func F1() + " F2 + func F2() + " + " + " + return + endfunc + " F3 + execute "func F3()\n\n\n\nreturn\nendfunc" + " F4 + execute "func F4()\n + \\n + \\n + \\n + \return\n + \endfunc" + endfunc + " F5 + execute "func F5()\n\n\n\nreturn\nendfunc" + " F6 + execute "func F6()\n + \\n + \\n + \\n + \return\n + \endfunc" + call F1() + verbose func F1 + verbose func F2 + verbose func F3 + verbose func F4 + verbose func F5 + verbose func F6 + qall! + [CODE] + + call writefile(lines, 'Xtest.vim') + let res = system(GetVimCommandClean() .. ' -es -X -S Xtest.vim') + call assert_equal(0, v:shell_error) + + let m = matchstr(res, 'function F1()[^[:print:]]*[[:print:]]*') + call assert_match(' line 2$', m) + + let m = matchstr(res, 'function F2()[^[:print:]]*[[:print:]]*') + call assert_match(' line 4$', m) + + let m = matchstr(res, 'function F3()[^[:print:]]*[[:print:]]*') + call assert_match(' line 11$', m) + + let m = matchstr(res, 'function F4()[^[:print:]]*[[:print:]]*') + call assert_match(' line 13$', m) + + let m = matchstr(res, 'function F5()[^[:print:]]*[[:print:]]*') + call assert_match(' line 21$', m) + + let m = matchstr(res, 'function F6()[^[:print:]]*[[:print:]]*') + call assert_match(' line 23$', m) + + call delete('Xtest.vim') +endfunc + +" Test for defining a function reference in the global scope +func Test_add_funcref_to_global_scope() + let x = g: + let caught_E862 = 0 + try + func x.Xfunc() + return 1 + endfunc + catch /E862:/ + let caught_E862 = 1 + endtry + call assert_equal(1, caught_E862) +endfunc + +func Test_funccall_garbage_collect() + func Func(x, ...) + call add(a:x, a:000) + endfunc + call Func([], []) + " Must not crash cause by invalid freeing + call test_garbagecollect_now() + call assert_true(v:true) + delfunc Func +endfunc + +" Test for script-local function +func <SID>DoLast() + call append(line('$'), "last line") +endfunc + +func s:DoNothing() + call append(line('$'), "nothing line") +endfunc + +func Test_script_local_func() + set nocp nomore viminfo+=nviminfo + new + nnoremap <buffer> _x :call <SID>DoNothing()<bar>call <SID>DoLast()<bar>delfunc <SID>DoNothing<bar>delfunc <SID>DoLast<cr> + + normal _x + call assert_equal('nothing line', getline(2)) + call assert_equal('last line', getline(3)) + close! + + " Try to call a script local function in global scope + let lines =<< trim [CODE] + :call assert_fails('call s:Xfunc()', 'E81:') + :call assert_fails('let x = call("<SID>Xfunc", [])', 'E120:') + :call writefile(v:errors, 'Xresult') + :qall + + [CODE] + call writefile(lines, 'Xscript') + if RunVim([], [], '-s Xscript') + call assert_equal([], readfile('Xresult')) + endif + call delete('Xresult') + call delete('Xscript') +endfunc + +" Test for errors in defining new functions +func Test_func_def_error() + call assert_fails('func Xfunc abc ()', 'E124:') + call assert_fails('func Xfunc(', 'E125:') + call assert_fails('func xfunc()', 'E128:') + + " Try to redefine a function that is in use + let caught_E127 = 0 + try + func! Test_func_def_error() + endfunc + catch /E127:/ + let caught_E127 = 1 + endtry + call assert_equal(1, caught_E127) + + " Try to define a function in a dict twice + let d = {} + let lines =<< trim END + func d.F1() + return 1 + endfunc + END + let l = join(lines, "\n") . "\n" + exe l + call assert_fails('exe l', 'E717:') + + " Define an autoload function with an incorrect file name + call writefile(['func foo#Bar()', 'return 1', 'endfunc'], 'Xscript') + call assert_fails('source Xscript', 'E746:') + call delete('Xscript') + + " Try to list functions using an invalid search pattern + call assert_fails('function /\%(/', 'E53:') +endfunc + +" Test for deleting a function +func Test_del_func() + call assert_fails('delfunction Xabc', 'E130:') + let d = {'a' : 10} + call assert_fails('delfunc d.a', 'E718:') + func d.fn() + return 1 + endfunc + + " cannot delete the dict function by number + let nr = substitute(execute('echo d'), '.*function(''\(\d\+\)'').*', '\1', '') + call assert_fails('delfunction g:' .. nr, 'E475: Invalid argument: g:') + + delfunc d.fn + call assert_equal({'a' : 10}, d) +endfunc + +" Test for calling return outside of a function +func Test_return_outside_func() + call writefile(['return 10'], 'Xscript') + call assert_fails('source Xscript', 'E133:') + call delete('Xscript') +endfunc + +" Test for errors in calling a function +func Test_func_arg_error() + " Too many arguments + call assert_fails("call call('min', range(1,20))", 'E118:') + call assert_fails("call call('min', range(1,21))", 'E699:') + call assert_fails('echo min(0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,0,1)', + \ 'E740:') + + " Missing dict argument + func Xfunc() dict + return 1 + endfunc + call assert_fails('call Xfunc()', 'E725:') + delfunc Xfunc +endfunc + +func Test_func_dict() + let mydict = {'a': 'b'} + function mydict.somefunc() dict + return len(self) + endfunc + + call assert_equal("{'a': 'b', 'somefunc': function('3')}", string(mydict)) + call assert_equal(2, mydict.somefunc()) + call assert_match("^\n function \\d\\\+() dict" + \ .. "\n1 return len(self)" + \ .. "\n endfunction$", execute('func mydict.somefunc')) + call assert_fails('call mydict.nonexist()', 'E716:') +endfunc + +func Test_func_range() + new + call setline(1, range(1, 8)) + func FuncRange() range + echo a:firstline + echo a:lastline + endfunc + 3 + call assert_equal("\n3\n3", execute('call FuncRange()')) + call assert_equal("\n4\n6", execute('4,6 call FuncRange()')) + call assert_equal("\n function FuncRange() range" + \ .. "\n1 echo a:firstline" + \ .. "\n2 echo a:lastline" + \ .. "\n endfunction", + \ execute('function FuncRange')) + + bwipe! +endfunc + +" Test for memory allocation failure when defining a new function +func Test_funcdef_alloc_failure() + CheckFunction test_alloc_fail + new + let lines =<< trim END + func Xtestfunc() + return 321 + endfunc + END + call setline(1, lines) + call test_alloc_fail(GetAllocId('get_func'), 0, 0) + call assert_fails('source', 'E342:') + call assert_false(exists('*Xtestfunc')) + call assert_fails('delfunc Xtestfunc', 'E117:') + %d _ + let lines =<< trim END + def g:Xvim9func(): number + return 456 + enddef + END + call setline(1, lines) + call test_alloc_fail(GetAllocId('get_func'), 0, 0) + call assert_fails('source', 'E342:') + call assert_false(exists('*Xvim9func')) + "call test_alloc_fail(GetAllocId('get_func'), 0, 0) + "call assert_fails('source', 'E342:') + "call assert_false(exists('*Xtestfunc')) + "call assert_fails('delfunc Xtestfunc', 'E117:') + bw! +endfunc + +func AddDefer(arg1, ...) + call extend(g:deferred, [a:arg1]) + if a:0 == 1 + call extend(g:deferred, [a:1]) + endif +endfunc + +func WithDeferTwo() + call extend(g:deferred, ['in Two']) + for nr in range(3) + defer AddDefer('Two' .. nr) + endfor + call extend(g:deferred, ['end Two']) +endfunc + +func WithDeferOne() + call extend(g:deferred, ['in One']) + call writefile(['text'], 'Xfuncdefer') + defer delete('Xfuncdefer') + defer AddDefer('One') + call WithDeferTwo() + call extend(g:deferred, ['end One']) +endfunc + +func WithPartialDefer() + call extend(g:deferred, ['in Partial']) + let Part = funcref('AddDefer', ['arg1']) + defer Part("arg2") + call extend(g:deferred, ['end Partial']) +endfunc + +func Test_defer() + let g:deferred = [] + call WithDeferOne() + + call assert_equal(['in One', 'in Two', 'end Two', 'Two2', 'Two1', 'Two0', 'end One', 'One'], g:deferred) + unlet g:deferred + + call assert_equal('', glob('Xfuncdefer')) + + call assert_fails('defer delete("Xfuncdefer")->Another()', 'E488:') + call assert_fails('defer delete("Xfuncdefer").member', 'E488:') + + let g:deferred = [] + call WithPartialDefer() + call assert_equal(['in Partial', 'end Partial', 'arg1', 'arg2'], g:deferred) + unlet g:deferred + + let Part = funcref('AddDefer', ['arg1'], {}) + call assert_fails('defer Part("arg2")', 'E1300:') +endfunc + +func DeferLevelTwo() + call writefile(['text'], 'XDeleteTwo', 'D') + throw 'someerror' +endfunc + +" def DeferLevelOne() +func DeferLevelOne() + call writefile(['text'], 'XDeleteOne', 'D') + call g:DeferLevelTwo() +" enddef +endfunc + +func Test_defer_throw() + let caught = 'no' + try + call DeferLevelOne() + catch /someerror/ + let caught = 'yes' + endtry + call assert_equal('yes', caught) + call assert_false(filereadable('XDeleteOne')) + call assert_false(filereadable('XDeleteTwo')) +endfunc + +func Test_defer_quitall_func() + let lines =<< trim END + func DeferLevelTwo() + call writefile(['text'], 'XQuitallFuncTwo', 'D') + call writefile(['quit'], 'XQuitallFuncThree', 'a') + qa! + endfunc + + func DeferLevelOne() + call writefile(['text'], 'XQuitalFunclOne', 'D') + defer DeferLevelTwo() + endfunc + + call DeferLevelOne() + END + call writefile(lines, 'XdeferQuitallFunc', 'D') + call system(GetVimCommand() .. ' -X -S XdeferQuitallFunc') + call assert_equal(0, v:shell_error) + call assert_false(filereadable('XQuitallFuncOne')) + call assert_false(filereadable('XQuitallFuncTwo')) + call assert_equal(['quit'], readfile('XQuitallFuncThree')) + + call delete('XQuitallFuncThree') +endfunc + +func Test_defer_quitall_def() + throw 'Skipped: Vim9 script is N/A' + let lines =<< trim END + vim9script + def DeferLevelTwo() + call writefile(['text'], 'XQuitallDefTwo', 'D') + call writefile(['quit'], 'XQuitallDefThree', 'a') + qa! + enddef + + def DeferLevelOne() + call writefile(['text'], 'XQuitallDefOne', 'D') + defer DeferLevelTwo() + enddef + + DeferLevelOne() + END + call writefile(lines, 'XdeferQuitallDef', 'D') + call system(GetVimCommand() .. ' -X -S XdeferQuitallDef') + call assert_equal(0, v:shell_error) + call assert_false(filereadable('XQuitallDefOne')) + call assert_false(filereadable('XQuitallDefTwo')) + call assert_equal(['quit'], readfile('XQuitallDefThree')) + + call delete('XQuitallDefThree') +endfunc + +func Test_defer_quitall_autocmd() + let lines =<< trim END + func DeferLevelFive() + defer writefile(['5'], 'XQuitallAutocmd', 'a') + qa! + endfunc + + autocmd User DeferAutocmdFive call DeferLevelFive() + + " def DeferLevelFour() + func DeferLevelFour() + defer writefile(['4'], 'XQuitallAutocmd', 'a') + doautocmd User DeferAutocmdFive + " enddef + endfunc + + func DeferLevelThree() + defer writefile(['3'], 'XQuitallAutocmd', 'a') + call DeferLevelFour() + endfunc + + autocmd User DeferAutocmdThree ++nested call DeferLevelThree() + + " def DeferLevelTwo() + func DeferLevelTwo() + defer writefile(['2'], 'XQuitallAutocmd', 'a') + doautocmd User DeferAutocmdThree + " enddef + endfunc + + func DeferLevelOne() + defer writefile(['1'], 'XQuitallAutocmd', 'a') + call DeferLevelTwo() + endfunc + + autocmd User DeferAutocmdOne ++nested call DeferLevelOne() + + doautocmd User DeferAutocmdOne + END + call writefile(lines, 'XdeferQuitallAutocmd', 'D') + call system(GetVimCommand() .. ' -X -S XdeferQuitallAutocmd') + call assert_equal(0, v:shell_error) + call assert_equal(['5', '4', '3', '2', '1'], readfile('XQuitallAutocmd')) + + call delete('XQuitallAutocmd') +endfunc + +func Test_defer_quitall_in_expr_func() + throw 'Skipped: Vim9 script is N/A' + let lines =<< trim END + def DefIndex(idx: number, val: string): bool + call writefile([idx .. ': ' .. val], 'Xentry' .. idx, 'D') + if val == 'b' + qa! + endif + return val == 'c' + enddef + + def Test_defer_in_funcref() + assert_equal(2, indexof(['a', 'b', 'c'], funcref('g:DefIndex'))) + enddef + call Test_defer_in_funcref() + END + call writefile(lines, 'XdeferQuitallExpr', 'D') + call system(GetVimCommand() .. ' -X -S XdeferQuitallExpr') + call assert_equal(0, v:shell_error) + call assert_false(filereadable('Xentry0')) + call assert_false(filereadable('Xentry1')) + call assert_false(filereadable('Xentry2')) +endfunc + +func FuncIndex(idx, val) + call writefile([a:idx .. ': ' .. a:val], 'Xentry' .. a:idx, 'D') + return a:val == 'c' +endfunc + +func Test_defer_wrong_arguments() + call assert_fails('defer delete()', 'E119:') + call assert_fails('defer FuncIndex(1)', 'E119:') + call assert_fails('defer delete(1, 2, 3)', 'E118:') + call assert_fails('defer FuncIndex(1, 2, 3)', 'E118:') + + throw 'Skipped: Vim9 script is N/A' + let lines =<< trim END + def DeferFunc0() + defer delete() + enddef + defcompile + END + call v9.CheckScriptFailure(lines, 'E119:') + let lines =<< trim END + def DeferFunc3() + defer delete(1, 2, 3) + enddef + defcompile + END + call v9.CheckScriptFailure(lines, 'E118:') + let lines =<< trim END + def DeferFunc2() + defer delete(1, 2) + enddef + defcompile + END + call v9.CheckScriptFailure(lines, 'E1013: Argument 1: type mismatch, expected string but got number') + + def g:FuncOneArg(arg: string) + echo arg + enddef + + let lines =<< trim END + def DeferUserFunc0() + defer g:FuncOneArg() + enddef + defcompile + END + call v9.CheckScriptFailure(lines, 'E119:') + let lines =<< trim END + def DeferUserFunc2() + defer g:FuncOneArg(1, 2) + enddef + defcompile + END + call v9.CheckScriptFailure(lines, 'E118:') + let lines =<< trim END + def DeferUserFunc1() + defer g:FuncOneArg(1) + enddef + defcompile + END + call v9.CheckScriptFailure(lines, 'E1013: Argument 1: type mismatch, expected string but got number') +endfunc + +" Test for calling a deferred function after an exception +func Test_defer_after_exception() + let g:callTrace = [] + func Bar() + let g:callTrace += [1] + throw 'InnerException' + endfunc + + func Defer() + let g:callTrace += [2] + let g:callTrace += [3] + try + call Bar() + catch /InnerException/ + let g:callTrace += [4] + endtry + let g:callTrace += [5] + let g:callTrace += [6] + endfunc + + func Foo() + defer Defer() + throw "TestException" + endfunc + + try + call Foo() + catch /TestException/ + let g:callTrace += [7] + endtry + call assert_equal([2, 3, 1, 4, 5, 6, 7], g:callTrace) + + delfunc Defer + delfunc Foo + delfunc Bar + unlet g:callTrace +endfunc + +" Test for multiple deferred function which throw exceptions. +" Exceptions thrown by deferred functions should result in error messages but +" not propagated into the calling functions. +func Test_multidefer_with_exception() + let g:callTrace = [] + func Except() + let g:callTrace += [1] + throw 'InnerException' + let g:callTrace += [2] + endfunc + + func FirstDefer() + let g:callTrace += [3] + let g:callTrace += [4] + endfunc + + func SecondDeferWithExcept() + let g:callTrace += [5] + call Except() + let g:callTrace += [6] + endfunc + + func ThirdDefer() + let g:callTrace += [7] + let g:callTrace += [8] + endfunc + + func Foo() + let g:callTrace += [9] + defer FirstDefer() + defer SecondDeferWithExcept() + defer ThirdDefer() + let g:callTrace += [10] + endfunc + + let v:errmsg = '' + try + let g:callTrace += [11] + call Foo() + let g:callTrace += [12] + catch /TestException/ + let g:callTrace += [13] + catch + let g:callTrace += [14] + finally + let g:callTrace += [15] + endtry + let g:callTrace += [16] + + call assert_equal('E605: Exception not caught: InnerException', v:errmsg) + call assert_equal([11, 9, 10, 7, 8, 5, 1, 3, 4, 12, 15, 16], g:callTrace) + + unlet g:callTrace + delfunc Except + delfunc FirstDefer + delfunc SecondDeferWithExcept + delfunc ThirdDefer + delfunc Foo +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_usercommands.vim b/test/old/testdir/test_usercommands.vim new file mode 100644 index 0000000000..e22f57b6f1 --- /dev/null +++ b/test/old/testdir/test_usercommands.vim @@ -0,0 +1,759 @@ +" Tests for user defined commands + +" Test for <mods> in user defined commands +function Test_cmdmods() + let g:mods = '' + + command! -nargs=* MyCmd let g:mods = '<mods>' + + MyCmd + call assert_equal('', g:mods) + aboveleft MyCmd + call assert_equal('aboveleft', g:mods) + abo MyCmd + call assert_equal('aboveleft', g:mods) + belowright MyCmd + call assert_equal('belowright', g:mods) + bel MyCmd + call assert_equal('belowright', g:mods) + botright MyCmd + call assert_equal('botright', g:mods) + bo MyCmd + call assert_equal('botright', g:mods) + browse MyCmd + call assert_equal('browse', g:mods) + bro MyCmd + call assert_equal('browse', g:mods) + confirm MyCmd + call assert_equal('confirm', g:mods) + conf MyCmd + call assert_equal('confirm', g:mods) + hide MyCmd + call assert_equal('hide', g:mods) + hid MyCmd + call assert_equal('hide', g:mods) + keepalt MyCmd + call assert_equal('keepalt', g:mods) + keepa MyCmd + call assert_equal('keepalt', g:mods) + keepjumps MyCmd + call assert_equal('keepjumps', g:mods) + keepj MyCmd + call assert_equal('keepjumps', g:mods) + keepmarks MyCmd + call assert_equal('keepmarks', g:mods) + kee MyCmd + call assert_equal('keepmarks', g:mods) + keeppatterns MyCmd + call assert_equal('keeppatterns', g:mods) + keepp MyCmd + call assert_equal('keeppatterns', g:mods) + leftabove MyCmd " results in :aboveleft + call assert_equal('aboveleft', g:mods) + lefta MyCmd + call assert_equal('aboveleft', g:mods) + lockmarks MyCmd + call assert_equal('lockmarks', g:mods) + loc MyCmd + call assert_equal('lockmarks', g:mods) + noautocmd MyCmd + call assert_equal('noautocmd', g:mods) + noa MyCmd + call assert_equal('noautocmd', g:mods) + noswapfile MyCmd + call assert_equal('noswapfile', g:mods) + nos MyCmd + call assert_equal('noswapfile', g:mods) + rightbelow MyCmd " results in :belowright + call assert_equal('belowright', g:mods) + rightb MyCmd + call assert_equal('belowright', g:mods) + " sandbox MyCmd + silent MyCmd + call assert_equal('silent', g:mods) + sil MyCmd + call assert_equal('silent', g:mods) + silent! MyCmd + call assert_equal('silent!', g:mods) + sil! MyCmd + call assert_equal('silent!', g:mods) + tab MyCmd + call assert_equal('tab', g:mods) + 0tab MyCmd + call assert_equal('0tab', g:mods) + tab split + tab MyCmd + call assert_equal('tab', g:mods) + 1tab MyCmd + call assert_equal('1tab', g:mods) + tabprev + tab MyCmd + call assert_equal('tab', g:mods) + 2tab MyCmd + call assert_equal('2tab', g:mods) + 2tabclose + topleft MyCmd + call assert_equal('topleft', g:mods) + to MyCmd + call assert_equal('topleft', g:mods) + unsilent MyCmd + call assert_equal('unsilent', g:mods) + uns MyCmd + call assert_equal('unsilent', g:mods) + verbose MyCmd + call assert_equal('verbose', g:mods) + verb MyCmd + call assert_equal('verbose', g:mods) + 0verbose MyCmd + call assert_equal('0verbose', g:mods) + 3verbose MyCmd + call assert_equal('3verbose', g:mods) + 999verbose MyCmd + call assert_equal('999verbose', g:mods) + vertical MyCmd + call assert_equal('vertical', g:mods) + vert MyCmd + call assert_equal('vertical', g:mods) + horizontal MyCmd + call assert_equal('horizontal', g:mods) + hor MyCmd + call assert_equal('horizontal', g:mods) + + aboveleft belowright botright browse confirm hide keepalt keepjumps + \ keepmarks keeppatterns lockmarks noautocmd noswapfile silent + \ tab topleft unsilent verbose vertical MyCmd + + call assert_equal('browse confirm hide keepalt keepjumps ' . + \ 'keepmarks keeppatterns lockmarks noswapfile unsilent noautocmd ' . + \ 'silent verbose aboveleft belowright botright tab topleft vertical', + \ g:mods) + + let g:mods = '' + command! -nargs=* MyQCmd let g:mods .= '<q-mods> ' + + vertical MyQCmd + call assert_equal('"vertical" ', g:mods) + + delcommand MyCmd + delcommand MyQCmd + unlet g:mods +endfunction + +func SaveCmdArgs(...) + let g:args = a:000 +endfunc + +func Test_f_args() + command -nargs=* TestFArgs call SaveCmdArgs(<f-args>) + + TestFArgs + call assert_equal([], g:args) + + TestFArgs one two three + call assert_equal(['one', 'two', 'three'], g:args) + + TestFArgs one\\two three + call assert_equal(['one\two', 'three'], g:args) + + TestFArgs one\ two three + call assert_equal(['one two', 'three'], g:args) + + TestFArgs one\"two three + call assert_equal(['one\"two', 'three'], g:args) + + delcommand TestFArgs +endfunc + +func Test_q_args() + command -nargs=* TestQArgs call SaveCmdArgs(<q-args>) + + TestQArgs + call assert_equal([''], g:args) + + TestQArgs one two three + call assert_equal(['one two three'], g:args) + + TestQArgs one\\two three + call assert_equal(['one\\two three'], g:args) + + TestQArgs one\ two three + call assert_equal(['one\ two three'], g:args) + + TestQArgs one\"two three + call assert_equal(['one\"two three'], g:args) + + delcommand TestQArgs +endfunc + +func Test_reg_arg() + command -nargs=* -reg TestRegArg call SaveCmdArgs("<reg>", "<register>") + + TestRegArg + call assert_equal(['', ''], g:args) + + TestRegArg x + call assert_equal(['x', 'x'], g:args) + + delcommand TestRegArg +endfunc + +func Test_no_arg() + command -nargs=* TestNoArg call SaveCmdArgs("<args>", "<>", "<x>", "<lt>") + + TestNoArg + call assert_equal(['', '<>', '<x>', '<'], g:args) + + TestNoArg one + call assert_equal(['one', '<>', '<x>', '<'], g:args) + + delcommand TestNoArg +endfunc + +func Test_range_arg() + command -range TestRangeArg call SaveCmdArgs(<range>, <line1>, <line2>) + new + call setline(1, range(100)) + let lnum = line('.') + + TestRangeArg + call assert_equal([0, lnum, lnum], g:args) + + 99TestRangeArg + call assert_equal([1, 99, 99], g:args) + + 88,99TestRangeArg + call assert_equal([2, 88, 99], g:args) + + call assert_fails('102TestRangeArg', 'E16:') + + bwipe! + delcommand TestRangeArg +endfunc + +func Test_Ambiguous() + command Doit let g:didit = 'yes' + command Dothat let g:didthat = 'also' + call assert_fails('Do', 'E464:') + Doit + call assert_equal('yes', g:didit) + Dothat + call assert_equal('also', g:didthat) + unlet g:didit + unlet g:didthat + + delcommand Doit + Do + call assert_equal('also', g:didthat) + delcommand Dothat + + " Nvim removed the ":Ni!" easter egg in 87e107d92. + call assert_fails("\x4ei\041", 'E492: Not an editor command: Ni!') +endfunc + +func Test_redefine_on_reload() + call writefile(['command ExistingCommand echo "yes"'], 'Xcommandexists') + call assert_equal(0, exists(':ExistingCommand')) + source Xcommandexists + call assert_equal(2, exists(':ExistingCommand')) + " Redefining a command when reloading a script is OK. + source Xcommandexists + call assert_equal(2, exists(':ExistingCommand')) + + " But redefining in another script is not OK. + call writefile(['command ExistingCommand echo "yes"'], 'Xcommandexists2') + call assert_fails('source Xcommandexists2', 'E174:') + call delete('Xcommandexists2') + + " And defining twice in one script is not OK. + delcommand ExistingCommand + call assert_equal(0, exists(':ExistingCommand')) + call writefile([ + \ 'command ExistingCommand echo "yes"', + \ 'command ExistingCommand echo "no"', + \ ], 'Xcommandexists') + call assert_fails('source Xcommandexists', 'E174:') + call assert_equal(2, exists(':ExistingCommand')) + + call delete('Xcommandexists') + delcommand ExistingCommand +endfunc + +func Test_CmdUndefined() + call assert_fails('Doit', 'E492:') + au CmdUndefined Doit :command Doit let g:didit = 'yes' + Doit + call assert_equal('yes', g:didit) + delcommand Doit + + call assert_fails('Dothat', 'E492:') + au CmdUndefined * let g:didnot = 'yes' + call assert_fails('Dothat', 'E492:') + call assert_equal('yes', g:didnot) +endfunc + +func Test_CmdErrors() + call assert_fails('com! docmd :', 'E183:') + call assert_fails('com! \<Tab> :', 'E182:') + call assert_fails('com! _ :', 'E182:') + call assert_fails('com! - DoCmd :', 'E175:') + call assert_fails('com! -xxx DoCmd :', 'E181:') + call assert_fails('com! -addr DoCmd :', 'E179:') + call assert_fails('com! -addr=asdf DoCmd :', 'E180:') + call assert_fails('com! -complete DoCmd :', 'E179:') + call assert_fails('com! -complete=xxx DoCmd :', 'E180:') + call assert_fails('com! -complete=custom DoCmd :', 'E467:') + call assert_fails('com! -complete=customlist DoCmd :', 'E467:') + " call assert_fails('com! -complete=behave,CustomComplete DoCmd :', 'E468:') + call assert_fails('com! -complete=file DoCmd :', 'E1208:') + call assert_fails('com! -nargs=0 -complete=file DoCmd :', 'E1208:') + call assert_fails('com! -nargs=x DoCmd :', 'E176:') + call assert_fails('com! -count=1 -count=2 DoCmd :', 'E177:') + call assert_fails('com! -count=x DoCmd :', 'E178:') + call assert_fails('com! -range=x DoCmd :', 'E178:') + + com! -nargs=0 DoCmd : + call assert_fails('DoCmd x', 'E488:') + + com! -nargs=1 DoCmd : + call assert_fails('DoCmd', 'E471:') + + com! -nargs=+ DoCmd : + call assert_fails('DoCmd', 'E471:') + + call assert_fails('com DoCmd :', 'E174:') + comclear + call assert_fails('delcom DoCmd', 'E184:') + + " These used to leak memory + call assert_fails('com! -complete=custom,CustomComplete _ :', 'E182:') + call assert_fails('com! -complete=custom,CustomComplete docmd :', 'E183:') + call assert_fails('com! -complete=custom,CustomComplete -xxx DoCmd :', 'E181:') +endfunc + +func CustomComplete(A, L, P) + return "January\nFebruary\nMars\n" +endfunc + +func CustomCompleteList(A, L, P) + return [ "Monday", "Tuesday", "Wednesday", {}, v:_null_string] +endfunc + +func Test_CmdCompletion() + call feedkeys(":com -\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"com -addr bang bar buffer complete count keepscript nargs range register', @:) + + call feedkeys(":com -nargs=0 -\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"com -nargs=0 -addr bang bar buffer complete count keepscript nargs range register', @:) + + call feedkeys(":com -nargs=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"com -nargs=* + 0 1 ?', @:) + + call feedkeys(":com -addr=\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"com -addr=arguments buffers lines loaded_buffers other quickfix tabs windows', @:) + + call feedkeys(":com -complete=co\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"com -complete=color command compiler', @:) + + " try completion for unsupported argument values + call feedkeys(":com -newarg=\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"com -newarg=\t", @:) + + " command completion after the name in a user defined command + call feedkeys(":com MyCmd chist\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"com MyCmd chistory", @:) + + command! DoCmd1 : + command! DoCmd2 : + call feedkeys(":com \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"com DoCmd1 DoCmd2', @:) + + call feedkeys(":DoC\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd1 DoCmd2', @:) + + call feedkeys(":delcom DoC\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"delcom DoCmd1 DoCmd2', @:) + + " try argument completion for a command without completion + call feedkeys(":DoCmd1 \<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal("\"DoCmd1 \t", @:) + + delcom DoCmd1 + call feedkeys(":delcom DoC\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"delcom DoCmd2', @:) + + call feedkeys(":com DoC\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"com DoCmd2', @:) + + delcom DoCmd2 + call feedkeys(":delcom DoC\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"delcom DoC', @:) + + call feedkeys(":com DoC\<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"com DoC', @:) + + " com! -nargs=1 -complete=behave DoCmd : + " call feedkeys(":DoCmd \<C-A>\<C-B>\"\<CR>", 'tx') + " call assert_equal('"DoCmd mswin xterm', @:) + + " Test for file name completion + com! -nargs=1 -complete=file DoCmd : + call feedkeys(":DoCmd READM\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd README.txt', @:) + + " Test for buffer name completion + com! -nargs=1 -complete=buffer DoCmd : + let bnum = bufadd('BufForUserCmd') + call setbufvar(bnum, '&buflisted', 1) + call feedkeys(":DoCmd BufFor\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd BufForUserCmd', @:) + bwipe BufForUserCmd + call feedkeys(":DoCmd BufFor\<Tab>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd BufFor', @:) + + com! -nargs=* -complete=custom,CustomComplete DoCmd : + call feedkeys(":DoCmd \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd January February Mars', @:) + + com! -nargs=? -complete=customlist,CustomCompleteList DoCmd : + call feedkeys(":DoCmd \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoCmd Monday Tuesday Wednesday', @:) + + com! -nargs=+ -complete=custom,CustomCompleteList DoCmd : + call assert_fails("call feedkeys(':DoCmd \<C-D>', 'tx')", 'E730:') + + com! -nargs=+ -complete=customlist,CustomComp DoCmd : + call assert_fails("call feedkeys(':DoCmd \<C-D>', 'tx')", 'E117:') + + " custom completion without a function + com! -nargs=? -complete=custom, DoCmd + call assert_beeps("call feedkeys(':DoCmd \t', 'tx')") + + " custom completion failure with the wrong function + com! -nargs=? -complete=custom,min DoCmd + call assert_fails("call feedkeys(':DoCmd \t', 'tx')", 'E118:') + + " custom completion for a pattern with a backslash + let g:ArgLead = '' + func! CustCompl(A, L, P) + let g:ArgLead = a:A + return ['one', 'two', 'three'] + endfunc + com! -nargs=? -complete=customlist,CustCompl DoCmd + call feedkeys(":DoCmd a\\\t", 'xt') + call assert_equal('a\', g:ArgLead) + delfunc CustCompl + + delcom DoCmd +endfunc + +func CallExecute(A, L, P) + " Drop first '\n' + return execute('echo "hi"')[1:] +endfunc + +func Test_use_execute_in_completion() + command! -nargs=* -complete=custom,CallExecute DoExec : + call feedkeys(":DoExec \<C-A>\<C-B>\"\<CR>", 'tx') + call assert_equal('"DoExec hi', @:) + delcommand DoExec +endfunc + +func Test_addr_all() + command! -addr=lines DoSomething let g:a1 = <line1> | let g:a2 = <line2> + %DoSomething + call assert_equal(1, g:a1) + call assert_equal(line('$'), g:a2) + + command! -addr=arguments DoSomething let g:a1 = <line1> | let g:a2 = <line2> + args one two three + %DoSomething + call assert_equal(1, g:a1) + call assert_equal(3, g:a2) + + command! -addr=buffers DoSomething let g:a1 = <line1> | let g:a2 = <line2> + %DoSomething + for low in range(1, bufnr('$')) + if buflisted(low) + break + endif + endfor + call assert_equal(low, g:a1) + call assert_equal(bufnr('$'), g:a2) + + command! -addr=loaded_buffers DoSomething let g:a1 = <line1> | let g:a2 = <line2> + %DoSomething + for low in range(1, bufnr('$')) + if bufloaded(low) + break + endif + endfor + call assert_equal(low, g:a1) + for up in range(bufnr('$'), 1, -1) + if bufloaded(up) + break + endif + endfor + call assert_equal(up, g:a2) + + command! -addr=windows DoSomething let g:a1 = <line1> | let g:a2 = <line2> + new + %DoSomething + call assert_equal(1, g:a1) + call assert_equal(winnr('$'), g:a2) + bwipe + + command! -addr=tabs DoSomething let g:a1 = <line1> | let g:a2 = <line2> + tabnew + %DoSomething + call assert_equal(1, g:a1) + call assert_equal(len(gettabinfo()), g:a2) + bwipe + + command! -addr=other DoSomething let g:a1 = <line1> | let g:a2 = <line2> + DoSomething + call assert_equal(line('.'), g:a1) + call assert_equal(line('.'), g:a2) + %DoSomething + call assert_equal(1, g:a1) + call assert_equal(line('$'), g:a2) + + delcommand DoSomething +endfunc + +func Test_command_list() + command! DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 :", + \ execute('command DoCmd')) + + " Test with various -range= and -count= argument values. + command! -range DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . :", + \ execute('command DoCmd')) + command! -range=% DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 % :", + \ execute('command! DoCmd')) + command! -range=2 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 2 :", + \ execute('command DoCmd')) + command! -count=2 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 2c ? :", + \ execute('command DoCmd')) + + " Test with various -addr= argument values. + command! -addr=lines DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . :", + \ execute('command DoCmd')) + command! -addr=arguments DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . arg :", + \ execute('command DoCmd')) + command! -addr=buffers DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . buf :", + \ execute('command DoCmd')) + command! -addr=loaded_buffers DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . load :", + \ execute('command DoCmd')) + command! -addr=windows DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . win :", + \ execute('command DoCmd')) + command! -addr=tabs DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . tab :", + \ execute('command DoCmd')) + command! -addr=other DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . ? :", + \ execute('command DoCmd')) + + " Test with various -complete= argument values (non-exhaustive list) + command! -nargs=1 -complete=arglist DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 1 arglist :", + \ execute('command DoCmd')) + command! -nargs=* -complete=augroup DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd * augroup :", + \ execute('command DoCmd')) + command! -nargs=? -complete=custom,CustomComplete DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd ? custom :", + \ execute('command DoCmd')) + command! -nargs=+ -complete=customlist,CustomComplete DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd + customlist :", + \ execute('command DoCmd')) + + " Test with various -narg= argument values. + command! -nargs=0 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 :", + \ execute('command DoCmd')) + command! -nargs=1 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 1 :", + \ execute('command DoCmd')) + command! -nargs=* DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd * :", + \ execute('command DoCmd')) + command! -nargs=? DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd ? :", + \ execute('command DoCmd')) + command! -nargs=+ DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd + :", + \ execute('command DoCmd')) + + " Test with other arguments. + command! -bang DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n! DoCmd 0 :", + \ execute('command DoCmd')) + command! -bar DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n| DoCmd 0 :", + \ execute('command DoCmd')) + command! -register DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n\" DoCmd 0 :", + \ execute('command DoCmd')) + command! -buffer DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\nb DoCmd 0 :" + \ .. "\n\" DoCmd 0 :", + \ execute('command DoCmd')) + comclear + + " Test with many args. + command! -bang -bar -register -buffer -nargs=+ -complete=environment -addr=windows -count=3 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n!\"b|DoCmd + 3c win environment :", + \ execute('command DoCmd')) + comclear + + " Test with special characters in command definition. + command! DoCmd :<cr><tab><c-d> + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 :<CR><Tab><C-D>", + \ execute('command DoCmd')) + + " Test output in verbose mode. + command! DoCmd : + call assert_match("^\n" + \ .. " Name Args Address Complete Definition\n" + \ .. " DoCmd 0 :\n" + \ .. "\tLast set from .*/test_usercommands.vim line \\d\\+$", + \ execute('verbose command DoCmd')) + + comclear + call assert_equal("\nNo user-defined commands found", execute(':command Xxx')) + call assert_equal("\nNo user-defined commands found", execute('command')) +endfunc + +" Test for a custom user completion returning the wrong value type +func Test_usercmd_custom() + func T1(a, c, p) + return "a\nb\n" + endfunc + command -nargs=* -complete=customlist,T1 TCmd1 + call feedkeys(":TCmd1 \<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"TCmd1 ', @:) + delcommand TCmd1 + delfunc T1 + + func T2(a, c, p) + return {} + endfunc + command -nargs=* -complete=customlist,T2 TCmd2 + call feedkeys(":TCmd2 \<C-A>\<C-B>\"\<CR>", 'xt') + call assert_equal('"TCmd2 ', @:) + delcommand TCmd2 + delfunc T2 +endfunc + +func Test_delcommand_buffer() + command Global echo 'global' + command -buffer OneBuffer echo 'one' + new + command -buffer TwoBuffer echo 'two' + call assert_equal(0, exists(':OneBuffer')) + call assert_equal(2, exists(':Global')) + call assert_equal(2, exists(':TwoBuffer')) + delcommand -buffer TwoBuffer + call assert_equal(0, exists(':TwoBuffer')) + call assert_fails('delcommand -buffer Global', 'E1237:') + call assert_fails('delcommand -buffer OneBuffer', 'E1237:') + bwipe! + call assert_equal(2, exists(':OneBuffer')) + delcommand -buffer OneBuffer + call assert_equal(0, exists(':OneBuffer')) + call assert_fails('delcommand -buffer Global', 'E1237:') + delcommand Global + call assert_equal(0, exists(':Global')) +endfunc + +func DefCmd(name) + if len(a:name) > 30 + return + endif + exe 'command ' .. a:name .. ' call DefCmd("' .. a:name .. 'x")' + echo a:name + exe a:name +endfunc + +func Test_recursive_define() + call DefCmd('Command') + + let name = 'Command' + while len(name) < 30 + exe 'delcommand ' .. name + let name ..= 'x' + endwhile +endfunc + +" Test for using buffer-local ambiguous user-defined commands +func Test_buflocal_ambiguous_usercmd() + new + command -buffer -nargs=1 -complete=sign TestCmd1 echo "Hello" + command -buffer -nargs=1 -complete=sign TestCmd2 echo "World" + + call assert_fails("call feedkeys(':TestCmd\<CR>', 'xt')", 'E464:') + call feedkeys(":TestCmd \<Tab>\<C-B>\"\<CR>", 'xt') + call assert_equal('"TestCmd ', @:) + + delcommand TestCmd1 + delcommand TestCmd2 + bw! +endfunc + +" Test for using buffer-local user command from cmdwin. +func Test_buflocal_usercmd_cmdwin() + new + command -buffer TestCmd edit Test + " This used to crash Vim + call assert_fails("norm q::TestCmd\<CR>", 'E11:') + bw! +endfunc + +" Test for using a multibyte character in a user command +func Test_multibyte_in_usercmd() + command SubJapanesePeriodToDot exe "%s/\u3002/./g" + new + call setline(1, "Hello\u3002") + SubJapanesePeriodToDot + call assert_equal('Hello.', getline(1)) + bw! + delcommand SubJapanesePeriodToDot +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_utf8.vim b/test/old/testdir/test_utf8.vim new file mode 100644 index 0000000000..a5a9624ec3 --- /dev/null +++ b/test/old/testdir/test_utf8.vim @@ -0,0 +1,346 @@ +" Tests for Unicode manipulations + +source check.vim +source view_util.vim +source screendump.vim + +" Visual block Insert adjusts for multi-byte char +func Test_visual_block_insert() + new + call setline(1, ["aaa", "あああ", "bbb"]) + exe ":norm! gg0l\<C-V>jjIx\<Esc>" + call assert_equal(['axaa', ' xあああ', 'bxbb'], getline(1, '$')) + bwipeout! +endfunc + +" Test for built-in functions strchars() and strcharlen() +func Test_strchars() + let inp = ["a", "あいa", "A\u20dd", "A\u20dd\u20dd", "\u20dd"] + let exp = [[1, 1, 1], [3, 3, 3], [2, 2, 1], [3, 3, 1], [1, 1, 1]] + for i in range(len(inp)) + call assert_equal(exp[i][0], strchars(inp[i])) + call assert_equal(exp[i][1], inp[i]->strchars(0)) + call assert_equal(exp[i][2], strchars(inp[i], 1)) + endfor + + let exp = [1, 3, 1, 1, 1] + for i in range(len(inp)) + call assert_equal(exp[i], inp[i]->strcharlen()) + call assert_equal(exp[i], strcharlen(inp[i])) + endfor + + call assert_fails("call strchars('abc', 2)", ['E1023:', 'E1023:']) + call assert_fails("call strchars('abc', -1)", ['E1023:', 'E1023:']) + call assert_fails("call strchars('abc', {})", ['E728:', 'E728:']) + call assert_fails("call strchars('abc', [])", ['E745:', 'E745:']) +endfunc + +" Test for customlist completion +func CustomComplete1(lead, line, pos) + return ['あ', 'い'] +endfunc + +func CustomComplete2(lead, line, pos) + return ['あたし', 'あたま', 'あたりめ'] +endfunc + +func CustomComplete3(lead, line, pos) + return ['Nこ', 'Nん', 'Nぶ'] +endfunc + +func Test_customlist_completion() + command -nargs=1 -complete=customlist,CustomComplete1 Test1 echo + call feedkeys(":Test1 \<C-L>\<C-B>\"\<CR>", 'itx') + call assert_equal('"Test1 ', getreg(':')) + + command -nargs=1 -complete=customlist,CustomComplete2 Test2 echo + call feedkeys(":Test2 \<C-L>\<C-B>\"\<CR>", 'itx') + call assert_equal('"Test2 あた', getreg(':')) + + command -nargs=1 -complete=customlist,CustomComplete3 Test3 echo + call feedkeys(":Test3 \<C-L>\<C-B>\"\<CR>", 'itx') + call assert_equal('"Test3 N', getreg(':')) + + call garbagecollect(1) +endfunc + +" Yank one 3 byte character and check the mark columns. +func Test_getvcol() + new + call setline(1, "x\u2500x") + normal 0lvy + call assert_equal(2, col("'[")) + call assert_equal(4, col("']")) + call assert_equal(2, virtcol("'[")) + call assert_equal(2, virtcol("']")) +endfunc + +func Test_screenchar_utf8() + new + + " 1-cell, with composing characters + call setline(1, ["ABC\u0308"]) + redraw + call assert_equal([0x0041], screenchars(1, 1)) + call assert_equal([0x0042], 1->screenchars(2)) + call assert_equal([0x0043, 0x0308], screenchars(1, 3)) + call assert_equal("A", screenstring(1, 1)) + call assert_equal("B", screenstring(1, 2)) + call assert_equal("C\u0308", screenstring(1, 3)) + + " 1-cell, with 6 composing characters + set maxcombine=6 + call setline(1, ["ABC" .. repeat("\u0308", 6)]) + redraw + call assert_equal([0x0041], screenchars(1, 1)) + call assert_equal([0x0042], 1->screenchars(2)) + " This should not use uninitialized memory + call assert_equal([0x0043] + repeat([0x0308], 6), screenchars(1, 3)) + call assert_equal("A", screenstring(1, 1)) + call assert_equal("B", screenstring(1, 2)) + call assert_equal("C" .. repeat("\u0308", 6), screenstring(1, 3)) + set maxcombine& + + " 2-cells, with composing characters + let text = "\u3042\u3044\u3046\u3099" + call setline(1, text) + redraw + call assert_equal([0x3042], screenchars(1, 1)) + call assert_equal([0], screenchars(1, 2)) + call assert_equal([0x3044], screenchars(1, 3)) + call assert_equal([0], screenchars(1, 4)) + call assert_equal([0x3046, 0x3099], screenchars(1, 5)) + + call assert_equal("\u3042", screenstring(1, 1)) + call assert_equal("", screenstring(1, 2)) + call assert_equal("\u3044", screenstring(1, 3)) + call assert_equal("", screenstring(1, 4)) + call assert_equal("\u3046\u3099", screenstring(1, 5)) + + call assert_equal([text . ' '], ScreenLines(1, 8)) + + bwipe! +endfunc + +func Test_list2str_str2list_utf8() + " One Unicode codepoint + let s = "\u3042\u3044" + let l = [0x3042, 0x3044] + call assert_equal(l, str2list(s, 1)) + call assert_equal(s, list2str(l, 1)) + if &enc ==# 'utf-8' + call assert_equal(str2list(s), str2list(s, 1)) + call assert_equal(list2str(l), list2str(l, 1)) + endif + + " With composing characters + let s = "\u304b\u3099\u3044" + let l = [0x304b, 0x3099, 0x3044] + call assert_equal(l, str2list(s, 1)) + call assert_equal(s, l->list2str(1)) + if &enc ==# 'utf-8' + call assert_equal(str2list(s), str2list(s, 1)) + call assert_equal(list2str(l), list2str(l, 1)) + endif + + " Null list is the same as an empty list + call assert_equal('', list2str([])) + call assert_equal('', list2str(v:_null_list)) +endfunc + +func Test_list2str_str2list_latin1() + " When 'encoding' is not multi-byte can still get utf-8 string. + " But we need to create the utf-8 string while 'encoding' is utf-8. + let s = "\u3042\u3044" + let l = [0x3042, 0x3044] + + let save_encoding = &encoding + " set encoding=latin1 + + let lres = str2list(s, 1) + let sres = list2str(l, 1) + call assert_equal([65, 66, 67], str2list("ABC")) + + " Try converting a list to a string in latin-1 encoding + call assert_equal([1, 2, 3], str2list(list2str([1, 2, 3]))) + + let &encoding = save_encoding + call assert_equal(l, lres) + call assert_equal(s, sres) +endfunc + +func Test_setcellwidths() + call setcellwidths([ + \ [0x1330, 0x1330, 2], + \ [9999, 10000, 1], + \ [0x1337, 0x1339, 2], + \]) + + call assert_equal(2, strwidth("\u1330")) + call assert_equal(1, strwidth("\u1336")) + call assert_equal(2, strwidth("\u1337")) + call assert_equal(2, strwidth("\u1339")) + call assert_equal(1, strwidth("\u133a")) + + for aw in ['single', 'double'] + exe 'set ambiwidth=' . aw + " Handle \u0080 to \u009F as control chars even on MS-Windows. + set isprint=@,161-255 + + call setcellwidths([]) + " Control chars + call assert_equal(4, strwidth("\u0081")) + call assert_equal(6, strwidth("\uFEFF")) + " Ambiguous width chars + call assert_equal((aw == 'single') ? 1 : 2, strwidth("\u00A1")) + call assert_equal((aw == 'single') ? 1 : 2, strwidth("\u2010")) + + call setcellwidths([[0x81, 0x81, 1], [0xA1, 0xA1, 1], + \ [0x2010, 0x2010, 1], [0xFEFF, 0xFEFF, 1]]) + " Control chars + call assert_equal(4, strwidth("\u0081")) + call assert_equal(6, strwidth("\uFEFF")) + " Ambiguous width chars + call assert_equal(1, strwidth("\u00A1")) + call assert_equal(1, strwidth("\u2010")) + + call setcellwidths([[0x81, 0x81, 2], [0xA1, 0xA1, 2], + \ [0x2010, 0x2010, 2], [0xFEFF, 0xFEFF, 2]]) + " Control chars + call assert_equal(4, strwidth("\u0081")) + call assert_equal(6, strwidth("\uFEFF")) + " Ambiguous width chars + call assert_equal(2, strwidth("\u00A1")) + call assert_equal(2, strwidth("\u2010")) + endfor + set ambiwidth& isprint& + + call setcellwidths([]) + + call assert_fails('call setcellwidths(1)', 'E714:') + + call assert_fails('call setcellwidths([1, 2, 0])', 'E1109:') + + call assert_fails('call setcellwidths([[0x101]])', 'E1110:') + call assert_fails('call setcellwidths([[0x101, 0x102]])', 'E1110:') + call assert_fails('call setcellwidths([[0x101, 0x102, 1, 4]])', 'E1110:') + call assert_fails('call setcellwidths([["a"]])', 'E1110:') + + call assert_fails('call setcellwidths([[0x102, 0x101, 1]])', 'E1111:') + + call assert_fails('call setcellwidths([[0x101, 0x102, 0]])', 'E1112:') + call assert_fails('call setcellwidths([[0x101, 0x102, 3]])', 'E1112:') + + call assert_fails('call setcellwidths([[0x111, 0x122, 1], [0x115, 0x116, 2]])', 'E1113:') + call assert_fails('call setcellwidths([[0x111, 0x122, 1], [0x122, 0x123, 2]])', 'E1113:') + + call assert_fails('call setcellwidths([[0x33, 0x44, 2]])', 'E1114:') + + set listchars=tab:--\\u2192 + call assert_fails('call setcellwidths([[0x2192, 0x2192, 2]])', 'E834:') + + set fillchars=stl:\\u2501 + call assert_fails('call setcellwidths([[0x2501, 0x2501, 2]])', 'E835:') + + set listchars& + set fillchars& + call setcellwidths([]) +endfunc + +func Test_getcellwidths() + call setcellwidths([]) + call assert_equal([], getcellwidths()) + + let widthlist = [ + \ [0x1330, 0x1330, 2], + \ [9999, 10000, 1], + \ [0x1337, 0x1339, 2], + \] + let widthlistsorted = [ + \ [0x1330, 0x1330, 2], + \ [0x1337, 0x1339, 2], + \ [9999, 10000, 1], + \] + call setcellwidths(widthlist) + call assert_equal(widthlistsorted, getcellwidths()) + + call setcellwidths([]) +endfunc + +func Test_setcellwidths_dump() + CheckRunVimInTerminal + + let lines =<< trim END + call setline(1, "\ue5ffDesktop") + END + call writefile(lines, 'XCellwidths', 'D') + let buf = RunVimInTerminal('-S XCellwidths', {'rows': 6}) + call VerifyScreenDump(buf, 'Test_setcellwidths_dump_1', {}) + + call term_sendkeys(buf, ":call setcellwidths([[0xe5ff, 0xe5ff, 2]])\<CR>") + call VerifyScreenDump(buf, 'Test_setcellwidths_dump_2', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_print_overlong() + " Text with more composing characters than MB_MAXBYTES. + new + call setline(1, 'axxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') + s/x/\=nr2char(1629)/g + print + bwipe! +endfunc + +func Test_recording_with_select_mode_utf8() + call Run_test_recording_with_select_mode_utf8() +endfunc + +func Run_test_recording_with_select_mode_utf8() + new + + " No escaping + call feedkeys("qacc12345\<Esc>gH哦\<Esc>q", "tx") + call assert_equal("哦", getline(1)) + call assert_equal("cc12345\<Esc>gH哦\<Esc>", @a) + call setline(1, 'asdf') + normal! @a + call assert_equal("哦", getline(1)) + + " 固 is 0xE5 0x9B 0xBA where 0x9B is CSI + call feedkeys("qacc12345\<Esc>gH固\<Esc>q", "tx") + call assert_equal("固", getline(1)) + call assert_equal("cc12345\<Esc>gH固\<Esc>", @a) + call setline(1, 'asdf') + normal! @a + call assert_equal("固", getline(1)) + + " 四 is 0xE5 0x9B 0x9B where 0x9B is CSI + call feedkeys("qacc12345\<Esc>gH四\<Esc>q", "tx") + call assert_equal("四", getline(1)) + call assert_equal("cc12345\<Esc>gH四\<Esc>", @a) + call setline(1, 'asdf') + normal! @a + call assert_equal("四", getline(1)) + + " 倒 is 0xE5 0x80 0x92 where 0x80 is K_SPECIAL + call feedkeys("qacc12345\<Esc>gH倒\<Esc>q", "tx") + call assert_equal("倒", getline(1)) + call assert_equal("cc12345\<Esc>gH倒\<Esc>", @a) + call setline(1, 'asdf') + normal! @a + call assert_equal("倒", getline(1)) + + bwipe! +endfunc + +" This must be done as one of the last tests, because it starts the GUI, which +" cannot be undone. +func Test_zz_recording_with_select_mode_utf8_gui() + CheckCanRunGui + + gui -f + call Run_test_recording_with_select_mode_utf8() +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_utf8_comparisons.vim b/test/old/testdir/test_utf8_comparisons.vim new file mode 100644 index 0000000000..f3c86b44fb --- /dev/null +++ b/test/old/testdir/test_utf8_comparisons.vim @@ -0,0 +1,94 @@ +" Tests for case-insensitive UTF-8 comparisons (utf_strnicmp() in mbyte.c) +" Also test "g~ap". + +func Ch(a, op, b, expected) + call assert_equal(eval(printf('"%s" %s "%s"', a:a, a:op, a:b)), a:expected, + \ printf('"%s" %s "%s" should return %d', a:a, a:op, a:b, a:expected)) +endfunc + +func Chk(a, b, result) + if a:result == 0 + call Ch(a:a, '==?', a:b, 1) + call Ch(a:a, '!=?', a:b, 0) + call Ch(a:a, '<=?', a:b, 1) + call Ch(a:a, '>=?', a:b, 1) + call Ch(a:a, '<?', a:b, 0) + call Ch(a:a, '>?', a:b, 0) + elseif a:result > 0 + call Ch(a:a, '==?', a:b, 0) + call Ch(a:a, '!=?', a:b, 1) + call Ch(a:a, '<=?', a:b, 0) + call Ch(a:a, '>=?', a:b, 1) + call Ch(a:a, '<?', a:b, 0) + call Ch(a:a, '>?', a:b, 1) + else + call Ch(a:a, '==?', a:b, 0) + call Ch(a:a, '!=?', a:b, 1) + call Ch(a:a, '<=?', a:b, 1) + call Ch(a:a, '>=?', a:b, 0) + call Ch(a:a, '<?', a:b, 1) + call Ch(a:a, '>?', a:b, 0) + endif +endfunc + +func Check(a, b, result) + call Chk(a:a, a:b, a:result) + call Chk(a:b, a:a, -a:result) +endfunc + +func LT(a, b) + call Check(a:a, a:b, -1) +endfunc + +func GT(a, b) + call Check(a:a, a:b, 1) +endfunc + +func EQ(a, b) + call Check(a:a, a:b, 0) +endfunc + +func Test_comparisons() + call EQ('', '') + call LT('', 'a') + call EQ('abc', 'abc') + call EQ('Abc', 'abC') + call LT('ab', 'abc') + call LT('AB', 'abc') + call LT('ab', 'aBc') + call EQ('\xd0\xb9\xd1\x86\xd1\x83\xd0\xba\xd0\xb5\xd0\xbd', '\xd0\xb9\xd0\xa6\xd0\xa3\xd0\xba\xd0\x95\xd0\xbd') + call LT('\xd0\xb9\xd1\x86\xd1\x83\xd0\xba\xd0\xb5\xd0\xbd', '\xd0\xaf\xd1\x86\xd1\x83\xd0\xba\xd0\xb5\xd0\xbd') + call EQ('\xe2\x84\xaa', 'k') + call LT('\xe2\x84\xaa', 'kkkkkk') + call EQ('\xe2\x84\xaa\xe2\x84\xaa\xe2\x84\xaa', 'kkk') + call LT('kk', '\xe2\x84\xaa\xe2\x84\xaa\xe2\x84\xaa') + call EQ('\xe2\x84\xaa\xe2\x84\xa6k\xe2\x84\xaak\xcf\x89', 'k\xcf\x89\xe2\x84\xaakk\xe2\x84\xa6') + call EQ('Abc\x80', 'AbC\x80') + call LT('Abc\x80', 'AbC\x81') + call LT('Abc', 'AbC\x80') + call LT('abc\x80DEF', 'abc\x80def') " case folding stops at the first bad character + call LT('\xc3XYZ', '\xc3xyz') + call EQ('\xef\xbc\xba', '\xef\xbd\x9a') " FF3A (upper), FF5A (lower) + call GT('\xef\xbc\xba', '\xef\xbc\xff') " first string is ok and equals \xef\xbd\x9a after folding, second string is illegal and was left unchanged, then the strings were bytewise compared + call LT('\xc3', '\xc3\x83') + call EQ('\xc3\xa3xYz', '\xc3\x83XyZ') + for n in range(0x60, 0xFF) + call LT(printf('xYz\x%.2X', n-1), printf('XyZ\x%.2X', n)) + endfor + for n in range(0x80, 0xBF) + call EQ(printf('xYz\xc2\x%.2XUvW', n), printf('XyZ\xc2\x%.2XuVw', n)) + endfor + for n in range(0xC0, 0xFF) + call LT(printf('xYz\xc2\x%.2XUvW', n), printf('XyZ\xc2\x%.2XuVw', n)) + endfor +endfunc + +" test that g~ap changes one paragraph only. +func Test_gap() + new + " setup text + call feedkeys("iabcd\<cr>\<cr>defg", "tx") + " modify only first line + call feedkeys("gg0g~ap", "tx") + call assert_equal(["ABCD", "", "defg"], getline(1,3)) +endfunc diff --git a/test/old/testdir/test_vartabs.vim b/test/old/testdir/test_vartabs.vim new file mode 100644 index 0000000000..e12c71d521 --- /dev/null +++ b/test/old/testdir/test_vartabs.vim @@ -0,0 +1,448 @@ +" Test for variable tabstops + +source check.vim +CheckFeature vartabs + +source view_util.vim + +func s:compare_lines(expect, actual) + call assert_equal(join(a:expect, "\n"), join(a:actual, "\n")) +endfunc + +func Test_vartabs() + new + %d + + " Test normal operation of tabstops ... + set ts=4 + call setline(1, join(split('aaaaa', '\zs'), "\t")) + retab 8 + let expect = "a a\<tab>a a\<tab>a" + call assert_equal(expect, getline(1)) + + " ... and softtabstops + set ts=8 sts=6 + exe "norm! Sb\<tab>b\<tab>b\<tab>b\<tab>b" + let expect = "b b\<tab> b\<tab> b\<tab>b" + call assert_equal(expect, getline(1)) + + " Test variable tabstops. + set sts=0 vts=4,8,4,8 + exe "norm! Sc\<tab>c\<tab>c\<tab>c\<tab>c\<tab>c" + retab 8 + let expect = "c c\<tab> c\<tab>c\<tab>c\<tab>c" + call assert_equal(expect, getline(1)) + + set et vts=4,8,4,8 + exe "norm! Sd\<tab>d\<tab>d\<tab>d\<tab>d\<tab>d" + let expect = "d d d d d d" + call assert_equal(expect, getline(1)) + + " Changing ts should have no effect if vts is in use. + call cursor(1, 1) + set ts=6 + exe "norm! Se\<tab>e\<tab>e\<tab>e\<tab>e\<tab>e" + let expect = "e e e e e e" + call assert_equal(expect, getline(1)) + + " Clearing vts should revert to using ts. + set vts= + exe "norm! Sf\<tab>f\<tab>f\<tab>f\<tab>f\<tab>f" + let expect = "f f f f f f" + call assert_equal(expect, getline(1)) + + " Test variable softtabstops. + set noet ts=8 vsts=12,2,6 + exe "norm! Sg\<tab>g\<tab>g\<tab>g\<tab>g\<tab>g" + let expect = "g\<tab> g g\<tab> g\<tab> g\<tab>g" + call assert_equal(expect, getline(1)) + + " Variable tabstops and softtabstops combined. + set vsts=6,12,8 vts=4,6,8 + exe "norm! Sh\<tab>h\<tab>h\<tab>h\<tab>h" + let expect = "h\<tab> h\<tab>\<tab>h\<tab>h\<tab>h" + call assert_equal(expect, getline(1)) + + " Retab with a single value, not using vts. + set ts=8 sts=0 vts= vsts= + exe "norm! Si\<tab>i\<tab>i\<tab>i\<tab>i" + retab 4 + let expect = "i\<tab>\<tab>i\<tab>\<tab>i\<tab>\<tab>i\<tab>\<tab>i" + call assert_equal(expect, getline(1)) + + " Retab with a single value, using vts. + set ts=8 sts=0 vts=6 vsts= + exe "norm! Sj\<tab>j\<tab>j\<tab>j\<tab>j" + retab 4 + let expect = "j\<tab> j\<tab>\<tab>j\<tab> j\<tab>\<tab>j" + call assert_equal(expect, getline(1)) + + " Retab with multiple values, not using vts. + set ts=6 sts=0 vts= vsts= + exe "norm! Sk\<tab>k\<tab>k\<tab>k\<tab>k\<tab>k" + retab 4,8 + let expect = "k\<tab> k\<tab>k k\<tab> k\<tab> k" + call assert_equal(expect, getline(1)) + + " Retab with multiple values, using vts. + set ts=8 sts=0 vts=6 vsts= + exe "norm! Sl\<tab>l\<tab>l\<tab>l\<tab>l\<tab>l" + retab 4,8 + let expect = "l\<tab> l\<tab>l l\<tab> l\<tab> l" + call assert_equal(expect, getline(1)) + + " Test for 'retab' with vts + set ts=8 sts=0 vts=5,3,6,2 vsts= + exe "norm! S l" + .retab! + call assert_equal("\t\t\t\tl", getline(1)) + + " Test for 'retab' with same values as vts + set ts=8 sts=0 vts=5,3,6,2 vsts= + exe "norm! S l" + .retab! 5,3,6,2 + call assert_equal("\t\t\t\tl", getline(1)) + + " Check that global and local values are set. + set ts=4 vts=6 sts=8 vsts=10 + call assert_equal(&ts, 4) + call assert_equal(&vts, '6') + call assert_equal(&sts, 8) + call assert_equal(&vsts, '10') + new + call assert_equal(&ts, 4) + call assert_equal(&vts, '6') + call assert_equal(&sts, 8) + call assert_equal(&vsts, '10') + bwipeout! + + " Check that local values only are set. + setlocal ts=5 vts=7 sts=9 vsts=11 + call assert_equal(&ts, 5) + call assert_equal(&vts, '7') + call assert_equal(&sts, 9) + call assert_equal(&vsts, '11') + new + call assert_equal(&ts, 4) + call assert_equal(&vts, '6') + call assert_equal(&sts, 8) + call assert_equal(&vsts, '10') + bwipeout! + + " Check that global values only are set. + setglobal ts=6 vts=8 sts=10 vsts=12 + call assert_equal(&ts, 5) + call assert_equal(&vts, '7') + call assert_equal(&sts, 9) + call assert_equal(&vsts, '11') + new + call assert_equal(&ts, 6) + call assert_equal(&vts, '8') + call assert_equal(&sts, 10) + call assert_equal(&vsts, '12') + bwipeout! + + set ts& vts& sts& vsts& et& + bwipeout! +endfunc + +func Test_retab_invalid_arg() + new + call setline(1, "\ttext") + retab 0 + call assert_fails("retab -8", 'E487: Argument must be positive') + call assert_fails("retab 10000", 'E475:') + call assert_fails("retab 720575940379279360", 'E475:') + bwipe! +endfunc + +func Test_vartabs_breakindent() + if !exists("+breakindent") + return + endif + new + %d + + " Test normal operation of tabstops ... + set ts=4 + call setline(1, join(split('aaaaa', '\zs'), "\t")) + retab 8 + let expect = "a a\<tab>a a\<tab>a" + call assert_equal(expect, getline(1)) + + " ... and softtabstops + set ts=8 sts=6 + exe "norm! Sb\<tab>b\<tab>b\<tab>b\<tab>b" + let expect = "b b\<tab> b\<tab> b\<tab>b" + call assert_equal(expect, getline(1)) + + " Test variable tabstops. + set sts=0 vts=4,8,4,8 + exe "norm! Sc\<tab>c\<tab>c\<tab>c\<tab>c\<tab>c" + retab 8 + let expect = "c c\<tab> c\<tab>c\<tab>c\<tab>c" + call assert_equal(expect, getline(1)) + + set et vts=4,8,4,8 + exe "norm! Sd\<tab>d\<tab>d\<tab>d\<tab>d\<tab>d" + let expect = "d d d d d d" + call assert_equal(expect, getline(1)) + + " Changing ts should have no effect if vts is in use. + call cursor(1, 1) + set ts=6 + exe "norm! Se\<tab>e\<tab>e\<tab>e\<tab>e\<tab>e" + let expect = "e e e e e e" + call assert_equal(expect, getline(1)) + + " Clearing vts should revert to using ts. + set vts= + exe "norm! Sf\<tab>f\<tab>f\<tab>f\<tab>f\<tab>f" + let expect = "f f f f f f" + call assert_equal(expect, getline(1)) + + " Test variable softtabstops. + set noet ts=8 vsts=12,2,6 + exe "norm! Sg\<tab>g\<tab>g\<tab>g\<tab>g\<tab>g" + let expect = "g\<tab> g g\<tab> g\<tab> g\<tab>g" + call assert_equal(expect, getline(1)) + + " Variable tabstops and softtabstops combined. + set vsts=6,12,8 vts=4,6,8 + exe "norm! Sh\<tab>h\<tab>h\<tab>h\<tab>h" + let expect = "h\<tab> h\<tab>\<tab>h\<tab>h\<tab>h" + call assert_equal(expect, getline(1)) + + " Retab with a single value, not using vts. + set ts=8 sts=0 vts= vsts= + exe "norm! Si\<tab>i\<tab>i\<tab>i\<tab>i" + retab 4 + let expect = "i\<tab>\<tab>i\<tab>\<tab>i\<tab>\<tab>i\<tab>\<tab>i" + call assert_equal(expect, getline(1)) + + " Retab with a single value, using vts. + set ts=8 sts=0 vts=6 vsts= + exe "norm! Sj\<tab>j\<tab>j\<tab>j\<tab>j" + retab 4 + let expect = "j\<tab> j\<tab>\<tab>j\<tab> j\<tab>\<tab>j" + call assert_equal(expect, getline(1)) + + " Retab with multiple values, not using vts. + set ts=6 sts=0 vts= vsts= + exe "norm! Sk\<tab>k\<tab>k\<tab>k\<tab>k\<tab>k" + retab 4,8 + let expect = "k\<tab> k\<tab>k k\<tab> k\<tab> k" + call assert_equal(expect, getline(1)) + + " Retab with multiple values, using vts. + set ts=8 sts=0 vts=6 vsts= + exe "norm! Sl\<tab>l\<tab>l\<tab>l\<tab>l\<tab>l" + retab 4,8 + let expect = "l\<tab> l\<tab>l l\<tab> l\<tab> l" + call assert_equal(expect, getline(1)) + + " Check that global and local values are set. + set ts=4 vts=6 sts=8 vsts=10 + call assert_equal(&ts, 4) + call assert_equal(&vts, '6') + call assert_equal(&sts, 8) + call assert_equal(&vsts, '10') + new + call assert_equal(&ts, 4) + call assert_equal(&vts, '6') + call assert_equal(&sts, 8) + call assert_equal(&vsts, '10') + bwipeout! + + " Check that local values only are set. + setlocal ts=5 vts=7 sts=9 vsts=11 + call assert_equal(&ts, 5) + call assert_equal(&vts, '7') + call assert_equal(&sts, 9) + call assert_equal(&vsts, '11') + new + call assert_equal(&ts, 4) + call assert_equal(&vts, '6') + call assert_equal(&sts, 8) + call assert_equal(&vsts, '10') + bwipeout! + + " Check that global values only are set. + setglobal ts=6 vts=8 sts=10 vsts=12 + call assert_equal(&ts, 5) + call assert_equal(&vts, '7') + call assert_equal(&sts, 9) + call assert_equal(&vsts, '11') + new + call assert_equal(&ts, 6) + call assert_equal(&vts, '8') + call assert_equal(&sts, 10) + call assert_equal(&vsts, '12') + bwipeout! + + bwipeout! +endfunc + +func Test_vartabs_linebreak() + if winwidth(0) < 40 + return + endif + new + 40vnew + %d + setl linebreak vartabstop=10,20,30,40 + call setline(1, "\tx\tx\tx\tx") + + let expect = [' x ', + \ 'x x ', + \ 'x '] + let lines = ScreenLines([1, 3], winwidth(0)) + call s:compare_lines(expect, lines) + setl list listchars=tab:>- + let expect = ['>---------x>------------------ ', + \ 'x>------------------x>------------------', + \ 'x '] + let lines = ScreenLines([1, 3], winwidth(0)) + call s:compare_lines(expect, lines) + setl linebreak vartabstop=40 + let expect = ['>---------------------------------------', + \ 'x>--------------------------------------', + \ 'x>--------------------------------------', + \ 'x>--------------------------------------', + \ 'x '] + let lines = ScreenLines([1, 5], winwidth(0)) + call s:compare_lines(expect, lines) + + " cleanup + bw! + bw! + set nolist listchars&vim +endfunc + +func Test_vartabs_shiftwidth() + "return + if winwidth(0) < 40 + return + endif + new + 40vnew + %d +" setl varsofttabstop=10,20,30,40 + setl shiftwidth=0 vartabstop=10,20,30,40 + call setline(1, "x") + + " Check without any change. + let expect = ['x '] + let lines = ScreenLines(1, winwidth(0)) + call s:compare_lines(expect, lines) + " Test 1: + " shiftwidth depends on the indent, first check with cursor at the end of the + " line (which is the same as the start of the line, since there is only one + " character). + norm! $>> + let expect1 = [' x '] + let lines = ScreenLines(1, winwidth(0)) + call s:compare_lines(expect1, lines) + call assert_equal(10, shiftwidth()) + call assert_equal(10, shiftwidth(1)) + call assert_equal(20, shiftwidth(virtcol('.'))) + norm! $>> + let expect2 = [' x ', '~ '] + let lines = ScreenLines([1, 2], winwidth(0)) + call s:compare_lines(expect2, lines) + call assert_equal(20, shiftwidth(virtcol('.')-2)) + call assert_equal(30, virtcol('.')->shiftwidth()) + norm! $>> + let expect3 = [' ', ' x ', '~ '] + let lines = ScreenLines([1, 3], winwidth(0)) + call s:compare_lines(expect3, lines) + call assert_equal(30, shiftwidth(virtcol('.')-2)) + call assert_equal(40, shiftwidth(virtcol('.'))) + norm! $>> + let expect4 = [' ', ' ', ' x '] + let lines = ScreenLines([1, 3], winwidth(0)) + call assert_equal(40, shiftwidth(virtcol('.'))) + call s:compare_lines(expect4, lines) + + " Test 2: Put the cursor at the first column, result should be the same + call setline(1, "x") + norm! 0>> + let lines = ScreenLines(1, winwidth(0)) + call s:compare_lines(expect1, lines) + norm! 0>> + let lines = ScreenLines([1, 2], winwidth(0)) + call s:compare_lines(expect2, lines) + norm! 0>> + let lines = ScreenLines([1, 3], winwidth(0)) + call s:compare_lines(expect3, lines) + norm! 0>> + let lines = ScreenLines([1, 3], winwidth(0)) + call s:compare_lines(expect4, lines) + + call assert_fails('call shiftwidth([])', 'E745:') + + " cleanup + bw! + bw! +endfunc + +func Test_vartabs_failures() + call assert_fails('set vts=8,') + call assert_fails('set vsts=8,') + call assert_fails('set vts=8,,8') + call assert_fails('set vsts=8,,8') + call assert_fails('set vts=8,,8,') + call assert_fails('set vsts=8,,8,') + call assert_fails('set vts=,8') + call assert_fails('set vsts=,8') +endfunc + +func Test_vartabs_reset() + set vts=8 + set all& + call assert_equal('', &vts) +endfunc + +func s:SaveCol(l) + call add(a:l, [col('.'), virtcol('.')]) + return '' +endfunc + +" Test for 'varsofttabstop' +func Test_varsofttabstop() + new + inoremap <expr> <F2> s:SaveCol(g:cols) + + set backspace=indent,eol,start + set varsofttabstop=6,2,5,3 + let g:cols = [] + call feedkeys("a\t\<F2>\t\<F2>\t\<F2>\t\<F2> ", 'xt') + call assert_equal("\t\t ", getline(1)) + call assert_equal([[7, 7], [2, 9], [7, 14], [3, 17]], g:cols) + + let g:cols = [] + call feedkeys("a\<bs>\<F2>\<bs>\<F2>\<bs>\<F2>\<bs>\<F2>\<bs>\<F2>", 'xt') + call assert_equal('', getline(1)) + call assert_equal([[3, 17], [7, 14], [2, 9], [7, 7], [1, 1]], g:cols) + + set varsofttabstop& + set backspace& + iunmap <F2> + close! +endfunc + +" Setting 'shiftwidth' to a negative value, should set it to either the value +" of 'tabstop' (if 'vartabstop' is not set) or to the first value in +" 'vartabstop' +func Test_shiftwidth_vartabstop() + throw 'Skipped: Nvim removed this behavior in #6377' + setlocal tabstop=7 vartabstop= + call assert_fails('set shiftwidth=-1', 'E487:') + call assert_equal(7, &shiftwidth) + setlocal tabstop=7 vartabstop=5,7,10 + call assert_fails('set shiftwidth=-1', 'E487:') + call assert_equal(5, &shiftwidth) + setlocal shiftwidth& vartabstop& tabstop& +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_version.vim b/test/old/testdir/test_version.vim new file mode 100644 index 0000000000..5fd38f7cdc --- /dev/null +++ b/test/old/testdir/test_version.vim @@ -0,0 +1,26 @@ +" Test :version Ex command + +so check.vim +so shared.vim + +func Test_version() + " version should always return the same string. + let v1 = execute('version') + let v2 = execute('version') + call assert_equal(v1, v2) + + call assert_match("^\n\nNVIM v[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+.*", v1) +endfunc + +func Test_version_redirect() + CheckNotGui + CheckCanRunGui + CheckUnix + + call RunVim([], [], '--clean -g --version >Xversion 2>&1') + call assert_match('Features included', readfile('Xversion')->join()) + + call delete('Xversion') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_viminfo.vim b/test/old/testdir/test_viminfo.vim new file mode 100644 index 0000000000..e792db90ab --- /dev/null +++ b/test/old/testdir/test_viminfo.vim @@ -0,0 +1,26 @@ + +" Test for errors in setting 'viminfo' +func Test_viminfo_option_error() + " Missing number + call assert_fails('set viminfo=\"', 'E526:') + for c in split("'/:<@s", '\zs') + call assert_fails('set viminfo=' .. c, 'E526:') + endfor + + " Missing comma + call assert_fails('set viminfo=%10!', 'E527:') + call assert_fails('set viminfo=!%10', 'E527:') + call assert_fails('set viminfo=h%10', 'E527:') + call assert_fails('set viminfo=c%10', 'E527:') + call assert_fails('set viminfo=:10%10', 'E527:') + + " Missing ' setting + call assert_fails('set viminfo=%10', 'E528:') +endfunc + +func Test_viminfo_oldfiles_newfile() + let v:oldfiles = v:_null_list + call assert_equal("\nNo old files", execute('oldfiles')) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_vimscript.vim b/test/old/testdir/test_vimscript.vim new file mode 100644 index 0000000000..6ce59e1a2e --- /dev/null +++ b/test/old/testdir/test_vimscript.vim @@ -0,0 +1,7443 @@ +" Test various aspects of the Vim script language. +" Most of this was formerly in test49.vim (developed by Servatius Brandt +" <Servatius.Brandt@fujitsu-siemens.com>) + +source check.vim +source shared.vim +source script_util.vim + +"------------------------------------------------------------------------------- +" Test environment {{{1 +"------------------------------------------------------------------------------- + +" Append a message to the "messages" file +func Xout(text) + split messages + $put =a:text + wq +endfunc + +com! -nargs=1 Xout call Xout(<args>) + +" Create a new instance of Vim and run the commands in 'test' and then 'verify' +" The commands in 'test' are expected to store the test results in the Xtest.out +" file. If the test passes successfully, then Xtest.out should be empty. +func RunInNewVim(test, verify) + let init =<< trim END + set cpo-=C " support line-continuation in sourced script + source script_util.vim + XpathINIT + XloopINIT + END + let cleanup =<< trim END + call writefile(v:errors, 'Xtest.out') + qall + END + call writefile(init, 'Xtest.vim') + call writefile(a:test, 'Xtest.vim', 'a') + call writefile(a:verify, 'Xverify.vim') + call writefile(cleanup, 'Xverify.vim', 'a') + call RunVim([], [], "-S Xtest.vim -S Xverify.vim") + call assert_equal([], readfile('Xtest.out')) + call delete('Xtest.out') + call delete('Xtest.vim') + call delete('Xverify.vim') +endfunc + +"------------------------------------------------------------------------------- +" Test 1: :endwhile in function {{{1 +" +" Detect if a broken loop is (incorrectly) reactivated by the +" :endwhile. Use a :return to prevent an endless loop, and make +" this test first to get a meaningful result on an error before other +" tests will hang. +"------------------------------------------------------------------------------- + +func T1_F() + Xpath 'a' + let first = 1 + while 1 + Xpath 'b' + if first + Xpath 'c' + let first = 0 + break + else + Xpath 'd' + return + endif + endwhile +endfunc + +func T1_G() + Xpath 'h' + let first = 1 + while 1 + Xpath 'i' + if first + Xpath 'j' + let first = 0 + break + else + Xpath 'k' + return + endif + if 1 " unmatched :if + endwhile +endfunc + +func Test_endwhile_function() + XpathINIT + call T1_F() + Xpath 'F' + + try + call T1_G() + catch + " Catch missing :endif + call assert_true(v:exception =~ 'E171') + Xpath 'x' + endtry + Xpath 'G' + + call assert_equal('abcFhijxG', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 2: :endwhile in script {{{1 +" +" Detect if a broken loop is (incorrectly) reactivated by the +" :endwhile. Use a :finish to prevent an endless loop, and place +" this test before others that might hang to get a meaningful result +" on an error. +" +" This test executes the bodies of the functions T1_F and T1_G from +" the previous test as script files (:return replaced by :finish). +"------------------------------------------------------------------------------- + +func Test_endwhile_script() + XpathINIT + ExecAsScript T1_F + Xpath 'F' + call DeleteTheScript() + + try + ExecAsScript T1_G + catch + " Catch missing :endif + call assert_true(v:exception =~ 'E171') + Xpath 'x' + endtry + Xpath 'G' + call DeleteTheScript() + + call assert_equal('abcFhijxG', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 3: :if, :elseif, :while, :continue, :break {{{1 +"------------------------------------------------------------------------------- + +func Test_if_while() + XpathINIT + if 1 + Xpath 'a' + let loops = 3 + while loops > -1 " main loop: loops == 3, 2, 1 (which breaks) + if loops <= 0 + let break_err = 1 + let loops = -1 + else + Xpath 'b' . loops + endif + if (loops == 2) + while loops == 2 " dummy loop + Xpath 'c' . loops + let loops = loops - 1 + continue " stop dummy loop + Xpath 'd' . loops + endwhile + continue " continue main loop + Xpath 'e' . loops + elseif (loops == 1) + let p = 1 + while p " dummy loop + Xpath 'f' . loops + let p = 0 + break " break dummy loop + Xpath 'g' . loops + endwhile + Xpath 'h' . loops + unlet p + break " break main loop + Xpath 'i' . loops + endif + if (loops > 0) + Xpath 'j' . loops + endif + while loops == 3 " dummy loop + let loops = loops - 1 + endwhile " end dummy loop + endwhile " end main loop + Xpath 'k' + else + Xpath 'l' + endif + Xpath 'm' + if exists("break_err") + Xpath 'm' + unlet break_err + endif + + unlet loops + + call assert_equal('ab3j3b2c2b1f1h1km', g:Xpath) +endfunc + +" Check double quote after skipped "elseif" does not give error E15 +func Test_skipped_elseif() + if "foo" ==? "foo" + let result = "first" + elseif "foo" ==? "foo" + let result = "second" + endif + call assert_equal('first', result) +endfunc + +"------------------------------------------------------------------------------- +" Test 4: :return {{{1 +"------------------------------------------------------------------------------- + +func T4_F() + if 1 + Xpath 'a' + let loops = 3 + while loops > 0 " 3: 2: 1: + Xpath 'b' . loops + if (loops == 2) + Xpath 'c' . loops + return + Xpath 'd' . loops + endif + Xpath 'e' . loops + let loops = loops - 1 + endwhile + Xpath 'f' + else + Xpath 'g' + endif +endfunc + +func Test_return() + XpathINIT + call T4_F() + Xpath '4' + + call assert_equal('ab3e3b2c24', g:Xpath) +endfunc + + +"------------------------------------------------------------------------------- +" Test 5: :finish {{{1 +" +" This test executes the body of the function T4_F from the previous +" test as a script file (:return replaced by :finish). +"------------------------------------------------------------------------------- + +func Test_finish() + XpathINIT + ExecAsScript T4_F + Xpath '5' + call DeleteTheScript() + + call assert_equal('ab3e3b2c25', g:Xpath) +endfunc + + + +"------------------------------------------------------------------------------- +" Test 6: Defining functions in :while loops {{{1 +" +" Functions can be defined inside other functions. An inner function +" gets defined when the outer function is executed. Functions may +" also be defined inside while loops. Expressions in braces for +" defining the function name are allowed. +" +" The functions are defined when sourcing the script, only the +" resulting path is checked in the test function. +"------------------------------------------------------------------------------- + +XpathINIT + +" The command CALL collects the argument of all its invocations in "calls" +" when used from a function (that is, when the global variable "calls" needs +" the "g:" prefix). This is to check that the function code is skipped when +" the function is defined. For inner functions, do so only if the outer +" function is not being executed. +" +let calls = "" +com! -nargs=1 CALL + \ if !exists("calls") && !exists("outer") | + \ let g:calls = g:calls . <args> | + \ endif + +let i = 0 +while i < 3 + let i = i + 1 + if i == 1 + Xpath 'a' + function! F1(arg) + CALL a:arg + let outer = 1 + + let j = 0 + while j < 1 + Xpath 'b' + let j = j + 1 + function! G1(arg) + CALL a:arg + endfunction + Xpath 'c' + endwhile + endfunction + Xpath 'd' + + continue + endif + + Xpath 'e' . i + function! F{i}(i, arg) + CALL a:arg + let outer = 1 + + if a:i == 3 + Xpath 'f' + endif + let k = 0 + while k < 3 + Xpath 'g' . k + let k = k + 1 + function! G{a:i}{k}(arg) + CALL a:arg + endfunction + Xpath 'h' . k + endwhile + endfunction + Xpath 'i' + +endwhile + +if exists("*G1") + Xpath 'j' +endif +if exists("*F1") + call F1("F1") + if exists("*G1") + call G1("G1") + endif +endif + +if exists("G21") || exists("G22") || exists("G23") + Xpath 'k' +endif +if exists("*F2") + call F2(2, "F2") + if exists("*G21") + call G21("G21") + endif + if exists("*G22") + call G22("G22") + endif + if exists("*G23") + call G23("G23") + endif +endif + +if exists("G31") || exists("G32") || exists("G33") + Xpath 'l' +endif +if exists("*F3") + call F3(3, "F3") + if exists("*G31") + call G31("G31") + endif + if exists("*G32") + call G32("G32") + endif + if exists("*G33") + call G33("G33") + endif +endif + +Xpath 'm' + +let g:test6_result = g:Xpath +let g:test6_calls = calls + +unlet calls +delfunction F1 +delfunction G1 +delfunction F2 +delfunction G21 +delfunction G22 +delfunction G23 +delfunction G31 +delfunction G32 +delfunction G33 + +func Test_defining_functions() + call assert_equal('ade2ie3ibcg0h1g1h2g2h3fg0h1g1h2g2h3m', g:test6_result) + call assert_equal('F1G1F2G21G22G23F3G31G32G33', g:test6_calls) +endfunc + +"------------------------------------------------------------------------------- +" Test 7: Continuing on errors outside functions {{{1 +" +" On an error outside a function, the script processing continues +" at the line following the outermost :endif or :endwhile. When not +" inside an :if or :while, the script processing continues at the next +" line. +"------------------------------------------------------------------------------- + +XpathINIT + +if 1 + Xpath 'a' + while 1 + Xpath 'b' + asdf + Xpath 'c' + break + endwhile | Xpath 'd' + Xpath 'e' +endif | Xpath 'f' +Xpath 'g' + +while 1 + Xpath 'h' + if 1 + Xpath 'i' + asdf + Xpath 'j' + endif | Xpath 'k' + Xpath 'l' + break +endwhile | Xpath 'm' +Xpath 'n' + +asdf +Xpath 'o' + +asdf | Xpath 'p' +Xpath 'q' + +let g:test7_result = g:Xpath + +func Test_error_in_script() + call assert_equal('abghinoq', g:test7_result) +endfunc + +"------------------------------------------------------------------------------- +" Test 8: Aborting and continuing on errors inside functions {{{1 +" +" On an error inside a function without the "abort" attribute, the +" script processing continues at the next line (unless the error was +" in a :return command). On an error inside a function with the +" "abort" attribute, the function is aborted and the script processing +" continues after the function call; the value -1 is returned then. +"------------------------------------------------------------------------------- + +XpathINIT + +func T8_F() + if 1 + Xpath 'a' + while 1 + Xpath 'b' + asdf + Xpath 'c' + asdf | Xpath 'd' + Xpath 'e' + break + endwhile + Xpath 'f' + endif | Xpath 'g' + Xpath 'h' + + while 1 + Xpath 'i' + if 1 + Xpath 'j' + asdf + Xpath 'k' + asdf | Xpath 'l' + Xpath 'm' + endif + Xpath 'n' + break + endwhile | Xpath 'o' + Xpath 'p' + + return novar " returns (default return value 0) + Xpath 'q' + return 1 " not reached +endfunc + +func T8_G() abort + if 1 + Xpath 'r' + while 1 + Xpath 's' + asdf " returns -1 + Xpath 't' + break + endwhile + Xpath 'v' + endif | Xpath 'w' + Xpath 'x' + + return -4 " not reached +endfunc + +func T8_H() abort + while 1 + Xpath 'A' + if 1 + Xpath 'B' + asdf " returns -1 + Xpath 'C' + endif + Xpath 'D' + break + endwhile | Xpath 'E' + Xpath 'F' + + return -4 " not reached +endfunc + +" Aborted functions (T8_G and T8_H) return -1. +let g:test8_sum = (T8_F() + 1) - 4 * T8_G() - 8 * T8_H() +Xpath 'X' +let g:test8_result = g:Xpath + +func Test_error_in_function() + call assert_equal(13, g:test8_sum) + call assert_equal('abcefghijkmnoprsABX', g:test8_result) + + delfunction T8_F + delfunction T8_G + delfunction T8_H +endfunc + + +"------------------------------------------------------------------------------- +" Test 9: Continuing after aborted functions {{{1 +" +" When a function with the "abort" attribute is aborted due to an +" error, the next function back in the call hierarchy without an +" "abort" attribute continues; the value -1 is returned then. +"------------------------------------------------------------------------------- + +XpathINIT + +func F() abort + Xpath 'a' + let result = G() " not aborted + Xpath 'b' + if result != 2 + Xpath 'c' + endif + return 1 +endfunc + +func G() " no abort attribute + Xpath 'd' + if H() != -1 " aborted + Xpath 'e' + endif + Xpath 'f' + return 2 +endfunc + +func H() abort + Xpath 'g' + call I() " aborted + Xpath 'h' + return 4 +endfunc + +func I() abort + Xpath 'i' + asdf " error + Xpath 'j' + return 8 +endfunc + +if F() != 1 + Xpath 'k' +endif + +let g:test9_result = g:Xpath + +delfunction F +delfunction G +delfunction H +delfunction I + +func Test_func_abort() + call assert_equal('adgifb', g:test9_result) +endfunc + + +"------------------------------------------------------------------------------- +" Test 10: :if, :elseif, :while argument parsing {{{1 +" +" A '"' or '|' in an argument expression must not be mixed up with +" a comment or a next command after a bar. Parsing errors should +" be recognized. +"------------------------------------------------------------------------------- + +XpathINIT + +func MSG(enr, emsg) + let english = v:lang == "C" || v:lang =~ '^[Ee]n' + if a:enr == "" + Xout "TODO: Add message number for:" a:emsg + let v:errmsg = ":" . v:errmsg + endif + let match = 1 + if v:errmsg !~ '^'.a:enr.':' || (english && v:errmsg !~ a:emsg) + let match = 0 + if v:errmsg == "" + Xout "Message missing." + else + let v:errmsg = v:errmsg->escape('"') + Xout "Unexpected message:" v:errmsg + endif + endif + return match +endfunc + +if 1 || strlen("\"") | Xpath 'a' + Xpath 'b' +endif +Xpath 'c' + +if 0 +elseif 1 || strlen("\"") | Xpath 'd' + Xpath 'e' +endif +Xpath 'f' + +while 1 || strlen("\"") | Xpath 'g' + Xpath 'h' + break +endwhile +Xpath 'i' + +let v:errmsg = "" +if 1 ||| strlen("\"") | Xpath 'j' + Xpath 'k' +endif +Xpath 'l' +if !MSG('E15', "Invalid expression") + Xpath 'm' +endif + +let v:errmsg = "" +if 0 +elseif 1 ||| strlen("\"") | Xpath 'n' + Xpath 'o' +endif +Xpath 'p' +if !MSG('E15', "Invalid expression") + Xpath 'q' +endif + +let v:errmsg = "" +while 1 ||| strlen("\"") | Xpath 'r' + Xpath 's' + break +endwhile +Xpath 't' +if !MSG('E15', "Invalid expression") + Xpath 'u' +endif + +let g:test10_result = g:Xpath +delfunction MSG + +func Test_expr_parsing() + call assert_equal('abcdefghilpt', g:test10_result) +endfunc + + +"------------------------------------------------------------------------------- +" Test 11: :if, :elseif, :while argument evaluation after abort {{{1 +" +" When code is skipped over due to an error, the boolean argument to +" an :if, :elseif, or :while must not be evaluated. +"------------------------------------------------------------------------------- + +XpathINIT + +let calls = 0 + +func P(num) + let g:calls = g:calls + a:num " side effect on call + return 0 +endfunc + +if 1 + Xpath 'a' + asdf " error + Xpath 'b' + if P(1) " should not be called + Xpath 'c' + elseif !P(2) " should not be called + Xpath 'd' + else + Xpath 'e' + endif + Xpath 'f' + while P(4) " should not be called + Xpath 'g' + endwhile + Xpath 'h' +endif +Xpath 'x' + +let g:test11_calls = calls +let g:test11_result = g:Xpath + +unlet calls +delfunction P + +func Test_arg_abort() + call assert_equal(0, g:test11_calls) + call assert_equal('ax', g:test11_result) +endfunc + + +"------------------------------------------------------------------------------- +" Test 12: Expressions in braces in skipped code {{{1 +" +" In code skipped over due to an error or inactive conditional, +" an expression in braces as part of a variable or function name +" should not be evaluated. +"------------------------------------------------------------------------------- + +XpathINIT + +func NULL() + Xpath 'a' + return 0 +endfunc + +func ZERO() + Xpath 'b' + return 0 +endfunc + +func! F0() + Xpath 'c' +endfunc + +func! F1(arg) + Xpath 'e' +endfunc + +let V0 = 1 + +Xpath 'f' +echo 0 ? F{NULL() + V{ZERO()}}() : 1 + +Xpath 'g' +if 0 + Xpath 'h' + call F{NULL() + V{ZERO()}}() +endif + +Xpath 'i' +if 1 + asdf " error + Xpath 'j' + call F1(F{NULL() + V{ZERO()}}()) +endif + +Xpath 'k' +if 1 + asdf " error + Xpath 'l' + call F{NULL() + V{ZERO()}}() +endif + +let g:test12_result = g:Xpath + +func Test_braces_skipped() + call assert_equal('fgik', g:test12_result) +endfunc + + +"------------------------------------------------------------------------------- +" Test 13: Failure in argument evaluation for :while {{{1 +" +" A failure in the expression evaluation for the condition of a :while +" causes the whole :while loop until the matching :endwhile being +" ignored. Continuation is at the next following line. +"------------------------------------------------------------------------------- + +XpathINIT + +Xpath 'a' +while asdf + Xpath 'b' + while 1 + Xpath 'c' + break + endwhile + Xpath 'd' + break +endwhile +Xpath 'e' + +while asdf | Xpath 'f' | endwhile | Xpath 'g' +Xpath 'h' +let g:test13_result = g:Xpath + +func Test_while_fail() + call assert_equal('aeh', g:test13_result) +endfunc + + +"------------------------------------------------------------------------------- +" Test 14: Failure in argument evaluation for :if {{{1 +" +" A failure in the expression evaluation for the condition of an :if +" does not cause the corresponding :else or :endif being matched to +" a previous :if/:elseif. Neither of both branches of the failed :if +" are executed. +"------------------------------------------------------------------------------- + +XpathINIT + +function! F() + Xpath 'a' + let x = 0 + if x " false + Xpath 'b' + elseif !x " always true + Xpath 'c' + let x = 1 + if g:boolvar " possibly undefined + Xpath 'd' + else + Xpath 'e' + endif + Xpath 'f' + elseif x " never executed + Xpath 'g' + endif + Xpath 'h' +endfunction + +let boolvar = 1 +call F() +Xpath '-' + +unlet boolvar +call F() +let g:test14_result = g:Xpath + +delfunction F + +func Test_if_fail() + call assert_equal('acdfh-acfh', g:test14_result) +endfunc + + +"------------------------------------------------------------------------------- +" Test 15: Failure in argument evaluation for :if (bar) {{{1 +" +" Like previous test, except that the failing :if ... | ... | :endif +" is in a single line. +"------------------------------------------------------------------------------- + +XpathINIT + +function! F() + Xpath 'a' + let x = 0 + if x " false + Xpath 'b' + elseif !x " always true + Xpath 'c' + let x = 1 + if g:boolvar | Xpath 'd' | else | Xpath 'e' | endif + Xpath 'f' + elseif x " never executed + Xpath 'g' + endif + Xpath 'h' +endfunction + +let boolvar = 1 +call F() +Xpath '-' + +unlet boolvar +call F() +let g:test15_result = g:Xpath + +delfunction F + +func Test_if_bar_fail() + call assert_equal('acdfh-acfh', g:test15_result) +endfunc + +"------------------------------------------------------------------------------- +" Test 16: Double :else or :elseif after :else {{{1 +" +" Multiple :elses or an :elseif after an :else are forbidden. +"------------------------------------------------------------------------------- + +func T16_F() abort + if 0 + Xpath 'a' + else + Xpath 'b' + else " aborts function + Xpath 'c' + endif + Xpath 'd' +endfunc + +func T16_G() abort + if 0 + Xpath 'a' + else + Xpath 'b' + elseif 1 " aborts function + Xpath 'c' + else + Xpath 'd' + endif + Xpath 'e' +endfunc + +func T16_H() abort + if 0 + Xpath 'a' + elseif 0 + Xpath 'b' + else + Xpath 'c' + else " aborts function + Xpath 'd' + endif + Xpath 'e' +endfunc + +func T16_I() abort + if 0 + Xpath 'a' + elseif 0 + Xpath 'b' + else + Xpath 'c' + elseif 1 " aborts function + Xpath 'd' + else + Xpath 'e' + endif + Xpath 'f' +endfunc + +func Test_Multi_Else() + XpathINIT + try + call T16_F() + catch /E583:/ + Xpath 'e' + endtry + call assert_equal('be', g:Xpath) + + XpathINIT + try + call T16_G() + catch /E584:/ + Xpath 'f' + endtry + call assert_equal('bf', g:Xpath) + + XpathINIT + try + call T16_H() + catch /E583:/ + Xpath 'f' + endtry + call assert_equal('cf', g:Xpath) + + XpathINIT + try + call T16_I() + catch /E584:/ + Xpath 'g' + endtry + call assert_equal('cg', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 17: Nesting of unmatched :if or :endif inside a :while {{{1 +" +" The :while/:endwhile takes precedence in nesting over an unclosed +" :if or an unopened :endif. +"------------------------------------------------------------------------------- + +" While loops inside a function are continued on error. +func T17_F() + let loops = 3 + while loops > 0 + let loops -= 1 + Xpath 'a' . loops + if (loops == 1) + Xpath 'b' . loops + continue + elseif (loops == 0) + Xpath 'c' . loops + break + elseif 1 + Xpath 'd' . loops + " endif missing! + endwhile " :endwhile after :if 1 + Xpath 'e' +endfunc + +func T17_G() + let loops = 2 + while loops > 0 + let loops -= 1 + Xpath 'a' . loops + if 0 + Xpath 'b' . loops + " endif missing + endwhile " :endwhile after :if 0 +endfunc + +func T17_H() + let loops = 2 + while loops > 0 + let loops -= 1 + Xpath 'a' . loops + " if missing! + endif " :endif without :if in while + Xpath 'b' . loops + endwhile +endfunc + +" Error continuation outside a function is at the outermost :endwhile or :endif. +XpathINIT +let v:errmsg = '' +let loops = 2 +while loops > 0 + let loops -= 1 + Xpath 'a' . loops + if 0 + Xpath 'b' . loops + " endif missing! Following :endwhile fails. +endwhile | Xpath 'c' +Xpath 'd' +call assert_match('E171:', v:errmsg) +call assert_equal('a1d', g:Xpath) + +func Test_unmatched_if_in_while() + XpathINIT + call assert_fails('call T17_F()', 'E171:') + call assert_equal('a2d2a1b1a0c0e', g:Xpath) + + XpathINIT + call assert_fails('call T17_G()', 'E171:') + call assert_equal('a1a0', g:Xpath) + + XpathINIT + call assert_fails('call T17_H()', 'E580:') + call assert_equal('a1b1a0b0', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 18: Interrupt (Ctrl-C pressed) {{{1 +" +" On an interrupt, the script processing is terminated immediately. +"------------------------------------------------------------------------------- + +func Test_interrupt_while_if() + let test =<< trim [CODE] + try + if 1 + Xpath 'a' + while 1 + Xpath 'b' + if 1 + Xpath 'c' + call interrupt() + call assert_report('should not get here') + break + finish + endif | call assert_report('should not get here') + call assert_report('should not get here') + endwhile | call assert_report('should not get here') + call assert_report('should not get here') + endif | call assert_report('should not get here') + call assert_report('should not get here') + catch /^Vim:Interrupt$/ + Xpath 'd' + endtry | Xpath 'e' + Xpath 'f' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdef', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_interrupt_try() + let test =<< trim [CODE] + try + try + Xpath 'a' + call interrupt() + call assert_report('should not get here') + endtry | call assert_report('should not get here') + call assert_report('should not get here') + catch /^Vim:Interrupt$/ + Xpath 'b' + endtry | Xpath 'c' + Xpath 'd' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcd', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_interrupt_func_while_if() + let test =<< trim [CODE] + func F() + if 1 + Xpath 'a' + while 1 + Xpath 'b' + if 1 + Xpath 'c' + call interrupt() + call assert_report('should not get here') + break + return + endif | call assert_report('should not get here') + call assert_report('should not get here') + endwhile | call assert_report('should not get here') + call assert_report('should not get here') + endif | call assert_report('should not get here') + call assert_report('should not get here') + endfunc + + Xpath 'd' + try + call F() | call assert_report('should not get here') + catch /^Vim:Interrupt$/ + Xpath 'e' + endtry | Xpath 'f' + Xpath 'g' + [CODE] + let verify =<< trim [CODE] + call assert_equal('dabcefg', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_interrupt_func_try() + let test =<< trim [CODE] + func G() + try + Xpath 'a' + call interrupt() + call assert_report('should not get here') + endtry | call assert_report('should not get here') + call assert_report('should not get here') + endfunc + + Xpath 'b' + try + call G() | call assert_report('should not get here') + catch /^Vim:Interrupt$/ + Xpath 'c' + endtry | Xpath 'd' + Xpath 'e' + [CODE] + let verify =<< trim [CODE] + call assert_equal('bacde', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 19: Aborting on errors inside :try/:endtry {{{1 +" +" An error in a command dynamically enclosed in a :try/:endtry region +" aborts script processing immediately. It does not matter whether +" the failing command is outside or inside a function and whether a +" function has an "abort" attribute. +"------------------------------------------------------------------------------- + +func Test_try_error_abort_1() + let test =<< trim [CODE] + func F() abort + Xpath 'a' + asdf + call assert_report('should not get here') + endfunc + + try + Xpath 'b' + call F() + call assert_report('should not get here') + endtry | call assert_report('should not get here') + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('ba', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_try_error_abort_2() + let test =<< trim [CODE] + func G() + Xpath 'a' + asdf + call assert_report('should not get here') + endfunc + + try + Xpath 'b' + call G() + call assert_report('should not get here') + endtry | call assert_report('should not get here') + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('ba', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_try_error_abort_3() + let test =<< trim [CODE] + try + Xpath 'a' + asdf + call assert_report('should not get here') + endtry | call assert_report('should not get here') + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('a', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_try_error_abort_4() + let test =<< trim [CODE] + if 1 + try + Xpath 'a' + asdf + call assert_report('should not get here') + endtry | call assert_report('should not get here') + endif | call assert_report('should not get here') + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('a', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_try_error_abort_5() + let test =<< trim [CODE] + let p = 1 + while p + let p = 0 + try + Xpath 'a' + asdf + call assert_report('should not get here') + endtry | call assert_report('should not get here') + endwhile | call assert_report('should not get here') + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('a', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_try_error_abort_6() + let test =<< trim [CODE] + let p = 1 + Xpath 'a' + while p + Xpath 'b' + let p = 0 + try + Xpath 'c' + endwhile | call assert_report('should not get here') + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('abc', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 20: Aborting on errors after :try/:endtry {{{1 +" +" When an error occurs after the last active :try/:endtry region has +" been left, termination behavior is as if no :try/:endtry has been +" seen. +"------------------------------------------------------------------------------- + +func Test_error_after_try_1() + let test =<< trim [CODE] + let p = 1 + while p + let p = 0 + Xpath 'a' + try + Xpath 'b' + endtry + asdf + call assert_report('should not get here') + endwhile | call assert_report('should not get here') + Xpath 'c' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abc', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_error_after_try_2() + let test =<< trim [CODE] + while 1 + try + Xpath 'a' + break + call assert_report('should not get here') + endtry + endwhile + Xpath 'b' + asdf + Xpath 'c' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abc', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_error_after_try_3() + let test =<< trim [CODE] + while 1 + try + Xpath 'a' + break + call assert_report('should not get here') + finally + Xpath 'b' + endtry + endwhile + Xpath 'c' + asdf + Xpath 'd' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcd', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_error_after_try_4() + let test =<< trim [CODE] + while 1 + try + Xpath 'a' + finally + Xpath 'b' + break + call assert_report('should not get here') + endtry + endwhile + Xpath 'c' + asdf + Xpath 'd' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcd', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_error_after_try_5() + let test =<< trim [CODE] + let p = 1 + while p + let p = 0 + try + Xpath 'a' + continue + call assert_report('should not get here') + endtry + endwhile + Xpath 'b' + asdf + Xpath 'c' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abc', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_error_after_try_6() + let test =<< trim [CODE] + let p = 1 + while p + let p = 0 + try + Xpath 'a' + continue + call assert_report('should not get here') + finally + Xpath 'b' + endtry + endwhile + Xpath 'c' + asdf + Xpath 'd' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcd', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_error_after_try_7() + let test =<< trim [CODE] + let p = 1 + while p + let p = 0 + try + Xpath 'a' + finally + Xpath 'b' + continue + call assert_report('should not get here') + endtry + endwhile + Xpath 'c' + asdf + Xpath 'd' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcd', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 21: :finally for :try after :continue/:break/:return/:finish {{{1 +" +" If a :try conditional stays inactive due to a preceding :continue, +" :break, :return, or :finish, its :finally clause should not be +" executed. +"------------------------------------------------------------------------------- + +func Test_finally_after_loop_ctrl_statement() + let test =<< trim [CODE] + func F() + let loops = 2 + while loops > 0 + XloopNEXT + let loops = loops - 1 + try + if loops == 1 + Xloop 'a' + continue + call assert_report('should not get here') + elseif loops == 0 + Xloop 'b' + break + call assert_report('should not get here') + endif + + try " inactive + call assert_report('should not get here') + finally + call assert_report('should not get here') + endtry + finally + Xloop 'c' + endtry + call assert_report('should not get here') + endwhile + + try + Xpath 'd' + return + call assert_report('should not get here') + try " inactive + call assert_report('should not get here') + finally + call assert_report('should not get here') + endtry + finally + Xpath 'e' + endtry + call assert_report('should not get here') + endfunc + + try + Xpath 'f' + call F() + Xpath 'g' + finish + call assert_report('should not get here') + try " inactive + call assert_report('should not get here') + finally + call assert_report('should not get here') + endtry + finally + Xpath 'h' + endtry + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('fa2c2b3c3degh', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 22: :finally for a :try after an error/interrupt/:throw {{{1 +" +" If a :try conditional stays inactive due to a preceding error or +" interrupt or :throw, its :finally clause should not be executed. +"------------------------------------------------------------------------------- + +func Test_finally_after_error_in_func() + let test =<< trim [CODE] + func Error() + try + Xpath 'b' + asdf " aborting error, triggering error exception + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endfunc + + Xpath 'a' + call Error() + call assert_report('should not get here') + + if 1 " not active due to error + try " not active since :if inactive + call assert_report('should not get here') + finally + call assert_report('should not get here') + endtry + endif + + try " not active due to error + call assert_report('should not get here') + finally + call assert_report('should not get here') + endtry + [CODE] + let verify =<< trim [CODE] + call assert_equal('ab', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_finally_after_interrupt() + let test =<< trim [CODE] + func Interrupt() + try + Xpath 'a' + call interrupt() " triggering interrupt exception + call assert_report('should not get here') + endtry + endfunc + + Xpath 'b' + try + call Interrupt() + catch /^Vim:Interrupt$/ + Xpath 'c' + finish + endtry + call assert_report('should not get here') + + if 1 " not active due to interrupt + try " not active since :if inactive + call assert_report('should not get here') + finally + call assert_report('should not get here') + endtry + endif + + try " not active due to interrupt + call assert_report('should not get here') + finally + call assert_report('should not get here') + endtry + [CODE] + let verify =<< trim [CODE] + call assert_equal('bac', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_finally_after_throw() + let test =<< trim [CODE] + func Throw() + Xpath 'a' + throw 'xyz' + endfunc + + Xpath 'b' + call Throw() + call assert_report('should not get here') + + if 1 " not active due to :throw + try " not active since :if inactive + call assert_report('should not get here') + finally + call assert_report('should not get here') + endtry + endif + + try " not active due to :throw + call assert_report('should not get here') + finally + call assert_report('should not get here') + endtry + [CODE] + let verify =<< trim [CODE] + call assert_equal('ba', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 23: :catch clauses for a :try after a :throw {{{1 +" +" If a :try conditional stays inactive due to a preceding :throw, +" none of its :catch clauses should be executed. +"------------------------------------------------------------------------------- + +func Test_catch_after_throw() + let test =<< trim [CODE] + try + Xpath 'a' + throw "xyz" + call assert_report('should not get here') + + if 1 " not active due to :throw + try " not active since :if inactive + call assert_report('should not get here') + catch /xyz/ + call assert_report('should not get here') + endtry + endif + catch /xyz/ + Xpath 'b' + endtry + + Xpath 'c' + throw "abc" + call assert_report('should not get here') + + try " not active due to :throw + call assert_report('should not get here') + catch /abc/ + call assert_report('should not get here') + endtry + [CODE] + let verify =<< trim [CODE] + call assert_equal('abc', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 24: :endtry for a :try after a :throw {{{1 +" +" If a :try conditional stays inactive due to a preceding :throw, +" its :endtry should not rethrow the exception to the next surrounding +" active :try conditional. +"------------------------------------------------------------------------------- + +func Test_endtry_after_throw() + let test =<< trim [CODE] + try " try 1 + try " try 2 + Xpath 'a' + throw "xyz" " makes try 2 inactive + call assert_report('should not get here') + + try " try 3 + call assert_report('should not get here') + endtry " no rethrow to try 1 + catch /xyz/ " should catch although try 2 inactive + Xpath 'b' + endtry + catch /xyz/ " try 1 active, but exception already caught + call assert_report('should not get here') + endtry + Xpath 'c' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abc', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 27: Executing :finally clauses after :return {{{1 +" +" For a :return command dynamically enclosed in a :try/:endtry region, +" :finally clauses are executed and the called function is ended. +"------------------------------------------------------------------------------- + +func T27_F() + try + Xpath 'a' + try + Xpath 'b' + return + call assert_report('should not get here') + finally + Xpath 'c' + endtry + Xpath 'd' + finally + Xpath 'e' + endtry + call assert_report('should not get here') +endfunc + +func T27_G() + try + Xpath 'f' + return + call assert_report('should not get here') + finally + Xpath 'g' + call T27_F() + Xpath 'h' + endtry + call assert_report('should not get here') +endfunc + +func T27_H() + try + Xpath 'i' + call T27_G() + Xpath 'j' + finally + Xpath 'k' + return + call assert_report('should not get here') + endtry + call assert_report('should not get here') +endfunction + +func Test_finally_after_return() + XpathINIT + try + Xpath 'l' + call T27_H() + Xpath 'm' + finally + Xpath 'n' + endtry + call assert_equal('lifgabcehjkmn', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 28: Executing :finally clauses after :finish {{{1 +" +" For a :finish command dynamically enclosed in a :try/:endtry region, +" :finally clauses are executed and the sourced file is finished. +" +" This test executes the bodies of the functions F, G, and H from the +" previous test as script files (:return replaced by :finish). +"------------------------------------------------------------------------------- + +func Test_finally_after_finish() + XpathINIT + + let scriptF = MakeScript("T27_F") + let scriptG = MakeScript("T27_G", scriptF) + let scriptH = MakeScript("T27_H", scriptG) + + try + Xpath 'A' + exec "source" scriptH + Xpath 'B' + finally + Xpath 'C' + endtry + Xpath 'D' + call assert_equal('AifgabcehjkBCD', g:Xpath) + call delete(scriptF) + call delete(scriptG) + call delete(scriptH) +endfunc + +"------------------------------------------------------------------------------- +" Test 29: Executing :finally clauses on errors {{{1 +" +" After an error in a command dynamically enclosed in a :try/:endtry +" region, :finally clauses are executed and the script processing is +" terminated. +"------------------------------------------------------------------------------- + +func Test_finally_after_error_1() + let test =<< trim [CODE] + func F() + while 1 + try + Xpath 'a' + while 1 + try + Xpath 'b' + asdf " error + call assert_report('should not get here') + finally + Xpath 'c' + endtry | call assert_report('should not get here') + call assert_report('should not get here') + break + endwhile + call assert_report('should not get here') + finally + Xpath 'd' + endtry | call assert_report('should not get here') + call assert_report('should not get here') + break + endwhile + call assert_report('should not get here') + endfunc + + while 1 + try + Xpath 'e' + while 1 + call F() + call assert_report('should not get here') + break + endwhile | call assert_report('should not get here') + call assert_report('should not get here') + finally + Xpath 'f' + endtry | call assert_report('should not get here') + endwhile | call assert_report('should not get here') + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('eabcdf', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_finally_after_error_2() + let test =<< trim [CODE] + func G() abort + if 1 + try + Xpath 'a' + asdf " error + call assert_report('should not get here') + finally + Xpath 'b' + endtry | Xpath 'c' + endif | Xpath 'd' + call assert_report('should not get here') + endfunc + + if 1 + try + Xpath 'e' + call G() + call assert_report('should not get here') + finally + Xpath 'f' + endtry | call assert_report('should not get here') + endif | call assert_report('should not get here') + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('eabf', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 30: Executing :finally clauses on interrupt {{{1 +" +" After an interrupt in a command dynamically enclosed in +" a :try/:endtry region, :finally clauses are executed and the +" script processing is terminated. +"------------------------------------------------------------------------------- + +func Test_finally_on_interrupt() + let test =<< trim [CODE] + func F() + try + Xloop 'a' + call interrupt() + call assert_report('should not get here') + finally + Xloop 'b' + endtry + call assert_report('should not get here') + endfunc + + try + try + Xpath 'c' + try + Xpath 'd' + call interrupt() + call assert_report('should not get here') + finally + Xpath 'e' + try + Xpath 'f' + try + Xpath 'g' + finally + Xpath 'h' + try + Xpath 'i' + call interrupt() + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + finally + Xpath 'j' + try + Xpath 'k' + call F() + call assert_report('should not get here') + finally + Xpath 'l' + try + Xpath 'm' + XloopNEXT + ExecAsScript F + call assert_report('should not get here') + finally + Xpath 'n' + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + catch /^Vim:Interrupt$/ + Xpath 'o' + endtry + [CODE] + let verify =<< trim [CODE] + call assert_equal('cdefghijka1b1lma2b2no', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 31: Executing :finally clauses after :throw {{{1 +" +" After a :throw dynamically enclosed in a :try/:endtry region, +" :finally clauses are executed and the script processing is +" terminated. +"------------------------------------------------------------------------------- + +func Test_finally_after_throw_2() + let test =<< trim [CODE] + func F() + try + Xloop 'a' + throw "exception" + call assert_report('should not get here') + finally + Xloop 'b' + endtry + call assert_report('should not get here') + endfunc + + try + Xpath 'c' + try + Xpath 'd' + throw "exception" + call assert_report('should not get here') + finally + Xpath 'e' + try + Xpath 'f' + try + Xpath 'g' + finally + Xpath 'h' + try + Xpath 'i' + throw "exception" + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + finally + Xpath 'j' + try + Xpath 'k' + call F() + call assert_report('should not get here') + finally + Xpath 'l' + try + Xpath 'm' + XloopNEXT + ExecAsScript F + call assert_report('should not get here') + finally + Xpath 'n' + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endtry + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('cdefghijka1b1lma2b2n', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 34: :finally reason discarded by :continue {{{1 +" +" When a :finally clause is executed due to a :continue, :break, +" :return, :finish, error, interrupt or :throw, the jump reason is +" discarded by a :continue in the finally clause. +"------------------------------------------------------------------------------- + +func Test_finally_after_continue() + let test =<< trim [CODE] + func C(jump) + XloopNEXT + let loop = 0 + while loop < 2 + let loop = loop + 1 + if loop == 1 + try + if a:jump == "continue" + continue + elseif a:jump == "break" + break + elseif a:jump == "return" || a:jump == "finish" + return + elseif a:jump == "error" + asdf + elseif a:jump == "interrupt" + call interrupt() + let dummy = 0 + elseif a:jump == "throw" + throw "abc" + endif + finally + continue " discards jump that caused the :finally + call assert_report('should not get here') + endtry + call assert_report('should not get here') + elseif loop == 2 + Xloop 'a' + endif + endwhile + endfunc + + call C("continue") + Xpath 'b' + call C("break") + Xpath 'c' + call C("return") + Xpath 'd' + let g:jump = "finish" + ExecAsScript C + unlet g:jump + Xpath 'e' + try + call C("error") + Xpath 'f' + finally + Xpath 'g' + try + call C("interrupt") + Xpath 'h' + finally + Xpath 'i' + call C("throw") + Xpath 'j' + endtry + endtry + Xpath 'k' + [CODE] + let verify =<< trim [CODE] + call assert_equal('a2ba3ca4da5ea6fga7hia8jk', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 35: :finally reason discarded by :break {{{1 +" +" When a :finally clause is executed due to a :continue, :break, +" :return, :finish, error, interrupt or :throw, the jump reason is +" discarded by a :break in the finally clause. +"------------------------------------------------------------------------------- + +func Test_finally_discard_by_break() + let test =<< trim [CODE] + func B(jump) + XloopNEXT + let loop = 0 + while loop < 2 + let loop = loop + 1 + if loop == 1 + try + if a:jump == "continue" + continue + elseif a:jump == "break" + break + elseif a:jump == "return" || a:jump == "finish" + return + elseif a:jump == "error" + asdf + elseif a:jump == "interrupt" + call interrupt() + let dummy = 0 + elseif a:jump == "throw" + throw "abc" + endif + finally + break " discards jump that caused the :finally + call assert_report('should not get here') + endtry + elseif loop == 2 + call assert_report('should not get here') + endif + endwhile + Xloop 'a' + endfunc + + call B("continue") + Xpath 'b' + call B("break") + Xpath 'c' + call B("return") + Xpath 'd' + let g:jump = "finish" + ExecAsScript B + unlet g:jump + Xpath 'e' + try + call B("error") + Xpath 'f' + finally + Xpath 'g' + try + call B("interrupt") + Xpath 'h' + finally + Xpath 'i' + call B("throw") + Xpath 'j' + endtry + endtry + Xpath 'k' + [CODE] + let verify =<< trim [CODE] + call assert_equal('a2ba3ca4da5ea6fga7hia8jk', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 36: :finally reason discarded by :return {{{1 +" +" When a :finally clause is executed due to a :continue, :break, +" :return, :finish, error, interrupt or :throw, the jump reason is +" discarded by a :return in the finally clause. +"------------------------------------------------------------------------------- + +func Test_finally_discard_by_return() + let test =<< trim [CODE] + func R(jump, retval) abort + let loop = 0 + while loop < 2 + let loop = loop + 1 + if loop == 1 + try + if a:jump == "continue" + continue + elseif a:jump == "break" + break + elseif a:jump == "return" + return + elseif a:jump == "error" + asdf + elseif a:jump == "interrupt" + call interrupt() + let dummy = 0 + elseif a:jump == "throw" + throw "abc" + endif + finally + return a:retval " discards jump that caused the :finally + call assert_report('should not get here') + endtry + elseif loop == 2 + call assert_report('should not get here') + endif + endwhile + call assert_report('should not get here') + endfunc + + let sum = -R("continue", -8) + Xpath 'a' + let sum = sum - R("break", -16) + Xpath 'b' + let sum = sum - R("return", -32) + Xpath 'c' + try + let sum = sum - R("error", -64) + Xpath 'd' + finally + Xpath 'e' + try + let sum = sum - R("interrupt", -128) + Xpath 'f' + finally + Xpath 'g' + let sum = sum - R("throw", -256) + Xpath 'h' + endtry + endtry + Xpath 'i' + + let expected = 8 + 16 + 32 + 64 + 128 + 256 + call assert_equal(sum, expected) + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefghi', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 37: :finally reason discarded by :finish {{{1 +" +" When a :finally clause is executed due to a :continue, :break, +" :return, :finish, error, interrupt or :throw, the jump reason is +" discarded by a :finish in the finally clause. +"------------------------------------------------------------------------------- + +func Test_finally_discard_by_finish() + let test =<< trim [CODE] + func F(jump) " not executed as function, transformed to a script + let loop = 0 + while loop < 2 + let loop = loop + 1 + if loop == 1 + try + if a:jump == "continue" + continue + elseif a:jump == "break" + break + elseif a:jump == "finish" + finish + elseif a:jump == "error" + asdf + elseif a:jump == "interrupt" + call interrupt() + let dummy = 0 + elseif a:jump == "throw" + throw "abc" + endif + finally + finish " discards jump that caused the :finally + call assert_report('should not get here') + endtry + elseif loop == 2 + call assert_report('should not get here') + endif + endwhile + call assert_report('should not get here') + endfunc + + let scriptF = MakeScript("F") + delfunction F + + let g:jump = "continue" + exec "source" scriptF + Xpath 'a' + let g:jump = "break" + exec "source" scriptF + Xpath 'b' + let g:jump = "finish" + exec "source" scriptF + Xpath 'c' + try + let g:jump = "error" + exec "source" scriptF + Xpath 'd' + finally + Xpath 'e' + try + let g:jump = "interrupt" + exec "source" scriptF + Xpath 'f' + finally + Xpath 'g' + try + let g:jump = "throw" + exec "source" scriptF + Xpath 'h' + finally + Xpath 'i' + endtry + endtry + endtry + unlet g:jump + call delete(scriptF) + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefghi', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 38: :finally reason discarded by an error {{{1 +" +" When a :finally clause is executed due to a :continue, :break, +" :return, :finish, error, interrupt or :throw, the jump reason is +" discarded by an error in the finally clause. +"------------------------------------------------------------------------------- + +func Test_finally_discard_by_error() + let test =<< trim [CODE] + func E(jump) + let loop = 0 + while loop < 2 + let loop = loop + 1 + if loop == 1 + try + if a:jump == "continue" + continue + elseif a:jump == "break" + break + elseif a:jump == "return" || a:jump == "finish" + return + elseif a:jump == "error" + asdf + elseif a:jump == "interrupt" + call interrupt() + let dummy = 0 + elseif a:jump == "throw" + throw "abc" + endif + finally + asdf " error; discards jump that caused the :finally + endtry + elseif loop == 2 + call assert_report('should not get here') + endif + endwhile + call assert_report('should not get here') + endfunc + + try + Xpath 'a' + call E("continue") + call assert_report('should not get here') + finally + try + Xpath 'b' + call E("break") + call assert_report('should not get here') + finally + try + Xpath 'c' + call E("return") + call assert_report('should not get here') + finally + try + Xpath 'd' + let g:jump = "finish" + ExecAsScript E + call assert_report('should not get here') + finally + unlet g:jump + try + Xpath 'e' + call E("error") + call assert_report('should not get here') + finally + try + Xpath 'f' + call E("interrupt") + call assert_report('should not get here') + finally + try + Xpath 'g' + call E("throw") + call assert_report('should not get here') + finally + Xpath 'h' + delfunction E + endtry + endtry + endtry + endtry + endtry + endtry + endtry + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefgh', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 39: :finally reason discarded by an interrupt {{{1 +" +" When a :finally clause is executed due to a :continue, :break, +" :return, :finish, error, interrupt or :throw, the jump reason is +" discarded by an interrupt in the finally clause. +"------------------------------------------------------------------------------- + +func Test_finally_discarded_by_interrupt() + let test =<< trim [CODE] + func I(jump) + let loop = 0 + while loop < 2 + let loop = loop + 1 + if loop == 1 + try + if a:jump == "continue" + continue + elseif a:jump == "break" + break + elseif a:jump == "return" || a:jump == "finish" + return + elseif a:jump == "error" + asdf + elseif a:jump == "interrupt" + call interrupt() + let dummy = 0 + elseif a:jump == "throw" + throw "abc" + endif + finally + call interrupt() + let dummy = 0 + endtry + elseif loop == 2 + call assert_report('should not get here') + endif + endwhile + call assert_report('should not get here') + endfunc + + try + try + Xpath 'a' + call I("continue") + call assert_report('should not get here') + finally + try + Xpath 'b' + call I("break") + call assert_report('should not get here') + finally + try + Xpath 'c' + call I("return") + call assert_report('should not get here') + finally + try + Xpath 'd' + let g:jump = "finish" + ExecAsScript I + call assert_report('should not get here') + finally + unlet g:jump + try + Xpath 'e' + call I("error") + call assert_report('should not get here') + finally + try + Xpath 'f' + call I("interrupt") + call assert_report('should not get here') + finally + try + Xpath 'g' + call I("throw") + call assert_report('should not get here') + finally + Xpath 'h' + delfunction I + endtry + endtry + endtry + endtry + endtry + endtry + endtry + call assert_report('should not get here') + catch /^Vim:Interrupt$/ + Xpath 'A' + endtry + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefghA', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 40: :finally reason discarded by :throw {{{1 +" +" When a :finally clause is executed due to a :continue, :break, +" :return, :finish, error, interrupt or :throw, the jump reason is +" discarded by a :throw in the finally clause. +"------------------------------------------------------------------------------- + +func Test_finally_discard_by_throw() + let test =<< trim [CODE] + func T(jump) + let loop = 0 + while loop < 2 + let loop = loop + 1 + if loop == 1 + try + if a:jump == "continue" + continue + elseif a:jump == "break" + break + elseif a:jump == "return" || a:jump == "finish" + return + elseif a:jump == "error" + asdf + elseif a:jump == "interrupt" + call interrupt() + let dummy = 0 + elseif a:jump == "throw" + throw "abc" + endif + finally + throw "xyz" " discards jump that caused the :finally + endtry + elseif loop == 2 + call assert_report('should not get here') + endif + endwhile + call assert_report('should not get here') + endfunc + + try + Xpath 'a' + call T("continue") + call assert_report('should not get here') + finally + try + Xpath 'b' + call T("break") + call assert_report('should not get here') + finally + try + Xpath 'c' + call T("return") + call assert_report('should not get here') + finally + try + Xpath 'd' + let g:jump = "finish" + ExecAsScript T + call assert_report('should not get here') + finally + unlet g:jump + try + Xpath 'e' + call T("error") + call assert_report('should not get here') + finally + try + Xpath 'f' + call T("interrupt") + call assert_report('should not get here') + finally + try + Xpath 'g' + call T("throw") + call assert_report('should not get here') + finally + Xpath 'h' + delfunction T + endtry + endtry + endtry + endtry + endtry + endtry + endtry + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefgh', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 49: Throwing exceptions across functions {{{1 +" +" When an exception is thrown but not caught inside a function, the +" caller is checked for a matching :catch clause. +"------------------------------------------------------------------------------- + +func T49_C() + try + Xpath 'a' + throw "arrgh" + call assert_report('should not get here') + catch /arrgh/ + Xpath 'b' + endtry + Xpath 'c' +endfunc + +func T49_T1() + XloopNEXT + try + Xloop 'd' + throw "arrgh" + call assert_report('should not get here') + finally + Xloop 'e' + endtry + Xloop 'f' +endfunc + +func T49_T2() + try + Xpath 'g' + call T49_T1() + call assert_report('should not get here') + finally + Xpath 'h' + endtry + call assert_report('should not get here') +endfunc + +func Test_throw_exception_across_funcs() + XpathINIT + XloopINIT + try + Xpath 'i' + call T49_C() " throw and catch + Xpath 'j' + catch /.*/ + call assert_report('should not get here') + endtry + + try + Xpath 'k' + call T49_T1() " throw, one level + call assert_report('should not get here') + catch /arrgh/ + Xpath 'l' + catch /.*/ + call assert_report('should not get here') + endtry + + try + Xpath 'm' + call T49_T2() " throw, two levels + call assert_report('should not get here') + catch /arrgh/ + Xpath 'n' + catch /.*/ + call assert_report('should not get here') + endtry + Xpath 'o' + + call assert_equal('iabcjkd2e2lmgd3e3hno', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 50: Throwing exceptions across script files {{{1 +" +" When an exception is thrown but not caught inside a script file, +" the sourcing script or function is checked for a matching :catch +" clause. +" +" This test executes the bodies of the functions C, T1, and T2 from +" the previous test as script files (:return replaced by :finish). +"------------------------------------------------------------------------------- + +func T50_F() + try + Xpath 'A' + exec "source" g:scriptC + Xpath 'B' + catch /.*/ + call assert_report('should not get here') + endtry + + try + Xpath 'C' + exec "source" g:scriptT1 + call assert_report('should not get here') + catch /arrgh/ + Xpath 'D' + catch /.*/ + call assert_report('should not get here') + endtry +endfunc + +func Test_throw_across_script() + XpathINIT + XloopINIT + let g:scriptC = MakeScript("T49_C") + let g:scriptT1 = MakeScript("T49_T1") + let scriptT2 = MakeScript("T49_T2", g:scriptT1) + + try + Xpath 'E' + call T50_F() + Xpath 'F' + exec "source" scriptT2 + call assert_report('should not get here') + catch /arrgh/ + Xpath 'G' + catch /.*/ + call assert_report('should not get here') + endtry + Xpath 'H' + call assert_equal('EAabcBCd2e2DFgd3e3hGH', g:Xpath) + + call delete(g:scriptC) + call delete(g:scriptT1) + call delete(scriptT2) + unlet g:scriptC g:scriptT1 scriptT2 +endfunc + +"------------------------------------------------------------------------------- +" Test 52: Uncaught exceptions {{{1 +" +" When an exception is thrown but not caught, an error message is +" displayed when the script is terminated. In case of an interrupt +" or error exception, the normal interrupt or error message(s) are +" displayed. +"------------------------------------------------------------------------------- + +func Test_uncaught_exception_1() + CheckEnglish + + let test =<< trim [CODE] + Xpath 'a' + throw "arrgh" + call assert_report('should not get here')` + [CODE] + let verify =<< trim [CODE] + call assert_equal('E605: Exception not caught: arrgh', v:errmsg) + call assert_equal('a', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_uncaught_exception_2() + CheckEnglish + + let test =<< trim [CODE] + try + Xpath 'a' + throw "oops" + call assert_report('should not get here')` + catch /arrgh/ + call assert_report('should not get here')` + endtry + call assert_report('should not get here')` + [CODE] + let verify =<< trim [CODE] + call assert_equal('E605: Exception not caught: oops', v:errmsg) + call assert_equal('a', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_uncaught_exception_3() + CheckEnglish + + let test =<< trim [CODE] + func T() + Xpath 'c' + throw "brrr" + call assert_report('should not get here')` + endfunc + + try + Xpath 'a' + throw "arrgh" + call assert_report('should not get here')` + catch /.*/ + Xpath 'b' + call T() + call assert_report('should not get here')` + endtry + call assert_report('should not get here')` + [CODE] + let verify =<< trim [CODE] + call assert_equal('E605: Exception not caught: brrr', v:errmsg) + call assert_equal('abc', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_uncaught_exception_4() + CheckEnglish + + let test =<< trim [CODE] + try + Xpath 'a' + throw "arrgh" + call assert_report('should not get here')` + finally + Xpath 'b' + throw "brrr" + call assert_report('should not get here')` + endtry + call assert_report('should not get here')` + [CODE] + let verify =<< trim [CODE] + call assert_equal('E605: Exception not caught: brrr', v:errmsg) + call assert_equal('ab', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_uncaught_exception_5() + CheckEnglish + + " Need to catch and handle interrupt, otherwise the test will wait for the + " user to press <Enter> to continue + let test =<< trim [CODE] + try + try + Xpath 'a' + call interrupt() + call assert_report('should not get here') + endtry + call assert_report('should not get here') + catch /^Vim:Interrupt$/ + Xpath 'b' + endtry + [CODE] + let verify =<< trim [CODE] + call assert_equal('ab', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_uncaught_exception_6() + CheckEnglish + + let test =<< trim [CODE] + try + Xpath 'a' + let x = novar " error E121; exception: E121 + catch /E15:/ " should not catch + call assert_report('should not get here') + endtry + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('a', g:Xpath) + call assert_equal('E121: Undefined variable: novar', v:errmsg) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_uncaught_exception_7() + CheckEnglish + + let test =<< trim [CODE] + try + Xpath 'a' + " error E108/E488; exception: E488 + unlet novar # + catch /E108:/ " should not catch + call assert_report('should not get here') + endtry + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('a', g:Xpath) + call assert_equal('E488: Trailing characters: #', v:errmsg) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 53: Nesting errors: :endif/:else/:elseif {{{1 +" +" For nesting errors of :if conditionals the correct error messages +" should be given. +"------------------------------------------------------------------------------- + +func Test_nested_if_else_errors() + CheckEnglish + + " :endif without :if + let code =<< trim END + endif + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endif):E580: :endif without :if') + + " :endif without :if + let code =<< trim END + while 1 + endif + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endif):E580: :endif without :if') + + " :endif without :if + let code =<< trim END + try + finally + endif + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endif):E580: :endif without :if') + + " :endif without :if + let code =<< trim END + try + endif + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endif):E580: :endif without :if') + + " :endif without :if + let code =<< trim END + try + throw "a" + catch /a/ + endif + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endif):E580: :endif without :if') + + " :else without :if + let code =<< trim END + else + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(else):E581: :else without :if') + + " :else without :if + let code =<< trim END + while 1 + else + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(else):E581: :else without :if') + + " :else without :if + let code =<< trim END + try + finally + else + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(else):E581: :else without :if') + + " :else without :if + let code =<< trim END + try + else + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(else):E581: :else without :if') + + " :else without :if + let code =<< trim END + try + throw "a" + catch /a/ + else + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(else):E581: :else without :if') + + " :elseif without :if + let code =<< trim END + elseif 1 + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(elseif):E582: :elseif without :if') + + " :elseif without :if + let code =<< trim END + while 1 + elseif 1 + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(elseif):E582: :elseif without :if') + + " :elseif without :if + let code =<< trim END + try + finally + elseif 1 + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(elseif):E582: :elseif without :if') + + " :elseif without :if + let code =<< trim END + try + elseif 1 + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(elseif):E582: :elseif without :if') + + " :elseif without :if + let code =<< trim END + try + throw "a" + catch /a/ + elseif 1 + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(elseif):E582: :elseif without :if') + + " multiple :else + let code =<< trim END + if 1 + else + else + endif + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(else):E583: Multiple :else') + + " :elseif after :else + let code =<< trim END + if 1 + else + elseif 1 + endif + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(elseif):E584: :elseif after :else') + + call delete('Xtest') +endfunc + +"------------------------------------------------------------------------------- +" Test 54: Nesting errors: :while/:endwhile {{{1 +" +" For nesting errors of :while conditionals the correct error messages +" should be given. +" +" This test reuses the function MESSAGES() from the previous test. +" This function checks the messages in g:msgfile. +"------------------------------------------------------------------------------- + +func Test_nested_while_error() + CheckEnglish + + " :endwhile without :while + let code =<< trim END + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E588: :endwhile without :while') + + " :endwhile without :while + let code =<< trim END + if 1 + endwhile + endif + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E588: :endwhile without :while') + + " Missing :endif + let code =<< trim END + while 1 + if 1 + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E171: Missing :endif') + + " :endwhile without :while + let code =<< trim END + try + finally + endwhile + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E588: :endwhile without :while') + + " Missing :endtry + let code =<< trim END + while 1 + try + finally + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E600: Missing :endtry') + + " Missing :endtry + let code =<< trim END + while 1 + if 1 + try + finally + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E600: Missing :endtry') + + " Missing :endif + let code =<< trim END + while 1 + try + finally + if 1 + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E171: Missing :endif') + + " :endwhile without :while + let code =<< trim END + try + endwhile + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E588: :endwhile without :while') + + " :endwhile without :while + let code =<< trim END + while 1 + try + endwhile + endtry + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E588: :endwhile without :while') + + " :endwhile without :while + let code =<< trim END + try + throw "a" + catch /a/ + endwhile + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E588: :endwhile without :while') + + " :endwhile without :while + let code =<< trim END + while 1 + try + throw "a" + catch /a/ + endwhile + endtry + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endwhile):E588: :endwhile without :while') + + call delete('Xtest') +endfunc + +"------------------------------------------------------------------------------- +" Test 55: Nesting errors: :continue/:break {{{1 +" +" For nesting errors of :continue and :break commands the correct +" error messages should be given. +" +" This test reuses the function MESSAGES() from the previous test. +" This function checks the messages in g:msgfile. +"------------------------------------------------------------------------------- + +func Test_nested_cont_break_error() + CheckEnglish + + " :continue without :while + let code =<< trim END + continue + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(continue):E586: :continue without :while or :for') + + " :continue without :while + let code =<< trim END + if 1 + continue + endif + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(continue):E586: :continue without :while or :for') + + " :continue without :while + let code =<< trim END + try + finally + continue + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(continue):E586: :continue without :while or :for') + + " :continue without :while + let code =<< trim END + try + continue + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(continue):E586: :continue without :while or :for') + + " :continue without :while + let code =<< trim END + try + throw "a" + catch /a/ + continue + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(continue):E586: :continue without :while or :for') + + " :break without :while + let code =<< trim END + break + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(break):E587: :break without :while or :for') + + " :break without :while + let code =<< trim END + if 1 + break + endif + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(break):E587: :break without :while or :for') + + " :break without :while + let code =<< trim END + try + finally + break + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(break):E587: :break without :while or :for') + + " :break without :while + let code =<< trim END + try + break + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(break):E587: :break without :while or :for') + + " :break without :while + let code =<< trim END + try + throw "a" + catch /a/ + break + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(break):E587: :break without :while or :for') + + call delete('Xtest') +endfunc + +"------------------------------------------------------------------------------- +" Test 56: Nesting errors: :endtry {{{1 +" +" For nesting errors of :try conditionals the correct error messages +" should be given. +" +" This test reuses the function MESSAGES() from the previous test. +" This function check the messages in g:msgfile. +"------------------------------------------------------------------------------- + +func Test_nested_endtry_error() + CheckEnglish + + " :endtry without :try + let code =<< trim END + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endtry):E602: :endtry without :try') + + " :endtry without :try + let code =<< trim END + if 1 + endtry + endif + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endtry):E602: :endtry without :try') + + " :endtry without :try + let code =<< trim END + while 1 + endtry + endwhile + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endtry):E602: :endtry without :try') + + " Missing :endif + let code =<< trim END + try + if 1 + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endtry):E171: Missing :endif') + + " Missing :endwhile + let code =<< trim END + try + while 1 + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endtry):E170: Missing :endwhile') + + " Missing :endif + let code =<< trim END + try + finally + if 1 + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endtry):E171: Missing :endif') + + " Missing :endwhile + let code =<< trim END + try + finally + while 1 + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endtry):E170: Missing :endwhile') + + " Missing :endif + let code =<< trim END + try + throw "a" + catch /a/ + if 1 + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endtry):E171: Missing :endif') + + " Missing :endwhile + let code =<< trim END + try + throw "a" + catch /a/ + while 1 + endtry + END + call writefile(code, 'Xtest') + call AssertException(['source Xtest'], 'Vim(endtry):E170: Missing :endwhile') + + call delete('Xtest') +endfunc + +"------------------------------------------------------------------------------- +" Test 57: v:exception and v:throwpoint for user exceptions {{{1 +" +" v:exception evaluates to the value of the exception that was caught +" most recently and is not finished. (A caught exception is finished +" when the next ":catch", ":finally", or ":endtry" is reached.) +" v:throwpoint evaluates to the script/function name and line number +" where that exception has been thrown. +"------------------------------------------------------------------------------- + +func Test_user_exception_info() + CheckEnglish + + XpathINIT + XloopINIT + + func FuncException() + let g:exception = v:exception + endfunc + + func FuncThrowpoint() + let g:throwpoint = v:throwpoint + endfunc + + let scriptException = MakeScript("FuncException") + let scriptThrowPoint = MakeScript("FuncThrowpoint") + + command! CmdException let g:exception = v:exception + command! CmdThrowpoint let g:throwpoint = v:throwpoint + + func T(arg, line) + if a:line == 2 + throw a:arg " in line 2 + elseif a:line == 4 + throw a:arg " in line 4 + elseif a:line == 6 + throw a:arg " in line 6 + elseif a:line == 8 + throw a:arg " in line 8 + endif + endfunc + + func G(arg, line) + call T(a:arg, a:line) + endfunc + + func F(arg, line) + call G(a:arg, a:line) + endfunc + + let scriptT = MakeScript("T") + let scriptG = MakeScript("G", scriptT) + let scriptF = MakeScript("F", scriptG) + + try + Xpath 'a' + call F("oops", 2) + catch /.*/ + Xpath 'b' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("oops", v:exception) + call assert_match('\<F\[1]\.\.G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<2\>', v:throwpoint) + + exec "let exception = v:exception" + exec "let throwpoint = v:throwpoint" + call assert_equal("oops", v:exception) + call assert_match('\<F\[1]\.\.G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<2\>', v:throwpoint) + + CmdException + CmdThrowpoint + call assert_equal("oops", v:exception) + call assert_match('\<F\[1]\.\.G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<2\>', v:throwpoint) + + call FuncException() + call FuncThrowpoint() + call assert_equal("oops", v:exception) + call assert_match('\<F\[1]\.\.G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<2\>', v:throwpoint) + + exec "source" scriptException + exec "source" scriptThrowPoint + call assert_equal("oops", v:exception) + call assert_match('\<F\[1]\.\.G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<2\>', v:throwpoint) + + try + Xpath 'c' + call G("arrgh", 4) + catch /.*/ + Xpath 'd' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("arrgh", v:exception) + call assert_match('\<G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<4\>', v:throwpoint) + + try + Xpath 'e' + let g:arg = "autsch" + let g:line = 6 + exec "source" scriptF + catch /.*/ + Xpath 'f' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("autsch", v:exception) + call assert_match(fnamemodify(scriptT, ':t'), v:throwpoint) + call assert_match('\<6\>', v:throwpoint) + finally + Xpath 'g' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("arrgh", v:exception) + call assert_match('\<G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<4\>', v:throwpoint) + try + Xpath 'h' + let g:arg = "brrrr" + let g:line = 8 + exec "source" scriptG + catch /.*/ + Xpath 'i' + let exception = v:exception + let throwpoint = v:throwpoint + " Resolve scriptT for matching it against v:throwpoint. + call assert_equal("brrrr", v:exception) + call assert_match(fnamemodify(scriptT, ':t'), v:throwpoint) + call assert_match('\<8\>', v:throwpoint) + finally + Xpath 'j' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("arrgh", v:exception) + call assert_match('\<G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<4\>', v:throwpoint) + endtry + Xpath 'k' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("arrgh", v:exception) + call assert_match('\<G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<4\>', v:throwpoint) + endtry + Xpath 'l' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("arrgh", v:exception) + call assert_match('\<G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<4\>', v:throwpoint) + finally + Xpath 'm' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("oops", v:exception) + call assert_match('\<F\[1]\.\.G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<2\>', v:throwpoint) + endtry + Xpath 'n' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("oops", v:exception) + call assert_match('\<F\[1]\.\.G\[1]\.\.T\>', v:throwpoint) + call assert_match('\<2\>', v:throwpoint) + finally + Xpath 'o' + let exception = v:exception + let throwpoint = v:throwpoint + call assert_equal("", v:exception) + call assert_match('^$', v:throwpoint) + call assert_match('^$', v:throwpoint) + endtry + + call assert_equal('abcdefghijklmno', g:Xpath) + + unlet exception throwpoint + delfunction FuncException + delfunction FuncThrowpoint + call delete(scriptException) + call delete(scriptThrowPoint) + unlet scriptException scriptThrowPoint + delcommand CmdException + delcommand CmdThrowpoint + delfunction T + delfunction G + delfunction F + call delete(scriptT) + call delete(scriptG) + call delete(scriptF) + unlet scriptT scriptG scriptF +endfunc + +"------------------------------------------------------------------------------- +" +" Test 58: v:exception and v:throwpoint for error/interrupt exceptions {{{1 +" +" v:exception and v:throwpoint work also for error and interrupt +" exceptions. +"------------------------------------------------------------------------------- + +func Test_exception_info_for_error() + CheckEnglish + + let test =<< trim [CODE] + func T(line) + if a:line == 2 + delfunction T " error (function in use) in line 2 + elseif a:line == 4 + call interrupt() + endif + endfunc + + while 1 + try + Xpath 'a' + call T(2) + call assert_report('should not get here') + catch /.*/ + Xpath 'b' + if v:exception !~ 'Vim(delfunction):' + call assert_report('should not get here') + endif + if v:throwpoint !~ '\<T\>' + call assert_report('should not get here') + endif + if v:throwpoint !~ '\<2\>' + call assert_report('should not get here') + endif + finally + Xpath 'c' + if v:exception != "" + call assert_report('should not get here') + endif + if v:throwpoint != "" + call assert_report('should not get here') + endif + break + endtry + endwhile + + Xpath 'd' + if v:exception != "" + call assert_report('should not get here') + endif + if v:throwpoint != "" + call assert_report('should not get here') + endif + + while 1 + try + Xpath 'e' + call T(4) + call assert_report('should not get here') + catch /.*/ + Xpath 'f' + if v:exception != 'Vim:Interrupt' + call assert_report('should not get here') + endif + if v:throwpoint !~ 'function T' + call assert_report('should not get here') + endif + if v:throwpoint !~ '\<4\>' + call assert_report('should not get here') + endif + finally + Xpath 'g' + if v:exception != "" + call assert_report('should not get here') + endif + if v:throwpoint != "" + call assert_report('should not get here') + endif + break + endtry + endwhile + + Xpath 'h' + if v:exception != "" + call assert_report('should not get here') + endif + if v:throwpoint != "" + call assert_report('should not get here') + endif + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefgh', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" +" Test 59: v:exception and v:throwpoint when discarding exceptions {{{1 +" +" When a :catch clause is left by a ":break" etc or an error or +" interrupt exception, v:exception and v:throwpoint are reset. They +" are not affected by an exception that is discarded before being +" caught. +"------------------------------------------------------------------------------- +func Test_exception_info_on_discard() + CheckEnglish + + let test =<< trim [CODE] + let sfile = expand("<sfile>") + + while 1 + try + throw "x1" + catch /.*/ + break + endtry + endwhile + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + while 1 + try + throw "x2" + catch /.*/ + break + finally + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + endtry + break + endwhile + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + while 1 + try + let errcaught = 0 + try + try + throw "x3" + catch /.*/ + let lnum = expand("<sflnum>") + asdf + endtry + catch /.*/ + let errcaught = 1 + call assert_match('Vim:E492: Not an editor command:', v:exception) + call assert_match('line ' .. (lnum + 1), v:throwpoint) + endtry + finally + call assert_equal(1, errcaught) + break + endtry + endwhile + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + Xpath 'a' + + while 1 + try + let intcaught = 0 + try + try + throw "x4" + catch /.*/ + let lnum = expand("<sflnum>") + call interrupt() + endtry + catch /.*/ + let intcaught = 1 + call assert_match('Vim:Interrupt', v:exception) + call assert_match('line ' .. (lnum + 1), v:throwpoint) + endtry + finally + call assert_equal(1, intcaught) + break + endtry + endwhile + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + Xpath 'b' + + while 1 + try + let errcaught = 0 + try + try + if 1 + let lnum = expand("<sflnum>") + throw "x5" + " missing endif + catch /.*/ + call assert_report('should not get here') + endtry + catch /.*/ + let errcaught = 1 + call assert_match('Vim(catch):E171: Missing :endif:', v:exception) + call assert_match('line ' .. (lnum + 3), v:throwpoint) + endtry + finally + call assert_equal(1, errcaught) + break + endtry + endwhile + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + Xpath 'c' + + try + while 1 + try + throw "x6" + finally + break + endtry + break + endwhile + catch /.*/ + call assert_report('should not get here') + endtry + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + try + while 1 + try + throw "x7" + finally + break + endtry + break + endwhile + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + endtry + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + while 1 + try + let errcaught = 0 + try + try + throw "x8" + finally + let lnum = expand("<sflnum>") + asdf + endtry + catch /.*/ + let errcaught = 1 + call assert_match('Vim:E492: Not an editor command:', v:exception) + call assert_match('line ' .. (lnum + 1), v:throwpoint) + endtry + finally + call assert_equal(1, errcaught) + break + endtry + endwhile + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + Xpath 'd' + + while 1 + try + let intcaught = 0 + try + try + throw "x9" + finally + let lnum = expand("<sflnum>") + call interrupt() + endtry + catch /.*/ + let intcaught = 1 + call assert_match('Vim:Interrupt', v:exception) + call assert_match('line ' .. (lnum + 1), v:throwpoint) + endtry + finally + call assert_equal(1, intcaught) + break + endtry + endwhile + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + Xpath 'e' + + while 1 + try + let errcaught = 0 + try + try + if 1 + let lnum = expand("<sflnum>") + throw "x10" + " missing endif + finally + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + endtry + catch /.*/ + let errcaught = 1 + call assert_match('Vim(finally):E171: Missing :endif:', v:exception) + call assert_match('line ' .. (lnum + 3), v:throwpoint) + endtry + finally + call assert_equal(1, errcaught) + break + endtry + endwhile + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + Xpath 'f' + + while 1 + try + let errcaught = 0 + try + try + if 1 + let lnum = expand("<sflnum>") + throw "x11" + " missing endif + endtry + catch /.*/ + let errcaught = 1 + call assert_match('Vim(endtry):E171: Missing :endif:', v:exception) + call assert_match('line ' .. (lnum + 3), v:throwpoint) + endtry + finally + call assert_equal(1, errcaught) + break + endtry + endwhile + call assert_equal('', v:exception) + call assert_equal('', v:throwpoint) + + Xpath 'g' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefg', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" +" Test 60: (Re)throwing v:exception; :echoerr. {{{1 +" +" A user exception can be rethrown after catching by throwing +" v:exception. An error or interrupt exception cannot be rethrown +" because Vim exceptions cannot be faked. A Vim exception using the +" value of v:exception can, however, be triggered by the :echoerr +" command. +"------------------------------------------------------------------------------- + +func Test_rethrow_exception_1() + XpathINIT + try + try + Xpath 'a' + throw "oops" + catch /oops/ + Xpath 'b' + throw v:exception " rethrow user exception + catch /.*/ + call assert_report('should not get here') + endtry + catch /^oops$/ " catches rethrown user exception + Xpath 'c' + catch /.*/ + call assert_report('should not get here') + endtry + call assert_equal('abc', g:Xpath) +endfunc + +func Test_rethrow_exception_2() + XpathINIT + try + let caught = 0 + try + Xpath 'a' + write /n/o/n/w/r/i/t/a/b/l/e/_/f/i/l/e + call assert_report('should not get here') + catch /^Vim(write):/ + let caught = 1 + throw v:exception " throw error: cannot fake Vim exception + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'b' + call assert_equal(1, caught) + endtry + catch /^Vim(throw):/ " catches throw error + let caught = caught + 1 + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + call assert_equal(2, caught) + endtry + call assert_equal('abc', g:Xpath) +endfunc + +func Test_rethrow_exception_3() + XpathINIT + try + let caught = 0 + try + Xpath 'a' + asdf + catch /^Vim/ " catch error exception + let caught = 1 + " Trigger Vim error exception with value specified after :echoerr + let value = substitute(v:exception, '^Vim\((.*)\)\=:', '', "") + echoerr value + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'b' + call assert_equal(1, caught) + endtry + catch /^Vim(echoerr):/ + let caught = caught + 1 + call assert_match(value, v:exception) + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + call assert_equal(2, caught) + endtry + call assert_equal('abc', g:Xpath) +endfunc + +func Test_rethrow_exception_3() + XpathINIT + try + let errcaught = 0 + try + Xpath 'a' + let intcaught = 0 + call interrupt() + catch /^Vim:/ " catch interrupt exception + let intcaught = 1 + " Trigger Vim error exception with value specified after :echoerr + echoerr substitute(v:exception, '^Vim\((.*)\)\=:', '', "") + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'b' + call assert_equal(1, intcaught) + endtry + catch /^Vim(echoerr):/ + let errcaught = 1 + call assert_match('Interrupt', v:exception) + finally + Xpath 'c' + call assert_equal(1, errcaught) + endtry + call assert_equal('abc', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 61: Catching interrupt exceptions {{{1 +" +" When an interrupt occurs inside a :try/:endtry region, an +" interrupt exception is thrown and can be caught. Its value is +" "Vim:Interrupt". If the interrupt occurs after an error or a :throw +" but before a matching :catch is reached, all following :catches of +" that try block are ignored, but the interrupt exception can be +" caught by the next surrounding try conditional. An interrupt is +" ignored when there is a previous interrupt that has not been caught +" or causes a :finally clause to be executed. +"------------------------------------------------------------------------------- + +func Test_catch_intr_exception() + let test =<< trim [CODE] + while 1 + try + try + Xpath 'a' + call interrupt() + call assert_report('should not get here') + catch /^Vim:Interrupt$/ + Xpath 'b' + finally + Xpath 'c' + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'd' + break + endtry + endwhile + + while 1 + try + try + try + Xpath 'e' + asdf + call assert_report('should not get here') + catch /do_not_catch/ + call assert_report('should not get here') + catch /.*/ + Xpath 'f' + call interrupt() + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'g' + call interrupt() + call assert_report('should not get here') + endtry + catch /^Vim:Interrupt$/ + Xpath 'h' + finally + Xpath 'i' + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'j' + break + endtry + endwhile + + while 1 + try + try + try + Xpath 'k' + throw "x" + call assert_report('should not get here') + catch /do_not_catch/ + call assert_report('should not get here') + catch /x/ + Xpath 'l' + call interrupt() + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + endtry + catch /^Vim:Interrupt$/ + Xpath 'm' + finally + Xpath 'n' + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'o' + break + endtry + endwhile + + while 1 + try + try + Xpath 'p' + call interrupt() + call assert_report('should not get here') + catch /do_not_catch/ + call interrupt() + call assert_report('should not get here') + catch /^Vim:Interrupt$/ + Xpath 'q' + finally + Xpath 'r' + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 's' + break + endtry + endwhile + + Xpath 't' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefghijklmnopqrst', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 62: Catching error exceptions {{{1 +" +" An error inside a :try/:endtry region is converted to an exception +" and can be caught. The error exception has a "Vim(cmdname):" prefix +" where cmdname is the name of the failing command, or a "Vim:" prefix +" if no command name is known. The "Vim" prefixes cannot be faked. +"------------------------------------------------------------------------------- + +func Test_catch_err_exception_1() + XpathINIT + while 1 + try + try + let caught = 0 + unlet novar + catch /^Vim(unlet):/ + Xpath 'a' + let caught = 1 + let v:errmsg = substitute(v:exception, '^Vim(unlet):', '', "") + finally + Xpath 'b' + call assert_equal(1, caught) + call assert_match('E108: No such variable: "novar"', v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abc', g:Xpath) +endfunc + +func Test_catch_err_exception_2() + XpathINIT + while 1 + try + try + let caught = 0 + throw novar " error in :throw + catch /^Vim(throw):/ + Xpath 'a' + let caught = 1 + let v:errmsg = substitute(v:exception, '^Vim(throw):', '', "") + finally + Xpath 'b' + call assert_equal(1, caught) + call assert_match('E121: Undefined variable: novar', v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abc', g:Xpath) +endfunc + +func Test_catch_err_exception_3() + XpathINIT + while 1 + try + try + let caught = 0 + throw "Vim:faked" " error: cannot fake Vim exception + catch /^Vim(throw):/ + Xpath 'a' + let caught = 1 + let v:errmsg = substitute(v:exception, '^Vim(throw):', '', "") + finally + Xpath 'b' + call assert_equal(1, caught) + call assert_match("E608: Cannot :throw exceptions with 'Vim' prefix", + \ v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abc', g:Xpath) +endfunc + +func Test_catch_err_exception_4() + XpathINIT + func F() + while 1 + " Missing :endwhile + endfunc + + while 1 + try + try + let caught = 0 + call F() + catch /^Vim(endfunction):/ + Xpath 'a' + let caught = 1 + let v:errmsg = substitute(v:exception, '^Vim(endfunction):', '', "") + finally + Xpath 'b' + call assert_equal(1, caught) + call assert_match("E170: Missing :endwhile", v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abc', g:Xpath) + delfunc F +endfunc + +func Test_catch_err_exception_5() + XpathINIT + func F() + while 1 + " Missing :endwhile + endfunc + + while 1 + try + try + let caught = 0 + ExecAsScript F + catch /^Vim:/ + Xpath 'a' + let caught = 1 + let v:errmsg = substitute(v:exception, '^Vim:', '', "") + finally + Xpath 'b' + call assert_equal(1, caught) + call assert_match("E170: Missing :endwhile", v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abc', g:Xpath) + delfunc F +endfunc + +func Test_catch_err_exception_6() + XpathINIT + func G() + call G() + endfunc + + while 1 + try + let mfd_save = &mfd + set mfd=3 + try + let caught = 0 + call G() + catch /^Vim(call):/ + Xpath 'a' + let caught = 1 + let v:errmsg = substitute(v:exception, '^Vim(call):', '', "") + finally + Xpath 'b' + call assert_equal(1, caught) + call assert_match("E132: Function call depth is higher than 'maxfuncdepth'", v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + let &mfd = mfd_save + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abc', g:Xpath) + delfunc G +endfunc + +func Test_catch_err_exception_7() + XpathINIT + func H() + return H() + endfunc + + while 1 + try + let mfd_save = &mfd + set mfd=3 + try + let caught = 0 + call H() + catch /^Vim(return):/ + Xpath 'a' + let caught = 1 + let v:errmsg = substitute(v:exception, '^Vim(return):', '', "") + finally + Xpath 'b' + call assert_equal(1, caught) + call assert_match("E132: Function call depth is higher than 'maxfuncdepth'", v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + let &mfd = mfd_save + break " discard error for $VIMNOERRTHROW + endtry + call assert_report('should not get here') + endwhile + + call assert_equal('abc', g:Xpath) + delfunc H +endfunc + +"------------------------------------------------------------------------------- +" Test 63: Suppressing error exceptions by :silent!. {{{1 +" +" A :silent! command inside a :try/:endtry region suppresses the +" conversion of errors to an exception and the immediate abortion on +" error. When the commands executed by the :silent! themselves open +" a new :try/:endtry region, conversion of errors to exception and +" immediate abortion is switched on again - until the next :silent! +" etc. The :silent! has the effect of setting v:errmsg to the error +" message text (without displaying it) and continuing with the next +" script line. +" +" When a command triggering autocommands is executed by :silent! +" inside a :try/:endtry, the autocommand execution is not suppressed +" on error. +" +" This test reuses the function MSG() from the previous test. +"------------------------------------------------------------------------------- + +func Test_silent_exception() + XpathINIT + XloopINIT + let g:taken = "" + + func S(n) abort + XloopNEXT + let g:taken = g:taken . "E" . a:n + let v:errmsg = "" + exec "asdf" . a:n + + " Check that ":silent!" continues: + Xloop 'a' + + " Check that ":silent!" sets "v:errmsg": + call assert_match("E492: Not an editor command", v:errmsg) + endfunc + + func Foo() + while 1 + try + try + let caught = 0 + " This is not silent: + call S(3) + catch /^Vim:/ + Xpath 'b' + let caught = 1 + let errmsg3 = substitute(v:exception, '^Vim:', '', "") + silent! call S(4) + finally + call assert_equal(1, caught) + Xpath 'c' + call assert_match("E492: Not an editor command", errmsg3) + silent! call S(5) + " Break out of try conditionals that cover ":silent!". This also + " discards the aborting error when $VIMNOERRTHROW is non-zero. + break + endtry + catch /.*/ + call assert_report('should not get here') + endtry + endwhile + " This is a double ":silent!" (see caller). + silent! call S(6) + endfunc + + func Bar() + try + silent! call S(2) + silent! execute "call Foo() | call S(7)" + silent! call S(8) + endtry " normal end of try cond that covers ":silent!" + " This has a ":silent!" from the caller: + call S(9) + endfunc + + silent! call S(1) + silent! call Bar() + silent! call S(10) + + call assert_equal("E1E2E3E4E5E6E7E8E9E10", g:taken) + + augroup TMP + au! + autocmd BufWritePost * Xpath 'd' + augroup END + + Xpath 'e' + silent! write /i/m/p/o/s/s/i/b/l/e + Xpath 'f' + + call assert_equal('a2a3ba5ca6a7a8a9a10a11edf', g:Xpath) + + augroup TMP + au! + augroup END + augroup! TMP + delfunction S + delfunction Foo + delfunction Bar +endfunc + +"------------------------------------------------------------------------------- +" Test 64: Error exceptions after error, interrupt or :throw {{{1 +" +" When an error occurs after an interrupt or a :throw but before +" a matching :catch is reached, all following :catches of that try +" block are ignored, but the error exception can be caught by the next +" surrounding try conditional. Any previous error exception is +" discarded. An error is ignored when there is a previous error that +" has not been caught. +"------------------------------------------------------------------------------- + +func Test_exception_after_error_1() + XpathINIT + while 1 + try + try + Xpath 'a' + let caught = 0 + while 1 + if 1 + " Missing :endif + endwhile " throw error exception + catch /^Vim(/ + Xpath 'b' + let caught = 1 + finally + Xpath 'c' + call assert_equal(1, caught) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'd' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abcd', g:Xpath) +endfunc + +func Test_exception_after_error_2() + XpathINIT + while 1 + try + try + Xpath 'a' + let caught = 0 + try + if 1 + " Missing :endif + catch /.*/ " throw error exception + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + endtry + catch /^Vim(/ + Xpath 'b' + let caught = 1 + finally + Xpath 'c' + call assert_equal(1, caught) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'd' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abcd', g:Xpath) +endfunc + +func Test_exception_after_error_3() + XpathINIT + while 1 + try + try + let caught = 0 + try + Xpath 'a' + call interrupt() + catch /do_not_catch/ + call assert_report('should not get here') + if 1 + " Missing :endif + catch /.*/ " throw error exception + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + endtry + catch /^Vim(/ + Xpath 'b' + let caught = 1 + finally + Xpath 'c' + call assert_equal(1, caught) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'd' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abcd', g:Xpath) +endfunc + +func Test_exception_after_error_4() + XpathINIT + while 1 + try + try + let caught = 0 + try + Xpath 'a' + throw "x" + catch /do_not_catch/ + call assert_report('should not get here') + if 1 + " Missing :endif + catch /x/ " throw error exception + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + endtry + catch /^Vim(/ + Xpath 'b' + let caught = 1 + finally + Xpath 'c' + call assert_equal(1, caught) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'd' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abcd', g:Xpath) +endfunc + +func Test_exception_after_error_5() + XpathINIT + while 1 + try + try + let caught = 0 + Xpath 'a' + endif " :endif without :if; throw error exception + if 1 + " Missing :endif + catch /do_not_catch/ " ignore new error + call assert_report('should not get here') + catch /^Vim(endif):/ + Xpath 'b' + let caught = 1 + catch /^Vim(/ + call assert_report('should not get here') + finally + Xpath 'c' + call assert_equal(1, caught) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'd' + break + endtry + call assert_report('should not get here') + endwhile + call assert_equal('abcd', g:Xpath) +endfunc + +"------------------------------------------------------------------------------- +" Test 65: Errors in the /pattern/ argument of a :catch {{{1 +" +" On an error in the /pattern/ argument of a :catch, the :catch does +" not match. Any following :catches of the same :try/:endtry don't +" match either. Finally clauses are executed. +"------------------------------------------------------------------------------- + +func Test_catch_pattern_error() + CheckEnglish + XpathINIT + + try + try + Xpath 'a' + throw "oops" + catch /^oops$/ + Xpath 'b' + catch /\)/ " not checked; exception has already been caught + call assert_report('should not get here') + endtry + Xpath 'c' + catch /.*/ + call assert_report('should not get here') + endtry + call assert_equal('abc', g:Xpath) + + XpathINIT + func F() + try + try + try + Xpath 'a' + throw "ab" + catch /abc/ " does not catch + call assert_report('should not get here') + catch /\)/ " error; discards exception + call assert_report('should not get here') + catch /.*/ " not checked + call assert_report('should not get here') + finally + Xpath 'b' + endtry + call assert_report('should not get here') + catch /^ab$/ " checked, but original exception is discarded + call assert_report('should not get here') + catch /^Vim(catch):/ + Xpath 'c' + call assert_match('Vim(catch):E475: Invalid argument:', v:exception) + finally + Xpath 'd' + endtry + Xpath 'e' + catch /.*/ + call assert_report('should not get here') + endtry + Xpath 'f' + endfunc + + call F() + call assert_equal('abcdef', g:Xpath) + + delfunc F +endfunc + +"------------------------------------------------------------------------------- +" Test 66: Stop range :call on error, interrupt, or :throw {{{1 +" +" When a function which is multiply called for a range since it +" doesn't handle the range itself has an error in a command +" dynamically enclosed by :try/:endtry or gets an interrupt or +" executes a :throw, no more calls for the remaining lines in the +" range are made. On an error in a command not dynamically enclosed +" by :try/:endtry, the function is executed again for the remaining +" lines in the range. +"------------------------------------------------------------------------------- + +func Test_stop_range_on_error() + let test =<< trim [CODE] + let file = tempname() + exec "edit" file + call setline(1, ['line 1', 'line 2', 'line 3']) + let taken = "" + let expected = "G1EF1E(1)F1E(2)F1E(3)G2EF2E(1)G3IF3I(1)G4TF4T(1)G5AF5A(1)" + + func F(reason, n) abort + let g:taken = g:taken .. "F" .. a:n .. + \ substitute(a:reason, '\(\l\).*', '\u\1', "") .. + \ "(" .. line(".") .. ")" + + if a:reason == "error" + asdf + elseif a:reason == "interrupt" + call interrupt() + elseif a:reason == "throw" + throw "xyz" + elseif a:reason == "aborting error" + XloopNEXT + call assert_equal(g:taken, g:expected) + try + bwipeout! + call delete(g:file) + asdf + endtry + endif + endfunc + + func G(reason, n) + let g:taken = g:taken .. "G" .. a:n .. + \ substitute(a:reason, '\(\l\).*', '\u\1', "") + 1,3call F(a:reason, a:n) + endfunc + + Xpath 'a' + call G("error", 1) + try + Xpath 'b' + try + call G("error", 2) + call assert_report('should not get here') + finally + Xpath 'c' + try + call G("interrupt", 3) + call assert_report('should not get here') + finally + Xpath 'd' + try + call G("throw", 4) + call assert_report('should not get here') + endtry + endtry + endtry + catch /xyz/ + Xpath 'e' + catch /.*/ + call assert_report('should not get here') + endtry + Xpath 'f' + call G("aborting error", 5) + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdef', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 67: :throw across :call command {{{1 +" +" On a call command, an exception might be thrown when evaluating the +" function name, during evaluation of the arguments, or when the +" function is being executed. The exception can be caught by the +" caller. +"------------------------------------------------------------------------------- + +func THROW(x, n) + if a:n == 1 + Xpath 'A' + elseif a:n == 2 + Xpath 'B' + elseif a:n == 3 + Xpath 'C' + endif + throw a:x +endfunc + +func NAME(x, n) + if a:n == 1 + call assert_report('should not get here') + elseif a:n == 2 + Xpath 'D' + elseif a:n == 3 + Xpath 'E' + elseif a:n == 4 + Xpath 'F' + endif + return a:x +endfunc + +func ARG(x, n) + if a:n == 1 + call assert_report('should not get here') + elseif a:n == 2 + call assert_report('should not get here') + elseif a:n == 3 + Xpath 'G' + elseif a:n == 4 + Xpath 'I' + endif + return a:x +endfunc + +func Test_throw_across_call_cmd() + XpathINIT + + func F(x, n) + if a:n == 2 + call assert_report('should not get here') + elseif a:n == 4 + Xpath 'a' + endif + endfunc + + while 1 + try + let v:errmsg = "" + + while 1 + try + Xpath 'b' + call {NAME(THROW("name", 1), 1)}(ARG(4711, 1), 1) + call assert_report('should not get here') + catch /^name$/ + Xpath 'c' + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + let v:errmsg = "" + break + endtry + endwhile + + while 1 + try + Xpath 'd' + call {NAME("F", 2)}(ARG(THROW("arg", 2), 2), 2) + call assert_report('should not get here') + catch /^arg$/ + Xpath 'e' + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + let v:errmsg = "" + break + endtry + endwhile + + while 1 + try + Xpath 'f' + call {NAME("THROW", 3)}(ARG("call", 3), 3) + call assert_report('should not get here') + catch /^call$/ + Xpath 'g' + catch /^0$/ " default return value + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + let v:errmsg = "" + break + endtry + endwhile + + while 1 + try + Xpath 'h' + call {NAME("F", 4)}(ARG(4711, 4), 4) + Xpath 'i' + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + let v:errmsg = "" + break + endtry + endwhile + + catch /^0$/ " default return value + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + let v:errmsg = "" + break + endtry + endwhile + + call assert_equal('bAcdDBefEGCghFIai', g:Xpath) + delfunction F +endfunc + +"------------------------------------------------------------------------------- +" Test 68: :throw across function calls in expressions {{{1 +" +" On a function call within an expression, an exception might be +" thrown when evaluating the function name, during evaluation of the +" arguments, or when the function is being executed. The exception +" can be caught by the caller. +" +" This test reuses the functions THROW(), NAME(), and ARG() from the +" previous test. +"------------------------------------------------------------------------------- + +func Test_throw_across_call_expr() + XpathINIT + + func F(x, n) + if a:n == 2 + call assert_report('should not get here') + elseif a:n == 4 + Xpath 'a' + endif + return a:x + endfunction + + while 1 + try + let error = 0 + let v:errmsg = "" + + while 1 + try + Xpath 'b' + let var1 = {NAME(THROW("name", 1), 1)}(ARG(4711, 1), 1) + call assert_report('should not get here') + catch /^name$/ + Xpath 'c' + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + let v:errmsg = "" + break + endtry + endwhile + call assert_true(!exists('var1')) + + while 1 + try + Xpath 'd' + let var2 = {NAME("F", 2)}(ARG(THROW("arg", 2), 2), 2) + call assert_report('should not get here') + catch /^arg$/ + Xpath 'e' + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + let v:errmsg = "" + break + endtry + endwhile + call assert_true(!exists('var2')) + + while 1 + try + Xpath 'f' + let var3 = {NAME("THROW", 3)}(ARG("call", 3), 3) + call assert_report('should not get here') + catch /^call$/ + Xpath 'g' + catch /^0$/ " default return value + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + let v:errmsg = "" + break + endtry + endwhile + call assert_true(!exists('var3')) + + while 1 + try + Xpath 'h' + let var4 = {NAME("F", 4)}(ARG(4711, 4), 4) + Xpath 'i' + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + let v:errmsg = "" + break + endtry + endwhile + call assert_true(exists('var4') && var4 == 4711) + + catch /^0$/ " default return value + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + finally + call assert_equal("", v:errmsg) + break + endtry + endwhile + + call assert_equal('bAcdDBefEGCghFIai', g:Xpath) + delfunc F +endfunc + +"------------------------------------------------------------------------------- +" Test 76: Errors, interrupts, :throw during expression evaluation {{{1 +" +" When a function call made during expression evaluation is aborted +" due to an error inside a :try/:endtry region or due to an interrupt +" or a :throw, the expression evaluation is aborted as well. No +" message is displayed for the cancelled expression evaluation. On an +" error not inside :try/:endtry, the expression evaluation continues. +"------------------------------------------------------------------------------- + +func Test_expr_eval_error() + let test =<< trim [CODE] + let taken = "" + + func ERR(n) + let g:taken = g:taken .. "E" .. a:n + asdf + endfunc + + func ERRabort(n) abort + let g:taken = g:taken .. "A" .. a:n + asdf + endfunc " returns -1; may cause follow-up msg for illegal var/func name + + func WRAP(n, arg) + let g:taken = g:taken .. "W" .. a:n + let g:saved_errmsg = v:errmsg + return arg + endfunc + + func INT(n) + let g:taken = g:taken .. "I" .. a:n + call interrupt() + endfunc + + func THR(n) + let g:taken = g:taken .. "T" .. a:n + throw "should not be caught" + endfunc + + func CONT(n) + let g:taken = g:taken .. "C" .. a:n + endfunc + + func MSG(n) + let g:taken = g:taken .. "M" .. a:n + let errmsg = (a:n >= 37 && a:n <= 44) ? g:saved_errmsg : v:errmsg + let msgptn = (a:n >= 10 && a:n <= 27) ? "^$" : "asdf" + call assert_match(msgptn, errmsg) + let v:errmsg = "" + let g:saved_errmsg = "" + endfunc + + let v:errmsg = "" + + try + let t = 1 + while t <= 9 + Xloop 'a' + try + if t == 1 + let v{ERR(t) + CONT(t)} = 0 + elseif t == 2 + let v{ERR(t) + CONT(t)} + elseif t == 3 + let var = exists('v{ERR(t) + CONT(t)}') + elseif t == 4 + unlet v{ERR(t) + CONT(t)} + elseif t == 5 + function F{ERR(t) + CONT(t)}() + endfunction + elseif t == 6 + function F{ERR(t) + CONT(t)} + elseif t == 7 + let var = exists('*F{ERR(t) + CONT(t)}') + elseif t == 8 + delfunction F{ERR(t) + CONT(t)} + elseif t == 9 + let var = ERR(t) + CONT(t) + endif + catch /asdf/ + " v:errmsg is not set when the error message is converted to an + " exception. Set it to the original error message. + let v:errmsg = substitute(v:exception, '^Vim:', '', "") + catch /^Vim\((\a\+)\)\=:/ + " An error exception has been thrown after the original error. + let v:errmsg = "" + finally + call MSG(t) + let t = t + 1 + XloopNEXT + continue " discard an aborting error + endtry + endwhile + catch /.*/ + call assert_report('should not get here') + endtry + + try + let t = 10 + while t <= 18 + Xloop 'b' + try + if t == 10 + let v{INT(t) + CONT(t)} = 0 + elseif t == 11 + let v{INT(t) + CONT(t)} + elseif t == 12 + let var = exists('v{INT(t) + CONT(t)}') + elseif t == 13 + unlet v{INT(t) + CONT(t)} + elseif t == 14 + function F{INT(t) + CONT(t)}() + endfunction + elseif t == 15 + function F{INT(t) + CONT(t)} + elseif t == 16 + let var = exists('*F{INT(t) + CONT(t)}') + elseif t == 17 + delfunction F{INT(t) + CONT(t)} + elseif t == 18 + let var = INT(t) + CONT(t) + endif + catch /^Vim\((\a\+)\)\=:\(Interrupt\)\@!/ + " An error exception has been triggered after the interrupt. + let v:errmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") + finally + call MSG(t) + let t = t + 1 + XloopNEXT + continue " discard interrupt + endtry + endwhile + catch /.*/ + call assert_report('should not get here') + endtry + + try + let t = 19 + while t <= 27 + Xloop 'c' + try + if t == 19 + let v{THR(t) + CONT(t)} = 0 + elseif t == 20 + let v{THR(t) + CONT(t)} + elseif t == 21 + let var = exists('v{THR(t) + CONT(t)}') + elseif t == 22 + unlet v{THR(t) + CONT(t)} + elseif t == 23 + function F{THR(t) + CONT(t)}() + endfunction + elseif t == 24 + function F{THR(t) + CONT(t)} + elseif t == 25 + let var = exists('*F{THR(t) + CONT(t)}') + elseif t == 26 + delfunction F{THR(t) + CONT(t)} + elseif t == 27 + let var = THR(t) + CONT(t) + endif + catch /^Vim\((\a\+)\)\=:/ + " An error exception has been triggered after the :throw. + let v:errmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") + finally + call MSG(t) + let t = t + 1 + XloopNEXT + continue " discard exception + endtry + endwhile + catch /.*/ + call assert_report('should not get here') + endtry + + let v{ERR(28) + CONT(28)} = 0 + call MSG(28) + let v{ERR(29) + CONT(29)} + call MSG(29) + let var = exists('v{ERR(30) + CONT(30)}') + call MSG(30) + unlet v{ERR(31) + CONT(31)} + call MSG(31) + function F{ERR(32) + CONT(32)}() + endfunction + call MSG(32) + function F{ERR(33) + CONT(33)} + call MSG(33) + let var = exists('*F{ERR(34) + CONT(34)}') + call MSG(34) + delfunction F{ERR(35) + CONT(35)} + call MSG(35) + let var = ERR(36) + CONT(36) + call MSG(36) + + let saved_errmsg = "" + + let v{WRAP(37, ERRabort(37)) + CONT(37)} = 0 + call MSG(37) + let v{WRAP(38, ERRabort(38)) + CONT(38)} + call MSG(38) + let var = exists('v{WRAP(39, ERRabort(39)) + CONT(39)}') + call MSG(39) + unlet v{WRAP(40, ERRabort(40)) + CONT(40)} + call MSG(40) + function F{WRAP(41, ERRabort(41)) + CONT(41)}() + endfunction + call MSG(41) + function F{WRAP(42, ERRabort(42)) + CONT(42)} + call MSG(42) + let var = exists('*F{WRAP(43, ERRabort(43)) + CONT(43)}') + call MSG(43) + delfunction F{WRAP(44, ERRabort(44)) + CONT(44)} + call MSG(44) + let var = ERRabort(45) + CONT(45) + call MSG(45) + Xpath 'd' + + let expected = "" + \ .. "E1M1E2M2E3M3E4M4E5M5E6M6E7M7E8M8E9M9" + \ .. "I10M10I11M11I12M12I13M13I14M14I15M15I16M16I17M17I18M18" + \ .. "T19M19T20M20T21M21T22M22T23M23T24M24T25M25T26M26T27M27" + \ .. "E28C28M28E29C29M29E30C30M30E31C31M31E32C32M32E33C33M33" + \ .. "E34C34M34E35C35M35E36C36M36" + \ .. "A37W37C37M37A38W38C38M38A39W39C39M39A40W40C40M40A41W41C41M41" + \ .. "A42W42C42M42A43W43C43M43A44W44C44M44A45C45M45" + call assert_equal(expected, taken) + [CODE] + let verify =<< trim [CODE] + let expected = "a1a2a3a4a5a6a7a8a9" + \ .. "b10b11b12b13b14b15b16b17b18" + \ .. "c19c20c21c22c23c24c25c26c27d" + call assert_equal(expected, g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 77: Errors, interrupts, :throw in name{brace-expression} {{{1 +" +" When a function call made during evaluation of an expression in +" braces as part of a function name after ":function" is aborted due +" to an error inside a :try/:endtry region or due to an interrupt or +" a :throw, the expression evaluation is aborted as well, and the +" function definition is ignored, skipping all commands to the +" ":endfunction". On an error not inside :try/:endtry, the expression +" evaluation continues and the function gets defined, and can be +" called and deleted. +"------------------------------------------------------------------------------- +func Test_brace_expr_error() + let test =<< trim [CODE] + func ERR() abort + Xloop 'a' + asdf + endfunc " returns -1 + + func OK() + Xloop 'b' + let v:errmsg = "" + return 0 + endfunc + + let v:errmsg = "" + + Xpath 'c' + func F{1 + ERR() + OK()}(arg) + " F0 should be defined. + if exists("a:arg") && a:arg == "calling" + Xpath 'd' + else + call assert_report('should not get here') + endif + endfunction + call assert_equal("", v:errmsg) + XloopNEXT + + Xpath 'e' + call F{1 + ERR() + OK()}("calling") + call assert_equal("", v:errmsg) + XloopNEXT + + Xpath 'f' + delfunction F{1 + ERR() + OK()} + call assert_equal("", v:errmsg) + XloopNEXT + + try + while 1 + try + Xpath 'g' + func G{1 + ERR() + OK()}(arg) + " G0 should not be defined, and the function body should be + " skipped. + call assert_report('should not get here') + " Use an unmatched ":finally" to check whether the body is + " skipped when an error occurs in ERR(). This works whether or + " not the exception is converted to an exception. + finally + call assert_report('should not get here') + endtry + try + call assert_report('should not get here') + endfunction + + call assert_report('should not get here') + catch /asdf/ + " Jumped to when the function is not defined and the body is + " skipped. + Xpath 'h' + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'i' + break + endtry " jumped to when the body is not skipped + endwhile + catch /.*/ + call assert_report('should not get here') + endtry + [CODE] + let verify =<< trim [CODE] + call assert_equal('ca1b1ea2b2dfa3b3ga4hi', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 78: Messages on parsing errors in expression evaluation {{{1 +" +" When an expression evaluation detects a parsing error, an error +" message is given and converted to an exception, and the expression +" evaluation is aborted. +"------------------------------------------------------------------------------- +func Test_expr_eval_error_msg() + CheckEnglish + + let test =<< trim [CODE] + let taken = "" + + func F(n) + let g:taken = g:taken . "F" . a:n + endfunc + + func MSG(n, enr, emsg) + let g:taken = g:taken . "M" . a:n + call assert_match('^' .. a:enr .. ':', v:errmsg) + call assert_match(a:emsg, v:errmsg) + endfunc + + func CONT(n) + let g:taken = g:taken . "C" . a:n + endfunc + + let v:errmsg = "" + try + let t = 1 + while t <= 14 + let g:taken = g:taken . "T" . t + let v:errmsg = "" + try + if t == 1 + let v{novar + CONT(t)} = 0 + elseif t == 2 + let v{novar + CONT(t)} + elseif t == 3 + let var = exists('v{novar + CONT(t)}') + elseif t == 4 + unlet v{novar + CONT(t)} + elseif t == 5 + function F{novar + CONT(t)}() + endfunction + elseif t == 6 + function F{novar + CONT(t)} + elseif t == 7 + let var = exists('*F{novar + CONT(t)}') + elseif t == 8 + delfunction F{novar + CONT(t)} + elseif t == 9 + echo novar + CONT(t) + elseif t == 10 + echo v{novar + CONT(t)} + elseif t == 11 + echo F{novar + CONT(t)} + elseif t == 12 + let var = novar + CONT(t) + elseif t == 13 + let var = v{novar + CONT(t)} + elseif t == 14 + let var = F{novar + CONT(t)}() + endif + catch /^Vim\((\a\+)\)\=:/ + Xloop 'a' + " v:errmsg is not set when the error message is converted to an + " exception. Set it to the original error message. + let v:errmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") + finally + Xloop 'b' + if t <= 8 && t != 3 && t != 7 + call MSG(t, 'E475', 'Invalid argument\>') + else + call MSG(t, 'E121', "Undefined variable") + endif + let t = t + 1 + XloopNEXT + continue " discard an aborting error + endtry + endwhile + catch /.*/ + call assert_report('should not get here') + endtry + + func T(n, expr, enr, emsg) + try + let g:taken = g:taken . "T" . a:n + let v:errmsg = "" + try + execute "let var = " . a:expr + catch /^Vim\((\a\+)\)\=:/ + Xloop 'c' + " v:errmsg is not set when the error message is converted to an + " exception. Set it to the original error message. + let v:errmsg = substitute(v:exception, '^Vim\((\a\+)\)\=:', '', "") + finally + Xloop 'd' + call MSG(a:n, a:enr, a:emsg) + XloopNEXT + " Discard an aborting error: + return + endtry + catch /.*/ + call assert_report('should not get here') + endtry + endfunc + + call T(15, 'Nofunc() + CONT(15)', 'E117', "Unknown function") + call T(16, 'F(1 2 + CONT(16))', 'E116', "Invalid arguments") + call T(17, 'F(1, 2) + CONT(17)', 'E118', "Too many arguments") + call T(18, 'F() + CONT(18)', 'E119', "Not enough arguments") + call T(19, '{(1} + CONT(19)', 'E110', "Missing ')'") + call T(20, '("abc"[1) + CONT(20)', 'E111', "Missing ']'") + call T(21, '(1 +) + CONT(21)', 'E15', "Invalid expression") + call T(22, '1 2 + CONT(22)', 'E488', "Trailing characters: 2 +") + call T(23, '(1 ? 2) + CONT(23)', 'E109', "Missing ':' after '?'") + call T(24, '("abc) + CONT(24)', 'E114', "Missing quote") + call T(25, "('abc) + CONT(25)", 'E115', "Missing quote") + call T(26, '& + CONT(26)', 'E112', "Option name missing") + call T(27, '&asdf + CONT(27)', 'E113', "Unknown option") + + let expected = "" + \ .. "T1M1T2M2T3M3T4M4T5M5T6M6T7M7T8M8T9M9T10M10T11M11T12M12T13M13T14M14" + \ .. "T15M15T16M16T17M17T18M18T19M19T20M20T21M21T22M22T23M23T24M24T25M25" + \ .. "T26M26T27M27" + + call assert_equal(expected, taken) + [CODE] + let verify =<< trim [CODE] + let expected = "a1b1a2b2a3b3a4b4a5b5a6b6a7b7a8b8a9b9a10b10a11b11a12b12" + \ .. "a13b13a14b14c15d15c16d16c17d17c18d18c19d19c20d20" + \ .. "c21d21c22d22c23d23c24d24c25d25c26d26c27d27" + call assert_equal(expected, g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 79: Throwing one of several errors for the same command {{{1 +" +" When several errors appear in a row (for instance during expression +" evaluation), the first as the most specific one is used when +" throwing an error exception. If, however, a syntax error is +" detected afterwards, this one is used for the error exception. +" On a syntax error, the next command is not executed, on a normal +" error, however, it is (relevant only in a function without the +" "abort" flag). v:errmsg is not set. +" +" If throwing error exceptions is configured off, v:errmsg is always +" set to the latest error message, that is, to the more general +" message or the syntax error, respectively. +"------------------------------------------------------------------------------- +func Test_throw_multi_error() + CheckEnglish + + let test =<< trim [CODE] + func NEXT(cmd) + exec a:cmd . " | Xloop 'a'" + endfun + + call NEXT('echo novar') " (checks nextcmd) + XloopNEXT + call NEXT('let novar #') " (skips nextcmd) + XloopNEXT + call NEXT('unlet novar #') " (skips nextcmd) + XloopNEXT + call NEXT('let {novar}') " (skips nextcmd) + XloopNEXT + call NEXT('unlet{ novar}') " (skips nextcmd) + + call assert_equal('a1', g:Xpath) + XpathINIT + XloopINIT + + func EXEC(cmd) + exec a:cmd + endfunc + + try + while 1 " dummy loop + try + let v:errmsg = "" + call EXEC('echo novar') " normal error + catch /^Vim\((\a\+)\)\=:/ + Xpath 'b' + call assert_match('E121: Undefined variable: novar', v:exception) + finally + Xpath 'c' + call assert_equal("", v:errmsg) + break + endtry + endwhile + + Xpath 'd' + let cmd = "let" + while cmd != "" + try + let v:errmsg = "" + call EXEC(cmd . ' novar #') " normal plus syntax error + catch /^Vim\((\a\+)\)\=:/ + Xloop 'e' + call assert_match('E488: Trailing characters', v:exception) + finally + Xloop 'f' + call assert_equal("", v:errmsg) + if cmd == "let" + let cmd = "unlet" + else + let cmd = "" + endif + XloopNEXT + continue + endtry + endwhile + + Xpath 'g' + let cmd = "let" + while cmd != "" + try + let v:errmsg = "" + call EXEC(cmd . ' {novar}') " normal plus syntax error + catch /^Vim\((\a\+)\)\=:/ + Xloop 'h' + call assert_match('E475: Invalid argument: {novar}', v:exception) + finally + Xloop 'i' + call assert_equal("", v:errmsg) + if cmd == "let" + let cmd = "unlet" + else + let cmd = "" + endif + XloopNEXT + continue + endtry + endwhile + catch /.*/ + call assert_report('should not get here') + endtry + Xpath 'j' + [CODE] + let verify =<< trim [CODE] + call assert_equal('bcde1f1e2f2gh3i3h4i4j', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 80: Syntax error in expression for illegal :elseif {{{1 +" +" If there is a syntax error in the expression after an illegal +" :elseif, an error message is given (or an error exception thrown) +" for the illegal :elseif rather than the expression error. +"------------------------------------------------------------------------------- +func Test_if_syntax_error() + CheckEnglish + + let test =<< trim [CODE] + let v:errmsg = "" + if 0 + else + elseif 1 ||| 2 + endif + Xpath 'a' + call assert_match('E584: :elseif after :else', v:errmsg) + + let v:errmsg = "" + if 1 + else + elseif 1 ||| 2 + endif + Xpath 'b' + call assert_match('E584: :elseif after :else', v:errmsg) + + let v:errmsg = "" + elseif 1 ||| 2 + Xpath 'c' + call assert_match('E582: :elseif without :if', v:errmsg) + + let v:errmsg = "" + while 1 + elseif 1 ||| 2 + endwhile + Xpath 'd' + call assert_match('E582: :elseif without :if', v:errmsg) + + while 1 + try + try + let v:errmsg = "" + if 0 + else + elseif 1 ||| 2 + endif + catch /^Vim\((\a\+)\)\=:/ + Xpath 'e' + call assert_match('E584: :elseif after :else', v:exception) + finally + Xpath 'f' + call assert_equal("", v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'g' + break + endtry + endwhile + + while 1 + try + try + let v:errmsg = "" + if 1 + else + elseif 1 ||| 2 + endif + catch /^Vim\((\a\+)\)\=:/ + Xpath 'h' + call assert_match('E584: :elseif after :else', v:exception) + finally + Xpath 'i' + call assert_equal("", v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'j' + break + endtry + endwhile + + while 1 + try + try + let v:errmsg = "" + elseif 1 ||| 2 + catch /^Vim\((\a\+)\)\=:/ + Xpath 'k' + call assert_match('E582: :elseif without :if', v:exception) + finally + Xpath 'l' + call assert_equal("", v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'm' + break + endtry + endwhile + + while 1 + try + try + let v:errmsg = "" + while 1 + elseif 1 ||| 2 + endwhile + catch /^Vim\((\a\+)\)\=:/ + Xpath 'n' + call assert_match('E582: :elseif without :if', v:exception) + finally + Xpath 'o' + call assert_equal("", v:errmsg) + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'p' + break + endtry + endwhile + Xpath 'q' + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefghijklmnopq', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 81: Discarding exceptions after an error or interrupt {{{1 +" +" When an exception is thrown from inside a :try conditional without +" :catch and :finally clauses and an error or interrupt occurs before +" the :endtry is reached, the exception is discarded. +"------------------------------------------------------------------------------- + +func Test_discard_exception_after_error_1() + let test =<< trim [CODE] + try + Xpath 'a' + try + Xpath 'b' + throw "arrgh" + call assert_report('should not get here') + if 1 + call assert_report('should not get here') + " error after :throw: missing :endif + endtry + call assert_report('should not get here') + catch /arrgh/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('ab', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +" interrupt the code before the endtry is invoked +func Test_discard_exception_after_error_2() + XpathINIT + let lines =<< trim [CODE] + try + Xpath 'a' + try + Xpath 'b' + throw "arrgh" + call assert_report('should not get here') + endtry " interrupt here + call assert_report('should not get here') + catch /arrgh/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + [CODE] + call writefile(lines, 'Xscript') + + breakadd file 7 Xscript + try + let caught_intr = 0 + debuggreedy + call feedkeys(":source Xscript\<CR>quit\<CR>", "xt") + catch /^Vim:Interrupt$/ + call assert_match('Xscript, line 7', v:throwpoint) + let caught_intr = 1 + endtry + 0debuggreedy + call assert_equal(1, caught_intr) + call assert_equal('ab', g:Xpath) + breakdel * + call delete('Xscript') +endfunc + +"------------------------------------------------------------------------------- +" Test 82: Ignoring :catch clauses after an error or interrupt {{{1 +" +" When an exception is thrown and an error or interrupt occurs before +" the matching :catch clause is reached, the exception is discarded +" and the :catch clause is ignored (also for the error or interrupt +" exception being thrown then). +"------------------------------------------------------------------------------- + +func Test_ignore_catch_after_error_1() + let test =<< trim [CODE] + try + try + Xpath 'a' + throw "arrgh" + call assert_report('should not get here') + if 1 + call assert_report('should not get here') + " error after :throw: missing :endif + catch /.*/ + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + catch /arrgh/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('a', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +func Test_ignore_catch_after_error_2() + let test =<< trim [CODE] + func E() + try + try + Xpath 'a' + throw "arrgh" + call assert_report('should not get here') + if 1 + call assert_report('should not get here') + " error after :throw: missing :endif + catch /.*/ + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + catch /arrgh/ + call assert_report('should not get here') + endtry + endfunc + + call E() + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('a', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +" interrupt right before a catch is invoked in a script +func Test_ignore_catch_after_intr_1() + " for unknown reasons this test sometimes fails on MS-Windows. + let g:test_is_flaky = 1 + + XpathINIT + let lines =<< trim [CODE] + try + try + Xpath 'a' + throw "arrgh" + call assert_report('should not get here') + catch /.*/ " interrupt here + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + catch /arrgh/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + [CODE] + call writefile(lines, 'Xscript') + + breakadd file 6 Xscript + try + let caught_intr = 0 + debuggreedy + call feedkeys(":source Xscript\<CR>quit\<CR>", "xt") + catch /^Vim:Interrupt$/ + call assert_match('Xscript, line 6', v:throwpoint) + let caught_intr = 1 + endtry + 0debuggreedy + call assert_equal(1, caught_intr) + call assert_equal('a', g:Xpath) + breakdel * + call delete('Xscript') +endfunc + +" interrupt right before a catch is invoked inside a function. +func Test_ignore_catch_after_intr_2() + " for unknown reasons this test sometimes fails on MS-Windows. + let g:test_is_flaky = 1 + + XpathINIT + func F() + try + try + Xpath 'a' + throw "arrgh" + call assert_report('should not get here') + catch /.*/ " interrupt here + call assert_report('should not get here') + catch /.*/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + catch /arrgh/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + endfunc + + breakadd func 6 F + try + let caught_intr = 0 + debuggreedy + call feedkeys(":call F()\<CR>quit\<CR>", "xt") + catch /^Vim:Interrupt$/ + call assert_match('\.F, line 6', v:throwpoint) + let caught_intr = 1 + endtry + 0debuggreedy + call assert_equal(1, caught_intr) + call assert_equal('a', g:Xpath) + breakdel * + delfunc F +endfunc + +"------------------------------------------------------------------------------- +" Test 83: Executing :finally clauses after an error or interrupt {{{1 +" +" When an exception is thrown and an error or interrupt occurs before +" the :finally of the innermost :try is reached, the exception is +" discarded and the :finally clause is executed. +"------------------------------------------------------------------------------- + +func Test_finally_after_error() + let test =<< trim [CODE] + try + Xpath 'a' + try + Xpath 'b' + throw "arrgh" + call assert_report('should not get here') + if 1 + call assert_report('should not get here') + " error after :throw: missing :endif + finally + Xpath 'c' + endtry + call assert_report('should not get here') + catch /arrgh/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + [CODE] + let verify =<< trim [CODE] + call assert_equal('abc', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +" interrupt the code right before the finally is invoked +func Test_finally_after_intr() + XpathINIT + let lines =<< trim [CODE] + try + Xpath 'a' + try + Xpath 'b' + throw "arrgh" + call assert_report('should not get here') + finally " interrupt here + Xpath 'c' + endtry + call assert_report('should not get here') + catch /arrgh/ + call assert_report('should not get here') + endtry + call assert_report('should not get here') + [CODE] + call writefile(lines, 'Xscript') + + breakadd file 7 Xscript + try + let caught_intr = 0 + debuggreedy + call feedkeys(":source Xscript\<CR>quit\<CR>", "xt") + catch /^Vim:Interrupt$/ + call assert_match('Xscript, line 7', v:throwpoint) + let caught_intr = 1 + endtry + 0debuggreedy + call assert_equal(1, caught_intr) + call assert_equal('abc', g:Xpath) + breakdel * + call delete('Xscript') +endfunc + +"------------------------------------------------------------------------------- +" Test 84: Exceptions in autocommand sequences. {{{1 +" +" When an exception occurs in a sequence of autocommands for +" a specific event, the rest of the sequence is not executed. The +" command that triggered the autocommand execution aborts, and the +" exception is propagated to the caller. +" +" For the FuncUndefined event under a function call expression or +" :call command, the function is not executed, even when it has +" been defined by the autocommands before the exception occurred. +"------------------------------------------------------------------------------- + +func Test_autocmd_exception() + let test =<< trim [CODE] + func INT() + call interrupt() + endfunc + + aug TMP + autocmd! + + autocmd User x1 Xpath 'a' + autocmd User x1 throw "x1" + autocmd User x1 call assert_report('should not get here') + + autocmd User x2 Xpath 'b' + autocmd User x2 asdf + autocmd User x2 call assert_report('should not get here') + + autocmd User x3 Xpath 'c' + autocmd User x3 call INT() + autocmd User x3 call assert_report('should not get here') + + autocmd FuncUndefined U1 func U1() + autocmd FuncUndefined U1 call assert_report('should not get here') + autocmd FuncUndefined U1 endfunc + autocmd FuncUndefined U1 Xpath 'd' + autocmd FuncUndefined U1 throw "U1" + autocmd FuncUndefined U1 call assert_report('should not get here') + + autocmd FuncUndefined U2 func U2() + autocmd FuncUndefined U2 call assert_report('should not get here') + autocmd FuncUndefined U2 endfunc + autocmd FuncUndefined U2 Xpath 'e' + autocmd FuncUndefined U2 ASDF + autocmd FuncUndefined U2 call assert_report('should not get here') + + autocmd FuncUndefined U3 func U3() + autocmd FuncUndefined U3 call assert_report('should not get here') + autocmd FuncUndefined U3 endfunc + autocmd FuncUndefined U3 Xpath 'f' + autocmd FuncUndefined U3 call INT() + autocmd FuncUndefined U3 call assert_report('should not get here') + aug END + + try + try + Xpath 'g' + doautocmd User x1 + catch /x1/ + Xpath 'h' + endtry + + while 1 + try + Xpath 'i' + doautocmd User x2 + catch /asdf/ + Xpath 'j' + finally + Xpath 'k' + break + endtry + endwhile + + while 1 + try + Xpath 'l' + doautocmd User x3 + catch /Vim:Interrupt/ + Xpath 'm' + finally + Xpath 'n' + " ... but break loop for caught interrupt exception, + " or discard interrupt and break loop if $VIMNOINTTHROW + break + endtry + endwhile + + if exists("*U1") | delfunction U1 | endif + if exists("*U2") | delfunction U2 | endif + if exists("*U3") | delfunction U3 | endif + + try + Xpath 'o' + call U1() + catch /U1/ + Xpath 'p' + endtry + + while 1 + try + Xpath 'q' + call U2() + catch /ASDF/ + Xpath 'r' + finally + Xpath 's' + " ... but break loop for caught error exception, + " or discard error and break loop if $VIMNOERRTHROW + break + endtry + endwhile + + while 1 + try + Xpath 't' + call U3() + catch /Vim:Interrupt/ + Xpath 'u' + finally + Xpath 'v' + " ... but break loop for caught interrupt exception, + " or discard interrupt and break loop if $VIMNOINTTHROW + break + endtry + endwhile + catch /.*/ + call assert_report('should not get here') + endtry + Xpath 'w' + [CODE] + let verify =<< trim [CODE] + call assert_equal('gahibjklcmnodpqerstfuvw', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 85: Error exceptions in autocommands for I/O command events {{{1 +" +" When an I/O command is inside :try/:endtry, autocommands to be +" executed after it should be skipped on an error (exception) in the +" command itself or in autocommands to be executed before the command. +" In the latter case, the I/O command should not be executed either. +" Example 1: BufWritePre, :write, BufWritePost +" Example 2: FileReadPre, :read, FileReadPost. +"------------------------------------------------------------------------------- + +func Test_autocmd_error_io_exception() + let test =<< trim [CODE] + " Remove the autocommands for the events specified as arguments in all used + " autogroups. + func Delete_autocommands(...) + let augfile = tempname() + while 1 + try + exec "redir >" . augfile + aug + redir END + exec "edit" augfile + g/^$/d + norm G$ + let wrap = "w" + while search('\%( \|^\)\@<=.\{-}\%( \)\@=', wrap) > 0 + let wrap = "W" + exec "norm y/ \n" + let argno = 1 + while argno <= a:0 + exec "au!" escape(@", " ") a:{argno} + let argno = argno + 1 + endwhile + endwhile + catch /.*/ + finally + bwipeout! + call delete(augfile) + break + endtry + endwhile + endfunc + + call Delete_autocommands("BufWritePre", "BufWritePost") + + while 1 + try + try + let post = 0 + aug TMP + au! BufWritePost * let post = 1 + aug END + write /n/o/n/e/x/i/s/t/e/n/t + catch /^Vim(write):/ + Xpath 'a' + call assert_match("E212: Can't open file for writing", v:exception) + finally + Xpath 'b' + call assert_equal(0, post) + au! TMP + aug! TMP + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'c' + break + endtry + endwhile + + while 1 + try + try + let post = 0 + aug TMP + au! BufWritePre * asdf + au! BufWritePost * let post = 1 + aug END + let tmpfile = tempname() + exec "write" tmpfile + catch /^Vim\((write)\)\=:/ + Xpath 'd' + call assert_match('E492: Not an editor command', v:exception) + finally + Xpath 'e' + if filereadable(tmpfile) + call assert_report('should not get here') + endif + call assert_equal(0, post) + au! TMP + aug! TMP + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'f' + break + endtry + endwhile + + call delete(tmpfile) + + call Delete_autocommands("BufWritePre", "BufWritePost", + \ "BufReadPre", "BufReadPost", "FileReadPre", "FileReadPost") + + while 1 + try + try + let post = 0 + aug TMP + au! FileReadPost * let post = 1 + aug END + let caught = 0 + read /n/o/n/e/x/i/s/t/e/n/t + catch /^Vim(read):/ + Xpath 'g' + call assert_match("E484: Can't open file", v:exception) + finally + Xpath 'h' + call assert_equal(0, post) + au! TMP + aug! TMP + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'i' + break + endtry + endwhile + + while 1 + try + let infile = tempname() + let tmpfile = tempname() + call writefile(["XYZ"], infile) + exec "edit" tmpfile + try + Xpath 'j' + try + let post = 0 + aug TMP + au! FileReadPre * asdf + au! FileReadPost * let post = 1 + aug END + exec "0read" infile + catch /^Vim\((read)\)\=:/ + Xpath 'k' + call assert_match('E492: Not an editor command', v:exception) + finally + Xpath 'l' + if getline("1") == "XYZ" + call assert_report('should not get here') + endif + call assert_equal(0, post) + au! TMP + aug! TMP + endtry + finally + Xpath 'm' + bwipeout! + endtry + catch /.*/ + call assert_report('should not get here') + finally + Xpath 'n' + break + endtry + endwhile + + call delete(infile) + call delete(tmpfile) + [CODE] + let verify =<< trim [CODE] + call assert_equal('abcdefghijklmn', g:Xpath) + [CODE] + call RunInNewVim(test, verify) +endfunc + +"------------------------------------------------------------------------------- +" Test 87 using (expr) ? funcref : funcref {{{1 +" +" Vim needs to correctly parse the funcref and even when it does +" not execute the funcref, it needs to consume the trailing () +"------------------------------------------------------------------------------- + +func Add2(x1, x2) + return a:x1 + a:x2 +endfu + +func GetStr() + return "abcdefghijklmnopqrstuvwxyp" +endfu + +func Test_funcref_with_condexpr() + call assert_equal(5, function('Add2')(2,3)) + + call assert_equal(3, 1 ? function('Add2')(1,2) : function('Add2')(2,3)) + call assert_equal(5, 0 ? function('Add2')(1,2) : function('Add2')(2,3)) + " Make sure, GetStr() still works. + call assert_equal('abcdefghijk', GetStr()[0:10]) +endfunc + +"------------------------------------------------------------------------------- +" Test 90: Recognizing {} in variable name. {{{1 +"------------------------------------------------------------------------------- + +func Test_curlies() + let s:var = 66 + let ns = 's' + call assert_equal(66, {ns}:var) + + let g:a = {} + let g:b = 't' + let g:a[g:b] = 77 + call assert_equal(77, g:a['t']) +endfunc + +"------------------------------------------------------------------------------- +" Test 91: using type(). {{{1 +"------------------------------------------------------------------------------- + +func Test_type() + call assert_equal(0, type(0)) + call assert_equal(1, type("")) + call assert_equal(2, type(function("tr"))) + call assert_equal(2, type(function("tr", [8]))) + call assert_equal(3, type([])) + call assert_equal(4, type({})) + call assert_equal(5, type(0.0)) + call assert_equal(6, type(v:false)) + call assert_equal(6, type(v:true)) + call assert_equal(7, type(v:null)) + call assert_equal(v:t_number, type(0)) + call assert_equal(v:t_string, type("")) + call assert_equal(v:t_func, type(function("tr"))) + call assert_equal(v:t_list, type([])) + call assert_equal(v:t_dict, type({})) + call assert_equal(v:t_float, type(0.0)) + call assert_equal(v:t_bool, type(v:false)) + call assert_equal(v:t_bool, type(v:true)) + " call assert_equal(v:t_none, type(v:none)) + " call assert_equal(v:t_none, type(v:null)) + call assert_equal(v:t_string, type(v:_null_string)) + call assert_equal(v:t_list, type(v:_null_list)) + call assert_equal(v:t_dict, type(v:_null_dict)) + if has('job') + call assert_equal(v:t_job, type(test_null_job())) + endif + if has('channel') + call assert_equal(v:t_channel, type(test_null_channel())) + endif + call assert_equal(v:t_blob, type(v:_null_blob)) + + call assert_equal(0, 0 + v:false) + call assert_equal(1, 0 + v:true) + " call assert_equal(0, 0 + v:none) + call assert_equal(0, 0 + v:null) + + call assert_equal('v:false', '' . v:false) + call assert_equal('v:true', '' . v:true) + " call assert_equal('v:none', '' . v:none) + call assert_equal('v:null', '' . v:null) + + call assert_true(v:false == 0) + call assert_false(v:false != 0) + call assert_true(v:true == 1) + call assert_false(v:true != 1) + call assert_false(v:true == v:false) + call assert_true(v:true != v:false) + + call assert_true(v:null == 0) + call assert_false(v:null != 0) + " call assert_true(v:none == 0) + " call assert_false(v:none != 0) + + call assert_true(v:false is v:false) + call assert_true(v:true is v:true) + " call assert_true(v:none is v:none) + call assert_true(v:null is v:null) + + call assert_false(v:false isnot v:false) + call assert_false(v:true isnot v:true) + " call assert_false(v:none isnot v:none) + call assert_false(v:null isnot v:null) + + call assert_false(v:false is 0) + call assert_false(v:true is 1) + call assert_false(v:true is v:false) + " call assert_false(v:none is 0) + call assert_false(v:null is 0) + " call assert_false(v:null is v:none) + + call assert_true(v:false isnot 0) + call assert_true(v:true isnot 1) + call assert_true(v:true isnot v:false) + " call assert_true(v:none isnot 0) + call assert_true(v:null isnot 0) + " call assert_true(v:null isnot v:none) + + call assert_equal(v:false, eval(string(v:false))) + call assert_equal(v:true, eval(string(v:true))) + " call assert_equal(v:none, eval(string(v:none))) + call assert_equal(v:null, eval(string(v:null))) + + call assert_equal(v:false, copy(v:false)) + call assert_equal(v:true, copy(v:true)) + " call assert_equal(v:none, copy(v:none)) + call assert_equal(v:null, copy(v:null)) + + call assert_equal([v:false], deepcopy([v:false])) + call assert_equal([v:true], deepcopy([v:true])) + " call assert_equal([v:none], deepcopy([v:none])) + call assert_equal([v:null], deepcopy([v:null])) + + call assert_true(empty(v:false)) + call assert_false(empty(v:true)) + call assert_true(empty(v:null)) + " call assert_true(empty(v:none)) + + func ChangeYourMind() + try + return v:true + finally + return 'something else' + endtry + endfunc + + call ChangeYourMind() +endfunc + +"------------------------------------------------------------------------------- +" Test 92: skipping code {{{1 +"------------------------------------------------------------------------------- + +func Test_skip() + let Fn = function('Test_type') + call assert_false(0 && Fn[1]) + call assert_false(0 && string(Fn)) + call assert_false(0 && len(Fn)) + let l = [] + call assert_false(0 && l[1]) + call assert_false(0 && string(l)) + call assert_false(0 && len(l)) + let f = 1.0 + call assert_false(0 && f[1]) + call assert_false(0 && string(f)) + call assert_false(0 && len(f)) + let sp = v:null + call assert_false(0 && sp[1]) + call assert_false(0 && string(sp)) + call assert_false(0 && len(sp)) + +endfunc + +"------------------------------------------------------------------------------- +" Test 93: :echo and string() {{{1 +"------------------------------------------------------------------------------- + +func Test_echo_and_string() + " String + let a = 'foo bar' + redir => result + echo a + echo string(a) + redir END + let l = split(result, "\n") + call assert_equal(["foo bar", + \ "'foo bar'"], l) + + " Float + if has('float') + let a = -1.2e0 + redir => result + echo a + echo string(a) + redir END + let l = split(result, "\n") + call assert_equal(["-1.2", + \ "-1.2"], l) + endif + + " Funcref + redir => result + echo function('string') + echo string(function('string')) + redir END + let l = split(result, "\n") + call assert_equal(["string", + \ "function('string')"], l) + + " Empty dictionaries in a list + let a = {} + redir => result + echo [a, a, a] + echo string([a, a, a]) + redir END + let l = split(result, "\n") + call assert_equal(["[{}, {}, {}]", + \ "[{}, {}, {}]"], l) + + " Empty dictionaries in a dictionary + let a = {} + let b = {"a": a, "b": a} + redir => result + echo b + echo string(b) + redir END + let l = split(result, "\n") + call assert_equal(["{'a': {}, 'b': {}}", + \ "{'a': {}, 'b': {}}"], l) + + " Empty lists in a list + let a = [] + redir => result + echo [a, a, a] + echo string([a, a, a]) + redir END + let l = split(result, "\n") + call assert_equal(["[[], [], []]", + \ "[[], [], []]"], l) + + " Empty lists in a dictionary + let a = [] + let b = {"a": a, "b": a} + redir => result + echo b + echo string(b) + redir END + let l = split(result, "\n") + call assert_equal(["{'a': [], 'b': []}", + \ "{'a': [], 'b': []}"], l) + + call assert_fails('echo &:', 'E112:') + call assert_fails('echo &g:', 'E112:') + call assert_fails('echo &l:', 'E112:') + +endfunc + +"------------------------------------------------------------------------------- +" Test 94: 64-bit Numbers {{{1 +"------------------------------------------------------------------------------- + +func Test_num64() + call assert_notequal( 4294967296, 0) + call assert_notequal(-4294967296, 0) + call assert_equal( 4294967296, 0xFFFFffff + 1) + call assert_equal(-4294967296, -0xFFFFffff - 1) + + call assert_equal( 9223372036854775807, 1 / 0) + call assert_equal(-9223372036854775807, -1 / 0) + call assert_equal(-9223372036854775807 - 1, 0 / 0) + + if has('float') + call assert_equal( 0x7FFFffffFFFFffff, float2nr( 1.0e150)) + call assert_equal(-0x7FFFffffFFFFffff, float2nr(-1.0e150)) + endif + + let rng = range(0xFFFFffff, 0x100000001) + call assert_equal([0xFFFFffff, 0x100000000, 0x100000001], rng) + call assert_equal(0x100000001, max(rng)) + call assert_equal(0xFFFFffff, min(rng)) + call assert_equal(rng, sort(range(0x100000001, 0xFFFFffff, -1), 'N')) +endfunc + +"------------------------------------------------------------------------------- +" Test 95: lines of :append, :change, :insert {{{1 +"------------------------------------------------------------------------------- + +func DefineFunction(name, body) + let func = join(['function! ' . a:name . '()'] + a:body + ['endfunction'], "\n") + exec func +endfunc + +func Test_script_lines() + " :append + try + call DefineFunction('T_Append', [ + \ 'append', + \ 'py <<EOS', + \ '.', + \ ]) + catch + call assert_report("Can't define function") + endtry + try + call DefineFunction('T_Append', [ + \ 'append', + \ 'abc', + \ ]) + call assert_report("Shouldn't be able to define function") + catch + call assert_exception('Vim(function):E1145: Missing heredoc end marker: .') + endtry + + " :change + try + call DefineFunction('T_Change', [ + \ 'change', + \ 'py <<EOS', + \ '.', + \ ]) + catch + call assert_report("Can't define function") + endtry + try + call DefineFunction('T_Change', [ + \ 'change', + \ 'abc', + \ ]) + call assert_report("Shouldn't be able to define function") + catch + call assert_exception('Vim(function):E1145: Missing heredoc end marker: .') + endtry + + " :insert + try + call DefineFunction('T_Insert', [ + \ 'insert', + \ 'py <<EOS', + \ '.', + \ ]) + catch + call assert_report("Can't define function") + endtry + try + call DefineFunction('T_Insert', [ + \ 'insert', + \ 'abc', + \ ]) + call assert_report("Shouldn't be able to define function") + catch + call assert_exception('Vim(function):E1145: Missing heredoc end marker: .') + endtry +endfunc + +"------------------------------------------------------------------------------- +" Test 96: line continuation {{{1 +" +" Undefined behavior was detected by ubsan with line continuation +" after an empty line. +"------------------------------------------------------------------------------- +func Test_script_empty_line_continuation() + + \ +endfunc + +"------------------------------------------------------------------------------- +" Test 97: bitwise functions {{{1 +"------------------------------------------------------------------------------- +func Test_bitwise_functions() + " and + call assert_equal(127, and(127, 127)) + call assert_equal(16, and(127, 16)) + eval 127->and(16)->assert_equal(16) + call assert_equal(0, and(127, 128)) + call assert_fails("call and(1.0, 1)", 'E805:') + call assert_fails("call and([], 1)", 'E745:') + call assert_fails("call and({}, 1)", 'E728:') + call assert_fails("call and(1, 1.0)", 'E805:') + call assert_fails("call and(1, [])", 'E745:') + call assert_fails("call and(1, {})", 'E728:') + " or + call assert_equal(23, or(16, 7)) + call assert_equal(15, or(8, 7)) + eval 8->or(7)->assert_equal(15) + call assert_equal(123, or(0, 123)) + call assert_fails("call or(1.0, 1)", 'E805:') + call assert_fails("call or([], 1)", 'E745:') + call assert_fails("call or({}, 1)", 'E728:') + call assert_fails("call or(1, 1.0)", 'E805:') + call assert_fails("call or(1, [])", 'E745:') + call assert_fails("call or(1, {})", 'E728:') + " xor + call assert_equal(0, xor(127, 127)) + call assert_equal(111, xor(127, 16)) + eval 127->xor(16)->assert_equal(111) + call assert_equal(255, xor(127, 128)) + call assert_fails("call xor(1.0, 1)", 'E805:') + call assert_fails("call xor([], 1)", 'E745:') + call assert_fails("call xor({}, 1)", 'E728:') + call assert_fails("call xor(1, 1.0)", 'E805:') + call assert_fails("call xor(1, [])", 'E745:') + call assert_fails("call xor(1, {})", 'E728:') + " invert + call assert_equal(65408, and(invert(127), 65535)) + eval 127->invert()->and(65535)->assert_equal(65408) + call assert_equal(65519, and(invert(16), 65535)) + call assert_equal(65407, and(invert(128), 65535)) + call assert_fails("call invert(1.0)", 'E805:') + call assert_fails("call invert([])", 'E745:') + call assert_fails("call invert({})", 'E728:') +endfunc + +" Test using bang after user command {{{1 +func Test_user_command_with_bang() + command -bang Nieuw let nieuw = 1 + Ni! + call assert_equal(1, nieuw) + unlet nieuw + delcommand Nieuw +endfunc + +func Test_script_expand_sfile() + let lines =<< trim END + func s:snr() + return expand('<sfile>') + endfunc + let g:result = s:snr() + END + call writefile(lines, 'Xexpand') + source Xexpand + call assert_match('<SNR>\d\+_snr', g:result) + source Xexpand + call assert_match('<SNR>\d\+_snr', g:result) + + call delete('Xexpand') + unlet g:result +endfunc + +func Test_compound_assignment_operators() + " Test for number + let x = 1 + let x += 10 + call assert_equal(11, x) + let x -= 5 + call assert_equal(6, x) + let x *= 4 + call assert_equal(24, x) + let x /= 3 + call assert_equal(8, x) + let x %= 3 + call assert_equal(2, x) + let x .= 'n' + call assert_equal('2n', x) + + " Test special cases: division or modulus with 0. + let x = 1 + let x /= 0 + call assert_equal(0x7FFFFFFFFFFFFFFF, x) + + let x = -1 + let x /= 0 + call assert_equal(-0x7FFFFFFFFFFFFFFF, x) + + let x = 0 + let x /= 0 + call assert_equal(-0x7FFFFFFFFFFFFFFF - 1, x) + + let x = 1 + let x %= 0 + call assert_equal(0, x) + + let x = -1 + let x %= 0 + call assert_equal(0, x) + + let x = 0 + let x %= 0 + call assert_equal(0, x) + + " Test for string + let x = 'str' + let x .= 'ing' + call assert_equal('string', x) + let x += 1 + call assert_equal(1, x) + + if has('float') + " Test for float + let x -= 1.5 + call assert_equal(-0.5, x) + let x = 0.5 + let x += 4.5 + call assert_equal(5.0, x) + let x -= 1.5 + call assert_equal(3.5, x) + let x *= 3.0 + call assert_equal(10.5, x) + let x /= 2.5 + call assert_equal(4.2, x) + call assert_fails('let x %= 0.5', 'E734') + call assert_fails('let x .= "f"', 'E734') + let x = !3.14 + call assert_equal(0.0, x) + + " integer and float operations + let x = 1 + let x *= 2.1 + call assert_equal(2.1, x) + let x = 1 + let x /= 0.25 + call assert_equal(4.0, x) + let x = 1 + call assert_fails('let x %= 0.25', 'E734:') + let x = 1 + call assert_fails('let x .= 0.25', 'E734:') + let x = 1.0 + call assert_fails('let x += [1.1]', 'E734:') + endif + + " Test for environment variable + let $FOO = 1 + call assert_fails('let $FOO += 1', 'E734') + call assert_fails('let $FOO -= 1', 'E734') + call assert_fails('let $FOO *= 1', 'E734') + call assert_fails('let $FOO /= 1', 'E734') + call assert_fails('let $FOO %= 1', 'E734') + let $FOO .= 's' + call assert_equal('1s', $FOO) + unlet $FOO + + " Test for option variable (type: number) + let &scrolljump = 1 + let &scrolljump += 5 + call assert_equal(6, &scrolljump) + let &scrolljump -= 2 + call assert_equal(4, &scrolljump) + let &scrolljump *= 3 + call assert_equal(12, &scrolljump) + let &scrolljump /= 2 + call assert_equal(6, &scrolljump) + let &scrolljump %= 5 + call assert_equal(1, &scrolljump) + call assert_fails('let &scrolljump .= "j"', ['E734:', 'E734:']) + set scrolljump&vim + + let &foldlevelstart = 2 + let &foldlevelstart -= 1 + call assert_equal(1, &foldlevelstart) + let &foldlevelstart -= 1 + call assert_equal(0, &foldlevelstart) + let &foldlevelstart = 2 + let &foldlevelstart -= 2 + call assert_equal(0, &foldlevelstart) + + " Test for register + let @/ = 1 + call assert_fails('let @/ += 1', 'E734:') + call assert_fails('let @/ -= 1', 'E734:') + call assert_fails('let @/ *= 1', 'E734:') + call assert_fails('let @/ /= 1', 'E734:') + call assert_fails('let @/ %= 1', 'E734:') + let @/ .= 's' + call assert_equal('1s', @/) + let @/ = '' +endfunc + +func Test_unlet_env() + let $TESTVAR = 'yes' + call assert_equal('yes', $TESTVAR) + call assert_fails('lockvar $TESTVAR', 'E940') + call assert_fails('unlockvar $TESTVAR', 'E940') + call assert_equal('yes', $TESTVAR) + if 0 + unlet $TESTVAR + endif + call assert_equal('yes', $TESTVAR) + unlet $TESTVAR + call assert_equal('', $TESTVAR) +endfunc + +func Test_refcount() + throw 'Skipped: Nvim does not support test_refcount()' + " Immediate values + call assert_equal(-1, test_refcount(1)) + call assert_equal(-1, test_refcount('s')) + call assert_equal(-1, test_refcount(v:true)) + call assert_equal(0, test_refcount([])) + call assert_equal(0, test_refcount({})) + call assert_equal(0, test_refcount(0zff)) + call assert_equal(0, test_refcount({-> line('.')})) + call assert_equal(-1, test_refcount(0.1)) + if has('job') + call assert_equal(0, test_refcount(job_start([&shell, &shellcmdflag, 'echo .']))) + endif + + " No refcount types + let x = 1 + call assert_equal(-1, test_refcount(x)) + let x = 's' + call assert_equal(-1, test_refcount(x)) + let x = v:true + call assert_equal(-1, test_refcount(x)) + let x = 0.1 + call assert_equal(-1, test_refcount(x)) + + " Check refcount + let x = [] + call assert_equal(1, test_refcount(x)) + + let x = {} + call assert_equal(1, x->test_refcount()) + + let x = 0zff + call assert_equal(1, test_refcount(x)) + + let X = {-> line('.')} + call assert_equal(1, test_refcount(X)) + let Y = X + call assert_equal(2, test_refcount(X)) + + if has('job') + let job = job_start([&shell, &shellcmdflag, 'echo .']) + call assert_equal(1, test_refcount(job)) + call assert_equal(1, test_refcount(job_getchannel(job))) + call assert_equal(1, test_refcount(job)) + endif + + " Function arguments, copying and unassigning + func ExprCheck(x, i) + let i = a:i + 1 + call assert_equal(i, test_refcount(a:x)) + let Y = a:x + call assert_equal(i + 1, test_refcount(a:x)) + call assert_equal(test_refcount(a:x), test_refcount(Y)) + let Y = 0 + call assert_equal(i, test_refcount(a:x)) + endfunc + call ExprCheck([], 0) + call ExprCheck({}, 0) + call ExprCheck(0zff, 0) + call ExprCheck({-> line('.')}, 0) + if has('job') + call ExprCheck(job, 1) + call ExprCheck(job_getchannel(job), 1) + call job_stop(job) + endif + delfunc ExprCheck + + " Regarding function + func Func(x) abort + call assert_equal(2, test_refcount(function('Func'))) + call assert_equal(0, test_refcount(funcref('Func'))) + endfunc + call assert_equal(1, test_refcount(function('Func'))) + call assert_equal(0, test_refcount(function('Func', [1]))) + call assert_equal(0, test_refcount(funcref('Func'))) + call assert_equal(0, test_refcount(funcref('Func', [1]))) + let X = function('Func') + let Y = X + call assert_equal(1, test_refcount(X)) + let X = function('Func', [1]) + let Y = X + call assert_equal(2, test_refcount(X)) + let X = funcref('Func') + let Y = X + call assert_equal(2, test_refcount(X)) + let X = funcref('Func', [1]) + let Y = X + call assert_equal(2, test_refcount(X)) + unlet X + unlet Y + call Func(1) + delfunc Func + + " Function with dict + func DictFunc() dict + call assert_equal(3, test_refcount(self)) + endfunc + let d = {'Func': function('DictFunc')} + call assert_equal(1, test_refcount(d)) + call assert_equal(0, test_refcount(d.Func)) + call d.Func() + unlet d + delfunc DictFunc + + if has('channel') + call assert_equal(-1, test_refcount(test_null_job())) + call assert_equal(-1, test_refcount(test_null_channel())) + endif + call assert_equal(-1, test_refcount(test_null_function())) + call assert_equal(-1, test_refcount(test_null_partial())) + call assert_equal(-1, test_refcount(test_null_blob())) + call assert_equal(-1, test_refcount(test_null_list())) + call assert_equal(-1, test_refcount(test_null_dict())) +endfunc + +" Test for missing :endif, :endfor, :endwhile and :endtry {{{1 +func Test_missing_end() + call writefile(['if 2 > 1', 'echo ">"'], 'Xscript') + call assert_fails('source Xscript', 'E171:') + call writefile(['for i in range(5)', 'echo i'], 'Xscript') + call assert_fails('source Xscript', 'E170:') + call writefile(['while v:true', 'echo "."'], 'Xscript') + call assert_fails('source Xscript', 'E170:') + call writefile(['try', 'echo "."'], 'Xscript') + call assert_fails('source Xscript', 'E600:') + call delete('Xscript') + + " Using endfor with :while + let caught_e732 = 0 + try + while v:true + endfor + catch /E732:/ + let caught_e732 = 1 + endtry + call assert_equal(1, caught_e732) + + " Using endwhile with :for + let caught_e733 = 0 + try + for i in range(1) + endwhile + catch /E733:/ + let caught_e733 = 1 + endtry + call assert_equal(1, caught_e733) + + " Using endfunc with :if + call assert_fails('exe "if 1 | endfunc | endif"', 'E193:') + + " Missing 'in' in a :for statement + call assert_fails('for i range(1) | endfor', 'E690:') + + " Incorrect number of variables in for + call assert_fails('for [i,] in range(3) | endfor', 'E475:') +endfunc + +" Test for deep nesting of if/for/while/try statements {{{1 +func Test_deep_nest() + CheckRunVimInTerminal + + let lines =<< trim [SCRIPT] + " Deep nesting of if ... endif + func Test1() + let @a = join(repeat(['if v:true'], 51), "\n") + let @a ..= "\n" + let @a ..= join(repeat(['endif'], 51), "\n") + @a + let @a = '' + endfunc + + " Deep nesting of for ... endfor + func Test2() + let @a = join(repeat(['for i in [1]'], 51), "\n") + let @a ..= "\n" + let @a ..= join(repeat(['endfor'], 51), "\n") + @a + let @a = '' + endfunc + + " Deep nesting of while ... endwhile + func Test3() + let @a = join(repeat(['while v:true'], 51), "\n") + let @a ..= "\n" + let @a ..= join(repeat(['endwhile'], 51), "\n") + @a + let @a = '' + endfunc + + " Deep nesting of try ... endtry + func Test4() + let @a = join(repeat(['try'], 51), "\n") + let @a ..= "\necho v:true\n" + let @a ..= join(repeat(['endtry'], 51), "\n") + @a + let @a = '' + endfunc + + " Deep nesting of function ... endfunction + func Test5() + let @a = join(repeat(['function X()'], 51), "\n") + let @a ..= "\necho v:true\n" + let @a ..= join(repeat(['endfunction'], 51), "\n") + @a + let @a = '' + endfunc + [SCRIPT] + call writefile(lines, 'Xscript') + + let buf = RunVimInTerminal('-S Xscript', {'rows': 6}) + + " Deep nesting of if ... endif + call term_sendkeys(buf, ":call Test1()\n") + call TermWait(buf) + call WaitForAssert({-> assert_match('^E579:', term_getline(buf, 5))}) + + " Deep nesting of for ... endfor + call term_sendkeys(buf, ":call Test2()\n") + call TermWait(buf) + call WaitForAssert({-> assert_match('^E585:', term_getline(buf, 5))}) + + " Deep nesting of while ... endwhile + call term_sendkeys(buf, ":call Test3()\n") + call TermWait(buf) + call WaitForAssert({-> assert_match('^E585:', term_getline(buf, 5))}) + + " Deep nesting of try ... endtry + call term_sendkeys(buf, ":call Test4()\n") + call TermWait(buf) + call WaitForAssert({-> assert_match('^E601:', term_getline(buf, 5))}) + + " Deep nesting of function ... endfunction + call term_sendkeys(buf, ":call Test5()\n") + call TermWait(buf) + call WaitForAssert({-> assert_match('^E1058:', term_getline(buf, 4))}) + call term_sendkeys(buf, "\<C-C>\n") + call TermWait(buf) + + "let l = '' + "for i in range(1, 6) + " let l ..= term_getline(buf, i) . "\n" + "endfor + "call assert_report(l) + + call StopVimInTerminal(buf) + call delete('Xscript') +endfunc + +" Test for errors in converting to float from various types {{{1 +func Test_float_conversion_errors() + if has('float') + call assert_fails('let x = 4.0 % 2.0', 'E804') + call assert_fails('echo 1.1[0]', 'E806') + call assert_fails('echo sort([function("min"), 1], "f")', 'E891:') + call assert_fails('echo 3.2 == "vim"', 'E892:') + call assert_fails('echo sort([[], 1], "f")', 'E893:') + call assert_fails('echo sort([{}, 1], "f")', 'E894:') + call assert_fails('echo 3.2 == v:true', 'E362:') + " call assert_fails('echo 3.2 == v:none', 'E907:') + endif +endfunc + +" invalid function names {{{1 +func Test_invalid_function_names() + " function name not starting with capital + let caught_e128 = 0 + try + func! g:test() + echo "test" + endfunc + catch /E128:/ + let caught_e128 = 1 + endtry + call assert_equal(1, caught_e128) + + " function name includes a colon + let caught_e884 = 0 + try + func! b:test() + echo "test" + endfunc + catch /E884:/ + let caught_e884 = 1 + endtry + call assert_equal(1, caught_e884) + + " function name followed by # + let caught_e128 = 0 + try + func! test2() "# + echo "test2" + endfunc + catch /E128:/ + let caught_e128 = 1 + endtry + call assert_equal(1, caught_e128) + + " function name starting with/without "g:", buffer-local funcref. + function! g:Foo(n) + return 'called Foo(' . a:n . ')' + endfunction + let b:my_func = function('Foo') + call assert_equal('called Foo(1)', b:my_func(1)) + call assert_equal('called Foo(2)', g:Foo(2)) + call assert_equal('called Foo(3)', Foo(3)) + delfunc g:Foo + + " script-local function used in Funcref must exist. + let lines =<< trim END + func s:Testje() + return "foo" + endfunc + let Bar = function('s:Testje') + call assert_equal(0, exists('s:Testje')) + call assert_equal(1, exists('*s:Testje')) + call assert_equal(1, exists('Bar')) + call assert_equal(1, exists('*Bar')) + END + call writefile(lines, 'Xscript') + source Xscript + call delete('Xscript') +endfunc + +" substring and variable name {{{1 +func Test_substring_var() + let str = 'abcdef' + let n = 3 + call assert_equal('def', str[n:]) + call assert_equal('abcd', str[:n]) + call assert_equal('d', str[n:n]) + unlet n + let nn = 3 + call assert_equal('def', str[nn:]) + call assert_equal('abcd', str[:nn]) + call assert_equal('d', str[nn:nn]) + unlet nn + let b:nn = 4 + call assert_equal('ef', str[b:nn:]) + call assert_equal('abcde', str[:b:nn]) + call assert_equal('e', str[b:nn:b:nn]) + unlet b:nn +endfunc + +" Test using s: with a typed command {{{1 +func Test_typed_script_var() + CheckRunVimInTerminal + + let buf = RunVimInTerminal('', {'rows': 6}) + + " Deep nesting of if ... endif + call term_sendkeys(buf, ":echo get(s:, 'foo', 'x')\n") + call TermWait(buf) + call WaitForAssert({-> assert_match('^E116:', term_getline(buf, 5))}) + + call StopVimInTerminal(buf) +endfunc + +" Test for issue6776 {{{1 +func Test_ternary_expression() + try + call eval('0 ? 0') + catch + endtry + " previous failure should not cause next expression to fail + call assert_equal(v:false, eval(string(v:false))) + + try + call eval('0 ? "burp') + catch + endtry + " previous failure should not cause next expression to fail + call assert_equal(v:false, eval(string(v:false))) + + try + call eval('1 ? 0 : "burp') + catch + endtry + " previous failure should not cause next expression to fail + call assert_equal(v:false, eval(string(v:false))) +endfunction + +func Test_for_over_string() + let res = '' + for c in 'aéc̀d' + let res ..= c .. '-' + endfor + call assert_equal('a-é-c̀-d-', res) + + let res = '' + for c in '' + let res ..= c .. '-' + endfor + call assert_equal('', res) + + let res = '' + for c in v:_null_string + let res ..= c .. '-' + endfor + call assert_equal('', res) +endfunc + +"------------------------------------------------------------------------------- +" Modelines {{{1 +" vim: ts=8 sw=2 sts=2 expandtab tw=80 fdm=marker +"------------------------------------------------------------------------------- diff --git a/test/old/testdir/test_virtualedit.vim b/test/old/testdir/test_virtualedit.vim new file mode 100644 index 0000000000..4780faa706 --- /dev/null +++ b/test/old/testdir/test_virtualedit.vim @@ -0,0 +1,696 @@ +" Tests for 'virtualedit'. + +func Test_yank_move_change() + new + call setline(1, [ + \ "func foo() error {", + \ "\tif n, err := bar();", + \ "\terr != nil {", + \ "\t\treturn err", + \ "\t}", + \ "\tn = n * n", + \ ]) + set virtualedit=all + set ts=4 + function! MoveSelectionDown(count) abort + normal! m` + silent! exe "'<,'>move'>+".a:count + norm! `` + endfunction + + xmap ]e :<C-U>call MoveSelectionDown(v:count1)<CR> + 2 + normal 2gg + normal J + normal jVj + normal ]e + normal ce + bwipe! + set virtualedit= + set ts=8 +endfunc + +func Test_paste_end_of_line() + new + set virtualedit=all + call setline(1, ['456', '123']) + normal! gg0"ay$ + exe "normal! 2G$lllA\<C-O>:normal! \"agP\r" + call assert_equal('123456', getline(2)) + + bwipe! + set virtualedit= +endfunc + +func Test_replace_end_of_line() + new + set virtualedit=all + call setline(1, range(20)) + exe "normal! gg2jv10lr-" + call assert_equal(["1", "-----------", "3"], getline(2,4)) + call setline(1, range(20)) + exe "normal! gg2jv10lr\<c-k>hh" + call assert_equal(["1", "───────────", "3"], getline(2,4)) + + bwipe! + set virtualedit= +endfunc + +func Test_edit_CTRL_G() + new + set virtualedit=insert + call setline(1, ['123', '1', '12']) + exe "normal! ggA\<c-g>jx\<c-g>jx" + call assert_equal(['123', '1 x', '12 x'], getline(1,'$')) + + set virtualedit=all + %d_ + call setline(1, ['1', '12']) + exe "normal! ggllix\<c-g>jx" + call assert_equal(['1 x', '12x'], getline(1,'$')) + + + bwipe! + set virtualedit= +endfunc + +func Test_edit_change() + new + set virtualedit=all + call setline(1, "\t⒌") + normal Cx + call assert_equal('x', getline(1)) + " Do a visual block change + call setline(1, ['a', 'b', 'c']) + exe "normal gg3l\<C-V>2jcx" + call assert_equal(['a x', 'b x', 'c x'], getline(1, '$')) + bwipe! + set virtualedit= +endfunc + +func Test_edit_special_char() + new + se ve=all + norm a0 + sil! exe "norm o00000\<Nul>k<a0s" + + bwipe! + set virtualedit= +endfunc + +" Tests for pasting at the beginning, end and middle of a tab character +" in virtual edit mode. +func Test_paste_in_tab() + new + call append(0, '') + set virtualedit=all + + " Tests for pasting a register with characterwise mode type + call setreg('"', 'xyz', 'c') + + " paste (p) unnamed register at the beginning of a tab + call setline(1, "a\tb") + call cursor(1, 2, 0) + normal p + call assert_equal('a xyz b', getline(1)) + + " paste (P) unnamed register at the beginning of a tab + call setline(1, "a\tb") + call cursor(1, 2, 0) + normal P + call assert_equal("axyz\tb", getline(1)) + + " paste (p) unnamed register at the end of a tab + call setline(1, "a\tb") + call cursor(1, 2, 6) + normal p + call assert_equal("a\txyzb", getline(1)) + + " paste (P) unnamed register at the end of a tab + call setline(1, "a\tb") + call cursor(1, 2, 6) + normal P + call assert_equal('a xyz b', getline(1)) + + " Tests for pasting a register with blockwise mode type + call setreg('"', 'xyz', 'b') + + " paste (p) unnamed register at the beginning of a tab + call setline(1, "a\tb") + call cursor(1, 2, 0) + normal p + call assert_equal('a xyz b', getline(1)) + + " paste (P) unnamed register at the beginning of a tab + call setline(1, "a\tb") + call cursor(1, 2, 0) + normal P + call assert_equal("axyz\tb", getline(1)) + + " paste (p) unnamed register at the end of a tab + call setline(1, "a\tb") + call cursor(1, 2, 6) + normal p + call assert_equal("a\txyzb", getline(1)) + + " paste (P) unnamed register at the end of a tab + call setline(1, "a\tb") + call cursor(1, 2, 6) + normal P + call assert_equal('a xyz b', getline(1)) + + " Tests for pasting with gp and gP in virtual edit mode + + " paste (gp) unnamed register at the beginning of a tab + call setline(1, "a\tb") + call cursor(1, 2, 0) + normal gp + call assert_equal('a xyz b', getline(1)) + call assert_equal([0, 1, 12, 0, 12], getcurpos()) + + " paste (gP) unnamed register at the beginning of a tab + call setline(1, "a\tb") + call cursor(1, 2, 0) + normal gP + call assert_equal("axyz\tb", getline(1)) + call assert_equal([0, 1, 5, 0, 5], getcurpos()) + + " paste (gp) unnamed register at the end of a tab + call setline(1, "a\tb") + call cursor(1, 2, 6) + normal gp + call assert_equal("a\txyzb", getline(1)) + call assert_equal([0, 1, 6, 0, 12], getcurpos()) + + " paste (gP) unnamed register at the end of a tab + call setline(1, "a\tb") + call cursor(1, 2, 6) + normal gP + call assert_equal('a xyz b', getline(1)) + call assert_equal([0, 1, 12, 0, 12], getcurpos()) + + " Tests for pasting a named register + let @r = 'xyz' + + " paste (gp) named register in the middle of a tab + call setline(1, "a\tb") + call cursor(1, 2, 2) + normal "rgp + call assert_equal('a xyz b', getline(1)) + call assert_equal([0, 1, 8, 0, 8], getcurpos()) + + " paste (gP) named register in the middle of a tab + call setline(1, "a\tb") + call cursor(1, 2, 2) + normal "rgP + call assert_equal('a xyz b', getline(1)) + call assert_equal([0, 1, 7, 0, 7], getcurpos()) + + bwipe! + set virtualedit= +endfunc + +" Test for yanking a few spaces within a tab to a register +func Test_yank_in_tab() + new + let @r = '' + call setline(1, "a\tb") + set virtualedit=all + call cursor(1, 2, 2) + normal "ry5l + call assert_equal(' ', @r) + + bwipe! + set virtualedit= +endfunc + +" Insert "keyword keyw", ESC, C CTRL-N, shows "keyword ykeyword". +" Repeating CTRL-N fixes it. (Mary Ellen Foster) +func Test_ve_completion() + new + set completeopt&vim + set virtualedit=all + exe "normal ikeyword keyw\<Esc>C\<C-N>" + call assert_equal('keyword keyword', getline(1)) + bwipe! + set virtualedit= +endfunc + +" Using "C" then <CR> moves the last remaining character to the next +" line. (Mary Ellen Foster) +func Test_ve_del_to_eol() + new + set virtualedit=all + call append(0, 'all your base are belong to us') + call search('are', 'w') + exe "normal C\<CR>are belong to vim" + call assert_equal(['all your base ', 'are belong to vim'], getline(1, 2)) + bwipe! + set virtualedit= +endfunc + +" When past the end of a line that ends in a single character "b" skips +" that word. +func Test_ve_b_past_eol() + new + set virtualedit=all + call append(0, '1 2 3 4 5 6') + normal gg^$15lbC7 + call assert_equal('1 2 3 4 5 7', getline(1)) + bwipe! + set virtualedit= +endfunc + +" Make sure 'i', 'C', 'a', 'A' and 'D' works +func Test_ve_ins_del() + new + set virtualedit=all + call append(0, ["'i'", "'C'", "'a'", "'A'", "'D'"]) + call cursor(1, 1) + normal $4lix + call assert_equal("'i' x", getline(1)) + call cursor(2, 1) + normal $4lCx + call assert_equal("'C' x", getline(2)) + call cursor(3, 1) + normal $4lax + call assert_equal("'a' x", getline(3)) + call cursor(4, 1) + normal $4lAx + call assert_equal("'A'x", getline(4)) + call cursor(5, 1) + normal $4lDix + call assert_equal("'D' x", getline(5)) + bwipe! + set virtualedit= +endfunc + +" Test for yank bug reported by Mark Waggoner. +func Test_yank_block() + new + set virtualedit=block + call append(0, repeat(['this is a test'], 3)) + exe "normal gg^2w\<C-V>3jy" + call assert_equal("a\na\na\n ", @") + bwipe! + set virtualedit= +endfunc + +" Test "r" beyond the end of the line +func Test_replace_after_eol() + new + set virtualedit=all + call append(0, '"r"') + normal gg$5lrxa + call assert_equal('"r" x', getline(1)) + " visual block replace + %d _ + call setline(1, ['a', '', 'b']) + exe "normal 2l\<C-V>2jrx" + call assert_equal(['a x', ' x', 'b x'], getline(1, '$')) + " visual characterwise selection replace after eol + %d _ + call setline(1, 'a') + normal 4lv2lrx + call assert_equal('a xxx', getline(1)) + bwipe! + set virtualedit= +endfunc + +" Test "r" on a tab +" Note that for this test, 'ts' must be 8 (the default). +func Test_replace_on_tab() + new + set virtualedit=all + call append(0, "'r'\t") + normal gg^5lrxAy + call assert_equal("'r' x y", getline(1)) + call setline(1, 'aaaaaaaaaaaa') + exe "normal! gg2lgR\<Tab>" + call assert_equal("aa\taaaa", getline(1)) + bwipe! + set virtualedit= +endfunc + +" Test to make sure 'x' can delete control characters +func Test_ve_del_ctrl_chars() + new + set virtualedit=all + call append(0, "a\<C-V>b\<CR>sd") + set display=uhex + normal gg^xxxxxxi[text] + set display= + call assert_equal('[text]', getline(1)) + bwipe! + set virtualedit= +endfunc + +" Test for ^Y/^E due to bad w_virtcol value, reported by +" Roy <royl@netropolis.net>. +func Test_ins_copy_char() + new + set virtualedit=all + call append(0, 'abcv8efi.him2kl') + exe "normal gg^O\<Esc>3li\<C-E>\<Esc>4li\<C-E>\<Esc>4li\<C-E> <--" + exe "normal j^o\<Esc>4li\<C-Y>\<Esc>4li\<C-Y>\<Esc>4li\<C-Y> <--" + call assert_equal(' v i m <--', getline(1)) + call assert_equal(' 8 . 2 <--', getline(3)) + bwipe! + set virtualedit= +endfunc + +" Test for yanking and pasting using the small delete register +func Test_yank_paste_small_del_reg() + new + set virtualedit=all + call append(0, "foo, bar") + normal ggdewve"-p + call assert_equal(', foo', getline(1)) + bwipe! + set virtualedit= +endfunc + +" Test for delete that breaks a tab into spaces +func Test_delete_break_tab() + new + call setline(1, "one\ttwo") + set virtualedit=all + normal v3ld + call assert_equal(' two', getline(1)) + set virtualedit& + close! +endfunc + +" Test for using <BS>, <C-W> and <C-U> in virtual edit mode +" to erase character, word and line. +func Test_ve_backspace() + new + call setline(1, 'sample') + set virtualedit=all + set backspace=indent,eol,start + exe "normal 15|i\<BS>\<BS>" + call assert_equal([0, 1, 7, 5], getpos('.')) + exe "normal 15|i\<C-W>" + call assert_equal([0, 1, 6, 0], getpos('.')) + exe "normal 15|i\<C-U>" + call assert_equal([0, 1, 1, 0], getpos('.')) + set backspace& + set virtualedit& + close! +endfunc + +" Test for delete (x) on EOL character and after EOL +func Test_delete_past_eol() + new + call setline(1, "ab") + set virtualedit=all + exe "normal 2lx" + call assert_equal('ab', getline(1)) + exe "normal 10lx" + call assert_equal('ab', getline(1)) + set virtualedit& + bw! +endfunc + +" After calling s:TryVirtualeditReplace(), line 1 will contain one of these +" two strings, depending on whether virtual editing is on or off. +let s:result_ve_on = 'a x' +let s:result_ve_off = 'x' + +" Utility function for Test_global_local_virtualedit() +func s:TryVirtualeditReplace() + call setline(1, 'a') + normal gg7l + normal rx +endfunc + +" Test for :set and :setlocal +func Test_global_local_virtualedit() + new + + " Verify that 'virtualedit' is initialized to empty, can be set globally to + " all and to empty, and can be set locally to all and to empty. + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + set ve=all + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + set ve= + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + setlocal ve=all + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + setlocal ve= + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + + " Verify that :set affects multiple windows. + split + set ve=all + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + wincmd p + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + set ve= + wincmd p + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + bwipe! + + " Verify that :setlocal affects only the current window. + new + split + setlocal ve=all + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + wincmd p + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + bwipe! + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + + " Verify that the buffer 'virtualedit' state follows the global value only + " when empty and that "none" works as expected. + " + " 'virtualedit' State + " +--------+--------------------------+ + " | Local | Global | + " | | | + " +--------+--------+--------+--------+ + " | | "" | "all" | "none" | + " +--------+--------+--------+--------+ + " | "" | off | on | off | + " | "all" | on | on | on | + " | "none" | off | off | off | + " +--------+--------+--------+--------+ + new + + setglobal ve= + setlocal ve= + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + setlocal ve=all + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + setlocal ve=none + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + + setglobal ve=all + setlocal ve= + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + setlocal ve=all + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + setlocal ve=none + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + setlocal ve=NONE + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + + setglobal ve=none + setlocal ve= + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + setlocal ve=all + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + setlocal ve=none + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + + bwipe! + + " Verify that the 'virtualedit' state is copied to new windows. + new + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + split + setlocal ve=all + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + split + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_on, getline(1)) + setlocal ve= + split + call s:TryVirtualeditReplace() + call assert_equal(s:result_ve_off, getline(1)) + bwipe! + + setlocal virtualedit& + set virtualedit& +endfunc + +func Test_virtualedit_setlocal() + enew + setglobal virtualedit=all + setlocal virtualedit=all + normal! l + redraw + setlocal virtualedit=none + call assert_equal(1, wincol()) + + setlocal virtualedit& + set virtualedit& +endfunc + +func Test_virtualedit_mouse() + let save_mouse = &mouse + set mouse=a + set virtualedit=all + botright new + let row = win_screenpos(0)[0] + 20vsplit + wincmd p + + call setline(1, ["text\tword"]) + redraw + call Ntest_setmouse(row, 21 + 4) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 4, 0, 4], getcurpos()) + call Ntest_setmouse(row, 21 + 5) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 5, 0, 5], getcurpos()) + call Ntest_setmouse(row, 21 + 6) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 5, 1, 6], getcurpos()) + call Ntest_setmouse(row, 21 + 7) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 5, 2, 7], getcurpos()) + call Ntest_setmouse(row, 21 + 8) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 5, 3, 8], getcurpos()) + call Ntest_setmouse(row, 21 + 9) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 6, 0, 9], getcurpos()) + call Ntest_setmouse(row, 21 + 12) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 9, 0, 12], getcurpos()) + call Ntest_setmouse(row, 21 + 13) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 10, 0, 13], getcurpos()) + call Ntest_setmouse(row, 21 + 15) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 10, 2, 15], getcurpos()) + call Ntest_setmouse(row, 21 + 20) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 10, 7, 20], getcurpos()) + + setlocal nowrap + call setline(2, repeat('a', 19)) + normal! j14zl + redraw + call Ntest_setmouse(row, 21 + 1) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 10, 2, 15], getcurpos()) + call Ntest_setmouse(row, 21 + 11) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 10, 12, 25], getcurpos()) + call Ntest_setmouse(row + 1, 21 + 1) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 2, 15, 0, 15], getcurpos()) + call Ntest_setmouse(row + 1, 21 + 11) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 2, 20, 5, 25], getcurpos()) + + setlocal number numberwidth=2 + redraw + call Ntest_setmouse(row, 21 + 3) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 10, 2, 15], getcurpos()) + call Ntest_setmouse(row, 21 + 13) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 10, 12, 25], getcurpos()) + call Ntest_setmouse(row + 1, 21 + 3) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 2, 15, 0, 15], getcurpos()) + call Ntest_setmouse(row + 1, 21 + 13) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 2, 20, 5, 25], getcurpos()) + setlocal nonumber + + if has('signs') + sign define Sign1 text=口 + sign place 1 name=Sign1 line=1 + sign place 2 name=Sign1 line=2 + redraw + call Ntest_setmouse(row, 21 + 3) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 10, 2, 15], getcurpos()) + call Ntest_setmouse(row, 21 + 13) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 10, 12, 25], getcurpos()) + call Ntest_setmouse(row + 1, 21 + 3) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 2, 15, 0, 15], getcurpos()) + call Ntest_setmouse(row + 1, 21 + 13) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 2, 20, 5, 25], getcurpos()) + sign unplace 1 + sign unplace 2 + sign undefine Sign1 + endif + + wincmd h + 4wincmd > + normal! gg24I. + redraw + call Ntest_setmouse(row + 1, 12) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 24 + 9, 0, 24 + 12], getcurpos()) + call Ntest_setmouse(row + 1, 13) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 24 + 10, 0, 24 + 13], getcurpos()) + call Ntest_setmouse(row + 1, 15) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 24 + 10, 2, 24 + 15], getcurpos()) + call Ntest_setmouse(row + 1, 20) + call feedkeys("\<LeftMouse>", "xt") + call assert_equal([0, 1, 24 + 10, 7, 24 + 20], getcurpos()) + + bwipe! + let &mouse = save_mouse + set virtualedit& +endfunc + +" this was replacing the NUL at the end of the line +func Test_virtualedit_replace_after_tab() + new + s/\v/ 0 + set ve=all + let @" = '' + sil! norm vPvr0 + + call assert_equal("\t0", getline(1)) + set ve& + bwipe! +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_visual.vim b/test/old/testdir/test_visual.vim new file mode 100644 index 0000000000..5d70492451 --- /dev/null +++ b/test/old/testdir/test_visual.vim @@ -0,0 +1,1594 @@ +" Tests for various Visual modes. + +source shared.vim +source check.vim +source screendump.vim + +func Test_block_shift_multibyte() + " Uses double-wide character. + split + call setline(1, ['xヹxxx', 'ヹxxx']) + exe "normal 1G0l\<C-V>jl>" + call assert_equal('x ヹxxx', getline(1)) + call assert_equal(' ヹxxx', getline(2)) + q! +endfunc + +func Test_block_shift_overflow() + " This used to cause a multiplication overflow followed by a crash. + new + normal ii + exe "normal \<C-V>876543210>" + q! +endfunc + +func Test_dotregister_paste() + new + exe "norm! ihello world\<esc>" + norm! 0ve".p + call assert_equal('hello world world', getline(1)) + q! +endfunc + +func Test_Visual_ctrl_o() + new + call setline(1, ['one', 'two', 'three']) + call cursor(1,2) + set noshowmode + set tw=0 + call feedkeys("\<c-v>jjlIa\<c-\>\<c-o>:set tw=88\<cr>\<esc>", 'tx') + call assert_equal(['oane', 'tawo', 'tahree'], getline(1, 3)) + call assert_equal(88, &tw) + set tw& + bw! +endfu + +func Test_Visual_vapo() + new + normal oxx + normal vapo + bwipe! +endfunc + +func Test_Visual_inner_quote() + new + normal oxX + normal vki' + bwipe! +endfunc + +" Test for Visual mode not being reset causing E315 error. +func TriggerTheProblem() + " At this point there is no visual selection because :call reset it. + " Let's restore the selection: + normal gv + '<,'>del _ + try + exe "normal \<Esc>" + catch /^Vim\%((\a\+)\)\=:E315/ + echom 'Snap! E315 error!' + let g:msg = 'Snap! E315 error!' + endtry +endfunc + +func Test_visual_mode_reset() + enew + let g:msg = "Everything's fine." + enew + setl buftype=nofile + call append(line('$'), 'Delete this line.') + + " NOTE: this has to be done by a call to a function because executing :del + " the ex-way will require the colon operator which resets the visual mode + " thus preventing the problem: + exe "normal! GV:call TriggerTheProblem()\<CR>" + call assert_equal("Everything's fine.", g:msg) +endfunc + +" Test for visual block shift and tab characters. +func Test_block_shift_tab() + new + call append(0, repeat(['one two three'], 5)) + call cursor(1,1) + exe "normal i\<C-G>u" + exe "normal fe\<C-V>4jR\<Esc>ugvr1" + call assert_equal('on1 two three', getline(1)) + call assert_equal('on1 two three', getline(2)) + call assert_equal('on1 two three', getline(5)) + + %d _ + call append(0, repeat(['abcdefghijklmnopqrstuvwxyz'], 5)) + call cursor(1,1) + exe "normal \<C-V>4jI \<Esc>j<<11|D" + exe "normal j7|a\<Tab>\<Tab>" + exe "normal j7|a\<Tab>\<Tab> " + exe "normal j7|a\<Tab> \<Tab>\<Esc>4k13|\<C-V>4j<" + call assert_equal(' abcdefghijklmnopqrstuvwxyz', getline(1)) + call assert_equal('abcdefghij', getline(2)) + call assert_equal(" abc\<Tab> defghijklmnopqrstuvwxyz", getline(3)) + call assert_equal(" abc\<Tab> defghijklmnopqrstuvwxyz", getline(4)) + call assert_equal(" abc\<Tab> defghijklmnopqrstuvwxyz", getline(5)) + + %s/\s\+//g + call cursor(1,1) + exe "normal \<C-V>4jI \<Esc>j<<" + exe "normal j7|a\<Tab>\<Tab>" + exe "normal j7|a\<Tab>\<Tab>\<Tab>\<Tab>\<Tab>" + exe "normal j7|a\<Tab> \<Tab>\<Tab>\<Esc>4k13|\<C-V>4j3<" + call assert_equal(' abcdefghijklmnopqrstuvwxyz', getline(1)) + call assert_equal('abcdefghij', getline(2)) + call assert_equal(" abc\<Tab> defghijklmnopqrstuvwxyz", getline(3)) + call assert_equal(" abc\<Tab>\<Tab>defghijklmnopqrstuvwxyz", getline(4)) + call assert_equal(" abc\<Tab> defghijklmnopqrstuvwxyz", getline(5)) + + " Test for block shift with space characters at the beginning and with + " 'noexpandtab' and 'expandtab' + %d _ + call setline(1, [" 1", " 2", " 3"]) + setlocal shiftwidth=2 noexpandtab + exe "normal gg\<C-V>3j>" + call assert_equal(["\t1", "\t2", "\t3"], getline(1, '$')) + %d _ + call setline(1, [" 1", " 2", " 3"]) + setlocal shiftwidth=2 expandtab + exe "normal gg\<C-V>3j>" + call assert_equal([" 1", " 2", " 3"], getline(1, '$')) + setlocal shiftwidth& + + bw! +endfunc + +" Tests Blockwise Visual when there are TABs before the text. +func Test_blockwise_visual() + new + call append(0, ['123456', + \ '234567', + \ '345678', + \ '', + \ 'test text test tex start here', + \ "\t\tsome text", + \ "\t\ttest text", + \ 'test text']) + call cursor(1,1) + exe "normal /start here$\<CR>" + exe 'normal "by$' . "\<C-V>jjlld" + exe "normal /456$\<CR>" + exe "normal \<C-V>jj" . '"bP' + call assert_equal(['123start here56', + \ '234start here67', + \ '345start here78', + \ '', + \ 'test text test tex rt here', + \ "\t\tsomext", + \ "\t\ttesext"], getline(1, 7)) + + bw! +endfunc + +" Test swapping corners in blockwise visual mode with o and O +func Test_blockwise_visual_o_O() + new + + exe "norm! 10i.\<Esc>Y4P3lj\<C-V>4l2jr " + exe "norm! gvO\<Esc>ra" + exe "norm! gvO\<Esc>rb" + exe "norm! gvo\<C-c>rc" + exe "norm! gvO\<C-c>rd" + set selection=exclusive + exe "norm! gvOo\<C-c>re" + call assert_equal('...a be.', getline(4)) + exe "norm! gvOO\<C-c>rf" + set selection& + + call assert_equal(['..........', + \ '...c d..', + \ '... ..', + \ '...a bf.', + \ '..........'], getline(1, '$')) + + bw! +endfun + +" Test Virtual replace mode. +func Test_virtual_replace() + if exists('&t_kD') + let save_t_kD = &t_kD + endif + if exists('&t_kb') + let save_t_kb = &t_kb + endif + exe "set t_kD=\<C-V>x7f t_kb=\<C-V>x08" + enew! + exe "normal a\nabcdefghi\njk\tlmn\n opq rst\n\<C-D>uvwxyz" + call cursor(1,1) + set ai bs=2 + exe "normal gR0\<C-D> 1\nA\nBCDEFGHIJ\n\tKL\nMNO\nPQR" + call assert_equal([' 1', + \ ' A', + \ ' BCDEFGHIJ', + \ ' KL', + \ ' MNO', + \ ' PQR', + \ ], getline(1, 6)) + normal G + mark a + exe "normal o0\<C-D>\nabcdefghi\njk\tlmn\n opq\trst\n\<C-D>uvwxyz\n" + exe "normal 'ajgR0\<C-D> 1\nA\nBCDEFGHIJ\n\tKL\nMNO\nPQR" . repeat("\<BS>", 29) + call assert_equal([' 1', + \ 'abcdefghi', + \ 'jk lmn', + \ ' opq rst', + \ 'uvwxyz'], getline(7, 11)) + normal G + exe "normal iab\tcdefghi\tjkl" + exe "normal 0gRAB......CDEFGHI.J\<Esc>o" + exe "normal iabcdefghijklmnopqrst\<Esc>0gRAB\tIJKLMNO\tQR" + call assert_equal(['AB......CDEFGHI.Jkl', + \ 'AB IJKLMNO QRst'], getline(12, 13)) + + " Test inserting Tab with 'noexpandtab' and 'softabstop' set to 4 + %d + call setline(1, 'aaaaaaaaaaaaa') + set softtabstop=4 + exe "normal gggR\<Tab>\<Tab>x" + call assert_equal("\txaaaa", getline(1)) + set softtabstop& + + enew! + set noai bs&vim + if exists('save_t_kD') + let &t_kD = save_t_kD + endif + if exists('save_t_kb') + let &t_kb = save_t_kb + endif +endfunc + +" Test Virtual replace mode. +func Test_virtual_replace2() + enew! + set bs=2 + exe "normal a\nabcdefghi\njk\tlmn\n opq rst\n\<C-D>uvwxyz" + call cursor(1,1) + " Test 1: Test that del deletes the newline + exe "normal gR0\<del> 1\nA\nBCDEFGHIJ\n\tKL\nMNO\nPQR" + call assert_equal(['0 1', + \ 'A', + \ 'BCDEFGHIJ', + \ ' KL', + \ 'MNO', + \ 'PQR', + \ ], getline(1, 6)) + " Test 2: + " a newline is not deleted, if no newline has been added in virtual replace mode + %d_ + call setline(1, ['abcd', 'efgh', 'ijkl']) + call cursor(2,1) + exe "norm! gR1234\<cr>5\<bs>\<bs>\<bs>" + call assert_equal(['abcd', + \ '123h', + \ 'ijkl'], getline(1, '$')) + " Test 3: + " a newline is deleted, if a newline has been inserted before in virtual replace mode + %d_ + call setline(1, ['abcd', 'efgh', 'ijkl']) + call cursor(2,1) + exe "norm! gR1234\<cr>\<cr>56\<bs>\<bs>\<bs>" + call assert_equal(['abcd', + \ '1234', + \ 'ijkl'], getline(1, '$')) + " Test 4: + " delete add a newline, delete it, add it again and check undo + %d_ + call setline(1, ['abcd', 'efgh', 'ijkl']) + call cursor(2,1) + " break undo sequence explicitly + let &ul = &ul + exe "norm! gR1234\<cr>\<bs>\<del>56\<cr>" + let &ul = &ul + call assert_equal(['abcd', + \ '123456', + \ ''], getline(1, '$')) + norm! u + call assert_equal(['abcd', + \ 'efgh', + \ 'ijkl'], getline(1, '$')) + + " Test for truncating spaces in a newly added line using 'autoindent' if + " characters are not added to that line. + %d_ + call setline(1, [' app', ' bee', ' cat']) + setlocal autoindent + exe "normal gg$gRt\n\nr" + call assert_equal([' apt', '', ' rat'], getline(1, '$')) + + " clean up + %d_ + set bs&vim +endfunc + +func Test_Visual_word_textobject() + new + call setline(1, ['First sentence. Second sentence.']) + + " When start and end of visual area are identical, 'aw' or 'iw' select + " the whole word. + norm! 1go2fcvawy + call assert_equal('Second ', @") + norm! 1go2fcviwy + call assert_equal('Second', @") + + " When start and end of visual area are not identical, 'aw' or 'iw' + " extend the word in direction of the end of the visual area. + norm! 1go2fcvlawy + call assert_equal('cond ', @") + norm! gv2awy + call assert_equal('cond sentence.', @") + + norm! 1go2fcvliwy + call assert_equal('cond', @") + norm! gv2iwy + call assert_equal('cond sentence', @") + + " Extend visual area in opposite direction. + norm! 1go2fcvhawy + call assert_equal(' Sec', @") + norm! gv2awy + call assert_equal(' sentence. Sec', @") + + norm! 1go2fcvhiwy + call assert_equal('Sec', @") + norm! gv2iwy + call assert_equal('. Sec', @") + + bwipe! +endfunc + +func Test_Visual_sentence_textobject() + new + call setline(1, ['First sentence. Second sentence. Third', 'sentence. Fourth sentence']) + + " When start and end of visual area are identical, 'as' or 'is' select + " the whole sentence. + norm! 1gofdvasy + call assert_equal('Second sentence. ', @") + norm! 1gofdvisy + call assert_equal('Second sentence.', @") + + " When start and end of visual area are not identical, 'as' or 'is' + " extend the sentence in direction of the end of the visual area. + norm! 1gofdvlasy + call assert_equal('d sentence. ', @") + norm! gvasy + call assert_equal("d sentence. Third\nsentence. ", @") + + norm! 1gofdvlisy + call assert_equal('d sentence.', @") + norm! gvisy + call assert_equal('d sentence. ', @") + norm! gvisy + call assert_equal("d sentence. Third\nsentence.", @") + + " Extend visual area in opposite direction. + norm! 1gofdvhasy + call assert_equal(' Second', @") + norm! gvasy + call assert_equal("First sentence. Second", @") + + norm! 1gofdvhisy + call assert_equal('Second', @") + norm! gvisy + call assert_equal(' Second', @") + norm! gvisy + call assert_equal('First sentence. Second', @") + + bwipe! +endfunc + +func Test_Visual_paragraph_textobject() + new + let lines =<< trim [END] + First line. + + Second line. + Third line. + Fourth line. + Fifth line. + + Sixth line. + [END] + call setline(1, lines) + + " When start and end of visual area are identical, 'ap' or 'ip' select + " the whole paragraph. + norm! 4ggvapy + call assert_equal("Second line.\nThird line.\nFourth line.\nFifth line.\n\n", @") + norm! 4ggvipy + call assert_equal("Second line.\nThird line.\nFourth line.\nFifth line.\n", @") + + " When start and end of visual area are not identical, 'ap' or 'ip' + " extend the sentence in direction of the end of the visual area. + " FIXME: actually, it is not sufficient to have different start and + " end of visual selection, the start line and end line have to differ, + " which is not consistent with the documentation. + norm! 4ggVjapy + call assert_equal("Third line.\nFourth line.\nFifth line.\n\n", @") + norm! gvapy + call assert_equal("Third line.\nFourth line.\nFifth line.\n\nSixth line.\n", @") + norm! 4ggVjipy + call assert_equal("Third line.\nFourth line.\nFifth line.\n", @") + norm! gvipy + call assert_equal("Third line.\nFourth line.\nFifth line.\n\n", @") + norm! gvipy + call assert_equal("Third line.\nFourth line.\nFifth line.\n\nSixth line.\n", @") + + " Extend visual area in opposite direction. + norm! 5ggVkapy + call assert_equal("\nSecond line.\nThird line.\nFourth line.\n", @") + norm! gvapy + call assert_equal("First line.\n\nSecond line.\nThird line.\nFourth line.\n", @") + norm! 5ggVkipy + call assert_equal("Second line.\nThird line.\nFourth line.\n", @") + norma gvipy + call assert_equal("\nSecond line.\nThird line.\nFourth line.\n", @") + norm! gvipy + call assert_equal("First line.\n\nSecond line.\nThird line.\nFourth line.\n", @") + + bwipe! +endfunc + +func Test_curswant_not_changed() + new + call setline(1, ['one', 'two']) + au InsertLeave * call getcurpos() + call feedkeys("gg0\<C-V>jI123 \<Esc>j", 'xt') + call assert_equal([0, 2, 1, 0, 1], getcurpos()) + + bwipe! + au! InsertLeave +endfunc + +" Tests for "vaBiB", end could be wrong. +func Test_Visual_Block() + new + a +- Bug in "vPPPP" on this text: + { + cmd; + { + cmd;\t/* <-- Start cursor here */ + { + } + } + } +. + normal gg + call search('Start cursor here') + normal vaBiBD + call assert_equal(['- Bug in "vPPPP" on this text:', + \ "\t{", + \ "\t}"], getline(1, '$')) + + close! +endfunc + +" Test for 'p'ut in visual block mode +func Test_visual_block_put() + new + call append(0, ['One', 'Two', 'Three']) + normal gg + yank + call feedkeys("jl\<C-V>ljp", 'xt') + call assert_equal(['One', 'T', 'Tee', 'One', ''], getline(1, '$')) + bw! +endfunc + +func Test_visual_block_put_invalid() + enew! + " behave mswin + set selection=exclusive + norm yy + norm v)Ps/^/ + " this was causing the column to become negative + silent norm ggv)P + + bwipe! + " behave xterm + set selection& +endfunc + +" Visual modes (v V CTRL-V) followed by an operator; count; repeating +func Test_visual_mode_op() + new + call append(0, '') + + call setline(1, 'apple banana cherry') + call cursor(1, 1) + normal lvld.l3vd. + call assert_equal('a y', getline(1)) + + call setline(1, ['line 1 line 1', 'line 2 line 2', 'line 3 line 3', + \ 'line 4 line 4', 'line 5 line 5', 'line 6 line 6']) + call cursor(1, 1) + exe "normal Vcnewline\<Esc>j.j2Vd." + call assert_equal(['newline', 'newline'], getline(1, '$')) + + call deletebufline('', 1, '$') + call setline(1, ['xxxxxxxxxxxxx', 'xxxxxxxxxxxxx', 'xxxxxxxxxxxxx', + \ 'xxxxxxxxxxxxx']) + exe "normal \<C-V>jlc \<Esc>l.l2\<C-V>c----\<Esc>l." + call assert_equal([' --------x', + \ ' --------x', + \ 'xxxx--------x', + \ 'xxxx--------x'], getline(1, '$')) + + bwipe! +endfunc + +" Visual mode maps (movement and text object) +" Visual mode maps; count; repeating +" - Simple +" - With an Ex command (custom text object) +func Test_visual_mode_maps() + new + call append(0, '') + + func SelectInCaps() + let [line1, col1] = searchpos('\u', 'bcnW') + let [line2, col2] = searchpos('.\u', 'nW') + call setpos("'<", [0, line1, col1, 0]) + call setpos("'>", [0, line2, col2, 0]) + normal! gv + endfunction + + vnoremap W /\u/s-1<CR> + vnoremap iW :<C-U>call SelectInCaps()<CR> + + call setline(1, 'KiwiRaspberryDateWatermelonPeach') + call cursor(1, 1) + exe "normal vWcNo\<Esc>l.fD2vd." + call assert_equal('NoNoberryach', getline(1)) + + call setline(1, 'JambuRambutanBananaTangerineMango') + call cursor(1, 1) + exe "normal llviWc-\<Esc>l.l2vdl." + call assert_equal('--ago', getline(1)) + + vunmap W + vunmap iW + bwipe! + delfunc SelectInCaps +endfunc + +" Operator-pending mode maps (movement and text object) +" - Simple +" - With Ex command moving the cursor +" - With Ex command and Visual selection (custom text object) +func Test_visual_oper_pending_mode_maps() + new + call append(0, '') + + func MoveToCap() + call search('\u', 'W') + endfunction + + func SelectInCaps() + let [line1, col1] = searchpos('\u', 'bcnW') + let [line2, col2] = searchpos('.\u', 'nW') + call setpos("'<", [0, line1, col1, 0]) + call setpos("'>", [0, line2, col2, 0]) + normal! gv + endfunction + + onoremap W /\u/<CR> + onoremap <Leader>W :<C-U>call MoveToCap()<CR> + onoremap iW :<C-U>call SelectInCaps()<CR> + + call setline(1, 'PineappleQuinceLoganberryOrangeGrapefruitKiwiZ') + call cursor(1, 1) + exe "normal cW-\<Esc>l.l2.l." + call assert_equal('----Z', getline(1)) + + call setline(1, 'JuniperDurianZ') + call cursor(1, 1) + exe "normal g?\WfD." + call assert_equal('WhavcreQhevnaZ', getline(1)) + + call setline(1, 'LemonNectarineZ') + call cursor(1, 1) + exe "normal yiWPlciWNew\<Esc>fr." + call assert_equal('LemonNewNewZ', getline(1)) + + ounmap W + ounmap <Leader>W + ounmap iW + bwipe! + delfunc MoveToCap + delfunc SelectInCaps +endfunc + +" Patch 7.3.879: Properly abort Operator-pending mode for "dv:<Esc>" etc. +func Test_op_pend_mode_abort() + new + call append(0, '') + + call setline(1, ['zzzz', 'zzzz']) + call cursor(1, 1) + + exe "normal dV:\<CR>dv:\<CR>" + call assert_equal(['zzz'], getline(1, 2)) + set nomodifiable + call assert_fails('exe "normal d:\<CR>"', 'E21:') + set modifiable + call feedkeys("dv:\<Esc>dV:\<Esc>", 'xt') + call assert_equal(['zzz'], getline(1, 2)) + set nomodifiable + let v:errmsg = '' + call feedkeys("d:\<Esc>", 'xt') + call assert_true(v:errmsg !~# '^E21:') + set modifiable + + bwipe! +endfunc + +func Test_characterwise_visual_mode() + new + + " characterwise visual mode: replace last line + $put ='a' + let @" = 'x' + normal v$p + call assert_equal('x', getline('$')) + + " characterwise visual mode: delete middle line + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + normal G + normal kkv$d + call assert_equal(['', 'b', 'c'], getline(1, '$')) + + " characterwise visual mode: delete middle two lines + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + normal Gkkvj$d + call assert_equal(['', 'c'], getline(1, '$')) + + " characterwise visual mode: delete last line + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + normal Gv$d + call assert_equal(['', 'a', 'b', ''], getline(1, '$')) + + " characterwise visual mode: delete last two lines + call deletebufline('', 1, '$') + call append('$', ['a', 'b', 'c']) + normal Gkvj$d + call assert_equal(['', 'a', ''], getline(1, '$')) + + " characterwise visual mode: use a count with the visual mode from the last + " line in the buffer + %d _ + call setline(1, ['one', 'two', 'three', 'four']) + norm! vj$y + norm! G1vy + call assert_equal('four', @") + + " characterwise visual mode: replace a single character line and the eol + %d _ + call setline(1, "a") + normal v$rx + call assert_equal(['x'], getline(1, '$')) + + " replace a character with composing characters + call setline(1, "xã̳x") + normal gg0lvrb + call assert_equal("xbx", getline(1)) + + bwipe! +endfunc + +func Test_visual_mode_put() + new + + " v_p: replace last character with line register at middle line + call append('$', ['aaa', 'bbb', 'ccc']) + normal G + -2yank + normal k$vp + call assert_equal(['', 'aaa', 'bb', 'aaa', '', 'ccc'], getline(1, '$')) + + " v_p: replace last character with line register at middle line selecting + " newline + call deletebufline('', 1, '$') + call append('$', ['aaa', 'bbb', 'ccc']) + normal G + -2yank + normal k$v$p + call assert_equal(['', 'aaa', 'bb', 'aaa', 'ccc'], getline(1, '$')) + + " v_p: replace last character with line register at last line + call deletebufline('', 1, '$') + call append('$', ['aaa', 'bbb', 'ccc']) + normal G + -2yank + normal $vp + call assert_equal(['', 'aaa', 'bbb', 'cc', 'aaa', ''], getline(1, '$')) + + " v_p: replace last character with line register at last line selecting + " newline + call deletebufline('', 1, '$') + call append('$', ['aaa', 'bbb', 'ccc']) + normal G + -2yank + normal $v$p + call assert_equal(['', 'aaa', 'bbb', 'cc', 'aaa', ''], getline(1, '$')) + + bwipe! +endfunc + +func Test_gv_with_exclusive_selection() + new + + " gv with exclusive selection after an operation + call append('$', ['zzz ', 'äà ']) + set selection=exclusive + normal Gkv3lyjv3lpgvcxxx + call assert_equal(['', 'zzz ', 'xxx '], getline(1, '$')) + + " gv with exclusive selection without an operation + call deletebufline('', 1, '$') + call append('$', 'zzz ') + set selection=exclusive + exe "normal G0v3l\<Esc>gvcxxx" + call assert_equal(['', 'xxx '], getline(1, '$')) + + set selection&vim + bwipe! +endfunc + +" Tests for the visual block mode commands +func Test_visual_block_mode() + new + call append(0, '') + call setline(1, repeat(['abcdefghijklm'], 5)) + call cursor(1, 1) + + " Test shift-right of a block + exe "normal jllll\<C-V>jj>wll\<C-V>jlll>" + " Test shift-left of a block + exe "normal G$hhhh\<C-V>kk<" + " Test block-insert + exe "normal Gkl\<C-V>kkkIxyz" + " Test block-replace + exe "normal Gllll\<C-V>kkklllrq" + " Test block-change + exe "normal G$khhh\<C-V>hhkkcmno" + call assert_equal(['axyzbcdefghijklm', + \ 'axyzqqqq mno ghijklm', + \ 'axyzqqqqef mno ghijklm', + \ 'axyzqqqqefgmnoklm', + \ 'abcdqqqqijklm'], getline(1, 5)) + + " Test 'C' to change till the end of the line + call cursor(3, 4) + exe "normal! \<C-V>j3lCooo" + call assert_equal(['axyooo', 'axyooo'], getline(3, 4)) + + " Test 'D' to delete till the end of the line + call cursor(3, 3) + exe "normal! \<C-V>j2lD" + call assert_equal(['ax', 'ax'], getline(3, 4)) + + " Test block insert with a short line that ends before the block + %d _ + call setline(1, [" one", "a", " two"]) + exe "normal gg\<C-V>2jIx" + call assert_equal([" xone", "a", " xtwo"], getline(1, '$')) + + " Test block append at EOL with '$' and without '$' + %d _ + call setline(1, ["one", "a", "two"]) + exe "normal gg$\<C-V>2jAx" + call assert_equal(["onex", "ax", "twox"], getline(1, '$')) + %d _ + call setline(1, ["one", "a", "two"]) + exe "normal gg3l\<C-V>2jAx" + call assert_equal(["onex", "a x", "twox"], getline(1, '$')) + + " Test block replace with an empty line in the middle and use $ to jump to + " the end of the line. + %d _ + call setline(1, ['one', '', 'two']) + exe "normal gg$\<C-V>2jrx" + call assert_equal(["onx", "", "twx"], getline(1, '$')) + + " Test block replace with an empty line in the middle and move cursor to the + " end of the line + %d _ + call setline(1, ['one', '', 'two']) + exe "normal gg2l\<C-V>2jrx" + call assert_equal(["onx", "", "twx"], getline(1, '$')) + + " Replace odd number of characters with a multibyte character + %d _ + call setline(1, ['abcd', 'efgh']) + exe "normal ggl\<C-V>2ljr\u1100" + call assert_equal(["a\u1100 ", "e\u1100 "], getline(1, '$')) + + " During visual block append, if the cursor moved outside of the selected + " range, then the edit should not be applied to the block. + %d _ + call setline(1, ['aaa', 'bbb', 'ccc']) + exe "normal 2G\<C-V>jAx\<Up>" + call assert_equal(['aaa', 'bxbb', 'ccc'], getline(1, '$')) + + " During visual block append, if the cursor is moved before the start of the + " block, then the new text should be appended there. + %d _ + call setline(1, ['aaa', 'bbb', 'ccc']) + exe "normal $\<C-V>2jA\<Left>x" + call assert_equal(['aaxa', 'bbxb', 'ccxc'], getline(1, '$')) + " Repeat the previous test but use 'l' to move the cursor instead of '$' + call setline(1, ['aaa', 'bbb', 'ccc']) + exe "normal! gg2l\<C-V>2jA\<Left>x" + call assert_equal(['aaxa', 'bbxb', 'ccxc'], getline(1, '$')) + + " Change a characterwise motion to a blockwise motion using CTRL-V + %d _ + call setline(1, ['123', '456', '789']) + exe "normal ld\<C-V>j" + call assert_equal(['13', '46', '789'], getline(1, '$')) + + " Test from ':help v_b_I_example' + %d _ + setlocal tabstop=8 shiftwidth=4 + let lines =<< trim END + abcdefghijklmnopqrstuvwxyz + abc defghijklmnopqrstuvwxyz + abcdef ghi jklmnopqrstuvwxyz + abcdefghijklmnopqrstuvwxyz + END + call setline(1, lines) + exe "normal ggfo\<C-V>3jISTRING" + let expected =<< trim END + abcdefghijklmnSTRINGopqrstuvwxyz + abc STRING defghijklmnopqrstuvwxyz + abcdef ghi STRING jklmnopqrstuvwxyz + abcdefghijklmnSTRINGopqrstuvwxyz + END + call assert_equal(expected, getline(1, '$')) + + " Test from ':help v_b_A_example' + %d _ + let lines =<< trim END + abcdefghijklmnopqrstuvwxyz + abc defghijklmnopqrstuvwxyz + abcdef ghi jklmnopqrstuvwxyz + abcdefghijklmnopqrstuvwxyz + END + call setline(1, lines) + exe "normal ggfo\<C-V>3j$ASTRING" + let expected =<< trim END + abcdefghijklmnopqrstuvwxyzSTRING + abc defghijklmnopqrstuvwxyzSTRING + abcdef ghi jklmnopqrstuvwxyzSTRING + abcdefghijklmnopqrstuvwxyzSTRING + END + call assert_equal(expected, getline(1, '$')) + + " Test from ':help v_b_<_example' + %d _ + let lines =<< trim END + abcdefghijklmnopqrstuvwxyz + abc defghijklmnopqrstuvwxyz + abcdef ghi jklmnopqrstuvwxyz + abcdefghijklmnopqrstuvwxyz + END + call setline(1, lines) + exe "normal ggfo\<C-V>3j3l<.." + let expected =<< trim END + abcdefghijklmnopqrstuvwxyz + abc defghijklmnopqrstuvwxyz + abcdef ghi jklmnopqrstuvwxyz + abcdefghijklmnopqrstuvwxyz + END + call assert_equal(expected, getline(1, '$')) + + " Test from ':help v_b_>_example' + %d _ + let lines =<< trim END + abcdefghijklmnopqrstuvwxyz + abc defghijklmnopqrstuvwxyz + abcdef ghi jklmnopqrstuvwxyz + abcdefghijklmnopqrstuvwxyz + END + call setline(1, lines) + exe "normal ggfo\<C-V>3j>.." + let expected =<< trim END + abcdefghijklmn opqrstuvwxyz + abc defghijklmnopqrstuvwxyz + abcdef ghi jklmnopqrstuvwxyz + abcdefghijklmn opqrstuvwxyz + END + call assert_equal(expected, getline(1, '$')) + + " Test from ':help v_b_r_example' + %d _ + let lines =<< trim END + abcdefghijklmnopqrstuvwxyz + abc defghijklmnopqrstuvwxyz + abcdef ghi jklmnopqrstuvwxyz + abcdefghijklmnopqrstuvwxyz + END + call setline(1, lines) + exe "normal ggfo\<C-V>5l3jrX" + let expected =<< trim END + abcdefghijklmnXXXXXXuvwxyz + abc XXXXXXhijklmnopqrstuvwxyz + abcdef ghi XXXXXX jklmnopqrstuvwxyz + abcdefghijklmnXXXXXXuvwxyz + END + call assert_equal(expected, getline(1, '$')) + + bwipe! + set tabstop& shiftwidth& +endfunc + +func Test_visual_force_motion_feedkeys() + onoremap <expr> i- execute('let g:mode = mode(1)')->slice(0, 0) + call feedkeys('dvi-', 'x') + call assert_equal('nov', g:mode) + call feedkeys('di-', 'x') + call assert_equal('no', g:mode) + ounmap i- +endfunc + +" Test block-insert using cursor keys for movement +func Test_visual_block_insert_cursor_keys() + new + call append(0, ['aaaaaa', 'bbbbbb', 'cccccc', 'dddddd']) + call cursor(1, 1) + + exe "norm! l\<C-V>jjjlllI\<Right>\<Right> \<Esc>" + call assert_equal(['aaa aaa', 'bbb bbb', 'ccc ccc', 'ddd ddd'], + \ getline(1, 4)) + + call deletebufline('', 1, '$') + call setline(1, ['xaaa', 'bbbb', 'cccc', 'dddd']) + call cursor(1, 1) + exe "norm! \<C-V>jjjI<>\<Left>p\<Esc>" + call assert_equal(['<p>xaaa', '<p>bbbb', '<p>cccc', '<p>dddd'], + \ getline(1, 4)) + bwipe! +endfunc + +func Test_visual_block_create() + new + call append(0, '') + " Test for Visual block was created with the last <C-v>$ + call setline(1, ['A23', '4567']) + call cursor(1, 1) + exe "norm! l\<C-V>j$Aab\<Esc>" + call assert_equal(['A23ab', '4567ab'], getline(1, 2)) + + " Test for Visual block was created with the middle <C-v>$ (1) + call deletebufline('', 1, '$') + call setline(1, ['B23', '4567']) + call cursor(1, 1) + exe "norm! l\<C-V>j$hAab\<Esc>" + call assert_equal(['B23 ab', '4567ab'], getline(1, 2)) + + " Test for Visual block was created with the middle <C-v>$ (2) + call deletebufline('', 1, '$') + call setline(1, ['C23', '4567']) + call cursor(1, 1) + exe "norm! l\<C-V>j$hhAab\<Esc>" + call assert_equal(['C23ab', '456ab7'], getline(1, 2)) + bwipe! +endfunc + +" Test for Visual block insert when virtualedit=all +func Test_virtualedit_visual_block() + set ve=all + new + call append(0, ["\t\tline1", "\t\tline2", "\t\tline3"]) + call cursor(1, 1) + exe "norm! 07l\<C-V>jjIx\<Esc>" + call assert_equal([" x \tline1", + \ " x \tline2", + \ " x \tline3"], getline(1, 3)) + + " Test for Visual block append when virtualedit=all + exe "norm! 012l\<C-v>jjAx\<Esc>" + call assert_equal([' x x line1', + \ ' x x line2', + \ ' x x line3'], getline(1, 3)) + set ve= + bwipe! +endfunc + +" Test for changing case +func Test_visual_change_case() + new + " gUe must uppercase a whole word, also when ß changes to SS + exe "normal Gothe youtußeuu end\<Esc>Ypk0wgUe\r" + " gUfx must uppercase until x, inclusive. + exe "normal O- youßtußexu -\<Esc>0fogUfx\r" + " VU must uppercase a whole line + exe "normal YpkVU\r" + " same, when it's the last line in the buffer + exe "normal YPGi111\<Esc>VUddP\r" + " Uppercase two lines + exe "normal Oblah di\rdoh dut\<Esc>VkUj\r" + " Uppercase part of two lines + exe "normal ddppi333\<Esc>k0i222\<Esc>fyllvjfuUk" + call assert_equal(['the YOUTUSSEUU end', '- yOUSSTUSSEXu -', + \ 'THE YOUTUSSEUU END', '111THE YOUTUSSEUU END', 'BLAH DI', 'DOH DUT', + \ '222the yoUTUSSEUU END', '333THE YOUTUßeuu end'], getline(2, '$')) + bwipe! +endfunc + +" Test for Visual replace using Enter or NL +func Test_visual_replace_crnl() + new + exe "normal G3o123456789\e2k05l\<C-V>2jr\r" + exe "normal G3o98765\e2k02l\<C-V>2jr\<C-V>\r\n" + exe "normal G3o123456789\e2k05l\<C-V>2jr\n" + exe "normal G3o98765\e2k02l\<C-V>2jr\<C-V>\n" + call assert_equal(['12345', '789', '12345', '789', '12345', '789', "98\r65", + \ "98\r65", "98\r65", '12345', '789', '12345', '789', '12345', '789', + \ "98\n65", "98\n65", "98\n65"], getline(2, '$')) + bwipe! +endfunc + +func Test_ve_block_curpos() + new + " Test cursor position. When ve=block and Visual block mode and $gj + call append(0, ['12345', '789']) + call cursor(1, 3) + set virtualedit=block + exe "norm! \<C-V>$gj\<Esc>" + call assert_equal([0, 2, 4, 0], getpos("'>")) + set virtualedit= + bwipe! +endfunc + +" Test for block_insert when replacing spaces in front of the a with tabs +func Test_block_insert_replace_tabs() + new + set ts=8 sts=4 sw=4 + call append(0, ["#define BO_ALL\t 0x0001", + \ "#define BO_BS\t 0x0002", + \ "#define BO_CRSR\t 0x0004"]) + call cursor(1, 1) + exe "norm! f0\<C-V>2jI\<tab>\<esc>" + call assert_equal([ + \ "#define BO_ALL\t\t0x0001", + \ "#define BO_BS\t \t0x0002", + \ "#define BO_CRSR\t \t0x0004", ''], getline(1, '$')) + set ts& sts& sw& + bwipe! +endfunc + +" Test for * register in : +func Test_star_register() + call assert_fails('*bfirst', 'E16:') + new + call setline(1, ['foo', 'bar', 'baz', 'qux']) + exe "normal jVj\<ESC>" + *yank r + call assert_equal("bar\nbaz\n", @r) + + delmarks < > + call assert_fails('*yank', 'E20:') + close! +endfunc + +" Test for changing text in visual mode with 'exclusive' selection +func Test_exclusive_selection() + new + call setline(1, ['one', 'two']) + set selection=exclusive + call feedkeys("vwcabc", 'xt') + call assert_equal('abctwo', getline(1)) + call setline(1, ["\tone"]) + set virtualedit=all + call feedkeys('0v2lcl', 'xt') + call assert_equal('l one', getline(1)) + set virtualedit& + set selection& + close! +endfunc + +" Test for starting linewise visual with a count. +" This test needs to be run without any previous visual mode. Otherwise the +" count will use the count from the previous visual mode. +func Test_linewise_visual_with_count() + let after =<< trim [CODE] + call setline(1, ['one', 'two', 'three', 'four']) + norm! 3Vy + call assert_equal("one\ntwo\nthree\n", @") + call writefile(v:errors, 'Xtestout') + qall! + [CODE] + if RunVim([], after, '') + call assert_equal([], readfile('Xtestout')) + call delete('Xtestout') + endif +endfunc + +" Test for starting characterwise visual with a count. +" This test needs to be run without any previous visual mode. Otherwise the +" count will use the count from the previous visual mode. +func Test_characterwise_visual_with_count() + let after =<< trim [CODE] + call setline(1, ['one two', 'three']) + norm! l5vy + call assert_equal("ne tw", @") + call writefile(v:errors, 'Xtestout') + qall! + [CODE] + if RunVim([], after, '') + call assert_equal([], readfile('Xtestout')) + call delete('Xtestout') + endif +endfunc + +" Test for visually selecting an inner block (iB) +func Test_visual_inner_block() + new + call setline(1, ['one', '{', 'two', '{', 'three', '}', 'four', '}', 'five']) + call cursor(5, 1) + " visually select all the lines in the block and then execute iB + call feedkeys("ViB\<C-C>", 'xt') + call assert_equal([0, 5, 1, 0], getpos("'<")) + call assert_equal([0, 5, 6, 0], getpos("'>")) + " visually select two inner blocks + call feedkeys("ViBiB\<C-C>", 'xt') + call assert_equal([0, 3, 1, 0], getpos("'<")) + call assert_equal([0, 7, 5, 0], getpos("'>")) + " try to select non-existing inner block + call cursor(5, 1) + call assert_beeps('normal ViBiBiB') + " try to select a unclosed inner block + 8,9d + call cursor(5, 1) + call assert_beeps('normal ViBiB') + close! +endfunc + +func Test_visual_put_in_block() + new + call setline(1, ['xxxx', 'y∞yy', 'zzzz']) + normal 1G2yl + exe "normal 1G2l\<C-V>jjlp" + call assert_equal(['xxxx', 'y∞xx', 'zzxx'], getline(1, 3)) + bwipe! +endfunc + +func Test_visual_put_in_block_using_zp() + new + " paste using zP + call setline(1, ['/path;text', '/path;text', '/path;text', '', + \ '/subdir', + \ '/longsubdir', + \ '/longlongsubdir']) + exe "normal! 5G\<c-v>2j$y" + norm! 1Gf;zP + call assert_equal(['/path/subdir;text', '/path/longsubdir;text', '/path/longlongsubdir;text'], getline(1, 3)) + %d + " paste using zP + call setline(1, ['/path;text', '/path;text', '/path;text', '', + \ '/subdir', + \ '/longsubdir', + \ '/longlongsubdir']) + exe "normal! 5G\<c-v>2j$y" + norm! 1Gf;hzp + call assert_equal(['/path/subdir;text', '/path/longsubdir;text', '/path/longlongsubdir;text'], getline(1, 3)) + bwipe! +endfunc + +func Test_visual_put_in_block_using_zy_and_zp() + new + + " Test 1) Paste using zp - after the cursor without trailing spaces + call setline(1, ['/path;text', '/path;text', '/path;text', '', + \ 'texttext /subdir columntext', + \ 'texttext /longsubdir columntext', + \ 'texttext /longlongsubdir columntext']) + exe "normal! 5G0f/\<c-v>2jezy" + norm! 1G0f;hzp + call assert_equal(['/path/subdir;text', '/path/longsubdir;text', '/path/longlongsubdir;text'], getline(1, 3)) + + " Test 2) Paste using zP - in front of the cursor without trailing spaces + %d + call setline(1, ['/path;text', '/path;text', '/path;text', '', + \ 'texttext /subdir columntext', + \ 'texttext /longsubdir columntext', + \ 'texttext /longlongsubdir columntext']) + exe "normal! 5G0f/\<c-v>2jezy" + norm! 1G0f;zP + call assert_equal(['/path/subdir;text', '/path/longsubdir;text', '/path/longlongsubdir;text'], getline(1, 3)) + + " Test 3) Paste using p - with trailing spaces + %d + call setline(1, ['/path;text', '/path;text', '/path;text', '', + \ 'texttext /subdir columntext', + \ 'texttext /longsubdir columntext', + \ 'texttext /longlongsubdir columntext']) + exe "normal! 5G0f/\<c-v>2jezy" + norm! 1G0f;hp + call assert_equal(['/path/subdir ;text', '/path/longsubdir ;text', '/path/longlongsubdir;text'], getline(1, 3)) + + " Test 4) Paste using P - with trailing spaces + %d + call setline(1, ['/path;text', '/path;text', '/path;text', '', + \ 'texttext /subdir columntext', + \ 'texttext /longsubdir columntext', + \ 'texttext /longlongsubdir columntext']) + exe "normal! 5G0f/\<c-v>2jezy" + norm! 1G0f;P + call assert_equal(['/path/subdir ;text', '/path/longsubdir ;text', '/path/longlongsubdir;text'], getline(1, 3)) + + " Test 5) Yank with spaces inside the block + %d + call setline(1, ['/path;text', '/path;text', '/path;text', '', + \ 'texttext /sub dir/ columntext', + \ 'texttext /lon gsubdir/ columntext', + \ 'texttext /lon glongsubdir/ columntext']) + exe "normal! 5G0f/\<c-v>2jf/zy" + norm! 1G0f;zP + call assert_equal(['/path/sub dir/;text', '/path/lon gsubdir/;text', '/path/lon glongsubdir/;text'], getline(1, 3)) + bwipe! +endfunc + +func Test_visual_put_blockedit_zy_and_zp() + new + + call setline(1, ['aa', 'bbbbb', 'ccc', '', 'XX', 'GGHHJ', 'RTZU']) + exe "normal! gg0\<c-v>2j$zy" + norm! 5gg0zP + call assert_equal(['aa', 'bbbbb', 'ccc', '', 'aaXX', 'bbbbbGGHHJ', 'cccRTZU'], getline(1, 7)) + " + " now with blockmode editing + sil %d + :set ve=block + call setline(1, ['aa', 'bbbbb', 'ccc', '', 'XX', 'GGHHJ', 'RTZU']) + exe "normal! gg0\<c-v>2j$zy" + norm! 5gg0zP + call assert_equal(['aa', 'bbbbb', 'ccc', '', 'aaXX', 'bbbbbGGHHJ', 'cccRTZU'], getline(1, 7)) + set ve&vim + bw! +endfunc + +func Test_visual_block_yank_zy() + new + " this was reading before the start of the line + exe "norm o\<C-T>\<Esc>\<C-V>zy" + bwipe! +endfunc + +func Test_visual_block_with_virtualedit() + CheckScreendump + + let lines =<< trim END + call setline(1, ['aaaaaa', 'bbbb', 'cc']) + set virtualedit=block + normal G + END + call writefile(lines, 'XTest_block') + + let buf = RunVimInTerminal('-S XTest_block', {'rows': 8, 'cols': 50}) + call term_sendkeys(buf, "\<C-V>gg$") + call VerifyScreenDump(buf, 'Test_visual_block_with_virtualedit', {}) + + call term_sendkeys(buf, "\<Esc>gg\<C-V>G$") + call VerifyScreenDump(buf, 'Test_visual_block_with_virtualedit2', {}) + + " clean up + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) + call delete('XTest_block') +endfunc + +func Test_visual_block_ctrl_w_f() + " Empty block selected in new buffer should not result in an error. + au! BufNew foo sil norm f + edit foo + + au! BufNew +endfunc + +func Test_visual_block_append_invalid_char() + " this was going over the end of the line + set isprint=@,161-255 + new + call setline(1, [' let xxx', 'xxxxx', 'xxxxxxxxxxx']) + exe "normal 0\<C-V>jjA-\<Esc>" + call assert_equal([' - let xxx', 'xxxxx -', 'xxxxxxxx-xxx'], getline(1, 3)) + bwipe! + set isprint& +endfunc + +func Test_visual_block_with_substitute() + " this was reading beyond the end of the line + new + norm a0) + sil! norm O + s/) + sil! norm + bwipe! +endfunc + +func Test_visual_reselect_with_count() + enew + call setline(1, ['aaaaaa', '✗ bbbb', '✗ bbbb']) + exe "normal! 2Gw\<C-V>jed" + exe "normal! gg0lP" + call assert_equal(['abbbbaaaaa', '✗bbbb ', '✗ '], getline(1, '$')) + + exe "normal! 1vr." + call assert_equal(['a....aaaaa', '✗.... ', '✗ '], getline(1, '$')) + + bwipe! + + " this was causing an illegal memory access + let lines =<< trim END + + + + : + r<sfile> + exe "%norm e3\<c-v>kr\t" + : + + : + END + call writefile(lines, 'XvisualReselect') + source XvisualReselect + + bwipe! + call delete('XvisualReselect') +endfunc + +func Test_visual_reselect_exclusive() + new + call setline(1, ['abcde', 'abcde']) + set selection=exclusive + normal 1G0viwd + normal 2G01vd + call assert_equal(['', ''], getline(1, 2)) + + set selection& + bwipe! +endfunc + +func Test_visual_block_insert_round_off() + new + " The number of characters are tuned to fill a 4096 byte allocated block, + " so that valgrind reports going over the end. + call setline(1, ['xxxxx', repeat('0', 1350), "\t", repeat('x', 60)]) + exe "normal gg0\<C-V>GI" .. repeat('0', 1320) .. "\<Esc>" + bwipe! +endfunc + +" this was causing an ml_get error +func Test_visual_exchange_windows() + enew! + new + call setline(1, ['foo', 'bar']) + exe "normal G\<C-V>gg\<C-W>\<C-X>OO\<Esc>" + bwipe! + bwipe! +endfunc + +" this was leaving the end of the Visual area beyond the end of a line +func Test_visual_ex_copy_line() + new + call setline(1, ["aaa", "bbbbbbbbbxbb"]) + /x + exe "normal ggvjfxO" + t0 + normal gNU + bwipe! +endfunc + +" This was leaving the end of the Visual area beyond the end of a line. +" Set 'undolevels' to start a new undo block. +func Test_visual_undo_deletes_last_line() + new + call setline(1, ["aaa", "ccc", "dyd"]) + set undolevels=100 + exe "normal obbbbbbbbbxbb\<Esc>" + set undolevels=100 + /y + exe "normal ggvjfxO" + undo + normal gNU + + bwipe! +endfunc + +func Test_visual_paste() + new + + " v_p overwrites unnamed register. + call setline(1, ['xxxx']) + call setreg('"', 'foo') + call setreg('-', 'bar') + normal gg0vp + call assert_equal('x', @") + call assert_equal('x', @-) + call assert_equal('fooxxx', getline(1)) + normal $vp + call assert_equal('x', @") + call assert_equal('x', @-) + call assert_equal('fooxxx', getline(1)) + " Test with a different register as unnamed register. + call setline(2, ['baz']) + normal 2gg0"rD + call assert_equal('baz', @") + normal gg0vp + call assert_equal('f', @") + call assert_equal('f', @-) + call assert_equal('bazooxxx', getline(1)) + normal $vp + call assert_equal('x', @") + call assert_equal('x', @-) + call assert_equal('bazooxxf', getline(1)) + + bwipe! +endfunc + +func Test_visual_paste_clipboard() + CheckFeature clipboard_working + + if has('gui') + " auto select feature breaks tests + set guioptions-=a + endif + + " v_P does not overwrite unnamed register. + call setline(1, ['xxxx']) + call setreg('"', 'foo') + call setreg('-', 'bar') + normal gg0vP + call assert_equal('foo', @") + call assert_equal('bar', @-) + call assert_equal('fooxxx', getline(1)) + normal $vP + call assert_equal('foo', @") + call assert_equal('bar', @-) + call assert_equal('fooxxfoo', getline(1)) + " Test with a different register as unnamed register. + call setline(2, ['baz']) + normal 2gg0"rD + call assert_equal('baz', @") + normal gg0vP + call assert_equal('baz', @") + call assert_equal('bar', @-) + call assert_equal('bazooxxfoo', getline(1)) + normal $vP + call assert_equal('baz', @") + call assert_equal('bar', @-) + call assert_equal('bazooxxfobaz', getline(1)) + + " Test for unnamed clipboard + set clipboard=unnamed + call setline(1, ['xxxx']) + call setreg('"', 'foo') + call setreg('-', 'bar') + call setreg('*', 'baz') + normal gg0vP + call assert_equal('foo', @") + call assert_equal('bar', @-) + call assert_equal('baz', @*) + call assert_equal('bazxxx', getline(1)) + + " Test for unnamedplus clipboard + if has('unnamedplus') + set clipboard=unnamedplus + call setline(1, ['xxxx']) + call setreg('"', 'foo') + call setreg('-', 'bar') + call setreg('+', 'baz') + normal gg0vP + call assert_equal('foo', @") + call assert_equal('bar', @-) + call assert_equal('baz', @+) + call assert_equal('bazxxx', getline(1)) + endif + + set clipboard& + if has('gui') + set guioptions& + endif + bwipe! +endfunc + +func Test_visual_area_adjusted_when_hiding() + " The Visual area ended after the end of the line after :hide + call setline(1, 'xxx') + vsplit Xfile + call setline(1, 'xxxxxxxx') + norm! $o + hid + norm! zW + bwipe! + bwipe! +endfunc + +func Test_switch_buffer_ends_visual_mode() + enew + call setline(1, 'foo') + set hidden + set virtualedit=all + let buf1 = bufnr() + enew + let buf2 = bufnr() + call setline(1, ['', '', '', '']) + call cursor(4, 5) + call feedkeys("\<C-V>3k4h", 'xt') + exe 'buffer' buf1 + call assert_equal('n', mode()) + + set nohidden + set virtualedit= + bwipe! + exe 'bwipe!' buf2 +endfunc + +" Check fix for the heap-based buffer overflow bug found in the function +" utfc_ptr2len and reported at +" https://huntr.dev/bounties/ae933869-a1ec-402a-bbea-d51764c6618e +func Test_heap_buffer_overflow() + enew + set updatecount=0 + + norm R0 + split other + norm R000 + exe "norm \<C-V>l" + ball + call assert_equal(getpos("."), getpos("v")) + call assert_equal('n', mode()) + norm zW + + %bwipe! + set updatecount& +endfunc + +" Test Visual highlight with cursor at end of screen line and 'showbreak' +func Test_visual_hl_with_showbreak() + CheckScreendump + + let lines =<< trim END + setlocal showbreak=+ + call setline(1, repeat('a', &columns + 10)) + normal g$v4lo + END + call writefile(lines, 'XTest_visual_sbr', 'D') + + let buf = RunVimInTerminal('-S XTest_visual_sbr', {'rows': 6, 'cols': 50}) + call VerifyScreenDump(buf, 'Test_visual_hl_with_showbreak', {}) + + " clean up + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) +endfunc + +func Test_Visual_r_CTRL_C() + new + " visual r_cmd + call setline(1, [' ']) + call feedkeys("\<c-v>$r\<c-c>", 'tx') + call assert_equal([''], getline(1, 1)) + + " visual gr_cmd + call setline(1, [' ']) + call feedkeys("\<c-v>$gr\<c-c>", 'tx') + call assert_equal([''], getline(1, 1)) + bw! +endfu + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_winbuf_close.vim b/test/old/testdir/test_winbuf_close.vim new file mode 100644 index 0000000000..26b4ba8778 --- /dev/null +++ b/test/old/testdir/test_winbuf_close.vim @@ -0,0 +1,231 @@ +" Test for commands that close windows and/or buffers: +" :quit +" :close +" :hide +" :only +" :sall +" :all +" :ball +" :buf +" :edit +" +func Test_winbuf_close() + enew | only + + call writefile(['testtext 1'], 'Xtest1') + call writefile(['testtext 2'], 'Xtest2') + call writefile(['testtext 3'], 'Xtest3') + + next! Xtest1 Xtest2 + call setline(1, 'testtext 1 1') + + " test for working :n when hidden set + set hidden + next + call assert_equal('Xtest2', bufname('%')) + + " test for failing :rew when hidden not set + set nohidden + call setline(1, 'testtext 2 2') + call assert_fails('rewind', 'E37') + call assert_equal('Xtest2', bufname('%')) + call assert_equal('testtext 2 2', getline(1)) + + " test for working :rew when hidden set + set hidden + rewind + call assert_equal('Xtest1', bufname('%')) + call assert_equal('testtext 1 1', getline(1)) + + " test for :all keeping a buffer when it's modified + set nohidden + call setline(1, 'testtext 1 1 1') + split + next Xtest2 Xtest3 + all + 1wincmd w + call assert_equal('Xtest1', bufname('%')) + call assert_equal('testtext 1 1 1', getline(1)) + + " test abandoning changed buffer, should be unloaded even when 'hidden' set + set hidden + call setline(1, 'testtext 1 1 1 1') + quit! + call assert_equal('Xtest2', bufname('%')) + call assert_equal('testtext 2 2', getline(1)) + unhide + call assert_equal('Xtest2', bufname('%')) + call assert_equal('testtext 2 2', getline(1)) + + " test ":hide" hides anyway when 'hidden' not set + set nohidden + call setline(1, 'testtext 2 2 2') + hide + call assert_equal('Xtest3', bufname('%')) + call assert_equal('testtext 3', getline(1)) + + " test ":edit" failing in modified buffer when 'hidden' not set + call setline(1, 'testtext 3 3') + call assert_fails('edit Xtest1', 'E37') + call assert_equal('Xtest3', bufname('%')) + call assert_equal('testtext 3 3', getline(1)) + + " test ":edit" working in modified buffer when 'hidden' set + set hidden + edit Xtest1 + call assert_equal('Xtest1', bufname('%')) + call assert_equal('testtext 1', getline(1)) + + " test ":close" not hiding when 'hidden' not set in modified buffer + split Xtest3 + set nohidden + call setline(1, 'testtext 3 3 3') + call assert_fails('close', 'E37') + call assert_equal('Xtest3', bufname('%')) + call assert_equal('testtext 3 3 3', getline(1)) + + " test ":close!" does hide when 'hidden' not set in modified buffer; + call setline(1, 'testtext 3 3 3 3') + close! + call assert_equal('Xtest1', bufname('%')) + call assert_equal('testtext 1', getline(1)) + + set nohidden + + " test ":all!" hides changed buffer + split Xtest4 + call setline(1, 'testtext 4') + all! + 1wincmd w + call assert_equal('Xtest2', bufname('%')) + call assert_equal('testtext 2 2 2', getline(1)) + + " test ":q!" and hidden buffer. + bwipe! Xtest1 Xtest2 Xtest3 Xtest4 + split Xtest1 + wincmd w + bwipe! + set modified + bot split Xtest2 + set modified + bot split Xtest3 + set modified + wincmd t + hide + call assert_equal('Xtest2', bufname('%')) + quit! + call assert_equal('Xtest3', bufname('%')) + call assert_fails('silent! quit!', 'E37') + call assert_equal('Xtest1', bufname('%')) + + call delete('Xtest1') + call delete('Xtest2') + call delete('Xtest3') +endfunc + +" Test that ":close" will respect 'winfixheight' when possible. +func Test_winfixheight_on_close() + set nosplitbelow nosplitright + + split | split | vsplit + + $wincmd w + setlocal winfixheight + let l:height = winheight(0) + + 3close + + call assert_equal(l:height, winheight(0)) + + %bwipeout! + setlocal nowinfixheight splitbelow& splitright& +endfunc + +" Test that ":close" will respect 'winfixwidth' when possible. +func Test_winfixwidth_on_close() + set nosplitbelow nosplitright + + vsplit | vsplit | split + + $wincmd w + setlocal winfixwidth + let l:width = winwidth(0) + + 3close + + call assert_equal(l:width, winwidth(0)) + + %bwipeout! + setlocal nowinfixwidth splitbelow& splitright& +endfunction + +" Test that 'winfixheight' will be respected even there is non-leaf frame +func Test_winfixheight_non_leaf_frame() + vsplit + botright 11new + let l:wid = win_getid() + setlocal winfixheight + call assert_equal(11, winheight(l:wid)) + botright new + bwipe! + call assert_equal(11, winheight(l:wid)) + %bwipe! +endf + +" Test that 'winfixwidth' will be respected even there is non-leaf frame +func Test_winfixwidth_non_leaf_frame() + split + topleft 11vnew + let l:wid = win_getid() + setlocal winfixwidth + call assert_equal(11, winwidth(l:wid)) + topleft new + bwipe! + call assert_equal(11, winwidth(l:wid)) + %bwipe! +endf + +func Test_tabwin_close() + enew + let l:wid = win_getid() + tabedit + call win_execute(l:wid, 'close') + " Should not crash. + call assert_true(v:true) + + " This tests closing a window in another tab, while leaving the tab open + " i.e. two windows in another tab. + tabedit + let w:this_win = 42 + new + let othertab_wid = win_getid() + tabprevious + call win_execute(othertab_wid, 'q') + " drawing the tabline helps check that the other tab's windows and buffers + " are still valid + redrawtabline + " but to be certain, ensure we can focus the other tab too + tabnext + call assert_equal(42, w:this_win) + + bwipe! +endfunc + +" Test when closing a split window (above/below) restores space to the window +" below when 'noequalalways' and 'splitright' are set. +func Test_window_close_splitright_noequalalways() + set noequalalways + set splitright + new + let w1 = win_getid() + new + let w2 = win_getid() + execute "normal \<c-w>b" + let h = winheight(0) + let w = win_getid() + new + q + call assert_equal(h, winheight(0), "Window height does not match eight before opening and closing another window") + call assert_equal(w, win_getid(), "Did not return to original window after opening and closing a window") +endfunc + diff --git a/test/old/testdir/test_window_cmd.vim b/test/old/testdir/test_window_cmd.vim new file mode 100644 index 0000000000..152d1bacc7 --- /dev/null +++ b/test/old/testdir/test_window_cmd.vim @@ -0,0 +1,1971 @@ +" Tests for window cmd (:wincmd, :split, :vsplit, :resize and etc...) + +source check.vim +source screendump.vim + +func Test_window_cmd_ls0_with_split() + set ls=0 + set splitbelow + split + quit + call assert_equal(0, &lines - &cmdheight - winheight(0)) + new | only! + " + set splitbelow&vim + botright split + quit + call assert_equal(0, &lines - &cmdheight - winheight(0)) + new | only! + set ls&vim +endfunc + +func Test_window_cmd_ls0_split_scrolling() + CheckRunVimInTerminal + + let lines =<< trim END + set laststatus=0 + call setline(1, range(1, 100)) + normal! G + END + call writefile(lines, 'XTestLs0SplitScrolling', 'D') + let buf = RunVimInTerminal('-S XTestLs0SplitScrolling', #{rows: 10}) + + call term_sendkeys(buf, ":botright split\<CR>") + call WaitForAssert({-> assert_match('Bot$', term_getline(buf, 5))}) + call assert_equal('100', term_getline(buf, 4)) + + call StopVimInTerminal(buf) +endfunc + +func Test_window_cmd_cmdwin_with_vsp() + let efmt = 'Expected 0 but got %d (in ls=%d, %s window)' + for v in range(0, 2) + exec "set ls=" . v + vsplit + call feedkeys("q:\<CR>") + let ac = &lines - (&cmdheight + winheight(0) + !!v) + let emsg = printf(efmt, ac, v, 'left') + call assert_equal(0, ac, emsg) + wincmd w + let ac = &lines - (&cmdheight + winheight(0) + !!v) + let emsg = printf(efmt, ac, v, 'right') + call assert_equal(0, ac, emsg) + new | only! + endfor + set ls&vim +endfunc + +" Test for jumping to windows +func Test_window_jump() + new + " jumping to a window with a count greater than the max windows + exe "normal 4\<C-W>w" + call assert_equal(2, winnr()) + only +endfunc + +func Test_window_cmd_wincmd_gf() + let fname = 'test_gf.txt' + let swp_fname = '.' . fname . '.swp' + call writefile([], fname) + call writefile([], swp_fname) + function s:swap_exists() + let v:swapchoice = s:swap_choice + endfunc + " Remove the catch-all that runtest.vim adds + au! SwapExists + augroup test_window_cmd_wincmd_gf + autocmd! + exec "autocmd SwapExists " . fname . " call s:swap_exists()" + augroup END + + call setline(1, fname) + " (E)dit anyway + let s:swap_choice = 'e' + wincmd gf + call assert_equal(2, tabpagenr()) + call assert_equal(fname, bufname("%")) + quit! + + " (Q)uit + let s:swap_choice = 'q' + wincmd gf + call assert_equal(1, tabpagenr()) + call assert_notequal(fname, bufname("%")) + new | only! + + call delete(fname) + call delete(swp_fname) + augroup! test_window_cmd_wincmd_gf +endfunc + +func Test_window_quit() + e Xa + split Xb + call assert_equal(2, '$'->winnr()) + call assert_equal('Xb', bufname(winbufnr(1))) + call assert_equal('Xa', bufname(winbufnr(2))) + + wincmd q + call assert_equal(1, winnr('$')) + call assert_equal('Xa', bufname(winbufnr(1))) + + bw Xa Xb +endfunc + +func Test_window_horizontal_split() + call assert_equal(1, winnr('$')) + 3wincmd s + call assert_equal(2, winnr('$')) + call assert_equal(3, winheight(0)) + call assert_equal(winwidth(1), 2->winwidth()) + + call assert_fails('botright topleft wincmd s', 'E442:') + bw +endfunc + +func Test_window_vertical_split() + call assert_equal(1, winnr('$')) + 3wincmd v + call assert_equal(2, winnr('$')) + call assert_equal(3, winwidth(0)) + call assert_equal(winheight(1), winheight(2)) + + call assert_fails('botright topleft wincmd v', 'E442:') + bw +endfunc + +" Test the ":wincmd ^" and "<C-W>^" commands. +func Test_window_split_edit_alternate() + " Test for failure when the alternate buffer/file no longer exists. + edit Xfoo | %bw + call assert_fails(':wincmd ^', 'E23:') + + " Test for the expected behavior when we have two named buffers. + edit Xfoo | edit Xbar + wincmd ^ + call assert_equal('Xfoo', bufname(winbufnr(1))) + call assert_equal('Xbar', bufname(winbufnr(2))) + only + + " Test for the expected behavior when the alternate buffer is not named. + enew | let l:nr1 = bufnr('%') + edit Xfoo | let l:nr2 = bufnr('%') + wincmd ^ + call assert_equal(l:nr1, winbufnr(1)) + call assert_equal(l:nr2, winbufnr(2)) + only + + " FIXME: this currently fails on AppVeyor, but passes locally + if !has('win32') + " Test the Normal mode command. + call feedkeys("\<C-W>\<C-^>", 'tx') + call assert_equal(l:nr2, winbufnr(1)) + call assert_equal(l:nr1, winbufnr(2)) + endif + + %bw! +endfunc + +" Test the ":[count]wincmd ^" and "[count]<C-W>^" commands. +func Test_window_split_edit_bufnr() + %bwipeout + let l:nr = bufnr('%') + 1 + call assert_fails(':execute "normal! ' . l:nr . '\<C-W>\<C-^>"', 'E92:') + call assert_fails(':' . l:nr . 'wincmd ^', 'E16:') + call assert_fails(':0wincmd ^', 'E16:') + + edit Xfoo | edit Xbar | edit Xbaz + let l:foo_nr = bufnr('Xfoo') + let l:bar_nr = bufnr('Xbar') + let l:baz_nr = bufnr('Xbaz') + + " FIXME: this currently fails on AppVeyor, but passes locally + if !has('win32') + call feedkeys(l:foo_nr . "\<C-W>\<C-^>", 'tx') + call assert_equal('Xfoo', bufname(winbufnr(1))) + call assert_equal('Xbaz', bufname(winbufnr(2))) + only + + call feedkeys(l:bar_nr . "\<C-W>\<C-^>", 'tx') + call assert_equal('Xbar', bufname(winbufnr(1))) + call assert_equal('Xfoo', bufname(winbufnr(2))) + only + + execute l:baz_nr . 'wincmd ^' + call assert_equal('Xbaz', bufname(winbufnr(1))) + call assert_equal('Xbar', bufname(winbufnr(2))) + endif + + %bw! +endfunc + +func Test_window_split_no_room() + " N horizontal windows need >= 2*N + 1 lines: + " - 1 line + 1 status line in each window + " - 1 Ex command line + " + " 2*N + 1 <= &lines + " N <= (lines - 1)/2 + " + " Beyond that number of windows, E36: Not enough room is expected. + let hor_win_count = (&lines - 1)/2 + let hor_split_count = hor_win_count - 1 + for s in range(1, hor_split_count) | split | endfor + call assert_fails('split', 'E36:') + + " N vertical windows need >= 2*(N - 1) + 1 columns: + " - 1 column + 1 separator for each window (except last window) + " - 1 column for the last window which does not have separator + " + " 2*(N - 1) + 1 <= &columns + " 2*N - 1 <= &columns + " N <= (&columns + 1)/2 + let ver_win_count = (&columns + 1)/2 + let ver_split_count = ver_win_count - 1 + for s in range(1, ver_split_count) | vsplit | endfor + call assert_fails('vsplit', 'E36:') + + %bw! +endfunc + +func Test_window_exchange() + e Xa + + " Nothing happens with window exchange when there is 1 window + wincmd x + call assert_equal(1, winnr('$')) + + split Xb + split Xc + + call assert_equal('Xc', bufname(winbufnr(1))) + call assert_equal('Xb', bufname(winbufnr(2))) + call assert_equal('Xa', bufname(winbufnr(3))) + + " Exchange current window 1 with window 3 + 3wincmd x + call assert_equal('Xa', bufname(winbufnr(1))) + call assert_equal('Xb', bufname(winbufnr(2))) + call assert_equal('Xc', bufname(winbufnr(3))) + + " Exchange window with next when at the top window + wincmd x + call assert_equal('Xb', bufname(winbufnr(1))) + call assert_equal('Xa', bufname(winbufnr(2))) + call assert_equal('Xc', bufname(winbufnr(3))) + + " Exchange window with next when at the middle window + wincmd j + wincmd x + call assert_equal('Xb', bufname(winbufnr(1))) + call assert_equal('Xc', bufname(winbufnr(2))) + call assert_equal('Xa', bufname(winbufnr(3))) + + " Exchange window with next when at the bottom window. + " When there is no next window, it exchanges with the previous window. + wincmd j + wincmd x + call assert_equal('Xb', bufname(winbufnr(1))) + call assert_equal('Xa', bufname(winbufnr(2))) + call assert_equal('Xc', bufname(winbufnr(3))) + + bw Xa Xb Xc +endfunc + +func Test_window_rotate() + e Xa + split Xb + split Xc + call assert_equal('Xc', bufname(winbufnr(1))) + call assert_equal('Xb', bufname(winbufnr(2))) + call assert_equal('Xa', bufname(winbufnr(3))) + + " Rotate downwards + wincmd r + call assert_equal('Xa', bufname(winbufnr(1))) + call assert_equal('Xc', bufname(winbufnr(2))) + call assert_equal('Xb', bufname(winbufnr(3))) + + 2wincmd r + call assert_equal('Xc', bufname(winbufnr(1))) + call assert_equal('Xb', bufname(winbufnr(2))) + call assert_equal('Xa', bufname(winbufnr(3))) + + " Rotate upwards + wincmd R + call assert_equal('Xb', bufname(winbufnr(1))) + call assert_equal('Xa', bufname(winbufnr(2))) + call assert_equal('Xc', bufname(winbufnr(3))) + + 2wincmd R + call assert_equal('Xc', bufname(winbufnr(1))) + call assert_equal('Xb', bufname(winbufnr(2))) + call assert_equal('Xa', bufname(winbufnr(3))) + + bot vsplit + call assert_fails('wincmd R', 'E443:') + + bw Xa Xb Xc +endfunc + +func Test_window_height() + e Xa + split Xb + + let [wh1, wh2] = [winheight(1), winheight(2)] + " Active window (1) should have the same height or 1 more + " than the other window. + call assert_inrange(wh2, wh2 + 1, wh1) + + wincmd - + call assert_equal(wh1 - 1, winheight(1)) + call assert_equal(wh2 + 1, winheight(2)) + + wincmd + + call assert_equal(wh1, winheight(1)) + call assert_equal(wh2, 2->winheight()) + + 2wincmd _ + call assert_equal(2, winheight(1)) + call assert_equal(wh1 + wh2 - 2, winheight(2)) + + wincmd = + call assert_equal(wh1, winheight(1)) + call assert_equal(wh2, winheight(2)) + + 2wincmd _ + set winfixheight + split Xc + let [wh1, wh2, wh3] = [winheight(1), winheight(2), winheight(3)] + call assert_equal(2, winheight(2)) + call assert_inrange(wh3, wh3 + 1, wh1) + 3wincmd + + call assert_equal(2, winheight(2)) + call assert_equal(wh1 + 3, winheight(1)) + call assert_equal(wh3 - 3, winheight(3)) + wincmd = + call assert_equal(2, winheight(2)) + call assert_equal(wh1, winheight(1)) + call assert_equal(wh3, winheight(3)) + + wincmd j + set winfixheight& + + wincmd = + let [wh1, wh2, wh3] = [winheight(1), winheight(2), winheight(3)] + " Current window (2) should have the same height or 1 more + " than the other windows. + call assert_inrange(wh1, wh1 + 1, wh2) + call assert_inrange(wh3, wh3 + 1, wh2) + + bw Xa Xb Xc +endfunc + +func Test_wincmd_equal() + edit Xone + below split Xtwo + rightbelow vsplit Xthree + call assert_equal('Xone', bufname(winbufnr(1))) + call assert_equal('Xtwo', bufname(winbufnr(2))) + call assert_equal('Xthree', bufname(winbufnr(3))) + + " Xone and Xtwo should be about the same height + let [wh1, wh2] = [winheight(1), winheight(2)] + call assert_inrange(wh1 - 1, wh1 + 1, wh2) + " Xtwo and Xthree should be about the same width + let [ww2, ww3] = [winwidth(2), winwidth(3)] + call assert_inrange(ww2 - 1, ww2 + 1, ww3) + + 1wincmd w + 10wincmd _ + 2wincmd w + 20wincmd | + call assert_equal(10, winheight(1)) + call assert_equal(20, winwidth(2)) + + " equalizing horizontally doesn't change the heights + hor wincmd = + call assert_equal(10, winheight(1)) + let [ww2, ww3] = [winwidth(2), winwidth(3)] + call assert_inrange(ww2 - 1, ww2 + 1, ww3) + + 2wincmd w + 20wincmd | + call assert_equal(20, winwidth(2)) + " equalizing vertically doesn't change the widths + vert wincmd = + call assert_equal(20, winwidth(2)) + let [wh1, wh2] = [winheight(1), winheight(2)] + call assert_inrange(wh1 - 1, wh1 + 1, wh2) + + bwipe Xone Xtwo Xthree +endfunc + +func Test_window_width() + e Xa + vsplit Xb + + let [ww1, ww2] = [winwidth(1), winwidth(2)] + " Active window (1) should have the same width or 1 more + " than the other window. + call assert_inrange(ww2, ww2 + 1, ww1) + + wincmd < + call assert_equal(ww1 - 1, winwidth(1)) + call assert_equal(ww2 + 1, winwidth(2)) + + wincmd > + call assert_equal(ww1, winwidth(1)) + call assert_equal(ww2, winwidth(2)) + + 2wincmd | + call assert_equal(2, winwidth(1)) + call assert_equal(ww1 + ww2 - 2, winwidth(2)) + + wincmd = + call assert_equal(ww1, winwidth(1)) + call assert_equal(ww2, winwidth(2)) + + 2wincmd | + set winfixwidth + vsplit Xc + let [ww1, ww2, ww3] = [winwidth(1), winwidth(2), winwidth(3)] + call assert_equal(2, winwidth(2)) + call assert_inrange(ww3, ww3 + 1, ww1) + 3wincmd > + call assert_equal(2, winwidth(2)) + call assert_equal(ww1 + 3, winwidth(1)) + call assert_equal(ww3 - 3, winwidth(3)) + wincmd = + call assert_equal(2, winwidth(2)) + call assert_equal(ww1, winwidth(1)) + call assert_equal(ww3, winwidth(3)) + + wincmd l + set winfixwidth& + + wincmd = + let [ww1, ww2, ww3] = [winwidth(1), winwidth(2), winwidth(3)] + " Current window (2) should have the same width or 1 more + " than the other windows. + call assert_inrange(ww1, ww1 + 1, ww2) + call assert_inrange(ww3, ww3 + 1, ww2) + + " when the current window width is less than the new 'winwidth', the current + " window width should be increased. + enew | only + split + 10vnew + set winwidth=15 + call assert_equal(15, winwidth(0)) + + %bw! +endfunc + +func Test_equalalways_on_close() + set equalalways + vsplit + windo split + split + wincmd J + " now we have a frame top-left with two windows, a frame top-right with two + " windows and a frame at the bottom, full-width. + let height_1 = winheight(1) + let height_2 = winheight(2) + let height_3 = winheight(3) + let height_4 = winheight(4) + " closing the bottom window causes all windows to be resized. + close + call assert_notequal(height_1, winheight(1)) + call assert_notequal(height_2, winheight(2)) + call assert_notequal(height_3, winheight(3)) + call assert_notequal(height_4, winheight(4)) + call assert_equal(winheight(1), winheight(3)) + call assert_equal(winheight(2), winheight(4)) + + 1wincmd w + split + 4wincmd w + resize + 5 + " left column has three windows, equalized heights. + " right column has two windows, top one a bit higher + let height_1 = winheight(1) + let height_2 = winheight(2) + let height_4 = winheight(4) + let height_5 = winheight(5) + 3wincmd w + " closing window in left column equalizes heights in left column but not in + " the right column + close + call assert_notequal(height_1, winheight(1)) + call assert_notequal(height_2, winheight(2)) + call assert_equal(height_4, winheight(3)) + call assert_equal(height_5, winheight(4)) + + only + set equalalways& +endfunc + +func Test_win_screenpos() + CheckFeature quickfix + + call assert_equal(1, winnr('$')) + split + vsplit + 10wincmd _ + 30wincmd | + call assert_equal([1, 1], win_screenpos(1)) + call assert_equal([1, 32], win_screenpos(2)) + call assert_equal([12, 1], win_screenpos(3)) + call assert_equal([0, 0], win_screenpos(4)) + call assert_fails('let l = win_screenpos([])', 'E745:') + only +endfunc + +func Test_window_jump_tag() + CheckFeature quickfix + + help + /iccf + call assert_match('^|iccf|', getline('.')) + call assert_equal(2, winnr('$')) + 2wincmd } + call assert_equal(3, winnr('$')) + call assert_match('^|iccf|', getline('.')) + wincmd k + call assert_match('\*iccf\*', getline('.')) + call assert_equal(2, winheight(0)) + + wincmd z + set previewheight=4 + help + /bugs + wincmd } + wincmd k + call assert_match('\*bugs\*', getline('.')) + call assert_equal(4, winheight(0)) + set previewheight& + + %bw! +endfunc + +func Test_window_newtab() + e Xa + + call assert_equal(1, tabpagenr('$')) + call assert_equal("\nAlready only one window", execute('wincmd T')) + + split Xb + split Xc + + wincmd T + call assert_equal(2, tabpagenr('$')) + call assert_equal(['Xb', 'Xa'], map(tabpagebuflist(1), 'bufname(v:val)')) + call assert_equal(['Xc' ], map(2->tabpagebuflist(), 'bufname(v:val)')) + call assert_equal(['Xc' ], map(tabpagebuflist(), 'bufname(v:val)')) + + %bw! +endfunc + +func Test_next_split_all() + " This was causing an illegal memory access. + n x + norm axxx + split + split + s/x + s/x + all + bwipe! +endfunc + +" Tests for adjusting window and contents +func GetScreenStr(row) + let str = "" + for c in range(1,3) + let str .= nr2char(screenchar(a:row, c)) + endfor + return str +endfunc + +func Test_window_contents() + enew! | only | new + call setline(1, range(1,256)) + + exe "norm! \<C-W>t\<C-W>=1Gzt\<C-W>w\<C-W>+" + redraw + let s3 = GetScreenStr(1) + wincmd p + call assert_equal(1, line("w0")) + call assert_equal('1 ', s3) + + exe "norm! \<C-W>t\<C-W>=50Gzt\<C-W>w\<C-W>+" + redraw + let s3 = GetScreenStr(1) + wincmd p + call assert_equal(50, line("w0")) + call assert_equal('50 ', s3) + + exe "norm! \<C-W>t\<C-W>=59Gzt\<C-W>w\<C-W>+" + redraw + let s3 = GetScreenStr(1) + wincmd p + call assert_equal(59, line("w0")) + call assert_equal('59 ', s3) + + %d + call setline(1, ['one', 'two', 'three']) + call assert_equal(1, line('w0')) + call assert_equal(3, line('w$')) + + bwipeout! + call test_garbagecollect_now() +endfunc + +func Test_window_colon_command() + " This was reading invalid memory. + exe "norm! v\<C-W>:\<C-U>echo v:version" +endfunc + +func Test_access_freed_mem() + call assert_equal(&columns, winwidth(0)) + " This was accessing freed memory (but with what events?) + au BufEnter,BufLeave,WinEnter,WinLeave 0 vs xxx + arg 0 + argadd + call assert_fails("all", "E242:") + au! + bwipe xxx + call assert_equal(&columns, winwidth(0)) +endfunc + +func Test_visual_cleared_after_window_split() + new | only! + let smd_save = &showmode + set showmode + let ls_save = &laststatus + set laststatus=1 + call setline(1, ['a', 'b', 'c', 'd', '']) + norm! G + exe "norm! kkvk" + redraw + exe "norm! \<C-W>v" + redraw + " check if '-- VISUAL --' disappeared from command line + let columns = range(1, &columns) + let cmdlinechars = map(columns, 'nr2char(screenchar(&lines, v:val))') + let cmdline = join(cmdlinechars, '') + let cmdline_ltrim = substitute(cmdline, '^\s*', "", "") + let mode_shown = substitute(cmdline_ltrim, '\s*$', "", "") + call assert_equal('', mode_shown) + let &showmode = smd_save + let &laststatus = ls_save + bwipe! +endfunc + +func Test_winrestcmd() + 2split + 3vsplit + let restcmd = winrestcmd() + call assert_equal(2, winheight(0)) + call assert_equal(3, winwidth(0)) + wincmd = + call assert_notequal(2, winheight(0)) + call assert_notequal(3, winwidth(0)) + exe restcmd + call assert_equal(2, winheight(0)) + call assert_equal(3, winwidth(0)) + only + + wincmd v + wincmd s + wincmd v + redraw + let restcmd = winrestcmd() + wincmd _ + wincmd | + exe restcmd + redraw + call assert_equal(restcmd, winrestcmd()) + + only +endfunc + +func Fun_RenewFile() + " Need to wait a bit for the timestamp to be older. + let old_ftime = getftime("tmp.txt") + while getftime("tmp.txt") == old_ftime + sleep 100m + silent execute '!echo "1" > tmp.txt' + endwhile + sp + wincmd p + edit! tmp.txt +endfunc + +func Test_window_prevwin() + " Can we make this work on MS-Windows? + if !has('unix') + return + endif + + set hidden autoread + call writefile(['2'], 'tmp.txt') + new tmp.txt + q + call Fun_RenewFile() + call assert_equal(2, winnr()) + wincmd p + call assert_equal(1, winnr()) + wincmd p + q + call Fun_RenewFile() + call assert_equal(2, winnr()) + wincmd p + call assert_equal(1, winnr()) + wincmd p + " reset + q + call delete('tmp.txt') + set hidden&vim autoread&vim + delfunc Fun_RenewFile +endfunc + +func Test_relative_cursor_position_in_one_line_window() + new + only + call setline(1, range(1, 10000)) + normal 50% + let lnum = getcurpos()[1] + split + split + " make third window take as many lines as possible, other windows will + " become one line + 3wincmd w + for i in range(1, &lines - 6) + wincmd + + redraw! + endfor + + " first and second window should show cursor line + let wininfo = getwininfo() + call assert_equal(lnum, wininfo[0].topline) + call assert_equal(lnum, wininfo[1].topline) + + only! + bwipe! + call assert_fails('call winrestview(v:_null_dict)', 'E1297:') +endfunc + +func Test_relative_cursor_position_after_move_and_resize() + let so_save = &so + set so=0 + enew + call setline(1, range(1, 10000)) + normal 50% + split + 1wincmd w + " Move cursor to first line in window + normal H + redraw! + " Reduce window height to two lines + let height = winheight(0) + while winheight(0) > 2 + wincmd - + redraw! + endwhile + " move cursor to second/last line in window + normal j + " restore previous height + while winheight(0) < height + wincmd + + redraw! + endwhile + " make window two lines again + while winheight(0) > 2 + wincmd - + redraw! + endwhile + + " cursor should be at bottom line + let info = getwininfo(win_getid())[0] + call assert_equal(info.topline + 1, getcurpos()[1]) + + only! + bwipe! + let &so = so_save +endfunc + +func Test_relative_cursor_position_after_resize() + let so_save = &so + set so=0 + enew + call setline(1, range(1, 10000)) + normal 50% + split + 1wincmd w + let winid1 = win_getid() + let info = getwininfo(winid1)[0] + " Move cursor to second line in window + exe "normal " . (info.topline + 1) . "G" + redraw! + let lnum = getcurpos()[1] + + " Make the window only two lines high, cursor should end up in top line + 2wincmd w + exe (info.height - 2) . "wincmd +" + redraw! + let info = getwininfo(winid1)[0] + call assert_equal(lnum, info.topline) + + only! + bwipe! + let &so = so_save +endfunc + +func Test_relative_cursor_second_line_after_resize() + let so_save = &so + set so=0 + enew + call setline(1, range(1, 10000)) + normal 50% + split + 1wincmd w + let winid1 = win_getid() + let info = getwininfo(winid1)[0] + + " Make the window only two lines high + 2wincmd _ + + " Move cursor to second line in window + normal H + normal j + + " Make window size bigger, then back to 2 lines + for i in range(1, 10) + wincmd + + redraw! + endfor + for i in range(1, 10) + wincmd - + redraw! + endfor + + " cursor should end up in bottom line + let info = getwininfo(winid1)[0] + call assert_equal(info.topline + 1, getcurpos()[1]) + + only! + bwipe! + let &so = so_save +endfunc + +func Test_split_noscroll() + let so_save = &so + enew + call setline(1, range(1, 8)) + normal 100% + split + + 1wincmd w + let winid1 = win_getid() + let info1 = getwininfo(winid1)[0] + + 2wincmd w + let winid2 = win_getid() + let info2 = getwininfo(winid2)[0] + + call assert_equal(1, info1.topline) + call assert_equal(1, info2.topline) + + " window that fits all lines by itself, but not when split: closing other + " window should restore fraction. + only! + call setline(1, range(1, &lines - 10)) + exe &lines / 4 + let winid1 = win_getid() + let info1 = getwininfo(winid1)[0] + call assert_equal(1, info1.topline) + new + redraw + close + let info1 = getwininfo(winid1)[0] + call assert_equal(1, info1.topline) + + bwipe! + let &so = so_save +endfunc + +" Tests for the winnr() function +func Test_winnr() + only | tabonly + call assert_equal(1, winnr('j')) + call assert_equal(1, winnr('k')) + call assert_equal(1, winnr('h')) + call assert_equal(1, winnr('l')) + + " create a set of horizontally and vertically split windows + leftabove new | wincmd p + leftabove new | wincmd p + rightbelow new | wincmd p + rightbelow new | wincmd p + leftabove vnew | wincmd p + leftabove vnew | wincmd p + rightbelow vnew | wincmd p + rightbelow vnew | wincmd p + + call assert_equal(8, winnr('j')) + call assert_equal(2, winnr('k')) + call assert_equal(4, winnr('h')) + call assert_equal(6, winnr('l')) + call assert_equal(9, winnr('2j')) + call assert_equal(1, winnr('2k')) + call assert_equal(3, winnr('2h')) + call assert_equal(7, winnr('2l')) + + " Error cases + call assert_fails("echo winnr('0.2k')", 'E15:') + call assert_equal(2, winnr('-2k')) + call assert_fails("echo winnr('-2xj')", 'E15:') + call assert_fails("echo winnr('j2j')", 'E15:') + call assert_fails("echo winnr('ll')", 'E15:') + call assert_fails("echo winnr('5')", 'E15:') + call assert_equal(4, winnr('0h')) + call assert_fails("let w = winnr([])", 'E730:') + call assert_equal('unknown', win_gettype(-1)) + call assert_equal(-1, winheight(-1)) + call assert_equal(-1, winwidth(-1)) + + tabnew + call assert_equal(8, tabpagewinnr(1, 'j')) + call assert_equal(2, 1->tabpagewinnr('k')) + call assert_equal(4, tabpagewinnr(1, 'h')) + call assert_equal(6, tabpagewinnr(1, 'l')) + + only | tabonly +endfunc + +func Test_winrestview() + split runtest.vim + normal 50% + let view = winsaveview() + close + split runtest.vim + eval view->winrestview() + call assert_equal(view, winsaveview()) + + bwipe! + call assert_fails('call winrestview(v:_null_dict)', 'E1297:') +endfunc + +func Test_win_splitmove() + CheckFeature quickfix + + edit a + leftabove split b + leftabove vsplit c + leftabove split d + call assert_equal(0, win_splitmove(winnr(), winnr('l'))) + call assert_equal(bufname(winbufnr(1)), 'c') + call assert_equal(bufname(winbufnr(2)), 'd') + call assert_equal(bufname(winbufnr(3)), 'b') + call assert_equal(bufname(winbufnr(4)), 'a') + call assert_equal(0, win_splitmove(winnr(), winnr('j'), {'vertical': 1})) + call assert_equal(0, win_splitmove(winnr(), winnr('j'), {'vertical': 1})) + call assert_equal(bufname(winbufnr(1)), 'c') + call assert_equal(bufname(winbufnr(2)), 'b') + call assert_equal(bufname(winbufnr(3)), 'd') + call assert_equal(bufname(winbufnr(4)), 'a') + call assert_equal(0, win_splitmove(winnr(), winnr('k'), {'vertical': 1})) + call assert_equal(bufname(winbufnr(1)), 'd') + call assert_equal(bufname(winbufnr(2)), 'c') + call assert_equal(bufname(winbufnr(3)), 'b') + call assert_equal(bufname(winbufnr(4)), 'a') + call assert_equal(0, win_splitmove(winnr(), winnr('j'), {'rightbelow': v:true})) + call assert_equal(bufname(winbufnr(1)), 'c') + call assert_equal(bufname(winbufnr(2)), 'b') + call assert_equal(bufname(winbufnr(3)), 'a') + call assert_equal(bufname(winbufnr(4)), 'd') + call assert_fails('call win_splitmove(winnr(), winnr("k"), v:_null_dict)', 'E1297:') + only | bd + + call assert_fails('call win_splitmove(winnr(), 123)', 'E957:') + call assert_fails('call win_splitmove(123, winnr())', 'E957:') + call assert_fails('call win_splitmove(winnr(), winnr())', 'E957:') + + tabnew + call assert_fails('call win_splitmove(1, win_getid(1, 1))', 'E957:') + tabclose +endfunc + +func Test_floatwin_splitmove() + vsplit + let win2 = win_getid() + let popup_winid = nvim_open_win(0, 0, {'relative': 'win', + \ 'row': 3, 'col': 3, 'width': 12, 'height': 3}) + call assert_fails('call win_splitmove(popup_winid, win2)', 'E957:') + call assert_fails('call win_splitmove(win2, popup_winid)', 'E957:') + + call nvim_win_close(popup_winid, 1) + bwipe +endfunc + +" Test for the :only command +func Test_window_only() + new + set modified + new + call assert_fails('only', 'E445:') + only! + " Test for :only with a count + let wid = win_getid() + new + new + 3only + call assert_equal(1, winnr('$')) + call assert_equal(wid, win_getid()) + call assert_fails('close', 'E444:') + call assert_fails('%close', 'E16:') +endfunc + +" Test for errors with :wincmd +func Test_wincmd_errors() + call assert_fails('wincmd g', 'E474:') + call assert_fails('wincmd ab', 'E474:') +endfunc + +" Test for errors with :winpos +func Test_winpos_errors() + throw 'Skipped: Nvim does not have :winpos' + if !has("gui_running") && !has('win32') + call assert_fails('winpos', 'E188:') + endif + call assert_fails('winpos 10', 'E466:') +endfunc + +" Test for +cmd in a :split command +func Test_split_cmd() + split +set\ readonly + call assert_equal(1, &readonly) + call assert_equal(2, winnr('$')) + close +endfunc + +" Create maximum number of horizontally or vertically split windows and then +" run commands that create a new horizontally/vertically split window +func Run_noroom_for_newwindow_test(dir_arg) + let dir = (a:dir_arg == 'v') ? 'vert ' : '' + + " Open as many windows as possible + for i in range(500) + try + exe dir . 'new' + catch /E36:/ + break + endtry + endfor + + call writefile(['first', 'second', 'third'], 'Xfile1') + call writefile([], 'Xfile2') + call writefile([], 'Xfile3') + + " Argument list related commands + args Xfile1 Xfile2 Xfile3 + next + for cmd in ['sargument 2', 'snext', 'sprevious', 'sNext', 'srewind', + \ 'sfirst', 'slast'] + call assert_fails(dir .. cmd, 'E36:') + endfor + %argdelete + + " Buffer related commands + set modified + hide enew + for cmd in ['sbuffer Xfile1', 'sbnext', 'sbprevious', 'sbNext', 'sbrewind', + \ 'sbfirst', 'sblast', 'sball', 'sbmodified', 'sunhide'] + call assert_fails(dir .. cmd, 'E36:') + endfor + + " Window related commands + for cmd in ['split', 'split Xfile2', 'new', 'new Xfile3', 'sview Xfile1', + \ 'sfind runtest.vim'] + call assert_fails(dir .. cmd, 'E36:') + endfor + + " Help + call assert_fails(dir .. 'help', 'E36:') + call assert_fails(dir .. 'helpgrep window', 'E36:') + + " Command-line window + if a:dir_arg == 'h' + " Cmd-line window is always a horizontally split window + call assert_beeps('call feedkeys("q:\<CR>", "xt")') + endif + + " Quickfix and location list window + if has('quickfix') + cexpr '' + call assert_fails(dir .. 'copen', 'E36:') + lexpr '' + call assert_fails(dir .. 'lopen', 'E36:') + + " Preview window + call assert_fails(dir .. 'pedit Xfile2', 'E36:') + call setline(1, 'abc') + call assert_fails(dir .. 'psearch abc', 'E36:') + endif + + " Window commands (CTRL-W ^ and CTRL-W f) + if a:dir_arg == 'h' + call assert_fails('call feedkeys("\<C-W>^", "xt")', 'E36:') + call setline(1, 'Xfile1') + call assert_fails('call feedkeys("gg\<C-W>f", "xt")', 'E36:') + endif + enew! + + " Tag commands (:stag, :stselect and :stjump) + call writefile(["!_TAG_FILE_ENCODING\tutf-8\t//", + \ "second\tXfile1\t2", + \ "third\tXfile1\t3",], + \ 'Xtags') + set tags=Xtags + call assert_fails(dir .. 'stag second', 'E36:') + call assert_fails('call feedkeys(":" .. dir .. "stselect second\n1\n", "xt")', 'E36:') + call assert_fails(dir .. 'stjump second', 'E36:') + call assert_fails(dir .. 'ptag second', 'E36:') + set tags& + call delete('Xtags') + + " :isplit and :dsplit + call setline(1, ['#define FOO 1', 'FOO']) + normal 2G + call assert_fails(dir .. 'isplit FOO', 'E36:') + call assert_fails(dir .. 'dsplit FOO', 'E36:') + + " terminal + if has('terminal') + call assert_fails(dir .. 'terminal', 'E36:') + endif + + %bwipe! + call delete('Xfile1') + call delete('Xfile2') + call delete('Xfile3') + only +endfunc + +func Test_split_cmds_with_no_room() + call Run_noroom_for_newwindow_test('h') + call Run_noroom_for_newwindow_test('v') +endfunc + +" Test for various wincmd failures +func Test_wincmd_fails() + only! + call assert_beeps("normal \<C-W>w") + call assert_beeps("normal \<C-W>p") + call assert_beeps("normal \<C-W>gk") + call assert_beeps("normal \<C-W>r") + call assert_beeps("normal \<C-W>K") + call assert_beeps("normal \<C-W>H") + call assert_beeps("normal \<C-W>2gt") +endfunc + +func Test_window_resize() + " Vertical :resize (absolute, relative, min and max size). + vsplit + vert resize 8 + call assert_equal(8, winwidth(0)) + vert resize +2 + call assert_equal(10, winwidth(0)) + vert resize -2 + call assert_equal(8, winwidth(0)) + vert resize + call assert_equal(&columns - 2, winwidth(0)) + vert resize 0 + call assert_equal(1, winwidth(0)) + vert resize 99999 + call assert_equal(&columns - 2, winwidth(0)) + + %bwipe! + + " Horizontal :resize (with absolute, relative size, min and max size). + split + resize 8 + call assert_equal(8, winheight(0)) + resize +2 + call assert_equal(10, winheight(0)) + resize -2 + call assert_equal(8, winheight(0)) + resize + call assert_equal(&lines - 4, winheight(0)) + resize 0 + call assert_equal(1, winheight(0)) + resize 99999 + call assert_equal(&lines - 4, winheight(0)) + + " :resize with explicit window number. + let other_winnr = winnr('j') + exe other_winnr .. 'resize 10' + call assert_equal(10, winheight(other_winnr)) + call assert_equal(&lines - 10 - 3, winheight(0)) + exe other_winnr .. 'resize +1' + exe other_winnr .. 'resize +1' + call assert_equal(12, winheight(other_winnr)) + call assert_equal(&lines - 10 - 3 -2, winheight(0)) + close + + vsplit + wincmd l + let other_winnr = winnr('h') + call assert_notequal(winnr(), other_winnr) + exe 'vert ' .. other_winnr .. 'resize -' .. &columns + call assert_equal(0, winwidth(other_winnr)) + + %bwipe! +endfunc + +" Test for adjusting the window width when a window is closed with some +" windows using 'winfixwidth' +func Test_window_width_adjust() + only + " Three vertical windows. Windows 1 and 2 have 'winfixwidth' set and close + " window 2. + wincmd v + vert resize 10 + set winfixwidth + wincmd v + set winfixwidth + wincmd c + call assert_inrange(10, 12, winwidth(1)) + " Three vertical windows. Windows 2 and 3 have 'winfixwidth' set and close + " window 3. + only + set winfixwidth + wincmd v + vert resize 10 + set winfixwidth + wincmd v + set nowinfixwidth + wincmd b + wincmd c + call assert_inrange(10, 12, winwidth(2)) + + new | only +endfunc + +" Test for jumping to a vertical/horizontal neighbor window based on the +" current cursor position +func Test_window_goto_neighbor() + %bw! + + " Vertical window movement + + " create the following window layout: + " +--+--+ + " |w1|w3| + " +--+ | + " |w2| | + " +--+--+ + " |w4 | + " +-----+ + new + vsplit + split + " vertically jump from w4 + wincmd b + call setline(1, repeat(' ', &columns)) + call cursor(1, 1) + wincmd k + call assert_equal(2, winnr()) + wincmd b + call cursor(1, &columns) + redraw! + wincmd k + call assert_equal(3, winnr()) + %bw! + + " create the following window layout: + " +--+--+--+ + " |w1|w2|w3| + " +--+--+--+ + " |w4 | + " +--------+ + new + vsplit + vsplit + wincmd b + call setline(1, repeat(' ', &columns)) + call cursor(1, 1) + wincmd k + call assert_equal(1, winnr()) + wincmd b + call cursor(1, &columns / 2) + redraw! + wincmd k + call assert_equal(2, winnr()) + wincmd b + call cursor(1, &columns) + redraw! + wincmd k + call assert_equal(3, winnr()) + %bw! + + " Horizontal window movement + + " create the following window layout: + " +--+--+--+ + " |w1|w2|w4| + " +--+--+ | + " |w3 | | + " +-----+--+ + vsplit + split + vsplit + 4wincmd l + call setline(1, repeat([' '], &lines)) + call cursor(1, 1) + redraw! + wincmd h + call assert_equal(2, winnr()) + 4wincmd l + call cursor(&lines, 1) + redraw! + wincmd h + call assert_equal(3, winnr()) + %bw! + + " create the following window layout: + " +--+--+ + " |w1|w4| + " +--+ + + " |w2| | + " +--+ + + " |w3| | + " +--+--+ + vsplit + split + split + wincmd l + call setline(1, repeat([' '], &lines)) + call cursor(1, 1) + redraw! + wincmd h + call assert_equal(1, winnr()) + wincmd l + call cursor(&lines / 2, 1) + redraw! + wincmd h + call assert_equal(2, winnr()) + wincmd l + call cursor(&lines, 1) + redraw! + wincmd h + call assert_equal(3, winnr()) + %bw! +endfunc + +" Test for an autocmd closing the destination window when jumping from one +" window to another. +func Test_close_dest_window() + split + edit Xfile + + " Test for BufLeave + augroup T1 + au! + au BufLeave Xfile $wincmd c + augroup END + wincmd b + call assert_equal(1, winnr('$')) + call assert_equal('Xfile', @%) + augroup T1 + au! + augroup END + + " Test for WinLeave + new + wincmd p + augroup T1 + au! + au WinLeave * 1wincmd c + augroup END + wincmd t + call assert_equal(1, winnr('$')) + call assert_equal('Xfile', @%) + augroup T1 + au! + augroup END + augroup! T1 + %bw! +endfunc + +func Test_win_move_separator() + edit a + leftabove vsplit b + let w = winwidth(0) + " check win_move_separator from left window on left window + call assert_equal(1, winnr()) + for offset in range(5) + call assert_true(win_move_separator(0, offset)) + call assert_equal(w + offset, winwidth(0)) + call assert_true(0->win_move_separator(-offset)) + call assert_equal(w, winwidth(0)) + endfor + " check win_move_separator from right window on left window number + wincmd l + call assert_notequal(1, winnr()) + for offset in range(5) + call assert_true(1->win_move_separator(offset)) + call assert_equal(w + offset, winwidth(1)) + call assert_true(win_move_separator(1, -offset)) + call assert_equal(w, winwidth(1)) + endfor + " check win_move_separator from right window on left window ID + let id = win_getid(1) + for offset in range(5) + call assert_true(win_move_separator(id, offset)) + call assert_equal(w + offset, winwidth(id)) + call assert_true(id->win_move_separator(-offset)) + call assert_equal(w, winwidth(id)) + endfor + " check win_move_separator from right window on right window is no-op + let w0 = winwidth(0) + call assert_true(win_move_separator(0, 1)) + call assert_equal(w0, winwidth(0)) + call assert_true(win_move_separator(0, -1)) + call assert_equal(w0, winwidth(0)) + + " check that win_move_separator doesn't error with offsets beyond moving + " possibility + call assert_true(win_move_separator(id, 5000)) + call assert_true(winwidth(id) > w) + call assert_true(win_move_separator(id, -5000)) + call assert_true(winwidth(id) < w) + + " check that win_move_separator returns false for an invalid window + wincmd = + let w = winwidth(0) + call assert_false(win_move_separator(-1, 1)) + call assert_equal(w, winwidth(0)) + + " check that win_move_separator returns false for a floating window + let id = nvim_open_win( + \ 0, 0, #{relative: 'editor', row: 2, col: 2, width: 5, height: 3}) + let w = winwidth(id) + call assert_false(win_move_separator(id, 1)) + call assert_equal(w, winwidth(id)) + call nvim_win_close(id, 1) + + " check that using another tabpage fails without crash + let id = win_getid() + tabnew + call assert_fails('call win_move_separator(id, -1)', 'E1308:') + tabclose + + %bwipe! +endfunc + +func Test_win_move_statusline() + edit a + leftabove split b + let h = winheight(0) + " check win_move_statusline from top window on top window + call assert_equal(1, winnr()) + for offset in range(5) + call assert_true(win_move_statusline(0, offset)) + call assert_equal(h + offset, winheight(0)) + call assert_true(0->win_move_statusline(-offset)) + call assert_equal(h, winheight(0)) + endfor + " check win_move_statusline from bottom window on top window number + wincmd j + call assert_notequal(1, winnr()) + for offset in range(5) + call assert_true(1->win_move_statusline(offset)) + call assert_equal(h + offset, winheight(1)) + call assert_true(win_move_statusline(1, -offset)) + call assert_equal(h, winheight(1)) + endfor + " check win_move_statusline from bottom window on bottom window + let h0 = winheight(0) + for offset in range(5) + call assert_true(0->win_move_statusline(-offset)) + call assert_equal(h0 - offset, winheight(0)) + call assert_equal(1 + offset, &cmdheight) + call assert_true(win_move_statusline(0, offset)) + call assert_equal(h0, winheight(0)) + call assert_equal(1, &cmdheight) + endfor + " supports cmdheight=0 + set cmdheight=0 + call assert_true(win_move_statusline(0, 1)) + call assert_equal(h0 + 1, winheight(0)) + call assert_equal(0, &cmdheight) + set cmdheight& + " check win_move_statusline from bottom window on top window ID + let id = win_getid(1) + for offset in range(5) + call assert_true(win_move_statusline(id, offset)) + call assert_equal(h + offset, winheight(id)) + call assert_true(id->win_move_statusline(-offset)) + call assert_equal(h, winheight(id)) + endfor + + " check that win_move_statusline doesn't error with offsets beyond moving + " possibility + call assert_true(win_move_statusline(id, 5000)) + call assert_true(winheight(id) > h) + call assert_true(win_move_statusline(id, -5000)) + call assert_true(winheight(id) < h) + + " check that win_move_statusline returns false for an invalid window + wincmd = + let h = winheight(0) + call assert_false(win_move_statusline(-1, 1)) + call assert_equal(h, winheight(0)) + + " check that win_move_statusline returns false for a floating window + let id = nvim_open_win( + \ 0, 0, #{relative: 'editor', row: 2, col: 2, width: 5, height: 3}) + let h = winheight(id) + call assert_false(win_move_statusline(id, 1)) + call assert_equal(h, winheight(id)) + call nvim_win_close(id, 1) + + " check that using another tabpage fails without crash + let id = win_getid() + tabnew + call assert_fails('call win_move_statusline(id, -1)', 'E1308:') + tabclose + + %bwipe! +endfunc + +" Test for window allocation failure +func Test_window_alloc_failure() + CheckFunction test_alloc_fail + %bw! + + " test for creating a new window above current window + call test_alloc_fail(GetAllocId('newwin_wvars'), 0, 0) + call assert_fails('above new', 'E342:') + call assert_equal(1, winnr('$')) + + " test for creating a new window below current window + call test_alloc_fail(GetAllocId('newwin_wvars'), 0, 0) + call assert_fails('below new', 'E342:') + call assert_equal(1, winnr('$')) + + " test for popup window creation failure + call test_alloc_fail(GetAllocId('newwin_wvars'), 0, 0) + call assert_fails('call popup_create("Hello", {})', 'E342:') + call assert_equal([], popup_list()) + + call test_alloc_fail(GetAllocId('newwin_wvars'), 0, 0) + call assert_fails('split', 'E342:') + call assert_equal(1, winnr('$')) + + edit Xfile1 + edit Xfile2 + call test_alloc_fail(GetAllocId('newwin_wvars'), 0, 0) + call assert_fails('sb Xfile1', 'E342:') + call assert_equal(1, winnr('$')) + call assert_equal('Xfile2', @%) + %bw! + + " FIXME: The following test crashes Vim + " test for new tabpage creation failure + " call test_alloc_fail(GetAllocId('newwin_wvars'), 0, 0) + " call assert_fails('tabnew', 'E342:') + " call assert_equal(1, tabpagenr('$')) + " call assert_equal(1, winnr('$')) + + " This test messes up the internal Vim window/frame information. So the + " Test_window_cmd_cmdwin_with_vsp() test fails after running this test. + " Open a new tab and close everything else to fix this issue. + tabnew + tabonly +endfunc + +func Test_win_equal_last_status() + let save_lines = &lines + set lines=20 + set splitbelow + set laststatus=0 + + split | split | quit + call assert_equal(winheight(1), winheight(2)) + + let &lines = save_lines + set splitbelow& + set laststatus& +endfunc + +" Test "screen" and "cursor" values for 'splitkeep' with a sequence of +" split operations for various options: with and without a winbar, +" tabline, for each possible value of 'laststatus', 'scrolloff', +" 'equalalways', and with the cursor at the top, middle and bottom. +func Test_splitkeep_options() + " disallow window resizing + " let save_WS = &t_WS + " set t_WS= + + let gui = has("gui_running") + inoremap <expr> c "<cmd>copen<bar>wincmd k<CR>" + for run in range(0, 20) + let &splitkeep = run > 10 ? 'topline' : 'screen' + let &scrolloff = (!(run % 4) ? 0 : run) + let &laststatus = (run % 3) + let &splitbelow = (run % 3) + let &equalalways = (run % 2) + " Nvim: both windows have a winbar after splitting + " let wsb = (run % 2) && &splitbelow + let wsb = 0 + let tl = (gui ? 0 : ((run % 5) ? 1 : 0)) + let pos = !(run % 3) ? 'H' : ((run % 2) ? 'M' : 'L') + tabnew | tabonly! | redraw + execute (run % 5) ? 'tabnew' : '' + " execute (run % 2) ? 'nnoremenu 1.10 WinBar.Test :echo' : '' + let &winbar = (run % 2) ? '%f' : '' + call setline(1, range(1, 256)) + " No scroll for restore_snapshot + norm G + try + copen | close | colder + catch /E380/ + endtry + call assert_equal(257 - winheight(0), line("w0")) + + " No scroll for firstwin horizontal split + execute 'norm gg' . pos + split | redraw | wincmd k + call assert_equal(1, line("w0")) + call assert_equal(&scroll, winheight(0) / 2) + wincmd j + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + + " No scroll when resizing windows + wincmd k | resize +2 | redraw + call assert_equal(1, line("w0")) + wincmd j + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + + " No scroll when dragging statusline + call win_move_statusline(1, -3) + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + wincmd k + call assert_equal(1, line("w0")) + + " No scroll when changing shellsize + set lines+=2 + call assert_equal(1, line("w0")) + wincmd j + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + set lines-=2 + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + wincmd k + call assert_equal(1, line("w0")) + + " No scroll when equalizing windows + wincmd = + call assert_equal(1, line("w0")) + wincmd j + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + wincmd k + call assert_equal(1, line("w0")) + + " No scroll in windows split multiple times + vsplit | split | 4wincmd w + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + 1wincmd w | quit | wincmd l | split + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + wincmd j + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + + " No scroll in small window + 2wincmd w | only | 5split | wincmd k + call assert_equal(1, line("w0")) + wincmd j + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + + " No scroll for vertical split + quit | vsplit | wincmd l + call assert_equal(1, line("w0")) + wincmd h + call assert_equal(1, line("w0")) + + " No scroll in windows split and quit multiple times + quit | redraw | split | split | quit | redraw + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl - wsb, line("w0")) + + " No scroll for new buffer + 1wincmd w | only | copen | wincmd k + call assert_equal(1, line("w0")) + only + call assert_equal(1, line("w0")) + above copen | wincmd j + call assert_equal(&spk == 'topline' ? 1 : win_screenpos(0)[0] - tl, line("w0")) + + " No scroll when opening cmdwin, and no cursor move when closing cmdwin. + only | norm ggL + let curpos = getcurpos() + norm q: + call assert_equal(1, line("w0")) + call assert_equal(curpos, getcurpos()) + + " Scroll when cursor becomes invalid in insert mode. + norm Lic + call assert_equal(curpos, getcurpos(), 'run ' .. run) + + " No scroll when topline not equal to 1 + only | execute "norm gg5\<C-e>" | split | wincmd k + call assert_equal(6, line("w0")) + wincmd j + call assert_equal(&spk == 'topline' ? 6 : 5 + win_screenpos(0)[0] - tl - wsb, line("w0")) + endfor + + tabnew | tabonly! | %bwipeout! + iunmap c + set scrolloff& + set splitbelow& + set laststatus& + set equalalways& + set splitkeep& + " let &t_WS = save_WS +endfunc + +func Test_splitkeep_cmdwin_cursor_position() + set splitkeep=screen + call setline(1, range(&lines)) + + " No scroll when cursor is at near bottom of window and cusor position + " recompution (done by line('w0') in this test) happens while in cmdwin. + normal! G + let firstline = line('w0') + autocmd CmdwinEnter * ++once autocmd WinEnter * ++once call line('w0') + execute "normal! q:\<C-w>q" + redraw! + call assert_equal(firstline, line('w0')) + + " User script can change cursor position successfully while in cmdwin and it + " shouldn't be changed when closing cmdwin. + execute "normal! Gq:\<Cmd>call win_execute(winnr('#')->win_getid(), 'call cursor(1, 1)')\<CR>\<C-w>q" + call assert_equal(1, line('.')) + call assert_equal(1, col('.')) + + execute "normal! Gq:\<Cmd>autocmd WinEnter * ++once call cursor(1, 1)\<CR>\<C-w>q" + call assert_equal(1, line('.')) + call assert_equal(1, col('.')) + + %bwipeout! + set splitkeep& +endfunc + +func Test_splitkeep_misc() + set splitkeep=screen + + call setline(1, range(1, &lines)) + " Cursor is adjusted to start and end of buffer + norm M + wincmd s + resize 1 + call assert_equal(1, line('.')) + wincmd j + norm GM + resize 1 + call assert_equal(&lines, line('.')) + only! + + set splitbelow + norm Gzz + let top = line('w0') + " No scroll when aucmd_win is opened + call setbufvar(bufnr("test", 1) , '&buftype', 'nofile') + call assert_equal(top, line('w0')) + " No scroll when tab is changed/closed + tab help | close + call assert_equal(top, line('w0')) + " No scroll when help is closed and buffer line count < window height + norm ggdG + call setline(1, range(1, &lines - 10)) + norm G + let top = line('w0') + help | quit + call assert_equal(top, line('w0')) + " No error when resizing window in autocmd and buffer length changed + autocmd FileType qf exe "resize" line('$') + cexpr getline(1, '$') + copen + wincmd p + norm dd + cexpr getline(1, '$') + + %bwipeout! + set splitbelow& + set splitkeep& +endfunc + +func Test_splitkeep_cursor() + CheckScreendump + let lines =<< trim END + set splitkeep=screen + autocmd CursorMoved * wincmd p | wincmd p + call setline(1, range(1, 200)) + func CursorEqualize() + call cursor(100, 1) + wincmd = + endfunc + wincmd s + call CursorEqualize() + END + call writefile(lines, 'XTestSplitkeepCallback', 'D') + let buf = RunVimInTerminal('-S XTestSplitkeepCallback', #{rows: 8}) + + call VerifyScreenDump(buf, 'Test_splitkeep_cursor_1', {}) + + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_splitkeep_cursor_2', {}) + + call term_sendkeys(buf, ":set scrolloff=0\<CR>G") + call VerifyScreenDump(buf, 'Test_splitkeep_cursor_3', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_splitkeep_callback() + CheckScreendump + let lines =<< trim END + set splitkeep=screen + call setline(1, range(&lines)) + function C1(a, b) + split | wincmd p + endfunction + function C2(a, b) + close | split + endfunction + nn j <cmd>call job_start([&sh, &shcf, "true"], { 'exit_cb': 'C1' })<CR> + nn t <cmd>call popup_create(term_start([&sh, &shcf, "true"], + \ { 'hidden': 1, 'exit_cb': 'C2' }), {})<CR> + END + call writefile(lines, 'XTestSplitkeepCallback', 'D') + let buf = RunVimInTerminal('-S XTestSplitkeepCallback', #{rows: 8}) + + call term_sendkeys(buf, "j") + call VerifyScreenDump(buf, 'Test_splitkeep_callback_1', {}) + + call term_sendkeys(buf, ":quit\<CR>Ht") + call VerifyScreenDump(buf, 'Test_splitkeep_callback_2', {}) + + call term_sendkeys(buf, ":set sb\<CR>:quit\<CR>Gj") + call VerifyScreenDump(buf, 'Test_splitkeep_callback_3', {}) + + call term_sendkeys(buf, ":quit\<CR>Gt") + call VerifyScreenDump(buf, 'Test_splitkeep_callback_4', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_splitkeep_fold() + CheckScreendump + + let lines =<< trim END + set splitkeep=screen + set foldmethod=marker + set number + let line = 1 + for n in range(1, &lines) + call setline(line, ['int FuncName() {/*{{{*/', 1, 2, 3, 4, 5, '}/*}}}*/', + \ 'after fold']) + let line += 8 + endfor + END + call writefile(lines, 'XTestSplitkeepFold', 'D') + let buf = RunVimInTerminal('-S XTestSplitkeepFold', #{rows: 10}) + + call term_sendkeys(buf, "L:wincmd s\<CR>") + call VerifyScreenDump(buf, 'Test_splitkeep_fold_1', {}) + + call term_sendkeys(buf, ":quit\<CR>") + call VerifyScreenDump(buf, 'Test_splitkeep_fold_2', {}) + + call term_sendkeys(buf, "H:below split\<CR>") + call VerifyScreenDump(buf, 'Test_splitkeep_fold_3', {}) + + call term_sendkeys(buf, ":wincmd k\<CR>:quit\<CR>") + call VerifyScreenDump(buf, 'Test_splitkeep_fold_4', {}) + + call StopVimInTerminal(buf) +endfunc + +func Test_splitkeep_status() + CheckScreendump + + let lines =<< trim END + call setline(1, ['a', 'b', 'c']) + set nomodified + set splitkeep=screen + let win = winnr() + wincmd s + wincmd j + END + call writefile(lines, 'XTestSplitkeepStatus', 'D') + let buf = RunVimInTerminal('-S XTestSplitkeepStatus', #{rows: 10}) + + call term_sendkeys(buf, ":call win_move_statusline(win, 1)\<CR>") + call VerifyScreenDump(buf, 'Test_splitkeep_status_1', {}) + + call StopVimInTerminal(buf) +endfunc + +" skipcol is not reset unnecessarily and is copied to new window +func Test_splitkeep_skipcol() + CheckScreendump + + let lines =<< trim END + set splitkeep=topline smoothscroll splitbelow scrolloff=0 + call setline(1, 'with lots of text in one line '->repeat(6)) + norm 2 + wincmd s + END + + call writefile(lines, 'XTestSplitkeepSkipcol', 'D') + let buf = RunVimInTerminal('-S XTestSplitkeepSkipcol', #{rows: 12, cols: 40}) + + call VerifyScreenDump(buf, 'Test_splitkeep_skipcol_1', {}) +endfunc + +func Test_new_help_window_on_error() + help change.txt + execute "normal! /CTRL-@\<CR>" + silent! execute "normal! \<C-W>]" + + let wincount = winnr('$') + help 'mod' + + call assert_equal(wincount, winnr('$')) + call assert_equal(expand("<cword>"), "'mod'") +endfunc + +func Test_smoothscroll_in_zero_width_window() + let save_lines = &lines + let save_columns = &columns + + winsize 0 24 + set cpo+=n + exe "noremap 0 \<C-W>n\<C-W>L" + norm 000000 + set number smoothscroll + exe "norm \<C-Y>" + + only! + let &lines = save_lines + let &columns = save_columns + set cpo-=n + unmap 0 + set nonumber nosmoothscroll +endfunc + + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_window_id.vim b/test/old/testdir/test_window_id.vim new file mode 100644 index 0000000000..396a49b55f --- /dev/null +++ b/test/old/testdir/test_window_id.vim @@ -0,0 +1,142 @@ +" Test using the window ID. + +source check.vim + +func Test_win_getid() + edit one + let id1 = win_getid() + let w:one = 'one' + split two + let id2 = win_getid() + let bufnr2 = bufnr('%') + let w:two = 'two' + split three + let id3 = win_getid() + let w:three = 'three' + tabnew + edit four + let id4 = win_getid() + let w:four = 'four' + split five + let id5 = win_getid() + let bufnr5 = bufnr('%') + let w:five = 'five' + tabnext + + wincmd w + call assert_equal("two", expand("%")) + call assert_equal(id2, win_getid()) + let nr2 = winnr() + wincmd w + call assert_equal("one", expand("%")) + call assert_equal(id1, win_getid()) + let nr1 = winnr() + wincmd w + call assert_equal("three", expand("%")) + call assert_equal(id3, win_getid()) + let nr3 = winnr() + call assert_equal('one', getwinvar(id1, 'one')) + call assert_equal('two', getwinvar(id2, 'two')) + call assert_equal('three', getwinvar(id3, 'three')) + tabnext + call assert_equal("five", expand("%")) + call assert_equal(id5, win_getid()) + let nr5 = winnr() + wincmd w + call assert_equal("four", expand("%")) + call assert_equal(id4, win_getid()) + let nr4 = winnr() + call assert_equal('four', getwinvar(id4, 'four')) + call assert_equal('five', getwinvar(id5, 'five')) + call settabwinvar(1, id2, 'two', '2') + call setwinvar(id4, 'four', '4') + tabnext + call assert_equal('4', gettabwinvar(2, id4, 'four')) + call assert_equal('five', gettabwinvar(2, id5, 'five')) + call assert_equal('2', getwinvar(id2, 'two')) + + exe nr1 . "wincmd w" + call assert_equal(id1, win_getid()) + exe nr2 . "wincmd w" + call assert_equal(id2, win_getid()) + exe nr3 . "wincmd w" + call assert_equal(id3, win_getid()) + tabnext + exe nr4 . "wincmd w" + call assert_equal(id4, win_getid()) + exe nr5 . "wincmd w" + call assert_equal(id5, win_getid()) + + call win_gotoid(id2) + call assert_equal("two", expand("%")) + eval id4->win_gotoid() + call assert_equal("four", expand("%")) + call win_gotoid(id1) + call assert_equal("one", expand("%")) + call win_gotoid(id5) + call assert_equal("five", expand("%")) + + call assert_equal(0, win_id2win(9999)) + call assert_equal(nr5, id5->win_id2win()) + call assert_equal(0, win_id2win(id1)) + tabnext + call assert_equal(nr1, win_id2win(id1)) + + call assert_equal([0, 0], win_id2tabwin(9999)) + call assert_equal([1, nr2], id2->win_id2tabwin()) + call assert_equal([2, nr4], win_id2tabwin(id4)) + + call assert_equal([], win_findbuf(9999)) + call assert_equal([id2], bufnr2->win_findbuf()) + call win_gotoid(id5) + split + call assert_equal(sort([id5, win_getid()]), sort(win_findbuf(bufnr5))) + + call assert_fails('let w = win_getid([])', 'E745:') + call assert_equal(0, win_getid(-1)) + call assert_equal(-1, win_getid(1, -1)) + + only! +endfunc + +func Test_win_getid_curtab() + CheckFeature quickfix + + tabedit X + tabfirst + copen + only + call assert_equal(win_getid(1), 1->win_getid( 1)) + tabclose! +endfunc + +func Test_winlayout() + let w1 = win_getid() + call assert_equal(['leaf', w1], winlayout()) + + split + let w2 = win_getid() + call assert_equal(['col', [['leaf', w2], ['leaf', w1]]], winlayout()) + + split + let w3 = win_getid() + call assert_equal(['col', [['leaf', w3], ['leaf', w2], ['leaf', w1]]], winlayout()) + + 2wincmd w + vsplit + let w4 = win_getid() + call assert_equal(['col', [['leaf', w3], ['row', [['leaf', w4], ['leaf', w2]]], ['leaf', w1]]], winlayout()) + + only! + + let w1 = win_getid() + call assert_equal(['leaf', w1], winlayout(1)) + tabnew + let w2 = win_getid() + call assert_equal(['leaf', w2], 2->winlayout()) + tabclose + + call assert_equal([], winlayout(-1)) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/test_windows_home.vim b/test/old/testdir/test_windows_home.vim new file mode 100644 index 0000000000..3c2db01444 --- /dev/null +++ b/test/old/testdir/test_windows_home.vim @@ -0,0 +1,120 @@ +" Test for $HOME on Windows. + +source check.vim +CheckMSWindows + +let s:env = {} + +func s:restore_env() + for i in keys(s:env) + exe 'let ' . i . '=s:env["' . i . '"]' + endfor +endfunc + +func s:save_env(...) + for i in a:000 + exe 'let s:env["' . i . '"]=' . i + endfor +endfunc + +func s:unlet_env(...) + for i in a:000 + exe 'let ' . i . '=""' + endfor +endfunc + +func CheckHomeIsMissingFromSubprocessEnvironment() + silent! let out = system('set') + let env = filter(split(out, "\n"), 'v:val=~"^HOME="') + call assert_equal(0, len(env)) +endfunc + +func CheckHomeIsInSubprocessEnvironment(exp) + silent! let out = system('set') + let env = filter(split(out, "\n"), 'v:val=~"^HOME="') + let home = len(env) == 0 ? "" : substitute(env[0], '[^=]\+=', '', '') + call assert_equal(a:exp, home) +endfunc + +func CheckHome(exp, ...) + call assert_equal(a:exp, $HOME) + call assert_equal(a:exp, expand('~', ':p')) + if !a:0 + call CheckHomeIsMissingFromSubprocessEnvironment() + else + call CheckHomeIsInSubprocessEnvironment(a:1) + endif +endfunc + +func Test_WindowsHome() + command! -nargs=* SaveEnv call <SID>save_env(<f-args>) + command! -nargs=* RestoreEnv call <SID>restore_env() + command! -nargs=* UnletEnv call <SID>unlet_env(<f-args>) + set noshellslash + + let save_home = $HOME + SaveEnv $USERPROFILE $HOMEDRIVE $HOMEPATH + try + " Normal behavior: use $HOMEDRIVE and $HOMEPATH, ignore $USERPROFILE + let $USERPROFILE = 'unused' + let $HOMEDRIVE = 'C:' + let $HOMEPATH = '\foobar' + let $HOME = '' " Force recomputing "homedir" + call CheckHome('C:\foobar') + + " Same, but with $HOMEPATH not set + UnletEnv $HOMEPATH + let $HOME = '' " Force recomputing "homedir" + call CheckHome('C:\') + + " Use $USERPROFILE if $HOMEPATH and $HOMEDRIVE are empty + UnletEnv $HOMEDRIVE $HOMEPATH + let $USERPROFILE = 'C:\foo' + let $HOME = '' " Force recomputing "homedir" + call CheckHome('C:\foo') + + " If $HOME is set the others don't matter + let $HOME = 'C:\bar' + let $USERPROFILE = 'unused' + let $HOMEDRIVE = 'unused' + let $HOMEPATH = 'unused' + call CheckHome('C:\bar', 'C:\bar') + + " If $HOME contains %USERPROFILE% it is expanded + let $USERPROFILE = 'C:\foo' + let $HOME = '%USERPROFILE%\bar' + let $HOMEDRIVE = 'unused' + let $HOMEPATH = 'unused' + call CheckHome('C:\foo\bar', '%USERPROFILE%\bar') + + " Invalid $HOME is kept + let $USERPROFILE = 'C:\foo' + let $HOME = '%USERPROFILE' + let $HOMEDRIVE = 'unused' + let $HOMEPATH = 'unused' + call CheckHome('%USERPROFILE', '%USERPROFILE') + + " %USERPROFILE% not at start of $HOME is not expanded + let $USERPROFILE = 'unused' + let $HOME = 'C:\%USERPROFILE%' + let $HOMEDRIVE = 'unused' + let $HOMEPATH = 'unused' + call CheckHome('C:\%USERPROFILE%', 'C:\%USERPROFILE%') + + if has('channel') + RestoreEnv + let $HOME = save_home + let env = '' + let job = job_start('cmd /c set', {'out_cb': {ch,x->[env,execute('let env=x')]}}) + sleep 1 + let env = filter(split(env, "\n"), 'v:val=="HOME"') + let home = len(env) == 0 ? "" : env[0] + call assert_equal('', home) + endif + finally + RestoreEnv + delcommand SaveEnv + delcommand RestoreEnv + delcommand UnletEnv + endtry +endfunc diff --git a/test/old/testdir/test_wnext.vim b/test/old/testdir/test_wnext.vim new file mode 100644 index 0000000000..3df61ceb78 --- /dev/null +++ b/test/old/testdir/test_wnext.vim @@ -0,0 +1,101 @@ +" Test :wnext :wNext and :wprevious + +func Test_wnext() + args X1 X2 + + call setline(1, '1') + wnext + call assert_equal(['1'], readfile('X1')) + call assert_equal('X2', bufname('%')) + + call setline(1, '2') + call assert_fails('wnext', 'E165:') + call assert_equal(['2'], readfile('X2')) + call assert_equal('X2', bufname('%')) + + " Test :wnext with a single file. + args X1 + call assert_equal('X1', bufname('%')) + call assert_fails('wnext', 'E163:') + + " Test :wnext with a count. + args X1 X2 X3 + call assert_equal('X1', bufname('%')) + 2wnext + call assert_equal('X3', bufname('%')) + + " Test :wnext {file}. + args X1 X2 X3 + wnext X4 + call assert_equal(['1'], readfile('X4')) + call assert_equal('X2', bufname('%')) + call assert_fails('wnext X4', 'E13:') + call assert_equal(['1'], readfile('X4')) + wnext! X4 + call assert_equal(['2'], readfile('X4')) + call assert_equal('X3', bufname('%')) + + args X1 X2 + " Commented out as, E13 occurs on Windows instead of E17 + "call assert_fails('wnext .', 'E17:') + call assert_fails('wnext! .', 'E502:') + + %bwipe! + call delete('X1') + call delete('X2') + call delete('X3') + call delete('X4') +endfunc + +func Test_wprevious() + args X1 X2 + + next + call assert_equal('X2', bufname('%')) + call setline(1, '2') + wprevious + call assert_equal(['2'], readfile('X2')) + call assert_equal('X1', bufname('%')) + + call setline(1, '1') + call assert_fails('wprevious', 'E164:') + call assert_fails('wNext', 'E164:') + + " Test :wprevious with a single file. + args X1 + call assert_fails('wprevious', 'E163:') + call assert_fails('wNext', 'E163:') + + " Test :wprevious with a count. + args X1 X2 X3 + 2next + call setline(1, '3') + call assert_equal('X3', bufname('%')) + 2wprevious + call assert_equal('X1', bufname('%')) + call assert_equal(['3'], readfile('X3')) + + " Test :wprevious {file} + args X1 X2 X3 + 2next + call assert_equal('X3', bufname('%')) + wprevious X4 + call assert_equal(['3'], readfile('X4')) + call assert_equal('X2', bufname('%')) + call assert_fails('wprevious X4', 'E13:') + call assert_equal(['3'], readfile('X4')) + wprevious! X4 + call assert_equal(['2'], readfile('X4')) + call assert_equal('X1', bufname('%')) + + args X1 X2 + " Commented out as, E13 occurs on Windows instead of E17 + "call assert_fails('wprevious .', 'E17:') + call assert_fails('wprevious! .', 'E502:') + + %bwipe! + call delete('X1') + call delete('X2') + call delete('X3') + call delete('X4') +endfunc diff --git a/test/old/testdir/test_wordcount.vim b/test/old/testdir/test_wordcount.vim new file mode 100644 index 0000000000..6a3d4109a8 --- /dev/null +++ b/test/old/testdir/test_wordcount.vim @@ -0,0 +1,104 @@ +" Test for wordcount() function + +func Test_wordcount() + let save_enc = &enc + set encoding=utf-8 + set selection=inclusive fileformat=unix fileformats=unix + + new + + " Test 1: empty window + call assert_equal({'chars': 0, 'cursor_chars': 0, 'words': 0, 'cursor_words': 0, + \ 'bytes': 0, 'cursor_bytes': 0}, wordcount()) + + " Test 2: some words, cursor at start + call append(1, 'one two three') + call cursor([1, 1, 0]) + call assert_equal({'chars': 15, 'cursor_chars': 1, 'words': 3, 'cursor_words': 0, + \ 'bytes': 15, 'cursor_bytes': 1}, wordcount()) + + " Test 3: some words, cursor at end + %d _ + call append(1, 'one two three') + call cursor([2, 99, 0]) + call assert_equal({'chars': 15, 'cursor_chars': 14, 'words': 3, 'cursor_words': 3, + \ 'bytes': 15, 'cursor_bytes': 14}, wordcount()) + + " Test 4: some words, cursor at end, ve=all + set ve=all + %d _ + call append(1, 'one two three') + call cursor([2, 99, 0]) + call assert_equal({'chars': 15, 'cursor_chars': 15, 'words': 3, 'cursor_words': 3, + \ 'bytes': 15, 'cursor_bytes': 15}, wordcount()) + set ve= + + " Test 5: several lines with words + %d _ + call append(1, ['one two three', 'one two three', 'one two three']) + call cursor([4, 99, 0]) + call assert_equal({'chars': 43, 'cursor_chars': 42, 'words': 9, 'cursor_words': 9, + \ 'bytes': 43, 'cursor_bytes': 42}, wordcount()) + + " Test 6: one line with BOM set + %d _ + call append(1, 'one two three') + set bomb + w! Xtest + call cursor([2, 99, 0]) + call assert_equal({'chars': 15, 'cursor_chars': 14, 'words': 3, 'cursor_words': 3, + \ 'bytes': 18, 'cursor_bytes': 14}, wordcount()) + set nobomb + w! + call delete('Xtest') + + " Test 7: one line with multibyte words + %d _ + call append(1, ['Äne M¤ne Müh']) + call cursor([2, 99, 0]) + call assert_equal({'chars': 14, 'cursor_chars': 13, 'words': 3, 'cursor_words': 3, + \ 'bytes': 17, 'cursor_bytes': 16}, wordcount()) + + " Test 8: several lines with multibyte words + %d _ + call append(1, ['Äne M¤ne Müh', 'und raus bist dü!']) + call cursor([3, 99, 0]) + call assert_equal({'chars': 32, 'cursor_chars': 31, 'words': 7, 'cursor_words': 7, + \ 'bytes': 36, 'cursor_bytes': 35}, wordcount()) + + " Visual map to capture wordcount() in visual mode + vnoremap <expr> <F2> execute("let g:visual_stat = wordcount()") + + " Test 9: visual mode, complete buffer + let g:visual_stat = {} + %d _ + call append(1, ['Äne M¤ne Müh', 'und raus bist dü!']) + " start visual mode and select the complete buffer + 0 + exe "normal V2j\<F2>y" + call assert_equal({'chars': 32, 'words': 7, 'bytes': 36, 'visual_chars': 32, + \ 'visual_words': 7, 'visual_bytes': 36}, g:visual_stat) + + " Test 10: visual mode (empty) + %d _ + call append(1, ['Äne M¤ne Müh', 'und raus bist dü!']) + " start visual mode and select the complete buffer + 0 + exe "normal v$\<F2>y" + call assert_equal({'chars': 32, 'words': 7, 'bytes': 36, 'visual_chars': 1, + \ 'visual_words': 0, 'visual_bytes': 1}, g:visual_stat) + + " Test 11: visual mode, single line + %d _ + call append(1, ['Äne M¤ne Müh', 'und raus bist dü!']) + " start visual mode and select the complete buffer + 2 + exe "normal 0v$\<F2>y" + call assert_equal({'chars': 32, 'words': 7, 'bytes': 36, 'visual_chars': 13, + \ 'visual_words': 3, 'visual_bytes': 16}, g:visual_stat) + + set selection& fileformat& fileformats& + let &enc = save_enc + enew! + close +endfunc diff --git a/test/old/testdir/test_writefile.vim b/test/old/testdir/test_writefile.vim new file mode 100644 index 0000000000..1e0556c92d --- /dev/null +++ b/test/old/testdir/test_writefile.vim @@ -0,0 +1,1016 @@ +" Tests for the writefile() function and some :write commands. + +source check.vim +source term_util.vim + +func Test_writefile() + let f = tempname() + call writefile(["over","written"], f, "b") + call writefile(["hello","world"], f, "b") + call writefile(["!", "good"], f, "a") + call writefile(["morning"], f, "ab") + call writefile(["", "vimmers"], f, "ab") + let l = readfile(f) + call assert_equal("hello", l[0]) + call assert_equal("world!", l[1]) + call assert_equal("good", l[2]) + call assert_equal("morning", l[3]) + call assert_equal("vimmers", l[4]) + call delete(f) + + call assert_fails('call writefile("text", "Xfile")', 'E475: Invalid argument: writefile() first argument must be a List or a Blob') +endfunc + +func Test_writefile_ignore_regexp_error() + write Xt[z-a]est.txt + call delete('Xt[z-a]est.txt') +endfunc + +func Test_writefile_fails_gently() + call assert_fails('call writefile(["test"], "Xfile", [])', 'E730:') + call assert_false(filereadable("Xfile")) + call delete("Xfile") + + call assert_fails('call writefile(["test", [], [], [], "tset"], "Xfile")', 'E745:') + call assert_false(filereadable("Xfile")) + call delete("Xfile") + + call assert_fails('call writefile([], "Xfile", [])', 'E730:') + call assert_false(filereadable("Xfile")) + call delete("Xfile") + + call assert_fails('call writefile([], [])', 'E730:') +endfunc + +func Test_writefile_fails_conversion() + if !has('iconv') || has('sun') + return + endif + " Without a backup file the write won't happen if there is a conversion + " error. + set nobackup nowritebackup backupdir=. backupskip= + new + let contents = ["line one", "line two"] + call writefile(contents, 'Xfile') + edit Xfile + call setline(1, ["first line", "cannot convert \u010b", "third line"]) + call assert_fails('write ++enc=cp932', 'E513:') + call assert_equal(contents, readfile('Xfile')) + + " With 'backupcopy' set, if there is a conversion error, the backup file is + " still created. + set backupcopy=yes writebackup& backup& + call delete('Xfile' .. &backupext) + call assert_fails('write ++enc=cp932', 'E513:') + call assert_equal(contents, readfile('Xfile')) + call assert_equal(contents, readfile('Xfile' .. &backupext)) + set backupcopy& + %bw! + + " Conversion error during write + new + call setline(1, ["\U10000000"]) + let output = execute('write! ++enc=utf-16 Xfile') + call assert_match('CONVERSION ERROR', output) + let output = execute('write! ++enc=ucs-2 Xfile') + call assert_match('CONVERSION ERROR', output) + call delete('Xfilz~') + call delete('Xfily~') + %bw! + + call delete('Xfile') + call delete('Xfile' .. &backupext) + bwipe! + set backup& writebackup& backupdir&vim backupskip&vim +endfunc + +func Test_writefile_fails_conversion2() + if !has('iconv') || has('sun') + return + endif + " With a backup file the write happens even if there is a conversion error, + " but then the backup file must remain + set nobackup writebackup backupdir=. backupskip= + let contents = ["line one", "line two"] + call writefile(contents, 'Xfile_conversion_err') + edit Xfile_conversion_err + call setline(1, ["first line", "cannot convert \u010b", "third line"]) + set fileencoding=latin1 + let output = execute('write') + call assert_match('CONVERSION ERROR', output) + call assert_equal(contents, readfile('Xfile_conversion_err~')) + + call delete('Xfile_conversion_err') + call delete('Xfile_conversion_err~') + bwipe! + set backup& writebackup& backupdir&vim backupskip&vim +endfunc + +func SetFlag(timer) + let g:flag = 1 +endfunc + +func Test_write_quit_split() + " Prevent exiting by splitting window on file write. + augroup testgroup + autocmd BufWritePre * split + augroup END + e! Xfile + call setline(1, 'nothing') + wq + + if has('timers') + " timer will not run if "exiting" is still set + let g:flag = 0 + call timer_start(1, 'SetFlag') + sleep 50m + call assert_equal(1, g:flag) + unlet g:flag + endif + au! testgroup + bwipe Xfile + call delete('Xfile') +endfunc + +func Test_nowrite_quit_split() + " Prevent exiting by opening a help window. + e! Xfile + help + wincmd w + exe winnr() . 'q' + + if has('timers') + " timer will not run if "exiting" is still set + let g:flag = 0 + call timer_start(1, 'SetFlag') + sleep 50m + call assert_equal(1, g:flag) + unlet g:flag + endif + bwipe Xfile +endfunc + +func Test_writefile_sync_arg() + " This doesn't check if fsync() works, only that the argument is accepted. + call writefile(['one'], 'Xtest', 's') + call writefile(['two'], 'Xtest', 'S') + call delete('Xtest') +endfunc + +func Test_writefile_sync_dev_stdout() + CheckUnix + if filewritable('/dev/stdout') + " Just check that this doesn't cause an error. + call writefile(['one'], '/dev/stdout', 's') + else + throw 'Skipped: /dev/stdout is not writable' + endif +endfunc + +func Test_writefile_autowrite() + set autowrite + new + next Xa Xb Xc + call setline(1, 'aaa') + next + call assert_equal(['aaa'], readfile('Xa')) + call setline(1, 'bbb') + call assert_fails('edit XX') + call assert_false(filereadable('Xb')) + + set autowriteall + edit XX + call assert_equal(['bbb'], readfile('Xb')) + + bwipe! + call delete('Xa') + call delete('Xb') + set noautowrite +endfunc + +func Test_writefile_autowrite_nowrite() + set autowrite + new + next Xa Xb Xc + set buftype=nowrite + call setline(1, 'aaa') + let buf = bufnr('%') + " buffer contents silently lost + edit XX + call assert_false(filereadable('Xa')) + rewind + call assert_equal('', getline(1)) + + bwipe! + set noautowrite +endfunc + +" Test for ':w !<cmd>' to pipe lines from the current buffer to an external +" command. +func Test_write_pipe_to_cmd() + CheckUnix + new + call setline(1, ['L1', 'L2', 'L3', 'L4']) + 2,3w !cat > Xfile + call assert_equal(['L2', 'L3'], readfile('Xfile')) + close! + call delete('Xfile') +endfunc + +" Test for :saveas +func Test_saveas() + call assert_fails('saveas', 'E471:') + call writefile(['L1'], 'Xfile') + new Xfile + new + call setline(1, ['L1']) + call assert_fails('saveas Xfile', 'E139:') + close! + enew | only + call delete('Xfile') + + " :saveas should detect and set the file type. + syntax on + saveas! Xsaveas.pl + call assert_equal('perl', &filetype) + syntax off + %bw! + call delete('Xsaveas.pl') + + " :saveas fails for "nofile" buffer + set buftype=nofile + call assert_fails('saveas Xsafile', 'E676: No matching autocommands for buftype=nofile buffer') + + bwipe! +endfunc + +func Test_write_errors() + " Test for writing partial buffer + call writefile(['L1', 'L2', 'L3'], 'Xfile') + new Xfile + call assert_fails('1,2write', 'E140:') + close! + + call assert_fails('w > Xtest', 'E494:') + + " Try to overwrite a directory + if has('unix') + call mkdir('Xdir1') + call assert_fails('write Xdir1', 'E17:') + call delete('Xdir1', 'd') + endif + + " Test for :wall for a buffer with no name + enew | only + call setline(1, ['L1']) + call assert_fails('wall', 'E141:') + enew! + + " Test for writing a 'readonly' file + new Xfile + set readonly + call assert_fails('write', 'E45:') + close + + " Test for writing to a read-only file + new Xfile + call setfperm('Xfile', 'r--r--r--') + call assert_fails('write', 'E505:') + call setfperm('Xfile', 'rw-rw-rw-') + close + + call delete('Xfile') + + " Nvim treats NULL list/blob more like empty list/blob + " call writefile(v:_null_list, 'Xfile') + " call assert_false(filereadable('Xfile')) + " call writefile(v:_null_blob, 'Xfile') + " call assert_false(filereadable('Xfile')) + call assert_fails('call writefile([], "")', 'E482:') + + " very long file name + let long_fname = repeat('n', 5000) + call assert_fails('exe "w " .. long_fname', 'E75:') + call assert_fails('call writefile([], long_fname)', 'E482:') + + " Test for writing to a block device on Unix-like systems + if has('unix') && getfperm('/dev/loop0') != '' + \ && getftype('/dev/loop0') == 'bdev' && !IsRoot() + new + edit /dev/loop0 + call assert_fails('write', 'E503: ') + call assert_fails('write!', 'E503: ') + close! + endif +endfunc + +" Test for writing to a file which is modified after Vim read it +func Test_write_file_mtime() + CheckEnglish + CheckRunVimInTerminal + + " First read the file into a buffer + call writefile(["Line1", "Line2"], 'Xfile') + let old_ftime = getftime('Xfile') + let buf = RunVimInTerminal('Xfile', #{rows : 10}) + call term_wait(buf) + call term_sendkeys(buf, ":set noswapfile\<CR>") + call term_wait(buf) + + " Modify the file directly. Make sure the file modification time is + " different. Note that on Linux/Unix, the file is considered modified + " outside, only if the difference is 2 seconds or more + sleep 1 + call writefile(["Line3", "Line4"], 'Xfile') + let new_ftime = getftime('Xfile') + while new_ftime - old_ftime < 2 + sleep 100m + call writefile(["Line3", "Line4"], 'Xfile') + let new_ftime = getftime('Xfile') + endwhile + + " Try to overwrite the file and check for the prompt + call term_sendkeys(buf, ":w\<CR>") + call term_wait(buf) + call WaitForAssert({-> assert_equal("WARNING: The file has been changed since reading it!!!", term_getline(buf, 9))}) + call assert_equal("Do you really want to write to it (y/n)?", + \ term_getline(buf, 10)) + call term_sendkeys(buf, "n\<CR>") + call term_wait(buf) + call assert_equal(new_ftime, getftime('Xfile')) + call term_sendkeys(buf, ":w\<CR>") + call term_wait(buf) + call term_sendkeys(buf, "y\<CR>") + call term_wait(buf) + call WaitForAssert({-> assert_equal('Line2', readfile('Xfile')[1])}) + + " clean up + call StopVimInTerminal(buf) + call delete('Xfile') +endfunc + +" Test for an autocmd unloading a buffer during a write command +func Test_write_autocmd_unloadbuf_lockmark() + augroup WriteTest + autocmd BufWritePre Xfile enew | write + augroup END + e Xfile + call assert_fails('lockmarks write', ['E32', 'E203:']) + augroup WriteTest + au! + augroup END + augroup! WriteTest +endfunc + +" Test for writing a buffer with 'acwrite' but without autocmds +func Test_write_acwrite_error() + new Xfile + call setline(1, ['line1', 'line2', 'line3']) + set buftype=acwrite + call assert_fails('write', 'E676:') + call assert_fails('1,2write!', 'E676:') + call assert_fails('w >>', 'E676:') + close! +endfunc + +" Test for adding and removing lines from an autocmd when writing a buffer +func Test_write_autocmd_add_remove_lines() + new Xfile + call setline(1, ['aaa', 'bbb', 'ccc', 'ddd']) + + " Autocmd deleting lines from the file when writing a partial file + augroup WriteTest2 + au! + autocmd FileWritePre Xfile 1,2d + augroup END + call assert_fails('2,3w!', 'E204:') + + " Autocmd adding lines to a file when writing a partial file + augroup WriteTest2 + au! + autocmd FileWritePre Xfile call append(0, ['xxx', 'yyy']) + augroup END + %d + call setline(1, ['aaa', 'bbb', 'ccc', 'ddd']) + 1,2w! + call assert_equal(['xxx', 'yyy', 'aaa', 'bbb'], readfile('Xfile')) + + " Autocmd deleting lines from the file when writing the whole file + augroup WriteTest2 + au! + autocmd BufWritePre Xfile 1,2d + augroup END + %d + call setline(1, ['aaa', 'bbb', 'ccc', 'ddd']) + w + call assert_equal(['ccc', 'ddd'], readfile('Xfile')) + + augroup WriteTest2 + au! + augroup END + augroup! WriteTest2 + + close! + call delete('Xfile') +endfunc + +" Test for writing to a readonly file +func Test_write_readonly() + call writefile([], 'Xfile') + call setfperm('Xfile', "r--------") + edit Xfile + set noreadonly backupskip= + call assert_fails('write', 'E505:') + let save_cpo = &cpo + set cpo+=W + call assert_fails('write!', 'E504:') + let &cpo = save_cpo + call setline(1, ['line1']) + write! + call assert_equal(['line1'], readfile('Xfile')) + + " Auto-saving a readonly file should fail with 'autowriteall' + %bw! + e Xfile + set noreadonly autowriteall + call setline(1, ['aaaa']) + call assert_fails('n', 'E505:') + set cpo+=W + call assert_fails('n', 'E504:') + set cpo-=W + set autowriteall& + + set backupskip& + call delete('Xfile') + %bw! +endfunc + +" Test for 'patchmode' +func Test_patchmode() + call writefile(['one'], 'Xfile') + set patchmode=.orig nobackup backupskip= writebackup + new Xfile + call setline(1, 'two') + " first write should create the .orig file + write + call assert_equal(['one'], readfile('Xfile.orig')) + call setline(1, 'three') + " subsequent writes should not create/modify the .orig file + write + call assert_equal(['one'], readfile('Xfile.orig')) + + " use 'patchmode' with 'nobackup' and 'nowritebackup' to create an empty + " original file + call delete('Xfile') + call delete('Xfile.orig') + %bw! + set patchmode=.orig nobackup nowritebackup + edit Xfile + call setline(1, ['xxx']) + write + call assert_equal(['xxx'], readfile('Xfile')) + call assert_equal([], readfile('Xfile.orig')) + + set patchmode& backup& backupskip& writebackup& + call delete('Xfile') + call delete('Xfile.orig') +endfunc + +" Test for writing to a file in a readonly directory +" NOTE: if you run tests as root this will fail. Don't run tests as root! +func Test_write_readonly_dir() + " On MS-Windows, modifying files in a read-only directory is allowed. + CheckUnix + " Root can do it too. + CheckNotRoot + + call mkdir('Xdir/') + call writefile(['one'], 'Xdir/Xfile1') + call setfperm('Xdir', 'r-xr--r--') + " try to create a new file in the directory + new Xdir/Xfile2 + call setline(1, 'two') + call assert_fails('write', 'E212:') + " try to create a backup file in the directory + edit! Xdir/Xfile1 + set backupdir=./Xdir backupskip= + set patchmode=.orig + call assert_fails('write', 'E509:') + call setfperm('Xdir', 'rwxr--r--') + call delete('Xdir', 'rf') + set backupdir& backupskip& patchmode& +endfunc + +" Test for writing a file using invalid file encoding +func Test_write_invalid_encoding() + new + call setline(1, 'abc') + call assert_fails('write ++enc=axbyc Xfile', 'E213:') + close! +endfunc + +" Tests for reading and writing files with conversion for Win32. +func Test_write_file_encoding() + throw 'Skipped: Nvim does not support encoding=latin1' + CheckMSWindows + let save_encoding = &encoding + let save_fileencodings = &fileencodings + set encoding=latin1 fileencodings& + let text =<< trim END + 1 utf-8 text: Для Vim version 6.2. Последнее изменение: 1970 Jan 01 + 2 cp1251 text: Vim version 6.2. : 1970 Jan 01 + 3 cp866 text: Vim version 6.2. : 1970 Jan 01 + END + call writefile(text, 'Xfile') + edit Xfile + + " write tests: + " combine three values for 'encoding' with three values for 'fileencoding' + " also write files for read tests + call cursor(1, 1) + set encoding=utf-8 + .w! ++enc=utf-8 Xtest + .w ++enc=cp1251 >> Xtest + .w ++enc=cp866 >> Xtest + .w! ++enc=utf-8 Xutf8 + let expected =<< trim END + 1 utf-8 text: Для Vim version 6.2. Последнее изменение: 1970 Jan 01 + 1 utf-8 text: Vim version 6.2. : 1970 Jan 01 + 1 utf-8 text: Vim version 6.2. : 1970 Jan 01 + END + call assert_equal(expected, readfile('Xtest')) + + call cursor(2, 1) + set encoding=cp1251 + .w! ++enc=utf-8 Xtest + .w ++enc=cp1251 >> Xtest + .w ++enc=cp866 >> Xtest + .w! ++enc=cp1251 Xcp1251 + let expected =<< trim END + 2 cp1251 text: Для Vim version 6.2. Последнее изменение: 1970 Jan 01 + 2 cp1251 text: Vim version 6.2. : 1970 Jan 01 + 2 cp1251 text: Vim version 6.2. : 1970 Jan 01 + END + call assert_equal(expected, readfile('Xtest')) + + call cursor(3, 1) + set encoding=cp866 + .w! ++enc=utf-8 Xtest + .w ++enc=cp1251 >> Xtest + .w ++enc=cp866 >> Xtest + .w! ++enc=cp866 Xcp866 + let expected =<< trim END + 3 cp866 text: Для Vim version 6.2. Последнее изменение: 1970 Jan 01 + 3 cp866 text: Vim version 6.2. : 1970 Jan 01 + 3 cp866 text: Vim version 6.2. : 1970 Jan 01 + END + call assert_equal(expected, readfile('Xtest')) + + " read three 'fileencoding's with utf-8 'encoding' + set encoding=utf-8 fencs=utf-8,cp1251 + e Xutf8 + .w! ++enc=utf-8 Xtest + e Xcp1251 + .w ++enc=utf-8 >> Xtest + set fencs=utf-8,cp866 + e Xcp866 + .w ++enc=utf-8 >> Xtest + let expected =<< trim END + 1 utf-8 text: Для Vim version 6.2. Последнее изменение: 1970 Jan 01 + 2 cp1251 text: Для Vim version 6.2. Последнее изменение: 1970 Jan 01 + 3 cp866 text: Для Vim version 6.2. Последнее изменение: 1970 Jan 01 + END + call assert_equal(expected, readfile('Xtest')) + + " read three 'fileencoding's with cp1251 'encoding' + set encoding=utf-8 fencs=utf-8,cp1251 + e Xutf8 + .w! ++enc=cp1251 Xtest + e Xcp1251 + .w ++enc=cp1251 >> Xtest + set fencs=utf-8,cp866 + e Xcp866 + .w ++enc=cp1251 >> Xtest + let expected =<< trim END + 1 utf-8 text: Vim version 6.2. : 1970 Jan 01 + 2 cp1251 text: Vim version 6.2. : 1970 Jan 01 + 3 cp866 text: Vim version 6.2. : 1970 Jan 01 + END + call assert_equal(expected, readfile('Xtest')) + + " read three 'fileencoding's with cp866 'encoding' + set encoding=cp866 fencs=utf-8,cp1251 + e Xutf8 + .w! ++enc=cp866 Xtest + e Xcp1251 + .w ++enc=cp866 >> Xtest + set fencs=utf-8,cp866 + e Xcp866 + .w ++enc=cp866 >> Xtest + let expected =<< trim END + 1 utf-8 text: Vim version 6.2. : 1970 Jan 01 + 2 cp1251 text: Vim version 6.2. : 1970 Jan 01 + 3 cp866 text: Vim version 6.2. : 1970 Jan 01 + END + call assert_equal(expected, readfile('Xtest')) + + call delete('Xfile') + call delete('Xtest') + call delete('Xutf8') + call delete('Xcp1251') + call delete('Xcp866') + let &encoding = save_encoding + let &fileencodings = save_fileencodings + %bw! +endfunc + +" Test for writing and reading a file starting with a BOM. +" Byte Order Mark (BOM) character for various encodings is below: +" UTF-8 : EF BB BF +" UTF-16 (BE): FE FF +" UTF-16 (LE): FF FE +" UTF-32 (BE): 00 00 FE FF +" UTF-32 (LE): FF FE 00 00 +func Test_readwrite_file_with_bom() + let utf8_bom = "\xEF\xBB\xBF" + let utf16be_bom = "\xFE\xFF" + let utf16le_bom = "\xFF\xFE" + let utf32be_bom = "\n\n\xFE\xFF" + let utf32le_bom = "\xFF\xFE\n\n" + let save_fileencoding = &fileencoding + set cpoptions+=S + + " Check that editing a latin1 file doesn't see a BOM + call writefile(["\xFE\xFElatin-1"], 'Xtest1') + edit Xtest1 + call assert_equal('latin1', &fileencoding) + call assert_equal(0, &bomb) + set fenc=latin1 + write Xfile2 + call assert_equal(["\xFE\xFElatin-1", ''], readfile('Xfile2', 'b')) + set bomb fenc=latin1 + write Xtest3 + call assert_equal(["\xFE\xFElatin-1", ''], readfile('Xtest3', 'b')) + set bomb& + + " Check utf-8 BOM + %bw! + call writefile([utf8_bom .. "utf-8"], 'Xtest1') + edit! Xtest1 + call assert_equal('utf-8', &fileencoding) + call assert_equal(1, &bomb) + call assert_equal('utf-8', getline(1)) + set fenc=latin1 + write! Xfile2 + call assert_equal(['utf-8', ''], readfile('Xfile2', 'b')) + set fenc=utf-8 + w! Xtest3 + call assert_equal([utf8_bom .. "utf-8", ''], readfile('Xtest3', 'b')) + + " Check utf-8 with an error (will fall back to latin-1) + %bw! + call writefile([utf8_bom .. "utf-8\x80err"], 'Xtest1') + edit! Xtest1 + call assert_equal('latin1', &fileencoding) + call assert_equal(0, &bomb) + call assert_equal("\xC3\xAF\xC2\xBB\xC2\xBFutf-8\xC2\x80err", getline(1)) + set fenc=latin1 + write! Xfile2 + call assert_equal([utf8_bom .. "utf-8\x80err", ''], readfile('Xfile2', 'b')) + set fenc=utf-8 + w! Xtest3 + call assert_equal(["\xC3\xAF\xC2\xBB\xC2\xBFutf-8\xC2\x80err", ''], + \ readfile('Xtest3', 'b')) + + " Check ucs-2 BOM + %bw! + call writefile([utf16be_bom .. "\nu\nc\ns\n-\n2\n"], 'Xtest1') + edit! Xtest1 + call assert_equal('utf-16', &fileencoding) + call assert_equal(1, &bomb) + call assert_equal('ucs-2', getline(1)) + set fenc=latin1 + write! Xfile2 + call assert_equal(["ucs-2", ''], readfile('Xfile2', 'b')) + set fenc=ucs-2 + w! Xtest3 + call assert_equal([utf16be_bom .. "\nu\nc\ns\n-\n2\n", ''], + \ readfile('Xtest3', 'b')) + + " Check ucs-2le BOM + %bw! + call writefile([utf16le_bom .. "u\nc\ns\n-\n2\nl\ne\n"], 'Xtest1') + " Need to add a NUL byte after the NL byte + call writefile(0z00, 'Xtest1', 'a') + edit! Xtest1 + call assert_equal('utf-16le', &fileencoding) + call assert_equal(1, &bomb) + call assert_equal('ucs-2le', getline(1)) + set fenc=latin1 + write! Xfile2 + call assert_equal(["ucs-2le", ''], readfile('Xfile2', 'b')) + set fenc=ucs-2le + w! Xtest3 + call assert_equal([utf16le_bom .. "u\nc\ns\n-\n2\nl\ne\n", "\n"], + \ readfile('Xtest3', 'b')) + + " Check ucs-4 BOM + %bw! + call writefile([utf32be_bom .. "\n\n\nu\n\n\nc\n\n\ns\n\n\n-\n\n\n4\n\n\n"], 'Xtest1') + edit! Xtest1 + call assert_equal('ucs-4', &fileencoding) + call assert_equal(1, &bomb) + call assert_equal('ucs-4', getline(1)) + set fenc=latin1 + write! Xfile2 + call assert_equal(["ucs-4", ''], readfile('Xfile2', 'b')) + set fenc=ucs-4 + w! Xtest3 + call assert_equal([utf32be_bom .. "\n\n\nu\n\n\nc\n\n\ns\n\n\n-\n\n\n4\n\n\n", ''], readfile('Xtest3', 'b')) + + " Check ucs-4le BOM + %bw! + call writefile([utf32le_bom .. "u\n\n\nc\n\n\ns\n\n\n-\n\n\n4\n\n\nl\n\n\ne\n\n\n"], 'Xtest1') + " Need to add three NUL bytes after the NL byte + call writefile(0z000000, 'Xtest1', 'a') + edit! Xtest1 + call assert_equal('ucs-4le', &fileencoding) + call assert_equal(1, &bomb) + call assert_equal('ucs-4le', getline(1)) + set fenc=latin1 + write! Xfile2 + call assert_equal(["ucs-4le", ''], readfile('Xfile2', 'b')) + set fenc=ucs-4le + w! Xtest3 + call assert_equal([utf32le_bom .. "u\n\n\nc\n\n\ns\n\n\n-\n\n\n4\n\n\nl\n\n\ne\n\n\n", "\n\n\n"], readfile('Xtest3', 'b')) + + set cpoptions-=S + let &fileencoding = save_fileencoding + call delete('Xtest1') + call delete('Xfile2') + call delete('Xtest3') + %bw! +endfunc + +func Test_read_write_bin() + " write file missing EOL + call writefile(['noeol'], "XNoEolSetEol", 'bS') + call assert_equal(0z6E6F656F6C, readfile('XNoEolSetEol', 'B')) + + " when file is read 'eol' is off + set nofixeol + e! ++ff=unix XNoEolSetEol + call assert_equal(0, &eol) + + " writing with 'eol' set adds the newline + setlocal eol + w + call assert_equal(0z6E6F656F6C0A, readfile('XNoEolSetEol', 'B')) + + call delete('XNoEolSetEol') + set ff& fixeol& + bwipe! XNoEolSetEol +endfunc + +" Test for the 'backupcopy' option when writing files +func Test_backupcopy() + CheckUnix + set backupskip= + " With the default 'backupcopy' setting, saving a symbolic link file + " should not break the link. + set backupcopy& + call writefile(['1111'], 'Xfile1') + silent !ln -s Xfile1 Xfile2 + new Xfile2 + call setline(1, ['2222']) + write + close + call assert_equal(['2222'], readfile('Xfile1')) + call assert_equal('Xfile1', resolve('Xfile2')) + call assert_equal('link', getftype('Xfile2')) + call delete('Xfile1') + call delete('Xfile2') + + " With the 'backupcopy' set to 'breaksymlink', saving a symbolic link file + " should break the link. + set backupcopy=yes,breaksymlink + call writefile(['1111'], 'Xfile1') + silent !ln -s Xfile1 Xfile2 + new Xfile2 + call setline(1, ['2222']) + write + close + call assert_equal(['1111'], readfile('Xfile1')) + call assert_equal(['2222'], readfile('Xfile2')) + call assert_equal('Xfile2', resolve('Xfile2')) + call assert_equal('file', getftype('Xfile2')) + call delete('Xfile1') + call delete('Xfile2') + set backupcopy& + + " With the default 'backupcopy' setting, saving a hard link file + " should not break the link. + set backupcopy& + call writefile(['1111'], 'Xfile1') + silent !ln Xfile1 Xfile2 + new Xfile2 + call setline(1, ['2222']) + write + close + call assert_equal(['2222'], readfile('Xfile1')) + call delete('Xfile1') + call delete('Xfile2') + + " With the 'backupcopy' set to 'breaksymlink', saving a hard link file + " should break the link. + set backupcopy=yes,breakhardlink + call writefile(['1111'], 'Xfile1') + silent !ln Xfile1 Xfile2 + new Xfile2 + call setline(1, ['2222']) + write + call assert_equal(['1111'], readfile('Xfile1')) + call assert_equal(['2222'], readfile('Xfile2')) + call delete('Xfile1') + call delete('Xfile2') + + " If a backup file is already present, then a slightly modified filename + " should be used as the backup file. Try with 'backupcopy' set to 'yes' and + " 'no'. + %bw + call writefile(['aaaa'], 'Xfile') + call writefile(['bbbb'], 'Xfile.bak') + set backupcopy=yes backupext=.bak + new Xfile + call setline(1, ['cccc']) + write + close + call assert_equal(['cccc'], readfile('Xfile')) + call assert_equal(['bbbb'], readfile('Xfile.bak')) + set backupcopy=no backupext=.bak + new Xfile + call setline(1, ['dddd']) + write + close + call assert_equal(['dddd'], readfile('Xfile')) + call assert_equal(['bbbb'], readfile('Xfile.bak')) + call delete('Xfile') + call delete('Xfile.bak') + + " Write to a device file (in Unix-like systems) which cannot be backed up. + if has('unix') + set writebackup backupcopy=yes nobackup + new + call setline(1, ['aaaa']) + let output = execute('write! /dev/null') + call assert_match('"/dev/null" \[Device]', output) + close + set writebackup backupcopy=no nobackup + new + call setline(1, ['aaaa']) + let output = execute('write! /dev/null') + call assert_match('"/dev/null" \[Device]', output) + close + set backup writebackup& backupcopy& + new + call setline(1, ['aaaa']) + let output = execute('write! /dev/null') + call assert_match('"/dev/null" \[Device]', output) + close + endif + + set backupcopy& backupskip& backupext& backup& +endfunc + +" Test for writing a file with 'encoding' set to 'utf-16' +func Test_write_utf16() + new + call setline(1, ["\U00010001"]) + write ++enc=utf-16 Xfile + bw! + call assert_equal(0zD800DC01, readfile('Xfile', 'B')[0:3]) + call delete('Xfile') +endfunc + +" Test for trying to save a backup file when the backup file is a symbolic +" link to the original file. The backup file should not be modified. +func Test_write_backup_symlink() + CheckUnix + call mkdir('Xbackup') + let save_backupdir = &backupdir + set backupdir=.,./Xbackup + call writefile(['1111'], 'Xfile') + silent !ln -s Xfile Xfile.bak + + new Xfile + set backup backupcopy=yes backupext=.bak + write + call assert_equal('link', getftype('Xfile.bak')) + call assert_equal('Xfile', resolve('Xfile.bak')) + " backup file should be created in the 'backup' directory + if !has('bsd') + " This check fails on FreeBSD + call assert_true(filereadable('./Xbackup/Xfile.bak')) + endif + set backup& backupcopy& backupext& + %bw + + call delete('Xfile') + call delete('Xfile.bak') + call delete('Xbackup', 'rf') + let &backupdir = save_backupdir +endfunc + +" Test for ':write ++bin' and ':write ++nobin' +func Test_write_binary_file() + " create a file without an eol/eof character + call writefile(0z616161, 'Xwbfile1', 'b') + new Xwbfile1 + write ++bin Xwbfile2 + write ++nobin Xwbfile3 + call assert_equal(0z616161, readblob('Xwbfile2')) + if has('win32') + call assert_equal(0z6161610D.0A, readblob('Xwbfile3')) + else + call assert_equal(0z6161610A, readblob('Xwbfile3')) + endif + call delete('Xwbfile1') + call delete('Xwbfile2') + call delete('Xwbfile3') +endfunc + +func DoWriteDefer() + call writefile(['some text'], 'XdeferDelete', 'D') + call assert_equal(['some text'], readfile('XdeferDelete')) +endfunc + +" def DefWriteDefer() +" writefile(['some text'], 'XdefdeferDelete', 'D') +" assert_equal(['some text'], readfile('XdefdeferDelete')) +" enddef + +func Test_write_with_deferred_delete() + call DoWriteDefer() + call assert_equal('', glob('XdeferDelete')) + " call DefWriteDefer() + " call assert_equal('', glob('XdefdeferDelete')) +endfunc + +func DoWriteFile() + call writefile(['text'], 'Xthefile', 'D') + cd .. +endfunc + +func Test_write_defer_delete_chdir() + let dir = getcwd() + call DoWriteFile() + call assert_notequal(dir, getcwd()) + call chdir(dir) + call assert_equal('', glob('Xthefile')) +endfunc + +" Check that buffer is written before triggering QuitPre +func Test_wq_quitpre_autocommand() + edit Xsomefile + call setline(1, 'hello') + split + let g:seq = [] + augroup Testing + au QuitPre * call add(g:seq, 'QuitPre - ' .. (&modified ? 'modified' : 'not modified')) + au BufWritePost * call add(g:seq, 'written') + augroup END + wq + call assert_equal(['written', 'QuitPre - not modified'], g:seq) + + augroup Testing + au! + augroup END + bwipe! + unlet g:seq + call delete('Xsomefile') +endfunc + +func Test_write_with_xattr_support() + CheckLinux + CheckFeature xattr + CheckExecutable setfattr + + let contents = ["file with xattrs", "line two"] + call writefile(contents, 'Xwattr.txt', 'D') + " write a couple of xattr + call system('setfattr -n user.cookie -v chocolate Xwattr.txt') + call system('setfattr -n user.frieda -v bar Xwattr.txt') + call system('setfattr -n user.empty Xwattr.txt') + + set backupcopy=no writebackup& backup& + sp Xwattr.txt + w + $r! getfattr -d % + let expected = ['file with xattrs', 'line two', '# file: Xwattr.txt', 'user.cookie="chocolate"', 'user.empty=""', 'user.frieda="bar"', ''] + call assert_equal(expected, getline(1,'$')) + + set backupcopy& + bw! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/test/old/testdir/unix.vim b/test/old/testdir/unix.vim new file mode 100644 index 0000000000..ce2beff7fe --- /dev/null +++ b/test/old/testdir/unix.vim @@ -0,0 +1,15 @@ +" Settings for test script execution +" Always use "sh", don't use the value of "$SHELL". +set shell=sh + +if has('win32') + set shellcmdflag=-c shellxquote= shellxescape= shellquote= + let &shellredir = '>%s 2>&1' + set shellslash +endif + +" Don't depend on system locale, always use utf-8 +set encoding=utf-8 + +" Use safer defaults for various directories +set backupdir=. directory=. undodir=. viewdir=. diff --git a/test/old/testdir/view_util.vim b/test/old/testdir/view_util.vim new file mode 100644 index 0000000000..a4d0e56af9 --- /dev/null +++ b/test/old/testdir/view_util.vim @@ -0,0 +1,64 @@ +" Functions about view shared by several tests + +" Only load this script once. +if exists('*Screenline') + finish +endif + +" Get line "lnum" as displayed on the screen. +" Trailing white space is trimmed. +func Screenline(lnum) + let chars = [] + for c in range(1, winwidth(0)) + call add(chars, nr2char(screenchar(a:lnum, c))) + endfor + let line = join(chars, '') + return matchstr(line, '^.\{-}\ze\s*$') +endfunc + +" Get text on the screen, including composing characters. +" ScreenLines(lnum, width) or +" ScreenLines([start, end], width) +func ScreenLines(lnum, width) abort + redraw! + if type(a:lnum) == v:t_list + let start = a:lnum[0] + let end = a:lnum[1] + else + let start = a:lnum + let end = a:lnum + endif + let lines = [] + for l in range(start, end) + let lines += [join(map(range(1, a:width), 'screenstring(l, v:val)'), '')] + endfor + return lines +endfunc + +func ScreenAttrs(lnum, width) abort + redraw! + if type(a:lnum) == v:t_list + let start = a:lnum[0] + let end = a:lnum[1] + else + let start = a:lnum + let end = a:lnum + endif + let attrs = [] + for l in range(start, end) + let attrs += [map(range(1, a:width), 'screenattr(l, v:val)')] + endfor + return attrs +endfunc + +func NewWindow(height, width) abort + exe a:height . 'new' + exe a:width . 'vsp' + set winfixwidth winfixheight + redraw! +endfunc + +func CloseWindow() abort + bw! + redraw! +endfunc diff --git a/test/old/testdir/vim9.vim b/test/old/testdir/vim9.vim new file mode 100644 index 0000000000..825f01c9d6 --- /dev/null +++ b/test/old/testdir/vim9.vim @@ -0,0 +1,140 @@ + +" Use a different file name for each run. +let s:sequence = 1 + +func CheckDefFailure(lines, error, lnum = -3) + return +endfunc + +func CheckDefExecFailure(lines, error, lnum = -3) + return +endfunc + +func CheckScriptFailure(lines, error, lnum = -3) + if get(a:lines, 0, '') ==# 'vim9script' + return + endif + let cwd = getcwd() + let fname = 'XScriptFailure' .. s:sequence + let s:sequence += 1 + call writefile(a:lines, fname) + try + call assert_fails('so ' .. fname, a:error, a:lines, a:lnum) + finally + call chdir(cwd) + call delete(fname) + endtry +endfunc + +func CheckScriptSuccess(lines) + if get(a:lines, 0, '') ==# 'vim9script' + return + endif + let cwd = getcwd() + let fname = 'XScriptSuccess' .. s:sequence + let s:sequence += 1 + call writefile(a:lines, fname) + try + exe 'so ' .. fname + finally + call chdir(cwd) + call delete(fname) + endtry +endfunc + +func CheckDefAndScriptSuccess(lines) + return +endfunc + +func CheckDefAndScriptFailure(lines, error, lnum = -3) + return +endfunc + +func CheckDefExecAndScriptFailure(lines, error, lnum = -3) + return +endfunc + +" Check that "lines" inside a legacy function has no error. +func CheckLegacySuccess(lines) + let cwd = getcwd() + let fname = 'XlegacySuccess' .. s:sequence + let s:sequence += 1 + call writefile(['func Func()'] + a:lines + ['endfunc'], fname) + try + exe 'so ' .. fname + call Func() + finally + delfunc! Func + call chdir(cwd) + call delete(fname) + endtry +endfunc + +" Check that "lines" inside a legacy function results in the expected error +func CheckLegacyFailure(lines, error) + let cwd = getcwd() + let fname = 'XlegacyFails' .. s:sequence + let s:sequence += 1 + call writefile(['func Func()'] + a:lines + ['endfunc', 'call Func()'], fname) + try + call assert_fails('so ' .. fname, a:error) + finally + delfunc! Func + call chdir(cwd) + call delete(fname) + endtry +endfunc + +" Execute "lines" in a legacy function, translated as in +" CheckLegacyAndVim9Success() +func CheckTransLegacySuccess(lines) + let legacylines = a:lines->mapnew({_, v -> + \ v->substitute('\<VAR\>', 'let', 'g') + \ ->substitute('\<LET\>', 'let', 'g') + \ ->substitute('\<LSTART\>', '{', 'g') + \ ->substitute('\<LMIDDLE\>', '->', 'g') + \ ->substitute('\<LEND\>', '}', 'g') + \ ->substitute('\<TRUE\>', '1', 'g') + \ ->substitute('\<FALSE\>', '0', 'g') + \ ->substitute('#"', ' "', 'g') + \ }) + call CheckLegacySuccess(legacylines) +endfunc + +func CheckTransDefSuccess(lines) + return +endfunc + +func CheckTransVim9Success(lines) + return +endfunc + +" Execute "lines" in a legacy function +" Use 'VAR' for a declaration. +" Use 'LET' for an assignment +" Use ' #"' for a comment +" Use LSTART arg LMIDDLE expr LEND for lambda +" Use 'TRUE' for 1 +" Use 'FALSE' for 0 +func CheckLegacyAndVim9Success(lines) + call CheckTransLegacySuccess(a:lines) +endfunc + +" Execute "lines" in a legacy function +" Use 'VAR' for a declaration. +" Use 'LET' for an assignment +" Use ' #"' for a comment +func CheckLegacyAndVim9Failure(lines, error) + if type(a:error) == type('string') + let legacyError = a:error + else + let legacyError = a:error[0] + endif + + let legacylines = a:lines->mapnew({_, v -> + \ v->substitute('\<VAR\>', 'let', 'g') + \ ->substitute('\<LET\>', 'let', 'g') + \ ->substitute('#"', ' "', 'g') + \ }) + call CheckLegacyFailure(legacylines, legacyError) +endfunc |