aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml34
-rwxr-xr-xci/before_install.sh16
-rw-r--r--ci/common/build.sh9
-rw-r--r--ci/common/test.sh4
-rwxr-xr-xci/install.sh12
-rw-r--r--runtime/CMakeLists.txt2
-rw-r--r--runtime/autoload/health/provider.vim16
-rw-r--r--runtime/autoload/man.vim4
-rw-r--r--runtime/doc/deprecated.txt8
-rw-r--r--runtime/doc/eval.txt42
-rw-r--r--runtime/doc/filetype.txt6
-rw-r--r--runtime/doc/options.txt4
-rw-r--r--runtime/doc/quickfix.txt6
-rw-r--r--runtime/doc/starting.txt9
-rw-r--r--runtime/doc/term.txt4
-rw-r--r--runtime/tutor/en/vim-01-beginner.tutor625
-rw-r--r--runtime/tutor/en/vim-01-beginner.tutor.json74
-rwxr-xr-xscripts/vim-patch.sh2
-rw-r--r--src/nvim/api/private/helpers.c8
-rw-r--r--src/nvim/eval.c500
-rw-r--r--src/nvim/eval/decode.c40
-rw-r--r--src/nvim/eval/typval.c169
-rw-r--r--src/nvim/eval/typval.h22
-rw-r--r--src/nvim/ex_cmds.c6
-rw-r--r--src/nvim/ex_docmd.c12
-rw-r--r--src/nvim/if_cscope.c4
-rw-r--r--src/nvim/lua/converter.c38
-rw-r--r--src/nvim/quickfix.c202
-rw-r--r--src/nvim/regexp_nfa.c24
-rw-r--r--src/nvim/search.c5
-rw-r--r--src/nvim/testdir/Makefile1
-rw-r--r--src/nvim/testdir/test_alot.vim3
-rw-r--r--src/nvim/testdir/test_changedtick.vim57
-rw-r--r--src/nvim/testdir/test_cmdline.vim32
-rw-r--r--src/nvim/testdir/test_expr.vim5
-rw-r--r--src/nvim/testdir/test_functions.vim42
-rw-r--r--src/nvim/testdir/test_quickfix.vim111
-rw-r--r--src/nvim/testdir/test_stat.vim31
-rw-r--r--src/nvim/testdir/test_substitute.vim67
-rw-r--r--src/nvim/testdir/test_visual.vim7
-rw-r--r--src/nvim/tui/terminfo.c4
-rw-r--r--src/nvim/tui/tui.c3
-rw-r--r--src/nvim/version.c26
-rw-r--r--src/nvim/window.c26
-rw-r--r--test/functional/autocmd/tabclose_spec.lua87
-rw-r--r--test/functional/autocmd/termclose_spec.lua9
-rw-r--r--test/functional/eval/system_spec.lua11
-rw-r--r--test/functional/helpers.lua5
-rw-r--r--test/functional/normal/K_spec.lua4
-rw-r--r--test/functional/options/autochdir_spec.lua5
-rw-r--r--test/functional/options/defaults_spec.lua92
-rw-r--r--test/functional/plugin/man_spec.lua4
-rw-r--r--test/functional/plugin/msgpack_spec.lua2
-rw-r--r--test/functional/plugin/shada_spec.lua14
-rw-r--r--test/functional/shada/helpers.lua1
-rw-r--r--test/functional/terminal/ex_terminal_spec.lua13
-rw-r--r--test/functional/ui/bufhl_spec.lua2
-rw-r--r--test/functional/ui/inccommand_spec.lua12
-rw-r--r--test/functional/ui/input_spec.lua2
-rw-r--r--test/functional/ui/mouse_spec.lua2
-rw-r--r--test/functional/ui/searchhl_spec.lua2
-rw-r--r--test/functional/ui/sign_spec.lua2
-rw-r--r--test/functional/ui/syntax_conceal_spec.lua2
-rw-r--r--test/functional/viml/completion_spec.lua2
-rw-r--r--test/unit/eval/helpers.lua18
-rw-r--r--test/unit/eval/typval_spec.lua266
-rw-r--r--test/unit/helpers.lua77
-rw-r--r--third-party/CMakeLists.txt16
68 files changed, 1805 insertions, 1167 deletions
diff --git a/.travis.yml b/.travis.yml
index 2bab1635ad..09ef8bba46 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -10,7 +10,7 @@ env:
# http://docs.travis-ci.com/user/speeding-up-the-build/#Paralellizing-your-build-on-one-VM
- MAKE_CMD="make -j2"
# Update PATH for pip.
- - PATH="$(python2.7 -c 'import site; print(site.getuserbase())')/bin:/usr/lib/llvm-symbolizer-4.0/bin:$PATH"
+ - PATH="$(python2.7 -c 'import site; print(site.getuserbase())')/bin:$PATH"
# Build directory for Neovim.
- BUILD_DIR="$TRAVIS_BUILD_DIR/build"
# Build directory for third-party dependencies.
@@ -51,40 +51,38 @@ env:
jobs:
include:
- - stage: sanitizers
+ - stage: normal builds
os: linux
- compiler: clang-4.0
+ compiler: clang
env: >
CLANG_SANITIZER=ASAN_UBSAN
CMAKE_FLAGS="$CMAKE_FLAGS -DPREFER_LUA=ON"
- - stage: normal builds
- os: linux
- compiler: gcc-5
+ - os: linux
+ compiler: gcc
env: FUNCTIONALTEST=functionaltest-lua
- os: linux
# Travis creates a cache per compiler.
# Set a different value here to store 32-bit
# dependencies in a separate cache.
- compiler: gcc-5 -m32
+ compiler: gcc -m32
env: BUILD_32BIT=ON
- os: osx
compiler: clang
osx_image: xcode7.3 # macOS 10.11
- os: osx
- compiler: gcc-4.9
+ compiler: gcc
osx_image: xcode7.3 # macOS 10.11
- - stage: lint
- os: linux
+ - os: linux
env: CI_TARGET=lint
- stage: Flaky builds
os: linux
- compiler: gcc-5
- env: GCOV=gcov-5 CMAKE_FLAGS="$CMAKE_FLAGS -DUSE_GCOV=ON"
+ compiler: gcc
+ env: GCOV=gcov CMAKE_FLAGS="$CMAKE_FLAGS -DUSE_GCOV=ON"
- os: linux
- compiler: clang-4.0
+ compiler: clang
env: CLANG_SANITIZER=TSAN
allow_failures:
- - env: GCOV=gcov-5 CMAKE_FLAGS="$CMAKE_FLAGS -DUSE_GCOV=ON"
+ - env: GCOV=gcov CMAKE_FLAGS="$CMAKE_FLAGS -DUSE_GCOV=ON"
- env: CLANG_SANITIZER=TSAN
fast_finish: true
@@ -97,26 +95,20 @@ after_success: ci/after_success.sh
addons:
apt:
- sources:
- - ubuntu-toolchain-r-test
- - llvm-toolchain-trusty-4.0
packages:
- autoconf
- automake
- apport
- build-essential
- - clang-4.0
+ - clang
- cmake
- cscope
- - g++-5-multilib
- g++-multilib
- - gcc-5-multilib
- gcc-multilib
- gdb
- language-pack-tr
- libc6-dev-i386
- libtool
- - llvm-4.0-dev
- locales
- pkg-config
- unzip
diff --git a/ci/before_install.sh b/ci/before_install.sh
index f5a57ad657..9f512ee5b9 100755
--- a/ci/before_install.sh
+++ b/ci/before_install.sh
@@ -38,14 +38,12 @@ else
pip3 -q install --user --upgrade pip || true
fi
-if [[ "${TRAVIS_OS_NAME}" == linux ]]; then
- echo "Install node (LTS)"
+echo "Install node (LTS)"
- if [ ! -f ~/.nvm/nvm.sh ]; then
- curl -o ~/.nvm/nvm.sh https://raw.githubusercontent.com/creationix/nvm/master/nvm.sh
- fi
-
- source ~/.nvm/nvm.sh
- nvm install --lts
- nvm use --lts
+if [[ "${TRAVIS_OS_NAME}" == osx ]] || [ ! -f ~/.nvm/nvm.sh ]; then
+ curl -o ~/.nvm/nvm.sh https://raw.githubusercontent.com/creationix/nvm/master/nvm.sh
fi
+
+source ~/.nvm/nvm.sh
+nvm install --lts
+nvm use --lts
diff --git a/ci/common/build.sh b/ci/common/build.sh
index f398a1a1cc..adfd7b9e8a 100644
--- a/ci/common/build.sh
+++ b/ci/common/build.sh
@@ -87,3 +87,12 @@ build_nvim() {
cd "${TRAVIS_BUILD_DIR}"
}
+
+macos_rvm_dance() {
+ # neovim-ruby gem requires a ruby newer than the macOS default.
+ source ~/.rvm/scripts/rvm
+ rvm get stable --auto-dotfiles
+ rvm reload
+ rvm use 2.2.5
+ rvm use
+}
diff --git a/ci/common/test.sh b/ci/common/test.sh
index 55f76ca798..1cb3a6224b 100644
--- a/ci/common/test.sh
+++ b/ci/common/test.sh
@@ -71,7 +71,9 @@ valgrind_check() {
}
asan_check() {
- check_logs "${1}" "*san.*"
+ if test "${CLANG_SANITIZER}" = "ASAN_UBSAN" ; then
+ check_logs "${1}" "*san.*" | asan_symbolize
+ fi
}
run_unittests() {(
diff --git a/ci/install.sh b/ci/install.sh
index 2fe4f88822..eb7fb14760 100755
--- a/ci/install.sh
+++ b/ci/install.sh
@@ -21,10 +21,10 @@ echo "Install neovim module for Python 3."
# https://github.com/travis-ci/travis-ci/issues/8363
CC=cc pip3 -q install --user --upgrade neovim || true
-echo "Install neovim RubyGem."
-gem install --no-document --version ">= 0.2.0" neovim
-
-if [[ "${TRAVIS_OS_NAME}" == linux ]]; then
- echo "Install neovim npm package"
- npm install -g neovim
+if ! [ "${TRAVIS_OS_NAME}" = osx ] ; then
+ echo "Install neovim RubyGem."
+ gem install --no-document --version ">= 0.2.0" neovim
fi
+
+echo "Install neovim npm package"
+npm install -g neovim
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index 6dbe049232..52a8609fec 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -138,7 +138,7 @@ endforeach()
file(GLOB_RECURSE RUNTIME_FILES
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
rgb.txt
- *.vim *.dict *.py *.rb *.ps *.tutor)
+ *.vim *.dict *.py *.rb *.ps *.tutor *.tutor.json)
foreach(F ${RUNTIME_FILES})
get_filename_component(BASEDIR ${F} PATH)
diff --git a/runtime/autoload/health/provider.vim b/runtime/autoload/health/provider.vim
index 83dee043a0..d1239db605 100644
--- a/runtime/autoload/health/provider.vim
+++ b/runtime/autoload/health/provider.vim
@@ -370,21 +370,9 @@ function! s:check_python(version) abort
let python_bin = ''
endif
-
- " Check if $VIRTUAL_ENV is active.
+ " Check if $VIRTUAL_ENV is valid.
if exists('$VIRTUAL_ENV')
- let virtualenv_inactive = 0
-
- if !empty(pyenv)
- let pyenv_prefix = resolve(s:trim(s:system([pyenv, 'prefix'])))
- if $VIRTUAL_ENV != pyenv_prefix
- let virtualenv_inactive = 1
- endif
- elseif !empty(pyname) && exepath(pyname) !~# '^'.$VIRTUAL_ENV.'/'
- let virtualenv_inactive = 1
- endif
-
- if virtualenv_inactive
+ if !empty(pyname) && $VIRTUAL_ENV !=# matchstr(exepath(pyname), '^\V'.$VIRTUAL_ENV)
call health#report_warn(
\ '$VIRTUAL_ENV exists but appears to be inactive. '
\ . 'This could lead to unexpected results.',
diff --git a/runtime/autoload/man.vim b/runtime/autoload/man.vim
index d20b8c05b0..00ce1c77d7 100644
--- a/runtime/autoload/man.vim
+++ b/runtime/autoload/man.vim
@@ -65,9 +65,9 @@ function! man#open_page(count, count1, mods, ...) abort
try
set eventignore+=BufReadCmd
if a:mods !~# 'tab' && s:find_man()
- execute 'silent edit' fnameescape(bufname)
+ execute 'silent keepalt edit' fnameescape(bufname)
else
- execute 'silent' a:mods 'split' fnameescape(bufname)
+ execute 'silent keepalt' a:mods 'split' fnameescape(bufname)
endif
finally
set eventignore-=BufReadCmd
diff --git a/runtime/doc/deprecated.txt b/runtime/doc/deprecated.txt
index 72dfe1230e..b3073ffe58 100644
--- a/runtime/doc/deprecated.txt
+++ b/runtime/doc/deprecated.txt
@@ -37,8 +37,8 @@ Functions ~
*file_readable()* Obsolete name for |filereadable()|.
*highlight_exists()* Obsolete name for |hlexists()|.
*highlightID()* Obsolete name for |hlID()|.
-*jobclose()* Obsolete name for |chanclose()|
-*jobsend()* Obsolete name for |chansend()|
+*jobclose()* Obsolete name for |chanclose()|
+*jobsend()* Obsolete name for |chansend()|
*last_buffer_nr()* Obsolete name for bufnr("$").
Modifiers ~
@@ -48,8 +48,10 @@ Modifiers ~
*:map-special* <> notation is always enabled. |cpo-<|
Options ~
+'gd'
+'gdefault' Enables the |:substitute| flag 'g' by default.
*'fe'* 'fenc'+'enc' before Vim 6.0; no longer used.
-*'highlight'* *'hl'* Names of builtin |highlight-groups| cannot be changed.
+*'highlight'* *'hl'* Names of builtin |highlight-groups| cannot be changed.
*'langnoremap'* Deprecated alias to 'nolangremap'.
*'vi'*
*'viminfo'* Deprecated alias to 'shada' option.
diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt
index a9474b58a3..ae62498d35 100644
--- a/runtime/doc/eval.txt
+++ b/runtime/doc/eval.txt
@@ -4327,17 +4327,25 @@ getqflist([{what}]) *getqflist()*
If the optional {what} dictionary argument is supplied, then
returns only the items listed in {what} as a dictionary. The
following string items are supported in {what}:
+ context get the context stored with |setqflist()|
+ items quickfix list entries
nr get information for this quickfix list; zero
- means the current quickfix list
+ means the current quickfix list and '$' means
+ the last quickfix list
title get the list title
winid get the |window-ID| (if opened)
all all of the above quickfix properties
Non-string items in {what} are ignored.
If "nr" is not present then the current quickfix list is used.
+ To get the number of lists in the quickfix stack, set 'nr' to
+ '$' in {what}. The 'nr' value in the returned dictionary
+ contains the quickfix stack size.
In case of error processing {what}, an empty dictionary is
returned.
The returned dictionary contains the following entries:
+ context context information stored with |setqflist()|
+ items quickfix list entries
nr quickfix list number
title quickfix list title text
winid quickfix |window-ID| (if opened)
@@ -6885,7 +6893,12 @@ setqflist({list} [, {action}[, {what}]]) *setqflist()*
only the items listed in {what} are set. The first {list}
argument is ignored. The following items can be specified in
{what}:
- nr list number in the quickfix stack
+ context any Vim type can be stored as a context
+ items list of quickfix entries. Same as the {list}
+ argument.
+ nr list number in the quickfix stack; zero
+ means the current quickfix list and '$' means
+ the last quickfix list
title quickfix list title text
Unsupported keys in {what} are ignored.
If the "nr" item is not present, then the current quickfix list
@@ -6990,18 +7003,22 @@ shellescape({string} [, {special}]) *shellescape()*
quotes within {string}.
Otherwise, it will enclose {string} in single quotes and
replace all "'" with "'\''".
+
When the {special} argument is present and it's a non-zero
Number or a non-empty String (|non-zero-arg|), then special
items such as "!", "%", "#" and "<cword>" will be preceded by
a backslash. This backslash will be removed again by the |:!|
command.
+
The "!" character will be escaped (again with a |non-zero-arg|
{special}) when 'shell' contains "csh" in the tail. That is
because for csh and tcsh "!" is used for history replacement
even when inside single quotes.
- The <NL> character is also escaped. With a |non-zero-arg|
- {special} and 'shell' containing "csh" in the tail it's
+
+ With a |non-zero-arg| {special} the <NL> character is also
+ escaped. When 'shell' containing "csh" in the tail it's
escaped a second time.
+
Example of use with a |:!| command: >
:exe '!dir ' . shellescape(expand('<cfile>'), 1)
< This results in a directory listing for the file under the
@@ -10508,18 +10525,19 @@ missing: >
To execute a command only when the |+eval| feature is disabled requires a trick,
as this example shows: >
- if 1
- nnoremap : :"
- endif
- normal :set history=111<CR>
- if 1
- nunmap :
- endif
+
+ silent! while 0
+ set history=111
+ silent! endwhile
+
+When the |+eval| feature is available the command is skipped because of the
+"while 0". Without the |+eval| feature the "while 0" is an error, which is
+silently ignored, and the command is executed.
The "<CR>" here is a real CR character, type CTRL-V Enter to get it.
When the |+eval| feature is available the ":" is remapped to add a double
-quote, which has the effect of commenting-out the command. without the
+quote, which has the effect of commenting-out the command. Without the
|+eval| feature the nnoremap command is skipped and the command is executed.
==============================================================================
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt
index 78402b47fe..74c453f79a 100644
--- a/runtime/doc/filetype.txt
+++ b/runtime/doc/filetype.txt
@@ -24,10 +24,8 @@ Each time a new or existing file is edited, Vim will try to recognize the type
of the file and set the 'filetype' option. This will trigger the FileType
event, which can be used to set the syntax highlighting, set options, etc.
-Detail: The ":filetype on" command will load one of these files:
- Mac $VIMRUNTIME/filetype.vim
- MS-DOS $VIMRUNTIME\filetype.vim
- Unix $VIMRUNTIME/filetype.vim
+Detail: The ":filetype on" command will load this file:
+ $VIMRUNTIME/filetype.vim
This file is a Vim script that defines autocommands for the
BufNewFile and BufRead events. If the file type is not found by the
name, the file $VIMRUNTIME/scripts.vim is used to detect it from the
diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt
index f70ec32bd8..067aad1f93 100644
--- a/runtime/doc/options.txt
+++ b/runtime/doc/options.txt
@@ -2712,6 +2712,10 @@ A jump table for the options with a short description can be found at |Q_op|.
:s///g subst. one subst. all
:s///gg subst. all subst. one
+ DEPRECATED: Setting this option may break plugins that are not aware
+ of this option. Also, many users get confused that adding the /g flag
+ has the opposite effect of that it normally does.
+
*'grepformat'* *'gfm'*
'grepformat' 'gfm' string (default "%f:%l:%m,%f:%l%m,%f %l%m")
global
diff --git a/runtime/doc/quickfix.txt b/runtime/doc/quickfix.txt
index 74f82b2c65..f280286290 100644
--- a/runtime/doc/quickfix.txt
+++ b/runtime/doc/quickfix.txt
@@ -470,7 +470,11 @@ keep its height, ignoring 'winheight' and 'equalalways'. You can change the
height manually (e.g., by dragging the status line above it with the mouse).
In the quickfix window, each line is one error. The line number is equal to
-the error number. You can use ":.cc" to jump to the error under the cursor.
+the error number. The current entry is highlighted with the QuickFixLine
+highlighting. You can change it to your liking, e.g.: >
+ :hi QuickFixLine ctermbg=Yellow guibg=Yellow
+
+You can use ":.cc" to jump to the error under the cursor.
Hitting the <Enter> key or double-clicking the mouse on a line has the same
effect. The file containing the error is opened in the window above the
quickfix window. If there already is a window for that file, it is used
diff --git a/runtime/doc/starting.txt b/runtime/doc/starting.txt
index 30c0641ef7..e9188ba641 100644
--- a/runtime/doc/starting.txt
+++ b/runtime/doc/starting.txt
@@ -439,15 +439,14 @@ accordingly. Vim proceeds in this order:
:runtime! filetype.vim
:runtime! ftplugin.vim
:runtime! indent.vim
-< This step is skipped if ":filetype ..." was called before now or if
- the "-u NONE" command line argument was given.
+< Skipped if ":filetype … off" was called or if the "-u NONE" command
+ line argument was given.
5. Enable syntax highlighting.
This does the same as the command: >
:runtime! syntax/syntax.vim
-< Note: This enables filetype detection even if ":filetype off" was
- called before now.
- This step is skipped if the "-u NONE" command line argument was given.
+< Skipped if ":syntax off" was called or if the "-u NONE" command
+ line argument was given.
6. Load the plugin scripts. *load-plugins*
This does the same as the command: >
diff --git a/runtime/doc/term.txt b/runtime/doc/term.txt
index a694185fc9..6cf62f9bb5 100644
--- a/runtime/doc/term.txt
+++ b/runtime/doc/term.txt
@@ -38,13 +38,13 @@ Otherwise Nvim cannot know what sequences your terminal expects, and weird
or sub-optimal behavior will result (scrolling quirks, wrong colors, etc.).
$TERM is also important because it is mirrored by SSH to the remote session,
-unlike other common client-end environment variables ($COLORTERM,
-$XTERM_VERSION, $VTE_VERSION, $KONSOLE_PROFILE_NAME, $TERM_PROGRAM, ...).
+unlike most other environment variables.
For this terminal Set $TERM to |builtin-terms|
-------------------------------------------------------------------------
iTerm (original) iterm, iTerm.app N
iTerm2 (new capabilities) iterm2, iTerm2.app Y
+ Konsole konsole-256color N
anything libvte-based vte, vte-256color Y
(e.g. GNOME Terminal) (aliases: gnome, gnome-256color)
tmux tmux, tmux-256color Y
diff --git a/runtime/tutor/en/vim-01-beginner.tutor b/runtime/tutor/en/vim-01-beginner.tutor
index 3f243a18fa..dce98d53a4 100644
--- a/runtime/tutor/en/vim-01-beginner.tutor
+++ b/runtime/tutor/en/vim-01-beginner.tutor
@@ -1,26 +1,26 @@
# Welcome to the VIM Tutor
-Vim is a very powerful editor that has many commands, too many to explain in a
-tutor such as this. This tutor is designed to describe enough of the commands
-that you will be able to easily use Vim as an all-purpose editor. It is
-IMPORTANT to remember that this tutor is set up to teach by use. That means
-that you need to do the exercises to learn them properly. If you only read
-the text, you will soon forget what is most important!
+Vim is a very powerful editor that has many commands, too many to explain in
+a tutor such as this. This tutor is designed to describe enough of the
+commands that you will be able to easily use Vim as an all-purpose editor.
+It is IMPORTANT to remember that this tutor is set up to teach by use. That
+means that you need to do the exercises to learn them properly. If you only
+read the text, you will soon forget what is most important!
-For now, make sure that your Shift-Lock key is NOT depressed and press the `j`{normal}
-key enough times to move the cursor so that Lesson 0 completely fills the
-screen.
+For now, make sure that your Shift-Lock key is NOT depressed and press the
+`j`{normal} key enough times to move the cursor so that Lesson 0 completely
+fills the screen.
# Lesson 0
-NOTE: The commands in the lessons will modify the text, but those changes won't
-be saved. Don't worry about messing things up; just remember that pressing
-[<Esc>](<Esc>) and then [u](u) will undo the latest change.
+NOTE: The commands in the lessons will modify the text, but those changes
+won't be saved. Don't worry about messing things up; just remember that
+pressing [<Esc>](<Esc>) and then [u](u) will undo the latest change.
This tutorial is interactive, and there are a few things you should know.
-Pressing [<Enter>](<Enter>) over text highlighted [like this](holy-grail) will take you to some
-relevant help (hopefully), and pressing K over any word will try to do so too.
-Sometimes you will be required to modify text like
+Pressing [<Enter>](<Enter>) over text highlighted [like this](holy-grail )
+will take you to some relevant help (hopefully), and pressing K over any
+word will try to do so too. Sometimes you will be required to modify text like
this here
Once you have done the changes correctly, the ✗ sign at the left will change
to ✓. I imagine you can already see how neat Vim can be. ;)
@@ -33,10 +33,10 @@ or press a sequence of keys
<Esc>0f<Space>d3wP$P
~~~
-Text within <'s and >'s (like `<Enter>`{normal}) describes a key to press instead of text
-to type.
+Text within <'s and >'s (like `<Enter>`{normal}) describes a key to press
+instead of text to type.
-Now, move to the next lesson (remember, use the `j`{normal} key to scroll down).
+Now, move to the next lesson (use the `j`{normal} key to scroll down).
## Lesson 1.1: MOVING THE CURSOR
@@ -63,87 +63,90 @@ NOTE: The cursor keys should also work. But using hjkl you will be able to
# Lesson 1.2: EXITING VIM
-!! NOTE: Before executing any of the steps below, read this entire lesson !!
+!! NOTE: Before executing any of the steps below,
+read this entire lesson !!
- 1. Press the <Esc> key (to make sure you are in [Normal mode](Normal-mode).
+ 1. Press the <Esc> key (to make sure you are in Normal mode).
- 2. Type:
+ 2. Type:
`:q!`{vim} `<Enter>`{normal}.
This exits the editor, DISCARDING any changes you have made.
- 3. Open vim and get back here by executing the command that got you into this
- tutor. That might be:
+ 3. Open vim and get back here by executing the command that got you into
+ this tutor. That might be:
:Tutor <Enter>
- 4. If you have these steps memorized and are confident, execute steps
+ 4. If you have these steps memorized and are confident, execute steps
1 through 3 to exit and re-enter the editor.
NOTE: [:q!](:q) <Enter> discards any changes you made. In a few lessons you
will learn how to save the changes to a file.
- 5. Move the cursor down to Lesson 1.3.
+ 5. Move the cursor down to Lesson 1.3.
## Lesson 1.3: TEXT EDITING - DELETION
** Press `x`{normal} to delete the character under the cursor. **
- 1. Move the cursor to the line below marked --->.
+ 1. Move the cursor to the line below marked --->.
- 2. To fix the errors, move the cursor until it is on top of the
+ 2. To fix the errors, move the cursor until it is on top of the
character to be deleted.
- 3. Press [the x key](x) to delete the unwanted character.
+ 3. Press [the x key](x) to delete the unwanted character.
- 4. Repeat steps 2 through 4 until the sentence is correct.
+ 4. Repeat steps 2 through 4 until the sentence is correct.
The ccow jumpedd ovverr thhe mooon.
- 5. Now that the line is correct, go on to Lesson 1.4.
+ 5. Now that the line is correct, go on to Lesson 1.4.
-NOTE: As you go through this tutor, do not try to memorize, learn by usage.
+NOTE: As you go through this tutor, do not try to memorize, learn by
+ usage.
# Lesson 1.4: TEXT EDITING: INSERTION
** Press `i`{normal} to insert text. **
- 1. Move the cursor to the first line below marked --->.
+ 1. Move the cursor to the first line below marked --->.
- 2. To make the first line the same as the second, move the cursor on top
+ 2. To make the first line the same as the second, move the cursor on top
of the first character AFTER where the text is to be inserted.
- 3. Press `i`{normal} and type in the necessary additions.
+ 3. Press `i`{normal} and type in the necessary additions.
- 4. As each error is fixed press `<Esc>`{normal} to return to Normal mode.
+ 4. As each error is fixed press `<Esc>`{normal} to return to Normal mode.
Repeat steps 2 through 4 to correct the sentence.
There is text misng this .
There is some text missing from this line.
- 5. When you are comfortable inserting text move to Lesson 1.5.
+ 5. When you are comfortable inserting text move to Lesson 1.5.
# Lesson 1.5: TEXT EDITING: APPENDING
** Press `A`{normal} to append text. **
- 1. Move the cursor to the first line below marked --->.
- It does not matter on what character the cursor is in that line.
+ 1. Move the cursor to the first line below marked --->.
+ It does not matter on what character the cursor is in that line.
- 2. Press [A](A) and type in the necessary additions.
+ 2. Press [A](A) and type in the necessary additions.
- 3. As the text has been appended press `<Esc>`{normal} to return to Normal mode.
+ 3. As the text has been appended press `<Esc>`{normal} to return to Normal
+ mode.
- 4. Move the cursor to the second line marked ---> and repeat
- steps 2 and 3 to correct this sentence.
+ 4. Move the cursor to the second line marked ---> and repeat
+ steps 2 and 3 to correct this sentence.
There is some text missing from th
There is some text missing from this line.
There is also some text miss
There is also some text missing here.
- 5. When you are comfortable appending text move to Lesson 1.6.
+ 5. When you are comfortable appending text move to Lesson 1.6.
# Lesson 1.6: EDITING A FILE
@@ -151,49 +154,51 @@ There is also some text missing here.
!! NOTE: Before executing any of the steps below, read this entire lesson !!
- 1. Exit this tutor as you did in Lesson 1.2: `:q!`{vim}
- Or, if you have access to another terminal, do the following there.
+ 1. Exit this tutor as you did in Lesson 1.2: `:q!`{vim}
+ Or, if you have access to another terminal, do the following there.
- 2. At the shell prompt type this command:
+ 2. At the shell prompt type this command:
~~~ sh
$ vim tutor
~~~
- 'vim' is the command to start the Vim editor, 'tutor' is the name of the
- file you wish to edit. Use a file that may be changed.
+ 'vim' is the command to start the Vim editor, 'tutor' is the name of
+ the file you wish to edit. Use a file that may be changed.
- 3. Insert and delete text as you learned in the previous lessons.
+ 3. Insert and delete text as you learned in the previous lessons.
- 4. Save the file with changes and exit Vim with:
+ 4. Save the file with changes and exit Vim with:
~~~ cmd
:wq
~~~
- Note you'll need to press `<Enter>` to execute the command.
+ Note you'll need to press `<Enter>` to execute the command.
- 5. If you have quit vimtutor in step 1 restart the vimtutor and move down to
- the following summary.
+ 5. If you have quit vimtutor in step 1 restart the vimtutor and move down
+ to the following summary.
- 6. After reading the above steps and understanding them: do it.
+ 6. After reading the above steps and understanding them: do it.
# Lesson 1 SUMMARY
- 1. The cursor is moved using either the arrow keys or the hjkl keys.
+ 1. The cursor is moved using either the arrow keys or the hjkl keys.
h (left) j (down) k (up) l (right)
- 2. To start Vim from the shell prompt type:
+ 2. To start Vim from the shell prompt type:
~~~ sh
$ vim FILENAME
~~~
- 3. To exit Vim type: `<Esc>`{normal} `:q!`{vim} `<Enter>`{normal} to trash all changes.
- OR type: `<Esc>`{normal} `:wq`{vim} `<Enter>`{normal} to save the changes.
+ 3. To exit Vim type: `<Esc>`{normal} `:q!`{vim} `<Enter>`{normal} to trash
+ all changes.
+ OR type: `<Esc>`{normal} `:wq`{vim} `<Enter>`{normal} to save
+ the changes.
- 4. To delete the character at the cursor type: `x`{normal}
+ 4. To delete the character at the cursor type: `x`{normal}
- 5. To insert or append text type:
- `i`{normal} insert text `<Esc>`{normal} insert before the cursor.
- `A`{normal} append text `<Esc>`{normal} append after the line.
+ 5. To insert or append text type:
+ `i`{normal} insert text `<Esc>`{normal} insert before the cursor.
+ `A`{normal} append text `<Esc>`{normal} append after the line.
NOTE: Pressing `<Esc>`{normal} will place you in Normal mode or will cancel
an unwanted and partially completed command.
@@ -204,38 +209,38 @@ Now continue with Lesson 2.
** Type `dw`{normal} to delete a word. **
- 1. Press `<Esc>`{normal} to make sure you are in Normal mode.
+ 1. Press `<Esc>`{normal} to make sure you are in Normal mode.
- 2. Move the cursor to the line below marked --->.
+ 2. Move the cursor to the line below marked --->.
- 3. Move the cursor to the beginning of a word that needs to be deleted.
+ 3. Move the cursor to the beginning of a word that needs to be deleted.
- 4. Type [d](d)[w](w) to make the word disappear.
+ 4. Type [d](d)[w](w) to make the word disappear.
There are a some words fun that don't belong paper in this sentence.
- 5. Repeat steps 3 and 4 until the sentence is correct and go to Lesson 2.2.
+ 5. Repeat steps 3 and 4 until the sentence is correct and go to Lesson 2.2.
# Lesson 2.2: MORE DELETION COMMANDS
** Type `d$`{normal} to delete to the end of the line. **
- 1. Press `<Esc>`{normal} to make sure you are in Normal mode.
+ 1. Press `<Esc>`{normal} to make sure you are in Normal mode.
- 2. Move the cursor to the line below marked --->.
+ 2. Move the cursor to the line below marked --->.
- 3. Move the cursor to the end of the correct line (AFTER the first . ).
+ 3. Move the cursor to the end of the correct line (AFTER the first . ).
- 4. Type `d$`{normal} to delete to the end of the line.
+ 4. Type `d$`{normal} to delete to the end of the line.
Somebody typed the end of this line twice. end of this line twice.
- 5. Move on to Lesson 2.3 to understand what is happening.
+ 5. Move on to Lesson 2.3 to understand what is happening.
# Lesson 2.3: ON OPERATORS AND MOTIONS
-
-Many commands that change text are made from an [operator](operator) and a [motion](navigation).
+Many commands that change text are made from an [operator](operator) and
+a [motion](navigation).
The format for a delete command with the [d](d) delete operator is as follows:
d motion
@@ -251,26 +256,26 @@ The format for a delete command with the [d](d) delete operator is as follows:
Thus typing `de`{normal} will delete from the cursor to the end of the word.
-NOTE: Pressing just the motion while in Normal mode without an operator will
- move the cursor as specified.
+NOTE: Pressing just the motion while in Normal mode without an operator
+ will move the cursor as specified.
# Lesson 2.4: USING A COUNT FOR A MOTION
** Typing a number before a motion repeats it that many times. **
- 1. Move the cursor to the start of the line marked ---> below.
+ 1. Move the cursor to the start of the line marked ---> below.
- 2. Type `2w`{normal} to move the cursor two words forward.
+ 2. Type `2w`{normal} to move the cursor two words forward.
- 3. Type `3e`{normal} to move the cursor to the end of the third word forward.
+ 3. Type `3e`{normal} to move the cursor to the end of the third word forward.
- 4. Type `0`{normal} ([zero](0)) to move to the start of the line.
+ 4. Type `0`{normal} ([zero](0)) to move to the start of the line.
- 5. Repeat steps 2 and 3 with different numbers.
+ 5. Repeat steps 2 and 3 with different numbers.
This is just a line with words you can move around in.
- 6. Move on to Lesson 2.5.
+ 6. Move on to Lesson 2.5.
# Lesson 2.5: USING A COUNT TO DELETE MORE
@@ -280,12 +285,12 @@ In the combination of the delete operator and a motion mentioned above you
insert a count before the motion to delete more:
d number motion
- 1. Move the cursor to the first UPPER CASE word in the line marked --->.
+ 1. Move the cursor to the first UPPER CASE word in the line marked --->.
- 2. Type `d2w`{normal} to delete the two UPPER CASE words
+ 2. Type `d2w`{normal} to delete the two UPPER CASE words
- 3. Repeat steps 1 and 2 with a different count to delete the consecutive
- UPPER CASE words with one command
+ 3. Repeat steps 1 and 2 with a different count to delete the consecutive
+ UPPER CASE words with one command
This ABC DE line FGHI JK LMN OP of words is Q RS TUV cleaned up.
@@ -293,13 +298,13 @@ This ABC DE line FGHI JK LMN OP of words is Q RS TUV cleaned up.
** Type `dd`{normal} to delete a whole line. **
- Due to the frequency of whole line deletion, the designers of Vi decided
- it would be easier to simply type two d's to delete a line.
+Due to the frequency of whole line deletion, the designers of Vi decided
+it would be easier to simply type two d's to delete a line.
- 1. Move the cursor to the second line in the phrase below.
- 2. Type [dd](dd) to delete the line.
- 3. Now move to the fourth line.
- 4. Type `2dd`{normal} to delete two lines.
+ 1. Move the cursor to the second line in the phrase below.
+ 2. Type [dd](dd) to delete the line.
+ 3. Now move to the fourth line.
+ 4. Type `2dd`{normal} to delete two lines.
1) Roses are red,
2) Mud is fun,
@@ -313,54 +318,56 @@ This ABC DE line FGHI JK LMN OP of words is Q RS TUV cleaned up.
** Press `u`{normal} to undo the last commands, `U`{normal} to fix a whole line. **
- 1. Move the cursor to the line below marked ---> and place it on the
- first error.
- 2. Type `x`{normal} to delete the first unwanted character.
- 3. Now type `u`{normal} to undo the last command executed.
- 4. This time fix all the errors on the line using the `x`{normal} command.
- 5. Now type a capital `U`{normal} to return the line to its original state.
- 6. Now type `u`{normal} a few times to undo the `U`{normal} and preceding commands.
- 7. Now type `<Ctrl-r>`{normal} a few times to redo the commands (undo the undo's).
+ 1. Move the cursor to the line below marked ---> and place it on the
+ first error.
+ 2. Type `x`{normal} to delete the first unwanted character.
+ 3. Now type `u`{normal} to undo the last command executed.
+ 4. This time fix all the errors on the line using the `x`{normal} command.
+ 5. Now type a capital `U`{normal} to return the line to its original state.
+ 6. Now type `u`{normal} a few times to undo the `U`{normal} and preceding
+ commands.
+ 7. Now type `<C-r>`{normal} (Control + R) a few times to redo the commands
+ (undo the undos).
Fiix the errors oon thhis line and reeplace them witth undo.
- 8. These are very useful commands. Now move on to the Lesson 2 Summary.
+ 8. These are very useful commands. Now move on to the Lesson 2 Summary.
# Lesson 2 SUMMARY
- 1. To delete from the cursor up to the next word type: `dw`{normal}
- 2. To delete from the cursor to the end of a line type: `d$`{normal}
- 3. To delete a whole line type: `dd`{normal}
- 4. To repeat a motion prepend it with a number: `2w`{normal}
+ 1. To delete from the cursor up to the next word type: `dw`{normal}
+ 2. To delete from the cursor to the end of a line type: `d$`{normal}
+ 3. To delete a whole line type: `dd`{normal}
+ 4. To repeat a motion prepend it with a number: `2w`{normal}
- 5. The format for a change command is:
+ 5. The format for a change command is:
operator [number] motion
- where:
+ where:
operator - is what to do, such as [d](d) for delete
[number] - is an optional count to repeat the motion
motion - moves over the text to operate on, such as:
[w](w) (word),
[$]($) (to the end of line), etc.
- 6. To move to the start of the line use a zero: [0](0)
+ 6. To move to the start of the line use a zero: [0](0)
- 7. To undo previous actions, type: `u`{normal} (lowercase u)
- To undo all the changes on a line, type: `U`{normal} (capital U)
- To undo the undo's, type: `<Ctrl-r>`{normal}
+ 7. To undo previous actions, type: `u`{normal} (lowercase u)
+ To undo all the changes on a line, type: `U`{normal} (capital U)
+ To undo the undo's, type: `<C-r>`{normal}
# Lesson 3.1: THE PUT COMMAND
** Type `p`{normal} to put previously deleted text after the cursor. **
- 1. Move the cursor to the first ---> line below.
+ 1. Move the cursor to the first ---> line below.
- 2. Type `dd`{normal} to delete the line and store it in a Vim register.
+ 2. Type `dd`{normal} to delete the line and store it in a Vim register.
- 3. Move the cursor to the c) line, ABOVE where the deleted line should go.
+ 3. Move the cursor to the c) line, ABOVE where the deleted line should go.
- 4. Type `p`{normal} to put the line below the cursor.
+ 4. Type `p`{normal} to put the line below the cursor.
- 5. Repeat steps 2 through 4 to put all the lines in correct order.
+ 5. Repeat steps 2 through 4 to put all the lines in correct order.
d) Can you learn too?
b) Violets are blue,
@@ -371,18 +378,18 @@ a) Roses are red,
** Type `rx`{normal} to replace the character at the cursor with x. **
- 1. Move the cursor to the first line below marked --->.
+ 1. Move the cursor to the first line below marked --->.
- 2. Move the cursor so that it is on top of the first error.
+ 2. Move the cursor so that it is on top of the first error.
- 3. Type `r`{normal} and then the character which should be there.
+ 3. Type `r`{normal} and then the character which should be there.
- 4. Repeat steps 2 and 3 until the first line is equal to the second one.
+ 4. Repeat steps 2 and 3 until the first line is equal to the second one.
Whan this lime was tuoed in, someone presswd some wrojg keys!
When this line was typed in, someone pressed some wrong keys!
- 5. Now move on to Lesson 3.3.
+ 5. Now move on to Lesson 3.3.
NOTE: Remember that you should be learning by doing, not memorization.
@@ -390,15 +397,16 @@ NOTE: Remember that you should be learning by doing, not memorization.
** To change until the end of a word, type `ce`{normal}. **
- 1. Move the cursor to the first line below marked --->.
+ 1. Move the cursor to the first line below marked --->.
- 2. Place the cursor on the "u" in "lubw".
+ 2. Place the cursor on the "u" in "lubw".
- 3. Type `ce`{normal} and the correct word (in this case, type "ine" ).
+ 3. Type `ce`{normal} and the correct word (in this case, type "ine" ).
- 4. Press `<Esc>`{normal} and move to the next character that needs to be changed.
+ 4. Press `<Esc>`{normal} and move to the next character that needs to be
+ changed.
- 5. Repeat steps 3 and 4 until the first sentence is the same as the second.
+ 5. Repeat steps 3 and 4 until the first sentence is the same as the second.
This lubw has a few wptfd that mrrf changing usf the change operator.
This line has a few words that need changing using the change operator.
@@ -409,17 +417,17 @@ Notice that [c](c)e deletes the word and places you in Insert mode.
** The change operator is used with the same motions as delete. **
- 1. The change operator works in the same way as delete. The format is:
+ 1. The change operator works in the same way as delete. The format is:
c [number] motion
- 2. The motions are the same, such as `w`{normal} (word) and `$`{normal} (end of line).
+ 2. The motions are the same, such as `w`{normal} (word) and `$`{normal} (end of line).
- 3. Move to the first line below marked --->.
+ 3. Move to the first line below marked --->.
- 4. Move the cursor to the first error.
+ 4. Move the cursor to the first error.
- 5. Type `c$`{normal} and type the rest of the line like the second and press `<Esc>`{normal}.
+ 5. Type `c$`{normal} and type the rest of the line like the second and press `<Esc>`{normal}.
The end of this line needs some help to make it like the second.
The end of this line needs to be corrected using the `c$`{normal} command.
@@ -428,18 +436,18 @@ NOTE: You can use the Backspace key to correct mistakes while typing.
# Lesson 3 SUMMARY
- 1. To put back text that has just been deleted, type [p](p). This puts the
- deleted text AFTER the cursor (if a line was deleted it will go on the
- line below the cursor).
+ 1. To put back text that has just been deleted, type [p](p). This puts the
+ deleted text AFTER the cursor (if a line was deleted it will go on the
+ line below the cursor).
- 2. To replace the character under the cursor, type [r](r) and then the
- character you want to have there.
+ 2. To replace the character under the cursor, type [r](r) and then the
+ character you want to have there.
- 3. The [change operator](c) allows you to change from the cursor to where the
- motion takes you. Type `ce`{normal} to change from the cursor to the end of
- the word, `c$`{normal} to change to the end of a line.
+ 3. The [change operator](c) allows you to change from the cursor to where
+ the motion takes you. Type `ce`{normal} to change from the cursor to the
+ end of the word, `c$`{normal} to change to the end of a line.
- 4. The format for change is:
+ 4. The format for change is:
c [number] motion
@@ -447,42 +455,44 @@ Now go on to the next lesson.
# Lesson 4.1: CURSOR LOCATION AND FILE STATUS
-** Type `<Ctrl-g>`{normal} to show your location in the file and the file status.
+** Type `<C-g>`{normal} to show your location in a file and the file status.
Type `G`{normal} to move to a line in the file. **
NOTE: Read this entire lesson before executing any of the steps!!
- 1. Hold down the `<Ctrl>`{normal} key and press `g`{normal}. We call this `<Ctrl-g>`{normal}.
- A message will appear at the bottom of the page with the filename and the
- position in the file. Remember the line number for Step 3.
+ 1. Hold down the `<Ctrl>`{normal} key and press `g`{normal}. We call this
+ `<C-g>`{normal}. A message will appear at the bottom of the page with the
+ filename and the position in the file. Remember the line number for
+ Step 3.
-NOTE: You may see the cursor position in the lower right corner of the screen
- This happens when the ['ruler']('ruler') option is set (see `:help 'ruler'`{vim} ).
+NOTE: You may see the cursor position in the lower right corner of the
+ screen. This happens when the ['ruler']('ruler') option is set.
+ 2. Press [G](G) to move you to the bottom of the file.
+ Type [gg](gg) to move you to the start of the file.
- 2. Press [G](G) to move you to the bottom of the file.
- Type [gg](gg) to move you to the start of the file.
+ 3. Type the number of the line you were on and then `G`{normal}. This will
+ return you to the line you were on when you first pressed `<C-g>`{normal}.
- 3. Type the number of the line you were on and then `G`{normal}. This will
- return you to the line you were on when you first pressed `<Ctrl-g>`{normal}.
-
- 4. If you feel confident to do this, execute steps 1 through 3.
+ 4. If you feel confident to do this, execute steps 1 through 3.
# Lesson 4.2: THE SEARCH COMMAND
** Type `/`{normal} followed by a phrase to search for the phrase. **
- 1. In Normal mode type the `/`{normal} character. Notice that it and the cursor
- appear at the bottom of the screen as with the `:`{normal} command.
+ 1. In Normal mode type the `/`{normal} character. Notice that it and the
+ cursor appear at the bottom of the screen as with the `:`{normal} command.
- 2. Now type 'errroor' `<Enter>`{normal}. This is the word you want to search for.
+ 2. Now type 'errroor' `<Enter>`{normal}. This is the word you want to search
+ for.
- 3. To search for the same phrase again, simply type [n](n).
- To search for the same phrase in the opposite direction, type [N](N).
+ 3. To search for the same phrase again, simply type [n](n).
+ To search for the same phrase in the opposite direction, type [N](N).
- 4. To search for a phrase in the backward direction, use [?](?) instead of `/`{normal}.
+ 4. To search for a phrase in the backward direction, use [?](?) instead
+ of `/`{normal}.
- 5. To go back to where you came from press `<Ctrl-o>`{normal} (keep `<Ctrl>`{normal} pressed down while
- pressing the letter `o`{normal}). Repeat to go back further. `<Ctrl-i>`{normal} goes forward.
+ 5. To go back to where you came from press `<C-o>`{normal} (keep `<Ctrl>`{normal} pressed down while pressing the letter `o`{normal}). Repeat to go back
+ further. `<C-i>`{normal} goes forward.
"errroor" is not the way to spell error; errroor is an error.
@@ -493,15 +503,15 @@ NOTE: When the search reaches the end of the file it will continue at the
** Type `%`{normal} to find a matching ),], or }. **
- 1. Place the cursor on any (, [, or { in the line below marked --->.
+ 1. Place the cursor on any (, [, or { in the line below marked --->.
- 2. Now type the [%](%) character.
+ 2. Now type the [%](%) character.
- 3. The cursor will move to the matching parenthesis or bracket.
+ 3. The cursor will move to the matching parenthesis or bracket.
- 4. Type `%`{normal} to move the cursor to the other matching bracket.
+ 4. Type `%`{normal} to move the cursor to the other matching bracket.
- 5. Move the cursor to another (,),[,],{ or } and see what `%`{normal} does.
+ 5. Move the cursor to another (,),[,],{ or } and see what `%`{normal} does.
This ( is a test line with ('s, ['s ] and {'s } in it. ))
@@ -511,75 +521,79 @@ NOTE: This is very useful in debugging a program with unmatched parentheses!
** Type `:s/old/new/g` to substitute "new" for "old". **
- 1. Move the cursor to the line below marked --->.
+ 1. Move the cursor to the line below marked --->.
- 2. Type
+ 2. Type
~~~ cmd
:s/thee/the/
~~~
NOTE that the [:s](:s) command only changed the first occurrence of "thee" in the line.
- 3. Now type
+ 3. Now type
~~~ cmd
:s/thee/the/g
~~~
- Adding the g [flag](:s_flags) means to substitute globally in the line, change
- all occurrences of "thee" in the line.
+ Adding the g [flag](:s_flags) means to substitute globally in the line,
+ change all occurrences of "thee" in the line.
Usually thee best time to see thee flowers is in thee spring.
- 4. To change every occurrence of a character string between two lines, type
+ 4. To change every occurrence of a character string between two lines, type
~~~ cmd
:#,#s/old/new/g
~~~
- where #,# are the line numbers of the range of lines where the substitution is to be done.
+ where #,# are the line numbers of the range of lines where the
+ substitution is to be done.
- Type
+ Type
~~~ cmd
- :%s/old/new/g
+ :%s/old/new/g
~~~
- to change every occurrence in the whole file.
+ to change every occurrence in the whole file.
- Type
+ Type
~~~ cmd
- :%s/old/new/gc
+ :%s/old/new/gc
~~~
- to find every occurrence in the whole file, with a prompt whether to substitute or not.
+ to find every occurrence in the whole file, with a prompt whether to
+ substitute or not.
# Lesson 4 SUMMARY
- 1. `<Ctrl-g>`{normal} displays your location in the file and the file status.
- `G`{normal} moves to the end of the file.
- number `G`{normal} moves to that line number.
- `gg`{normal} moves to the first line.
+ 1. `<C-g>`{normal} displays your location and the file status.
+ `G`{normal} moves to the end of the file.
+ number `G`{normal} moves to that line number.
+ `gg`{normal} moves to the first line.
- 2. Typing `/`{normal} followed by a phrase searches FORWARD for the phrase.
- Typing `?`{normal} followed by a phrase searches BACKWARD for the phrase.
- After a search type `n`{normal} to find the next occurrence in the same direction
- or `N`{normal} to search in the opposite direction.
- `<Ctrl-o>`{normal} takes you back to older positions, `<Ctrl-i>`{normal} to newer positions.
+ 2. Typing `/`{normal} followed by a phrase searches FORWARD for the phrase.
+ Typing `?`{normal} followed by a phrase searches BACKWARD for the phrase.
+ After a search type `n`{normal} to find the next occurrence in the same
+ direction or `N`{normal} to search in the opposite direction.
+ `<C-o>`{normal} takes you back to older positions, `<C-i>`{normal} to
+ newer positions.
- 3. Typing `%`{normal} while the cursor is on a (,),[,],{, or } goes to its match.
+ 3. Typing `%`{normal} while the cursor is on a (,),[,],{, or } goes to its
+ match.
- 4. To substitute new for the first old in a line type
+ 4. To substitute new for the first old in a line type
~~~ cmd
:s/old/new
~~~
- To substitute new for all 'old's on a line type
+ To substitute new for all 'old's on a line type
~~~ cmd
:s/old/new/g
~~~
- To substitute phrases between two line #'s type
+ To substitute phrases between two line #'s type
~~~ cmd
:#,#s/old/new/g
~~~
- To substitute all occurrences in the file type
+ To substitute all occurrences in the file type
~~~ cmd
:%s/old/new/g
~~~
- To ask for confirmation each time add 'c'
+ To ask for confirmation each time add 'c'
~~~ cmd
:%s/old/new/gc
~~~
@@ -588,15 +602,15 @@ Usually thee best time to see thee flowers is in thee spring.
** Type `:!`{vim} followed by an external command to execute that command. **
- 1. Type the familiar command `:`{normal} to set the cursor at the bottom of the
- screen. This allows you to enter a command-line command.
+ 1. Type the familiar command `:`{normal} to set the cursor at the bottom of
+ the screen. This allows you to enter a command-line command.
- 2. Now type the [!](!cmd) (exclamation point) character. This allows you to
- execute any external shell command.
+ 2. Now type the [!](!cmd) (exclamation point) character. This allows you to
+ execute any external shell command.
- 3. As an example type "ls" following the "!" and then hit `<Enter>`{normal}. This
- will show you a listing of your directory, just as if you were at the
- shell prompt.
+ 3. As an example type "ls" following the "!" and then hit `<Enter>`{normal}.
+ This will show you a listing of your directory, just as if you were
+ at the shell prompt.
NOTE: It is possible to execute any external command this way, also with
arguments.
@@ -608,24 +622,24 @@ NOTE: All `:`{vim} commands must be finished by hitting `<Enter>`{normal}.
** To save the changes made to the text, type `:w`{vim} FILENAME. **
- 1. Type `:!ls`{vim} to get a listing of your directory.
- You already know you must hit `<Enter>`{normal} after this.
+ 1. Type `:!ls`{vim} to get a listing of your directory.
+ You already know you must hit `<Enter>`{normal} after this.
- 2. Choose a filename that does not exist yet, such as TEST.
+ 2. Choose a filename that does not exist yet, such as TEST.
- 3. Now type:
+ 3. Now type:
~~~ cmd
:w TEST
~~~
- (where TEST is the filename you chose.)
+ (where TEST is the filename you chose.)
- 4. This saves the whole file (the Vim Tutor) under the name TEST.
- To verify this, type `:!ls`{vim} again to see your directory.
+ 4. This saves the whole file (the Vim Tutor) under the name TEST.
+ To verify this, type `:!ls`{vim} again to see your directory.
NOTE: If you were to exit Vim and start it again with `nvim TEST`, the file
would be an exact copy of the tutor when you saved it.
- 5. Now remove the file by typing:
+ 5. Now remove the file by typing:
~~~ cmd
:!rm TEST
~~~
@@ -634,53 +648,52 @@ NOTE: If you were to exit Vim and start it again with `nvim TEST`, the file
** To save part of the file, type `v`{normal} motion `:w FILENAME`{vim}. **
- 1. Move the cursor to this line.
+ 1. Move the cursor to this line.
- 2. Press [v](v) and move the cursor to the fifth item below. Notice that the
- text is highlighted.
+ 2. Press [v](v) and move the cursor to the fifth item below. Notice that the
+ text is highlighted.
- 3. Press the `:`{normal} character. At the bottom of the screen
+ 3. Press the `:`{normal} character. At the bottom of the screen
:'<,'>
will appear.
- 4. Type
+ 4. Type
`:w TEST`{vim}
- where TEST is a filename that does not exist yet. Verify that you see
+ where TEST is a filename that does not exist yet. Verify that you see
`:'<,'>w TEST`{vim}
- before you press `<Enter>`{normal}.
+ before you press `<Enter>`{normal}.
- 5. Vim will write the selected lines to the file TEST. Use `:!ls`{vim} to see it.
- Do not remove it yet! We will use it in the next lesson.
+ 5. Vim will write the selected lines to the file TEST. Use `:!ls`{vim} to see it. Do not remove it yet! We will use it in the next lesson.
NOTE: Pressing [v](v) starts [Visual selection](visual-mode). You can move
the cursor around to make the selection bigger or smaller. Then you can
- use an operator to do something with the text. For example, `d`{normal} deletes
- the text.
+ use an operator to do something with the text. For example, `d`{normal}
+ deletes the text.
# Lesson 5.4: RETRIEVING AND MERGING FILES
** To insert the contents of a file, type `:r FILENAME`{vim}. **
- 1. Place the cursor just above this line.
+ 1. Place the cursor just above this line.
NOTE: After executing Step 2 you will see text from Lesson 5.3. Then move
DOWN to see this lesson again.
- 2. Now retrieve your TEST file using the command
+ 2. Now retrieve your TEST file using the command
`:r TEST`{vim}
where TEST is the name of the file you used.
The file you retrieve is placed below the cursor line.
- 3. To verify that a file was retrieved, cursor back and notice that there
- are now two copies of Lesson 5.3, the original and the file version.
+ 3. To verify that a file was retrieved, cursor back and notice that there
+ are now two copies of Lesson 5.3, the original and the file version.
NOTE: You can also read the output of an external command. For example,
@@ -690,39 +703,39 @@ NOTE: You can also read the output of an external command. For example,
# Lesson 5 SUMMARY
- 1. [:!command](:!cmd) executes an external command.
+ 1. [:!command](:!cmd) executes an external command.
Some useful examples are:
`:!ls`{vim} - shows a directory listing
`:!rm FILENAME`{vim} - removes file FILENAME
- 2. [:w](:w) FILENAME writes the current Vim file to disk with
- name FILENAME.
+ 2. [:w](:w) FILENAME writes the current Vim file to disk with
+ name FILENAME.
- 3. [v](v) motion :w FILENAME saves the Visually selected lines in file
- FILENAME.
+ 3. [v](v) motion :w FILENAME saves the Visually selected lines in file
+ FILENAME.
- 4. [:r](:r) FILENAME retrieves disk file FILENAME and puts it
- below the cursor position.
+ 4. [:r](:r) FILENAME retrieves disk file FILENAME and puts it
+ below the cursor position.
- 5. [:r !dir](:r!) reads the output of the dir command and
- puts it below the cursor position.
+ 5. [:r !dir](:r!) reads the output of the dir command and
+ puts it below the cursor position.
# Lesson 6.1: THE OPEN COMMAND
** Type `o`{normal} to open a line below the cursor and place you in Insert mode. **
- 1. Move the cursor to the line below marked --->.
+ 1. Move the cursor to the line below marked --->.
- 2. Type the lowercase letter `o`{normal} to [open](o) up a line BELOW the cursor and place
- you in Insert mode.
+ 2. Type the lowercase letter `o`{normal} to [open](o) up a line BELOW the
+ cursor and place you in Insert mode.
- 3. Now type some text and press `<Esc>`{normal} to exit Insert mode.
+ 3. Now type some text and press `<Esc>`{normal} to exit Insert mode.
After typing `o`{normal} the cursor is placed on the open line in Insert mode.
- 4. To open up a line ABOVE the cursor, simply type a [capital O](O), rather
- than a lowercase `o`{normal}. Try this on the line below.
+ 4. To open up a line ABOVE the cursor, simply type a [capital O](O), rather
+ than a lowercase `o`{normal}. Try this on the line below.
Open up a line above this by typing O while the cursor is on this line.
@@ -730,37 +743,39 @@ Open up a line above this by typing O while the cursor is on this line.
** Type `a`{normal} to insert text AFTER the cursor. **
- 1. Move the cursor to the start of the line below marked --->.
+ 1. Move the cursor to the start of the line below marked --->.
- 2. Press `e`{normal} until the cursor is on the end of "li".
+ 2. Press `e`{normal} until the cursor is on the end of "li".
- 3. Type the lowercase letter `a`{normal} to [append](a) text AFTER the cursor.
+ 3. Type the lowercase letter `a`{normal} to [append](a) text AFTER the
+ cursor.
- 4. Complete the word like the line below it. Press `<Esc>`{normal} to exit Insert
- mode.
+ 4. Complete the word like the line below it. Press `<Esc>`{normal} to exit
+ Insert mode.
- 5. Use `e`{normal} to move to the next incomplete word and repeat steps 3 and 4.
+ 5. Use `e`{normal} to move to the next incomplete word and repeat steps 3
+ and 4.
This li will allow you to pract appendi text to a line.
This line will allow you to practice appending text to a line.
-NOTE: [a](a), [i](i) and [A](A) all go to the same Insert mode, the only difference is where
- the characters are inserted.
+NOTE: [a](a), [i](i) and [A](A) all go to the same Insert mode, the only
+ difference is where the characters are inserted.
# Lesson 6.3: ANOTHER WAY TO REPLACE
** Type a capital `R`{normal} to replace more than one character. **
- 1. Move the cursor to the first line below marked --->. Move the cursor to
+ 1. Move the cursor to the first line below marked --->. Move the cursor to
the beginning of the first "xxx".
- 2. Now press `R`{normal} ([capital R](R)) and type the number below it in the second line, so that it
- replaces the "xxx".
+ 2. Now press `R`{normal} ([capital R](R)) and type the number below it in the
+ second line, so that it replaces the "xxx".
- 3. Press `<Esc>`{normal} to leave [Replace mode](mode-replace). Notice that the rest of the line
- remains unmodified.
+ 3. Press `<Esc>`{normal} to leave [Replace mode](mode-replace). Notice that
+ the rest of the line remains unmodified.
- 4. Repeat the steps to replace the remaining "xxx".
+ 4. Repeat the steps to replace the remaining "xxx".
Adding 123 to xxx gives you xxx.
Adding 123 to 456 gives you 579.
@@ -772,51 +787,53 @@ NOTE: Replace mode is like Insert mode, but every typed character deletes an
** Use the `y`{normal} operator to copy text and `p`{normal} to paste it. **
- 1. Go to the line marked with ---> below and place the cursor after "a)".
+ 1. Go to the line marked with ---> below and place the cursor after "a)".
- 2. Start Visual mode with `v`{normal} and move the cursor to just before "first".
+ 2. Start Visual mode with `v`{normal} and move the cursor to just before
+ "first".
- 3. Type `y`{normal} to [yank](yank) (copy) the highlighted text.
+ 3. Type `y`{normal} to [yank](yank) (copy) the highlighted text.
- 4. Move the cursor to the end of the next line: `j$`{normal}
+ 4. Move the cursor to the end of the next line: `j$`{normal}
- 5. Type `p`{normal} to [put](put) (paste) the text.
+ 5. Type `p`{normal} to [put](put) (paste) the text.
- 6. Press `a`{normal} and then type "second". Press `<Esc>`{normal} to leave Insert mode.
+ 6. Press `a`{normal} and then type "second". Press `<Esc>`{normal} to leave
+ Insert mode.
- 7. Use Visual mode to select " item.", yank it with `y`{normal}, move to the end of
- the next line with `j$`{normal} and put the text there with `p`{normal}.
+ 7. Use Visual mode to select "item.", yank it with `y`{normal}, move to the
+ end of the next line with `j$`{normal} and put the text there with `p`{normal}
a) This is the first item.
b)
-NOTE: you can also use `y`{normal} as an operator; `yw`{normal} yanks one word.
+NOTE: you can use `y`{normal} as an operator: `yw`{normal} yanks one word.
# Lesson 6.5: SET OPTION
** Set an option so a search or substitute ignores case. **
- 1. Search for 'ignore' by entering: `/ignore`
- Repeat several times by pressing `n`{normal}.
+ 1. Search for 'ignore' by entering: `/ignore`
+ Repeat several times by pressing `n`{normal}.
- 2. Set the 'ic' (Ignore case) option by entering:
+ 2. Set the 'ic' (Ignore case) option by entering:
~~~ cmd
:set ic
~~~
- 3. Now search for 'ignore' again by pressing `n`{normal}.
- Notice that Ignore and IGNORE are now also found.
+ 3. Now search for 'ignore' again by pressing `n`{normal}.
+ Notice that Ignore and IGNORE are now also found.
- 4. Set the 'hlsearch' and 'incsearch' options:
+ 4. Set the 'hlsearch' and 'incsearch' options:
~~~ cmd
:set hls is
~~~
- 5. Now type the search command again and see what happens: /ignore <Enter>
+ 5. Now type the search command again and see what happens: /ignore <Enter>
- 6. To disable ignoring case enter:
+ 6. To disable ignoring case enter:
~~~ cmd
:set noic
~~~
- 7. To toggle the value of a setting, prepend it with "inv":
+ 7. To toggle the value of a setting, prepend it with "inv":
~~~ cmd
:set invic
~~~
@@ -829,19 +846,20 @@ NOTE: If you want to ignore case for just one search command, use [\c](/\c)
# Lesson 6 SUMMARY
- 1. Type `o`{normal} to open a line BELOW the cursor and start Insert mode.
- Type `O`{normal} to open a line ABOVE the cursor.
+ 1. Type `o`{normal} to open a line BELOW the cursor and start Insert mode.
+ Type `O`{normal} to open a line ABOVE the cursor.
- 2. Type `a`{normal} to insert text AFTER the cursor.
- Type `A`{normal} to insert text after the end of the line.
+ 2. Type `a`{normal} to insert text AFTER the cursor.
+ Type `A`{normal} to insert text after the end of the line.
- 3. The `e`{normal} command moves to the end of a word.
+ 3. The `e`{normal} command moves to the end of a word.
- 4. The `y`{normal} operator yanks (copies) text, `p`{normal} puts (pastes) it.
+ 4. The `y`{normal} operator copies text, `p`{normal} pastes it.
- 5. Typing a capital `R`{normal} enters Replace mode until `<Esc>`{normal} is pressed.
+ 5. Typing a capital `R`{normal} enters Replace mode until `<Esc>`{normal} is
+ pressed.
- 6. Typing "[:set](:set) xxx" sets the option "xxx". Some options are:
+ 6. Typing "[:set](:set) xxx" sets the option "xxx". Some options are:
'ic' 'ignorecase' ignore upper/lower case when searching
'is' 'incsearch' show partial matches for a search phrase
@@ -849,11 +867,11 @@ NOTE: If you want to ignore case for just one search command, use [\c](/\c)
You can either use the long or the short option name.
- 7. Prepend "no" to switch an option off:
+ 7. Prepend "no" to switch an option off:
~~~ cmd
:set noic
~~~
- 8. Prepend "inv" to toggle an option:
+ 8. Prepend "inv" to toggle an option:
~~~ cmd
:set invic
~~~
@@ -870,7 +888,7 @@ these three:
`:help`{vim}
Read the text in the help window to find out how the help works.
-Type `<Ctrl-w><Ctrl-w>`{normal} to jump from one window to another.
+Type `<C-w><C-w>`{normal} to jump from one window to another.
Type `:q`{vim} to close the help window.
You can find help on just about any subject, by giving an argument to the
@@ -888,13 +906,13 @@ You can find help on just about any subject, by giving an argument to the
Vim has many more features than Vi, but most of them are disabled by
default. To start using more features you have to create a "vimrc" file.
- 1. Start editing the "vimrc" file. This depends on your system:
+ 1. Start editing the "vimrc" file. This depends on your system:
`:e ~/.config/nvim/init.vim`{vim} for Unix-like systems
- 2. Now read the example "vimrc" file contents:
+ 2. Now read the example "vimrc" file contents:
`:r $VIMRUNTIME/vimrc_example.vim`{vim}
- 3. Write the file with:
+ 3. Write the file with:
`:w`{vim}
The next time you start Vim it will use syntax highlighting.
@@ -903,36 +921,38 @@ default. To start using more features you have to create a "vimrc" file.
# Lesson 7.3: COMPLETION
-** Command line completion with `<Ctrl-d>`{normal} and `<Tab>`{normal}. **
+** Command line completion with `<C-d>`{normal} and `<Tab>`{normal}. **
- 1. Look what files exist in the directory: `:!ls`{vim}
+ 1. Look what files exist in the directory: `:!ls`{vim}
- 2. Type the start of a command: `:e`{vim}
+ 2. Type the start of a command: `:e`{vim}
- 3. Press `<Ctrl-d>`{normal} and Vim will show a list of commands that start with "e".
+ 3. Press `<C-d>`{normal} and Vim will show a list of commands that start
+ with "e".
- 4. Press `<Tab>`{normal} and Vim will complete the command name to ":edit".
+ 4. Press `<Tab>`{normal} and Vim will complete the command name to ":edit".
- 5. Now add a space and the start of an existing file name: `:edit FIL`{vim}
+ 5. Now add a space and the start of an existing file name: `:edit FIL`{vim}
- 6. Press `<Tab>`{normal}. Vim will complete the name (if it is unique).
+ 6. Press `<Tab>`{normal}. Vim will complete the name (if it is unique).
-NOTE: Completion works for many commands. It is especially useful for `:help`{vim}.
+NOTE: Completion works for many commands. It is especially useful for
+ `:help`{vim}.
# Lesson 7 SUMMARY
- 1. Type `:help`{vim}
- or press `<F1>`{normal} or `<Help>`{normal} to open a help window.
+ 1. Type `:help`{vim}
+ or press `<F1>`{normal} or `<Help>`{normal} to open a help window.
- 2. Type `:help TOPIC`{vim} to find help on TOPIC.
+ 2. Type `:help TOPIC`{vim} to find help on TOPIC.
- 3. Type `<Ctrl-w><Ctrl-w>`{normal} to jump to another window
+ 3. Type `<C-w><C-w>`{normal} to jump to another window
- 4. Type `:q`{vim} to close the help window
+ 4. Type `:q`{vim} to close the help window
- 5. Create a vimrc startup script to keep your preferred settings.
+ 5. Create a vimrc startup script to keep your preferred settings.
- 6. While in command mode, press `<Ctrl-d>`{normal} to see possible completions.
+ 6. While in command mode, press `<C-d>`{normal} to see possible completions.
Press `<Tab>`{normal} to use one completion.
# CONCLUSION
@@ -941,7 +961,8 @@ This was intended to give a brief overview of the Vim editor, just enough to
allow you to use the editor fairly easily. It is far from complete as Vim has
many many more commands. Consult the help often.
-There are many resources online to learn more about vim. Here's a bunch of them:
+There are many resources online to learn more about vim. Here's a bunch of
+them:
- *Learn Vim Progressively*: http://yannesposito.com/Scratch/en/blog/Learn-Vim-Progressively/
- *Learning Vim in 2014*: http://benmccormick.org/learning-vim-in-2014/
@@ -951,8 +972,8 @@ There are many resources online to learn more about vim. Here's a bunch of them:
- *7 Habits of Effective Text Editing*: http://www.moolenaar.net/habits.html
- *vim-galore*: https://github.com/mhinz/vim-galore
-If you prefer a book, *Practical Vim* by Drew Neil is recommended often (the sequel, *Modern
-Vim*, includes material specific to nvim).
+If you prefer a book, *Practical Vim* by Drew Neil is recommended often
+(the sequel, *Modern Vim*, includes material specific to nvim).
This tutorial was written by Michael C. Pierce and Robert K. Ware, Colorado
School of Mines using ideas supplied by Charles Smith, Colorado State
diff --git a/runtime/tutor/en/vim-01-beginner.tutor.json b/runtime/tutor/en/vim-01-beginner.tutor.json
index 444bd7c4b7..2f87d7543f 100644
--- a/runtime/tutor/en/vim-01-beginner.tutor.json
+++ b/runtime/tutor/en/vim-01-beginner.tutor.json
@@ -1,45 +1,43 @@
{
"expect": {
"24": -1,
- "102": "The cow jumped over the moon.",
- "122": "There is some text missing from this line.",
- "123": "There is some text missing from this line.",
- "141": "There is some text missing from this line.",
- "142": "There is some text missing from this line.",
- "143": "There is also some text missing here.",
- "144": "There is also some text missing here.",
- "215": "There are some words that don't belong in this sentence.",
- "231": "Somebody typed the end of this line twice.",
- "271": -1,
- "290": "This line of words is cleaned up.",
- "304": -1,
- "305": -1,
- "306": -1,
- "307": -1,
- "308": -1,
+ "103": "The cow jumped over the moon.",
+ "124": "There is some text missing from this line.",
+ "125": "There is some text missing from this line.",
+ "144": "There is some text missing from this line.",
+ "145": "There is some text missing from this line.",
+ "146": "There is also some text missing here.",
+ "147": "There is also some text missing here.",
+ "220": "There are some words that don't belong in this sentence.",
+ "236": "Somebody typed the end of this line twice.",
+ "276": -1,
+ "295": "This line of words is cleaned up.",
"309": -1,
"310": -1,
- "325": "Fix the errors on this line and replace them with undo.",
- "365": -1,
- "366": -1,
- "367": -1,
- "368": -1,
- "382": "When this line was typed in, someone pressed some wrong keys!",
- "383": "When this line was typed in, someone pressed some wrong keys!",
- "403": "This line has a few words that need changing using the change operator.",
- "404": "This line has a few words that need changing using the change operator.",
- "424": "The end of this line needs to be corrected using the c$ command.",
- "425": "The end of this line needs to be corrected using the c$ command.",
- "487": -1,
- "506": -1,
- "531": "Usually the best time to see the flowers is in the spring.",
- "722": -1,
- "727": -1,
- "744": "This line will allow you to practice appending text to a line.",
- "745": "This line will allow you to practice appending text to a line.",
- "765": "Adding 123 to 456 gives you 579.",
- "766": "Adding 123 to 456 gives you 579.",
- "790": "a) This is the first item.",
- "791": " b) This is the second item."
+ "311": -1,
+ "312": -1,
+ "313": -1,
+ "314": -1,
+ "315": -1,
+ "332": "Fix the errors on this line and replace them with undo.",
+ "372": -1,
+ "373": -1,
+ "374": -1,
+ "375": -1,
+ "389": "When this line was typed in, someone pressed some wrong keys!",
+ "390": "When this line was typed in, someone pressed some wrong keys!",
+ "411": "This line has a few words that need changing using the change operator.",
+ "412": "This line has a few words that need changing using the change operator.",
+ "432": "The end of this line needs to be corrected using the c$ command.",
+ "433": "The end of this line needs to be corrected using the c$ command.",
+ "497": -1,
+ "516": -1,
+ "541": "Usually the best time to see the flowers is in the spring.",
+ "759": "This line will allow you to practice appending text to a line.",
+ "760": "This line will allow you to practice appending text to a line.",
+ "780": "Adding 123 to 456 gives you 579.",
+ "781": "Adding 123 to 456 gives you 579.",
+ "807": "a) This is the first item.",
+ "808": " b) This is the second item."
}
}
diff --git a/scripts/vim-patch.sh b/scripts/vim-patch.sh
index c6ff280bb5..ac5e326e9d 100755
--- a/scripts/vim-patch.sh
+++ b/scripts/vim-patch.sh
@@ -234,7 +234,7 @@ stage_patch() {
printf "\n✘ 'patch' command not found\n"
else
printf "\nApplying patch...\n"
- patch -p1 --posix < "${patch_file}"
+ patch -p1 --posix < "${patch_file}" || true
fi
printf "\nInstructions:\n Proceed to port the patch.\n"
else
diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c
index 4492f8bb93..26ad7ac1a6 100644
--- a/src/nvim/api/private/helpers.c
+++ b/src/nvim/api/private/helpers.c
@@ -787,16 +787,14 @@ bool object_to_vim(Object obj, typval_T *tv, Error *err)
for (uint32_t i = 0; i < obj.data.array.size; i++) {
Object item = obj.data.array.items[i];
- listitem_T *li = tv_list_item_alloc();
+ typval_T li_tv;
- if (!object_to_vim(item, TV_LIST_ITEM_TV(li), err)) {
- // cleanup
- tv_list_item_free(li);
+ if (!object_to_vim(item, &li_tv, err)) {
tv_list_free(list);
return false;
}
- tv_list_append(list, li);
+ tv_list_append_owned_tv(list, li_tv);
}
tv_list_ref(list);
diff --git a/src/nvim/eval.c b/src/nvim/eval.c
index e6cb8cdec0..f34b6db8d8 100644
--- a/src/nvim/eval.c
+++ b/src/nvim/eval.c
@@ -215,6 +215,15 @@ static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL};
static int echo_attr = 0; /* attributes used for ":echo" */
+/// Describe data to return from find_some_match()
+typedef enum {
+ kSomeMatch, ///< Data for match().
+ kSomeMatchEnd, ///< Data for matchend().
+ kSomeMatchList, ///< Data for matchlist().
+ kSomeMatchStr, ///< Data for matchstr().
+ kSomeMatchStrPos, ///< Data for matchstrpos().
+} SomeMatchType;
+
/// trans_function_name() flags
typedef enum {
TFN_INT = 1, ///< May use internal function name
@@ -1506,7 +1515,6 @@ ex_let_vars (
)
{
char_u *arg = arg_start;
- int i;
typval_T ltv;
if (*arg != '[') {
@@ -1525,17 +1533,17 @@ ex_let_vars (
}
list_T *const l = tv->vval.v_list;
- i = tv_list_len(l);
- if (semicolon == 0 && var_count < i) {
+ const int len = tv_list_len(l);
+ if (semicolon == 0 && var_count < len) {
EMSG(_("E687: Less targets than List items"));
return FAIL;
}
- if (var_count - semicolon > i) {
+ if (var_count - semicolon > len) {
EMSG(_("E688: More targets than List items"));
return FAIL;
}
- // l may actually be NULL, but it should fail with E688 or even earlier if you
- // try to do ":let [] = v:_null_list".
+ // List l may actually be NULL, but it should fail with E688 or even earlier
+ // if you try to do ":let [] = v:_null_list".
assert(l != NULL);
listitem_T *item = tv_list_first(l);
@@ -1543,11 +1551,11 @@ ex_let_vars (
arg = skipwhite(arg + 1);
arg = ex_let_one(arg, TV_LIST_ITEM_TV(item), true, (const char_u *)",;]",
nextchars);
- item = TV_LIST_ITEM_NEXT(l, item);
if (arg == NULL) {
return FAIL;
}
+ item = TV_LIST_ITEM_NEXT(l, item);
arg = skipwhite(arg);
if (*arg == ';') {
/* Put the rest of the list (may be empty) in the var after ';'.
@@ -1559,7 +1567,7 @@ ex_let_vars (
}
ltv.v_type = VAR_LIST;
- ltv.v_lock = 0;
+ ltv.v_lock = VAR_UNLOCKED;
ltv.vval.v_list = rest_list;
tv_list_ref(rest_list);
@@ -2076,6 +2084,8 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
* Loop until no more [idx] or .key is following.
*/
lp->ll_tv = &v->di_tv;
+ var1.v_type = VAR_UNKNOWN;
+ var2.v_type = VAR_UNKNOWN;
while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT)) {
if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
&& !(lp->ll_tv->v_type == VAR_DICT
@@ -2126,9 +2136,7 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
if (!quiet) {
EMSG(_(e_dictrange));
}
- if (!empty1) {
- tv_clear(&var1);
- }
+ tv_clear(&var1);
return NULL;
}
if (rettv != NULL && (rettv->v_type != VAR_LIST
@@ -2136,9 +2144,7 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
if (!quiet) {
emsgf(_("E709: [:] requires a List value"));
}
- if (!empty1) {
- tv_clear(&var1);
- }
+ tv_clear(&var1);
return NULL;
}
p = skipwhite(p + 1);
@@ -2147,16 +2153,12 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
} else {
lp->ll_empty2 = false;
if (eval1(&p, &var2, true) == FAIL) { // Recursive!
- if (!empty1) {
- tv_clear(&var1);
- }
+ tv_clear(&var1);
return NULL;
}
if (!tv_check_str(&var2)) {
// Not a number or string.
- if (!empty1) {
- tv_clear(&var1);
- }
+ tv_clear(&var1);
tv_clear(&var2);
return NULL;
}
@@ -2169,12 +2171,8 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
if (!quiet) {
emsgf(_(e_missbrac));
}
- if (!empty1) {
- tv_clear(&var1);
- }
- if (lp->ll_range && !lp->ll_empty2) {
- tv_clear(&var2);
- }
+ tv_clear(&var1);
+ tv_clear(&var2);
return NULL;
}
@@ -2228,9 +2226,7 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
if (!quiet) {
emsgf(_(e_dictkey), key);
}
- if (len == -1) {
- tv_clear(&var1);
- }
+ tv_clear(&var1);
return NULL;
}
if (len == -1) {
@@ -2238,32 +2234,28 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
} else {
lp->ll_newkey = vim_strnsave(key, len);
}
- if (len == -1) {
- tv_clear(&var1);
- }
+ tv_clear(&var1);
break;
// existing variable, need to check if it can be changed
} else if (!(flags & GLV_READ_ONLY) && var_check_ro(lp->ll_di->di_flags,
(const char *)name,
(size_t)(p - name))) {
- if (len == -1) {
- tv_clear(&var1);
- }
+ tv_clear(&var1);
return NULL;
}
- if (len == -1) {
- tv_clear(&var1);
- }
+ tv_clear(&var1);
lp->ll_tv = &lp->ll_di->di_tv;
} else {
// Get the number and item for the only or first index of the List.
if (empty1) {
lp->ll_n1 = 0;
} else {
- lp->ll_n1 = (long)tv_get_number(&var1); // Is number or string.
- tv_clear(&var1);
+ // Is number or string.
+ lp->ll_n1 = (long)tv_get_number(&var1);
}
+ tv_clear(&var1);
+
lp->ll_dict = NULL;
lp->ll_list = lp->ll_tv->vval.v_list;
lp->ll_li = tv_list_find(lp->ll_list, lp->ll_n1);
@@ -2274,9 +2266,7 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
}
}
if (lp->ll_li == NULL) {
- if (lp->ll_range && !lp->ll_empty2) {
- tv_clear(&var2);
- }
+ tv_clear(&var2);
if (!quiet) {
EMSGN(_(e_listidx), lp->ll_n1);
}
@@ -2318,6 +2308,7 @@ static char_u *get_lval(char_u *const name, typval_T *const rettv,
}
}
+ tv_clear(&var1);
return p;
}
@@ -2409,12 +2400,15 @@ static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv,
if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1)) {
break;
}
+ assert(lp->ll_li != NULL);
if (TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li) == NULL) {
// Need to add an empty item.
tv_list_append_number(lp->ll_list, 0);
- assert(TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li));
+ // ll_li may have become invalid after append, don’t use it.
+ lp->ll_li = tv_list_last(lp->ll_list); // Valid again.
+ } else {
+ lp->ll_li = TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li);
}
- lp->ll_li = TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li);
lp->ll_n1++;
}
if (ri != NULL) {
@@ -2469,9 +2463,11 @@ static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv,
notify:
if (watched) {
if (oldtv.v_type == VAR_UNKNOWN) {
+ assert(lp->ll_newkey != NULL);
tv_dict_watcher_notify(dict, (char *)lp->ll_newkey, lp->ll_tv, NULL);
} else {
dictitem_T *di = lp->ll_di;
+ assert(di->di_key != NULL);
tv_dict_watcher_notify(dict, (char *)di->di_key, lp->ll_tv, &oldtv);
tv_clear(&oldtv);
}
@@ -2887,28 +2883,26 @@ static int do_unlet_var(lval_T *const lp, char_u *const name_end, int forceit)
lp->ll_name_len))) {
return FAIL;
} else if (lp->ll_range) {
- listitem_T *li;
- listitem_T *ll_li = lp->ll_li;
- int ll_n1 = lp->ll_n1;
-
- while (ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= ll_n1)) {
- li = TV_LIST_ITEM_NEXT(lp->ll_list, ll_li);
- if (tv_check_lock(TV_LIST_ITEM_TV(ll_li)->v_lock,
+ assert(lp->ll_list != NULL);
+ // Delete a range of List items.
+ listitem_T *const first_li = lp->ll_li;
+ listitem_T *last_li = first_li;
+ for (;;) {
+ listitem_T *const li = TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li);
+ if (tv_check_lock(TV_LIST_ITEM_TV(lp->ll_li)->v_lock,
(const char *)lp->ll_name,
lp->ll_name_len)) {
return false;
}
- ll_li = li;
- ll_n1++;
- }
-
- // Delete a range of List items.
- while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1)) {
- li = TV_LIST_ITEM_NEXT(lp->ll_list, lp->ll_li);
- tv_list_item_remove(lp->ll_list, lp->ll_li);
lp->ll_li = li;
lp->ll_n1++;
+ if (lp->ll_li == NULL || (!lp->ll_empty2 && lp->ll_n2 < lp->ll_n1)) {
+ break;
+ } else {
+ last_li = lp->ll_li;
+ }
}
+ tv_list_remove_items(lp->ll_list, first_li, last_li);
} else {
if (lp->ll_list != NULL) {
// unlet a List item.
@@ -2916,6 +2910,7 @@ static int do_unlet_var(lval_T *const lp, char_u *const name_end, int forceit)
} else {
// unlet a Dictionary item.
dict_T *d = lp->ll_dict;
+ assert(d != NULL);
dictitem_T *di = lp->ll_di;
bool watched = tv_dict_is_watched(d);
char *key = NULL;
@@ -4522,7 +4517,7 @@ eval_index (
item = tv_list_find(rettv->vval.v_list, n1);
while (n1++ <= n2) {
tv_list_append_tv(l, TV_LIST_ITEM_TV(item));
- item = TV_LIST_ITEM_NEXT(l, item);
+ item = TV_LIST_ITEM_NEXT(rettv->vval.v_list, item);
}
tv_clear(rettv);
rettv->v_type = VAR_LIST;
@@ -4874,8 +4869,6 @@ void partial_unref(partial_T *pt)
static int get_list_tv(char_u **arg, typval_T *rettv, int evaluate)
{
list_T *l = NULL;
- typval_T tv;
- listitem_T *item;
if (evaluate) {
l = tv_list_alloc();
@@ -4883,13 +4876,13 @@ static int get_list_tv(char_u **arg, typval_T *rettv, int evaluate)
*arg = skipwhite(*arg + 1);
while (**arg != ']' && **arg != NUL) {
- if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
+ typval_T tv;
+ if (eval1(arg, &tv, evaluate) == FAIL) { // Recursive!
goto failret;
+ }
if (evaluate) {
- item = tv_list_item_alloc();
- *TV_LIST_ITEM_TV(item) = tv;
- TV_LIST_ITEM_TV(item)->v_lock = VAR_UNLOCKED;
- tv_list_append(l, item);
+ tv.v_lock = VAR_UNLOCKED;
+ tv_list_append_owned_tv(l, tv);
}
if (**arg == ']') {
@@ -8469,7 +8462,6 @@ static void findfilendir(typval_T *argvars, typval_T *rettv, int find_what)
static void filter_map(typval_T *argvars, typval_T *rettv, int map)
{
typval_T *expr;
- listitem_T *li, *nli;
list_T *l = NULL;
dictitem_T *di;
hashtab_T *ht;
@@ -8553,20 +8545,21 @@ static void filter_map(typval_T *argvars, typval_T *rettv, int map)
} else {
vimvars[VV_KEY].vv_type = VAR_NUMBER;
- for (li = tv_list_first(l); li != NULL; li = nli) {
+ for (listitem_T *li = tv_list_first(l); li != NULL;) {
if (map
&& tv_check_lock(TV_LIST_ITEM_TV(li)->v_lock, arg_errmsg,
TV_TRANSLATE)) {
break;
}
- nli = TV_LIST_ITEM_NEXT(l, li);
vimvars[VV_KEY].vv_nr = idx;
if (filter_map_one(TV_LIST_ITEM_TV(li), expr, map, &rem) == FAIL
|| did_emsg) {
break;
}
if (!map && rem) {
- tv_list_item_remove(l, li);
+ li = tv_list_item_remove(l, li);
+ } else {
+ li = TV_LIST_ITEM_NEXT(l, li);
}
idx++;
}
@@ -11441,40 +11434,38 @@ static void dict_list(typval_T *const tv, typval_T *const rettv,
tv_list_alloc_ret(rettv);
TV_DICT_ITER(tv->vval.v_dict, di, {
- listitem_T *const li = tv_list_item_alloc();
- tv_list_append(rettv->vval.v_list, li);
+ typval_T tv = { .v_lock = VAR_UNLOCKED };
switch (what) {
case kDictListKeys: {
- TV_LIST_ITEM_TV(li)->v_type = VAR_STRING;
- TV_LIST_ITEM_TV(li)->v_lock = VAR_UNLOCKED;
- TV_LIST_ITEM_TV(li)->vval.v_string = vim_strsave(di->di_key);
+ tv.v_type = VAR_STRING;
+ tv.vval.v_string = vim_strsave(di->di_key);
break;
}
case kDictListValues: {
- tv_copy(&di->di_tv, TV_LIST_ITEM_TV(li));
+ tv_copy(&di->di_tv, &tv);
break;
}
case kDictListItems: {
// items()
list_T *const sub_l = tv_list_alloc();
- TV_LIST_ITEM_TV(li)->v_type = VAR_LIST;
- TV_LIST_ITEM_TV(li)->v_lock = VAR_UNLOCKED;
- TV_LIST_ITEM_TV(li)->vval.v_list = sub_l;
+ tv.v_type = VAR_LIST;
+ tv.vval.v_list = sub_l;
tv_list_ref(sub_l);
- listitem_T *sub_li = tv_list_item_alloc();
- tv_list_append(sub_l, sub_li);
- TV_LIST_ITEM_TV(sub_li)->v_type = VAR_STRING;
- TV_LIST_ITEM_TV(sub_li)->v_lock = VAR_UNLOCKED;
- TV_LIST_ITEM_TV(sub_li)->vval.v_string = vim_strsave(di->di_key);
+ tv_list_append_owned_tv(sub_l, (typval_T) {
+ .v_type = VAR_STRING,
+ .v_lock = VAR_UNLOCKED,
+ .vval.v_string = (char_u *)xstrdup((const char *)di->di_key),
+ });
+
+ tv_list_append_tv(sub_l, &di->di_tv);
- sub_li = tv_list_item_alloc();
- tv_list_append(sub_l, sub_li);
- tv_copy(&di->di_tv, TV_LIST_ITEM_TV(sub_li));
break;
}
}
+
+ tv_list_append_owned_tv(rettv->vval.v_list, tv);
});
}
@@ -12190,7 +12181,8 @@ static void f_mapcheck(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
-static void find_some_match(typval_T *argvars, typval_T *rettv, int type)
+static void find_some_match(typval_T *const argvars, typval_T *const rettv,
+ const SomeMatchType type)
{
char_u *str = NULL;
long len = 0;
@@ -12211,24 +12203,37 @@ static void find_some_match(typval_T *argvars, typval_T *rettv, int type)
p_cpo = (char_u *)"";
rettv->vval.v_number = -1;
- if (type == 3 || type == 4) {
- // type 3: return empty list when there are no matches.
- // type 4: return ["", -1, -1, -1]
- tv_list_alloc_ret(rettv);
- if (type == 4) {
+ switch (type) {
+ // matchlist(): return empty list when there are no matches.
+ case kSomeMatchList: {
+ tv_list_alloc_ret(rettv);
+ break;
+ }
+ // matchstrpos(): return ["", -1, -1, -1]
+ case kSomeMatchStrPos: {
+ tv_list_alloc_ret(rettv);
tv_list_append_string(rettv->vval.v_list, "", 0);
tv_list_append_number(rettv->vval.v_list, -1);
tv_list_append_number(rettv->vval.v_list, -1);
tv_list_append_number(rettv->vval.v_list, -1);
+ break;
+ }
+ case kSomeMatchStr: {
+ rettv->v_type = VAR_STRING;
+ rettv->vval.v_string = NULL;
+ break;
+ }
+ case kSomeMatch:
+ case kSomeMatchEnd: {
+ // Do nothing: zero is default.
+ break;
}
- } else if (type == 2) {
- rettv->v_type = VAR_STRING;
- rettv->vval.v_string = NULL;
}
if (argvars[0].v_type == VAR_LIST) {
- if ((l = argvars[0].vval.v_list) == NULL)
+ if ((l = argvars[0].vval.v_list) == NULL) {
goto theend;
+ }
li = tv_list_first(l);
} else {
expr = str = (char_u *)tv_get_string(&argvars[0]);
@@ -12318,63 +12323,73 @@ static void find_some_match(typval_T *argvars, typval_T *rettv, int type)
}
if (match) {
- if (type == 4) {
- list_T *const ret_l = rettv->vval.v_list;
- listitem_T *li1 = tv_list_first(ret_l);
- listitem_T *li2 = TV_LIST_ITEM_NEXT(ret_l, li1);
- listitem_T *li3 = TV_LIST_ITEM_NEXT(ret_l, li2);
- listitem_T *li4 = TV_LIST_ITEM_NEXT(ret_l, li3);
- xfree(TV_LIST_ITEM_TV(li1)->vval.v_string);
-
- const size_t rd = (size_t)(regmatch.endp[0] - regmatch.startp[0]);
- TV_LIST_ITEM_TV(li1)->vval.v_string = xmemdupz(
- (const char *)regmatch.startp[0], rd);
- TV_LIST_ITEM_TV(li3)->vval.v_number = (varnumber_T)(
- regmatch.startp[0] - expr);
- TV_LIST_ITEM_TV(li4)->vval.v_number = (varnumber_T)(
- regmatch.endp[0] - expr);
- if (l != NULL) {
- TV_LIST_ITEM_TV(li2)->vval.v_number = (varnumber_T)idx;
+ switch (type) {
+ case kSomeMatchStrPos: {
+ list_T *const ret_l = rettv->vval.v_list;
+ listitem_T *li1 = tv_list_first(ret_l);
+ listitem_T *li2 = TV_LIST_ITEM_NEXT(ret_l, li1);
+ listitem_T *li3 = TV_LIST_ITEM_NEXT(ret_l, li2);
+ listitem_T *li4 = TV_LIST_ITEM_NEXT(ret_l, li3);
+ xfree(TV_LIST_ITEM_TV(li1)->vval.v_string);
+
+ const size_t rd = (size_t)(regmatch.endp[0] - regmatch.startp[0]);
+ TV_LIST_ITEM_TV(li1)->vval.v_string = xmemdupz(
+ (const char *)regmatch.startp[0], rd);
+ TV_LIST_ITEM_TV(li3)->vval.v_number = (varnumber_T)(
+ regmatch.startp[0] - expr);
+ TV_LIST_ITEM_TV(li4)->vval.v_number = (varnumber_T)(
+ regmatch.endp[0] - expr);
+ if (l != NULL) {
+ TV_LIST_ITEM_TV(li2)->vval.v_number = (varnumber_T)idx;
+ }
+ break;
}
- } else if (type == 3) {
- int i;
-
- /* return list with matched string and submatches */
- for (i = 0; i < NSUBEXP; ++i) {
- if (regmatch.endp[i] == NULL) {
- tv_list_append_string(rettv->vval.v_list, NULL, 0);
- } else {
- tv_list_append_string(rettv->vval.v_list,
- (const char *)regmatch.startp[i],
- (regmatch.endp[i] - regmatch.startp[i]));
+ case kSomeMatchList: {
+ // Return list with matched string and submatches.
+ for (int i = 0; i < NSUBEXP; i++) {
+ if (regmatch.endp[i] == NULL) {
+ tv_list_append_string(rettv->vval.v_list, NULL, 0);
+ } else {
+ tv_list_append_string(rettv->vval.v_list,
+ (const char *)regmatch.startp[i],
+ (regmatch.endp[i] - regmatch.startp[i]));
+ }
}
+ break;
}
- } else if (type == 2) {
- // Return matched string.
- if (l != NULL) {
- tv_copy(TV_LIST_ITEM_TV(li), rettv);
- } else {
- rettv->vval.v_string = (char_u *)xmemdupz(
- (const char *)regmatch.startp[0],
- (size_t)(regmatch.endp[0] - regmatch.startp[0]));
+ case kSomeMatchStr: {
+ // Return matched string.
+ if (l != NULL) {
+ tv_copy(TV_LIST_ITEM_TV(li), rettv);
+ } else {
+ rettv->vval.v_string = (char_u *)xmemdupz(
+ (const char *)regmatch.startp[0],
+ (size_t)(regmatch.endp[0] - regmatch.startp[0]));
+ }
+ break;
}
- } else if (l != NULL) {
- rettv->vval.v_number = idx;
- } else {
- if (type != 0) {
- rettv->vval.v_number =
- (varnumber_T)(regmatch.startp[0] - str);
- } else {
- rettv->vval.v_number =
- (varnumber_T)(regmatch.endp[0] - str);
+ case kSomeMatch:
+ case kSomeMatchEnd: {
+ if (l != NULL) {
+ rettv->vval.v_number = idx;
+ } else {
+ if (type == kSomeMatch) {
+ rettv->vval.v_number =
+ (varnumber_T)(regmatch.startp[0] - str);
+ } else {
+ rettv->vval.v_number =
+ (varnumber_T)(regmatch.endp[0] - str);
+ }
+ rettv->vval.v_number += (varnumber_T)(str - expr);
+ }
+ break;
}
- rettv->vval.v_number += (varnumber_T)(str - expr);
}
}
vim_regfree(regmatch.regprog);
}
- if (type == 4 && l == NULL) {
+ if (type == kSomeMatchStrPos && l == NULL) {
// matchstrpos() without a list: drop the second item
list_T *const ret_l = rettv->vval.v_list;
tv_list_item_remove(ret_l, TV_LIST_ITEM_NEXT(ret_l, tv_list_first(ret_l)));
@@ -12390,7 +12405,7 @@ theend:
*/
static void f_match(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
- find_some_match(argvars, rettv, 1);
+ find_some_match(argvars, rettv, kSomeMatch);
}
/*
@@ -12505,12 +12520,12 @@ static void f_matcharg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_list_alloc_ret(rettv);
- int id = tv_get_number(&argvars[0]);
+ const int id = tv_get_number(&argvars[0]);
if (id >= 1 && id <= 3) {
- matchitem_T *m;
+ matchitem_T *const m = (matchitem_T *)get_match(curwin, id);
- if ((m = (matchitem_T *)get_match(curwin, id)) != NULL) {
+ if (m != NULL) {
tv_list_append_string(rettv->vval.v_list,
(const char *)syn_id2name(m->hlg_id), -1);
tv_list_append_string(rettv->vval.v_list, (const char *)m->pattern, -1);
@@ -12535,7 +12550,7 @@ static void f_matchdelete(typval_T *argvars, typval_T *rettv, FunPtr fptr)
*/
static void f_matchend(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
- find_some_match(argvars, rettv, 0);
+ find_some_match(argvars, rettv, kSomeMatchEnd);
}
/*
@@ -12543,7 +12558,7 @@ static void f_matchend(typval_T *argvars, typval_T *rettv, FunPtr fptr)
*/
static void f_matchlist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
- find_some_match(argvars, rettv, 3);
+ find_some_match(argvars, rettv, kSomeMatchList);
}
/*
@@ -12551,13 +12566,13 @@ static void f_matchlist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
*/
static void f_matchstr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
- find_some_match(argvars, rettv, 2);
+ find_some_match(argvars, rettv, kSomeMatchStr);
}
/// "matchstrpos()" function
static void f_matchstrpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
- find_some_match(argvars, rettv, 4);
+ find_some_match(argvars, rettv, kSomeMatchStrPos);
}
/// Get maximal/minimal number value in a list or dictionary
@@ -12762,13 +12777,12 @@ static void f_msgpackparse(typval_T *argvars, typval_T *rettv, FunPtr fptr)
goto f_msgpackparse_exit;
}
if (result == MSGPACK_UNPACK_SUCCESS) {
- listitem_T *li = tv_list_item_alloc();
- TV_LIST_ITEM_TV(li)->v_type = VAR_UNKNOWN;
- tv_list_append(ret_list, li);
- if (msgpack_to_vim(unpacked.data, TV_LIST_ITEM_TV(li)) == FAIL) {
+ typval_T tv = { .v_type = VAR_UNKNOWN };
+ if (msgpack_to_vim(unpacked.data, &tv) == FAIL) {
EMSG2(_(e_invarg2), "Failed to convert msgpack string");
goto f_msgpackparse_exit;
}
+ tv_list_append_owned_tv(ret_list, tv);
}
if (result == MSGPACK_UNPACK_CONTINUE) {
if (rlret == OK) {
@@ -12995,9 +13009,6 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
long prevlen = 0; /* length of data in prev */
long prevsize = 0; /* size of prev buffer */
long maxline = MAXLNUM;
- long cnt = 0;
- char_u *p; /* position in buf */
- char_u *start; /* start of current line */
if (argvars[1].v_type != VAR_UNKNOWN) {
if (strcmp(tv_get_string(&argvars[1]), "b") == 0) {
@@ -13009,6 +13020,7 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
tv_list_alloc_ret(rettv);
+ list_T *const l = rettv->vval.v_list;
// Always open the file in binary mode, library functions have a mind of
// their own about CR-LF conversion.
@@ -13018,19 +13030,20 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
return;
}
- while (cnt < maxline || maxline < 0) {
+ while (maxline < 0 || tv_list_len(l) < maxline) {
readlen = (int)fread(buf, 1, io_size, fd);
- /* This for loop processes what was read, but is also entered at end
- * of file so that either:
- * - an incomplete line gets written
- * - a "binary" file gets an empty line at the end if it ends in a
- * newline. */
+ // This for loop processes what was read, but is also entered at end
+ // of file so that either:
+ // - an incomplete line gets written
+ // - a "binary" file gets an empty line at the end if it ends in a
+ // newline.
+ char_u *p; // Position in buf.
+ char_u *start; // Start of current line.
for (p = buf, start = buf;
p < buf + readlen || (readlen <= 0 && (prevlen > 0 || binary));
- ++p) {
+ p++) {
if (*p == '\n' || readlen <= 0) {
- listitem_T *li;
char_u *s = NULL;
size_t len = p - start;
@@ -13057,22 +13070,32 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
prevlen = prevsize = 0;
}
- li = tv_list_item_alloc();
- TV_LIST_ITEM_TV(li)->v_type = VAR_STRING;
- TV_LIST_ITEM_TV(li)->v_lock = VAR_UNLOCKED;
- TV_LIST_ITEM_TV(li)->vval.v_string = s;
- tv_list_append(rettv->vval.v_list, li);
-
- start = p + 1; /* step over newline */
- if ((++cnt >= maxline && maxline >= 0) || readlen <= 0)
+ tv_list_append_owned_tv(l, (typval_T) {
+ .v_type = VAR_STRING,
+ .v_lock = VAR_UNLOCKED,
+ .vval.v_string = s,
+ });
+
+ start = p + 1; // Step over newline.
+ if (maxline < 0) {
+ if (tv_list_len(l) > -maxline) {
+ assert(tv_list_len(l) == 1 + (-maxline));
+ tv_list_item_remove(l, tv_list_first(l));
+ }
+ } else if (tv_list_len(l) >= maxline) {
+ assert(tv_list_len(l) == maxline);
+ break;
+ }
+ if (readlen <= 0) {
break;
- } else if (*p == NUL)
+ }
+ } else if (*p == NUL) {
*p = '\n';
- /* Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
- * when finding the BF and check the previous two bytes. */
- else if (*p == 0xbf && enc_utf8 && !binary) {
- /* Find the two bytes before the 0xbf. If p is at buf, or buf
- * + 1, these may be in the "prev" string. */
+ // Check for utf8 "bom"; U+FEFF is encoded as EF BB BF. Do this
+ // when finding the BF and check the previous two bytes.
+ } else if (*p == 0xbf && !binary) {
+ // Find the two bytes before the 0xbf. If p is at buf, or buf + 1,
+ // these may be in the "prev" string.
char_u back1 = p >= buf + 1 ? p[-1]
: prevlen >= 1 ? prev[prevlen - 1] : NUL;
char_u back2 = p >= buf + 2 ? p[-2]
@@ -13106,8 +13129,9 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
} /* for */
- if ((cnt >= maxline && maxline >= 0) || readlen <= 0)
+ if ((maxline >= 0 && tv_list_len(l) >= maxline) || readlen <= 0) {
break;
+ }
if (start < p) {
/* There's part of a line in buf, store it in "prev". */
if (p - start + prevlen >= prevsize) {
@@ -13131,17 +13155,6 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
} /* while */
- /*
- * For a negative line count use only the lines at the end of the file,
- * free the rest.
- */
- if (maxline < 0)
- while (cnt > -maxline) {
- tv_list_item_remove(rettv->vval.v_list,
- tv_list_first(rettv->vval.v_list));
- cnt--;
- }
-
xfree(prev);
fclose(fd);
}
@@ -13291,7 +13304,7 @@ static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr)
} else {
if (argvars[2].v_type == VAR_UNKNOWN) {
// Remove one item, return its value.
- tv_list_remove_items(l, item, item);
+ tv_list_drop_items(l, item, item);
*rettv = *TV_LIST_ITEM_TV(item);
xfree(item);
} else {
@@ -14310,11 +14323,7 @@ static void f_serverlist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
// Copy addrs into a linked list.
list_T *l = tv_list_alloc_ret(rettv);
for (size_t i = 0; i < n; i++) {
- listitem_T *li = tv_list_item_alloc();
- TV_LIST_ITEM_TV(li)->v_type = VAR_STRING;
- TV_LIST_ITEM_TV(li)->v_lock = VAR_UNLOCKED;
- TV_LIST_ITEM_TV(li)->vval.v_string = (char_u *)addrs[i];
- tv_list_append(l, li);
+ tv_list_append_allocated_string(l, addrs[i]);
}
xfree(addrs);
}
@@ -15120,12 +15129,6 @@ static void f_sockconnect(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->v_type = VAR_NUMBER;
}
-/// struct used in the array that's given to qsort()
-typedef struct {
- listitem_T *item;
- int idx;
-} sortItem_T;
-
/// struct storing information about current sort
typedef struct {
int item_compare_ic;
@@ -15146,8 +15149,8 @@ static sortinfo_T *sortinfo = NULL;
*/
static int item_compare(const void *s1, const void *s2, bool keep_zero)
{
- sortItem_T *const si1 = (sortItem_T *)s1;
- sortItem_T *const si2 = (sortItem_T *)s2;
+ ListSortItem *const si1 = (ListSortItem *)s1;
+ ListSortItem *const si2 = (ListSortItem *)s2;
typval_T *const tv1 = TV_LIST_ITEM_TV(si1->item);
typval_T *const tv2 = TV_LIST_ITEM_TV(si2->item);
@@ -15241,7 +15244,7 @@ static int item_compare_not_keeping_zero(const void *s1, const void *s2)
static int item_compare2(const void *s1, const void *s2, bool keep_zero)
{
- sortItem_T *si1, *si2;
+ ListSortItem *si1, *si2;
int res;
typval_T rettv;
typval_T argv[3];
@@ -15254,8 +15257,8 @@ static int item_compare2(const void *s1, const void *s2, bool keep_zero)
return 0;
}
- si1 = (sortItem_T *)s1;
- si2 = (sortItem_T *)s2;
+ si1 = (ListSortItem *)s1;
+ si2 = (ListSortItem *)s2;
if (partial == NULL) {
func_name = sortinfo->item_compare_func;
@@ -15312,7 +15315,7 @@ static int item_compare2_not_keeping_zero(const void *s1, const void *s2)
*/
static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort)
{
- sortItem_T *ptrs;
+ ListSortItem *ptrs;
long len;
long i;
@@ -15401,43 +15404,22 @@ static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort)
}
}
- /* Make an array with each entry pointing to an item in the List. */
- ptrs = xmalloc((size_t)(len * sizeof (sortItem_T)));
+ // Make an array with each entry pointing to an item in the List.
+ ptrs = xmalloc((size_t)(len * sizeof(ListSortItem)));
- i = 0;
if (sort) {
- // sort(): ptrs will be the list to sort.
- TV_LIST_ITER(l, li, {
- ptrs[i].item = li;
- ptrs[i].idx = i;
- i++;
- });
-
info.item_compare_func_err = false;
- // Test the compare function.
- if ((info.item_compare_func != NULL
- || info.item_compare_partial != NULL)
- && item_compare2_not_keeping_zero(&ptrs[0], &ptrs[1])
- == ITEM_COMPARE_FAIL) {
+ tv_list_item_sort(l, ptrs,
+ ((info.item_compare_func == NULL
+ && info.item_compare_partial == NULL)
+ ? item_compare_not_keeping_zero
+ : item_compare2_not_keeping_zero),
+ &info.item_compare_func_err);
+ if (info.item_compare_func_err) {
EMSG(_("E702: Sort compare function failed"));
- } else {
- // Sort the array with item pointers.
- qsort(ptrs, (size_t)len, sizeof (sortItem_T),
- (info.item_compare_func == NULL
- && info.item_compare_partial == NULL ?
- item_compare_not_keeping_zero :
- item_compare2_not_keeping_zero));
-
- if (!info.item_compare_func_err) {
- // Clear the list and append the items in the sorted order.
- tv_list_clear(l);
- for (i = 0; i < len; i++) {
- tv_list_append(l, ptrs[i].item);
- }
- }
}
} else {
- int (*item_compare_func_ptr)(const void *, const void *);
+ ListSorter item_compare_func_ptr;
// f_uniq(): ptrs will be a stack of items to remove.
info.item_compare_func_err = false;
@@ -15450,18 +15432,17 @@ static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort)
int idx = 0;
for (listitem_T *li = TV_LIST_ITEM_NEXT(l, tv_list_first(l))
- ; li != NULL
- ; li = TV_LIST_ITEM_NEXT(l, li)) {
+ ; li != NULL;) {
listitem_T *const prev_li = TV_LIST_ITEM_PREV(l, li);
if (item_compare_func_ptr(&prev_li, &li) == 0) {
if (info.item_compare_func_err) {
EMSG(_("E882: Uniq compare function failed"));
break;
}
- tv_list_item_remove(l, li);
- li = tv_list_find(l, idx);
+ li = tv_list_item_remove(l, li);
} else {
idx++;
+ li = TV_LIST_ITEM_NEXT(l, li);
}
}
}
@@ -15619,12 +15600,7 @@ static void f_spellsuggest(typval_T *argvars, typval_T *rettv, FunPtr fptr)
for (int i = 0; i < ga.ga_len; i++) {
char *p = ((char **)ga.ga_data)[i];
-
- listitem_T *const li = tv_list_item_alloc();
- TV_LIST_ITEM_TV(li)->v_type = VAR_STRING;
- TV_LIST_ITEM_TV(li)->v_lock = VAR_LOCKED;
- TV_LIST_ITEM_TV(li)->vval.v_string = (char_u *)p;
- tv_list_append(rettv->vval.v_list, li);
+ tv_list_append_allocated_string(rettv->vval.v_list, p);
}
ga_clear(&ga);
}
@@ -19023,6 +18999,9 @@ static void set_var(const char *name, const size_t name_len, typval_T *const tv,
return;
}
+ // Make sure dict is valid
+ assert(dict != NULL);
+
v = xmalloc(sizeof(dictitem_T) + strlen(varname));
STRCPY(v->di_key, varname);
if (tv_dict_add(dict, v) == FAIL) {
@@ -21263,15 +21242,17 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars,
}
}
+ const bool do_profiling_yes = do_profiling == PROF_YES;
+
bool func_not_yet_profiling_but_should =
- do_profiling == PROF_YES
- && !fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL);
+ do_profiling_yes
+ && !fp->uf_profiling && has_profiling(false, fp->uf_name, NULL);
if (func_not_yet_profiling_but_should)
func_do_profile(fp);
bool func_or_func_caller_profiling =
- do_profiling == PROF_YES
+ do_profiling_yes
&& (fp->uf_profiling
|| (fc->caller != NULL && fc->caller->func->uf_profiling));
@@ -21281,7 +21262,7 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars,
fp->uf_tm_children = profile_zero();
}
- if (do_profiling == PROF_YES) {
+ if (do_profiling_yes) {
script_prof_save(&wait_start);
}
@@ -21357,8 +21338,9 @@ void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars,
sourcing_name = save_sourcing_name;
sourcing_lnum = save_sourcing_lnum;
current_SID = save_current_SID;
- if (do_profiling == PROF_YES)
+ if (do_profiling_yes) {
script_prof_restore(&wait_start);
+ }
if (p_verbose >= 12 && sourcing_name != NULL) {
++no_wait_return;
diff --git a/src/nvim/eval/decode.c b/src/nvim/eval/decode.c
index d5c65ebe81..af4e055d23 100644
--- a/src/nvim/eval/decode.c
+++ b/src/nvim/eval/decode.c
@@ -127,9 +127,7 @@ static inline int json_decoder_pop(ValuesStackItem obj,
return FAIL;
}
assert(last_container.special_val == NULL);
- listitem_T *obj_li = tv_list_item_alloc();
- *TV_LIST_ITEM_TV(obj_li) = obj.val;
- tv_list_append(last_container.container.vval.v_list, obj_li);
+ tv_list_append_owned_tv(last_container.container.vval.v_list, obj.val);
} else if (last_container.stack_index == kv_size(*stack) - 2) {
if (!obj.didcolon) {
EMSG2(_("E474: Expected colon before dictionary value: %s"),
@@ -154,12 +152,8 @@ static inline int json_decoder_pop(ValuesStackItem obj,
} else {
list_T *const kv_pair = tv_list_alloc();
tv_list_append_list(last_container.special_val, kv_pair);
- listitem_T *const key_li = tv_list_item_alloc();
- *TV_LIST_ITEM_TV(key_li) = key.val;
- tv_list_append(kv_pair, key_li);
- listitem_T *const val_li = tv_list_item_alloc();
- *TV_LIST_ITEM_TV(val_li) = obj.val;
- tv_list_append(kv_pair, val_li);
+ tv_list_append_owned_tv(kv_pair, key.val);
+ tv_list_append_owned_tv(kv_pair, obj.val);
}
} else {
// Object with key only
@@ -1047,10 +1041,10 @@ int msgpack_to_vim(const msgpack_object mobj, typval_T *const rettv)
.vval = { .v_list = list },
};
for (size_t i = 0; i < mobj.via.array.size; i++) {
- listitem_T *const li = tv_list_item_alloc();
- TV_LIST_ITEM_TV(li)->v_type = VAR_UNKNOWN;
- tv_list_append(list, li);
- if (msgpack_to_vim(mobj.via.array.ptr[i], TV_LIST_ITEM_TV(li))
+ // Not populated yet, need to create list item to push.
+ tv_list_append_owned_tv(list, (typval_T) { .v_type = VAR_UNKNOWN });
+ if (msgpack_to_vim(mobj.via.array.ptr[i],
+ TV_LIST_ITEM_TV(tv_list_last(list)))
== FAIL) {
return FAIL;
}
@@ -1095,20 +1089,20 @@ msgpack_to_vim_generic_map: {}
for (size_t i = 0; i < mobj.via.map.size; i++) {
list_T *const kv_pair = tv_list_alloc();
tv_list_append_list(list, kv_pair);
- listitem_T *const key_li = tv_list_item_alloc();
- TV_LIST_ITEM_TV(key_li)->v_type = VAR_UNKNOWN;
- tv_list_append(kv_pair, key_li);
- listitem_T *const val_li = tv_list_item_alloc();
- TV_LIST_ITEM_TV(val_li)->v_type = VAR_UNKNOWN;
- tv_list_append(kv_pair, val_li);
- if (msgpack_to_vim(mobj.via.map.ptr[i].key, TV_LIST_ITEM_TV(key_li))
- == FAIL) {
+
+ typval_T key_tv = { .v_type = VAR_UNKNOWN };
+ if (msgpack_to_vim(mobj.via.map.ptr[i].key, &key_tv) == FAIL) {
+ tv_clear(&key_tv);
return FAIL;
}
- if (msgpack_to_vim(mobj.via.map.ptr[i].val, TV_LIST_ITEM_TV(val_li))
- == FAIL) {
+ tv_list_append_owned_tv(kv_pair, key_tv);
+
+ typval_T val_tv = { .v_type = VAR_UNKNOWN };
+ if (msgpack_to_vim(mobj.via.map.ptr[i].val, &val_tv) == FAIL) {
+ tv_clear(&val_tv);
return FAIL;
}
+ tv_list_append_owned_tv(kv_pair, val_tv);
}
break;
}
diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c
index 53c56d0ffd..ac6c8c8aa6 100644
--- a/src/nvim/eval/typval.c
+++ b/src/nvim/eval/typval.c
@@ -3,6 +3,7 @@
#include <stdio.h>
#include <stddef.h>
+#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>
@@ -52,35 +53,29 @@ const char *const tv_empty_string = "";
/// and specifically set lv_lock.
///
/// @return [allocated] new list item.
-listitem_T *tv_list_item_alloc(void)
+static listitem_T *tv_list_item_alloc(void)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_MALLOC
{
return xmalloc(sizeof(listitem_T));
}
-/// Free a list item
-///
-/// Also clears the value. Does not touch watchers.
-///
-/// @param[out] item Item to free.
-void tv_list_item_free(listitem_T *const item)
- FUNC_ATTR_NONNULL_ALL
-{
- tv_clear(TV_LIST_ITEM_TV(item));
- xfree(item);
-}
-
/// Remove a list item from a List and free it
///
/// Also clears the value.
///
/// @param[out] l List to remove item from.
/// @param[in,out] item Item to remove.
-void tv_list_item_remove(list_T *const l, listitem_T *const item)
+///
+/// @return Pointer to the list item just after removed one, NULL if removed
+/// item was the last one.
+listitem_T *tv_list_item_remove(list_T *const l, listitem_T *const item)
FUNC_ATTR_NONNULL_ALL
{
- tv_list_remove_items(l, item, item);
- tv_list_item_free(item);
+ listitem_T *const next_item = TV_LIST_ITEM_NEXT(l, item);
+ tv_list_drop_items(l, item, item);
+ tv_clear(TV_LIST_ITEM_TV(item));
+ xfree(item);
+ return next_item;
}
//{{{2 List watchers
@@ -267,8 +262,8 @@ void tv_list_unref(list_T *const l)
/// @param[out] l List to remove from.
/// @param[in] item First item to remove.
/// @param[in] item2 Last item to remove.
-void tv_list_remove_items(list_T *const l, listitem_T *const item,
- listitem_T *const item2)
+void tv_list_drop_items(list_T *const l, listitem_T *const item,
+ listitem_T *const item2)
FUNC_ATTR_NONNULL_ALL
{
// Notify watchers.
@@ -290,6 +285,23 @@ void tv_list_remove_items(list_T *const l, listitem_T *const item,
l->lv_idx_item = NULL;
}
+/// Like tv_list_drop_items, but also frees all removed items
+void tv_list_remove_items(list_T *const l, listitem_T *const item,
+ listitem_T *const item2)
+ FUNC_ATTR_NONNULL_ALL
+{
+ tv_list_drop_items(l, item, item2);
+ for (listitem_T *li = item;;) {
+ tv_clear(TV_LIST_ITEM_TV(li));
+ listitem_T *const nli = li->li_next;
+ xfree(li);
+ if (li == item2) {
+ break;
+ }
+ li = nli;
+ }
+}
+
/// Move items "item" to "item2" from list "l" to the end of the list "tgt_l"
///
/// @param[out] l List to move from.
@@ -302,7 +314,7 @@ void tv_list_move_items(list_T *const l, listitem_T *const item,
const int cnt)
FUNC_ATTR_NONNULL_ALL
{
- tv_list_remove_items(l, item, item2);
+ tv_list_drop_items(l, item, item2);
item->li_prev = tgt_l->lv_last;
item2->li_next = NULL;
if (tgt_l->lv_last == NULL) {
@@ -393,19 +405,30 @@ void tv_list_append_tv(list_T *const l, typval_T *const tv)
tv_list_append(l, li);
}
+/// Like tv_list_append_tv(), but tv is moved to a list
+///
+/// This means that it is no longer valid to use contents of the typval_T after
+/// function exits.
+void tv_list_append_owned_tv(list_T *const l, typval_T tv)
+ FUNC_ATTR_NONNULL_ALL
+{
+ listitem_T *const li = tv_list_item_alloc();
+ *TV_LIST_ITEM_TV(li) = tv;
+ tv_list_append(l, li);
+}
+
/// Append a list to a list as one item
///
/// @param[out] l List to append to.
/// @param[in,out] itemlist List to append. Reference count is increased.
-void tv_list_append_list(list_T *const list, list_T *const itemlist)
+void tv_list_append_list(list_T *const l, list_T *const itemlist)
FUNC_ATTR_NONNULL_ARG(1)
{
- listitem_T *const li = tv_list_item_alloc();
-
- TV_LIST_ITEM_TV(li)->v_type = VAR_LIST;
- TV_LIST_ITEM_TV(li)->v_lock = VAR_UNLOCKED;
- TV_LIST_ITEM_TV(li)->vval.v_list = itemlist;
- tv_list_append(list, li);
+ tv_list_append_owned_tv(l, (typval_T) {
+ .v_type = VAR_LIST,
+ .v_lock = VAR_UNLOCKED,
+ .vval.v_list = itemlist,
+ });
tv_list_ref(itemlist);
}
@@ -413,15 +436,14 @@ void tv_list_append_list(list_T *const list, list_T *const itemlist)
///
/// @param[out] l List to append to.
/// @param[in,out] dict Dictionary to append. Reference count is increased.
-void tv_list_append_dict(list_T *const list, dict_T *const dict)
+void tv_list_append_dict(list_T *const l, dict_T *const dict)
FUNC_ATTR_NONNULL_ARG(1)
{
- listitem_T *const li = tv_list_item_alloc();
-
- TV_LIST_ITEM_TV(li)->v_type = VAR_DICT;
- TV_LIST_ITEM_TV(li)->v_lock = VAR_UNLOCKED;
- TV_LIST_ITEM_TV(li)->vval.v_dict = dict;
- tv_list_append(list, li);
+ tv_list_append_owned_tv(l, (typval_T) {
+ .v_type = VAR_DICT,
+ .v_lock = VAR_UNLOCKED,
+ .vval.v_dict = dict,
+ });
if (dict != NULL) {
dict->dv_refcount++;
}
@@ -438,14 +460,15 @@ void tv_list_append_string(list_T *const l, const char *const str,
const ssize_t len)
FUNC_ATTR_NONNULL_ARG(1)
{
- if (str == NULL) {
- assert(len == 0 || len == -1);
- tv_list_append_allocated_string(l, NULL);
- } else {
- tv_list_append_allocated_string(l, (len >= 0
- ? xmemdupz(str, (size_t)len)
- : xstrdup(str)));
- }
+ tv_list_append_owned_tv(l, (typval_T) {
+ .v_type = VAR_STRING,
+ .v_lock = VAR_UNLOCKED,
+ .vval.v_string = (str == NULL
+ ? NULL
+ : (len >= 0
+ ? xmemdupz(str, (size_t)len)
+ : xstrdup(str))),
+ });
}
/// Append given string to the list
@@ -457,12 +480,11 @@ void tv_list_append_string(list_T *const l, const char *const str,
void tv_list_append_allocated_string(list_T *const l, char *const str)
FUNC_ATTR_NONNULL_ARG(1)
{
- listitem_T *const li = tv_list_item_alloc();
-
- tv_list_append(l, li);
- TV_LIST_ITEM_TV(li)->v_type = VAR_STRING;
- TV_LIST_ITEM_TV(li)->v_lock = VAR_UNLOCKED;
- TV_LIST_ITEM_TV(li)->vval.v_string = (char_u *)str;
+ tv_list_append_owned_tv(l, (typval_T) {
+ .v_type = VAR_STRING,
+ .v_lock = VAR_UNLOCKED,
+ .vval.v_string = (char_u *)str,
+ });
}
/// Append number to the list
@@ -472,11 +494,11 @@ void tv_list_append_allocated_string(list_T *const l, char *const str)
/// listitem_T.
void tv_list_append_number(list_T *const l, const varnumber_T n)
{
- listitem_T *const li = tv_list_item_alloc();
- TV_LIST_ITEM_TV(li)->v_type = VAR_NUMBER;
- TV_LIST_ITEM_TV(li)->v_lock = VAR_UNLOCKED;
- TV_LIST_ITEM_TV(li)->vval.v_number = n;
- tv_list_append(l, li);
+ tv_list_append_owned_tv(l, (typval_T) {
+ .v_type = VAR_NUMBER,
+ .v_lock = VAR_UNLOCKED,
+ .vval.v_number = n,
+ });
}
//{{{2 Operations on the whole list
@@ -736,6 +758,47 @@ void tv_list_reverse(list_T *const l)
l->lv_idx = l->lv_len - l->lv_idx - 1;
}
+// FIXME Add unit tests for tv_list_item_sort().
+
+/// Sort list using libc qsort
+///
+/// @param[in,out] l List to sort, will be sorted in-place.
+/// @param ptrs Preallocated array of items to sort, must have at least
+/// tv_list_len(l) entries. Should not be initialized.
+/// @param[in] item_compare_func Function used to compare list items.
+/// @param errp Location where information about whether error occurred is
+/// saved by item_compare_func. If boolean there appears to be
+/// true list will not be modified. Must be initialized to false
+/// by the caller.
+void tv_list_item_sort(list_T *const l, ListSortItem *const ptrs,
+ const ListSorter item_compare_func,
+ bool *errp)
+ FUNC_ATTR_NONNULL_ARG(3, 4)
+{
+ const int len = tv_list_len(l);
+ if (len <= 1) {
+ return;
+ }
+ int i = 0;
+ TV_LIST_ITER(l, li, {
+ ptrs[i].item = li;
+ ptrs[i].idx = i;
+ i++;
+ });
+ // Sort the array with item pointers.
+ qsort(ptrs, (size_t)len, sizeof(ListSortItem), item_compare_func);
+ if (!(*errp)) {
+ // Clear the list and append the items in the sorted order.
+ l->lv_first = NULL;
+ l->lv_last = NULL;
+ l->lv_idx_item = NULL;
+ l->lv_len = 0;
+ for (i = 0; i < len; i++) {
+ tv_list_append(l, ptrs[i].item);
+ }
+ }
+}
+
//{{{2 Indexing/searching
/// Locate item with a given index in a list and return it
@@ -2090,7 +2153,7 @@ void tv_free(typval_T *tv)
///
/// @param[in] from Location to copy from.
/// @param[out] to Location to copy to.
-void tv_copy(typval_T *const from, typval_T *const to)
+void tv_copy(const typval_T *const from, typval_T *const to)
{
to->v_type = from->v_type;
to->v_lock = VAR_UNLOCKED;
diff --git a/src/nvim/eval/typval.h b/src/nvim/eval/typval.h
index 2bce7bd6b2..c9a9a3e7e8 100644
--- a/src/nvim/eval/typval.h
+++ b/src/nvim/eval/typval.h
@@ -296,6 +296,14 @@ typedef struct list_stack_S {
struct list_stack_S *prev;
} list_stack_T;
+/// Structure representing one list item, used for sort array.
+typedef struct {
+ listitem_T *item; ///< Sorted list item.
+ int idx; ///< Sorted list item index.
+} ListSortItem;
+
+typedef int (*ListSorter)(const void *, const void *);
+
// In a hashtab item "hi_key" points to "di_key" in a dictitem.
// This avoids adding a pointer to the hashtab item.
@@ -403,20 +411,6 @@ static inline list_T *tv_list_latest_copy(const list_T *const l)
return l->lv_copylist;
}
-/// Clear the list without freeing anything at all
-///
-/// For use in sort() which saves items to a separate array and readds them back
-/// after sorting via a number of tv_list_append() calls.
-///
-/// @param[out] l List to clear.
-static inline void tv_list_clear(list_T *const l)
-{
- l->lv_first = NULL;
- l->lv_last = NULL;
- l->lv_idx_item = NULL;
- l->lv_len = 0;
-}
-
static inline int tv_list_uidx(const list_T *const l, int n)
REAL_FATTR_PURE REAL_FATTR_WARN_UNUSED_RESULT;
diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c
index 4f54d4c88b..c5825963c0 100644
--- a/src/nvim/ex_cmds.c
+++ b/src/nvim/ex_cmds.c
@@ -4619,7 +4619,8 @@ int find_help_tags(char_u *arg, int *num_matches, char_u ***matches, int keep_la
"/\\(\\)", "/\\%(\\)",
"?", ":?", "?<CR>", "g?", "g?g?", "g??", "z?",
"/\\?", "/\\z(\\)", "\\=", ":s\\=",
- "[count]", "[quotex]", "[range]",
+ "[count]", "[quotex]",
+ "[range]", ":[range]",
"[pattern]", "\\|", "\\%$",
"s/\\~", "s/\\U", "s/\\L",
"s/\\1", "s/\\2", "s/\\3", "s/\\9"};
@@ -4628,7 +4629,8 @@ int find_help_tags(char_u *arg, int *num_matches, char_u ***matches, int keep_la
"/\\\\(\\\\)", "/\\\\%(\\\\)",
"?", ":?", "?<CR>", "g?", "g?g?", "g??", "z?",
"/\\\\?", "/\\\\z(\\\\)", "\\\\=", ":s\\\\=",
- "\\[count]", "\\[quotex]", "\\[range]",
+ "\\[count]", "\\[quotex]",
+ "\\[range]", ":\\[range]",
"\\[pattern]", "\\\\bar", "/\\\\%\\$",
"s/\\\\\\~", "s/\\\\U", "s/\\\\L",
"s/\\\\1", "s/\\\\2", "s/\\\\3", "s/\\\\9"};
diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c
index f6a5f59676..2fa8db6b82 100644
--- a/src/nvim/ex_docmd.c
+++ b/src/nvim/ex_docmd.c
@@ -6230,7 +6230,6 @@ void tabpage_close_other(tabpage_T *tp, int forceit)
if (!valid_tabpage(tp) || tp->tp_firstwin == wp)
break;
}
- apply_autocmds(EVENT_TABCLOSED, prev_idx, prev_idx, FALSE, curbuf);
redraw_tabline = TRUE;
if (h != tabline_height())
@@ -9719,17 +9718,18 @@ static void ex_filetype(exarg_T *eap)
EMSG2(_(e_invarg2), arg);
}
-/// Do ":filetype plugin indent on" if user did not already do some
-/// permutation thereof.
+/// Set all :filetype options ON if user did not explicitly set any to OFF.
void filetype_maybe_enable(void)
{
- if (filetype_detect == kNone
- && filetype_plugin == kNone
- && filetype_indent == kNone) {
+ if (filetype_detect == kNone) {
source_runtime((char_u *)FILETYPE_FILE, true);
filetype_detect = kTrue;
+ }
+ if (filetype_plugin == kNone) {
source_runtime((char_u *)FTPLUGIN_FILE, true);
filetype_plugin = kTrue;
+ }
+ if (filetype_indent == kNone) {
source_runtime((char_u *)INDENT_FILE, true);
filetype_indent = kTrue;
}
diff --git a/src/nvim/if_cscope.c b/src/nvim/if_cscope.c
index 654b4630c5..773e29693c 100644
--- a/src/nvim/if_cscope.c
+++ b/src/nvim/if_cscope.c
@@ -1369,8 +1369,8 @@ static char *cs_manage_matches(char **matches, char **contexts,
case Print:
cs_print_tags_priv(mp, cp, cnt);
break;
- default: /* should not reach here */
- (void)EMSG(_("E570: fatal error in cs_manage_matches"));
+ default: // should not reach here
+ IEMSG(_("E570: fatal error in cs_manage_matches"));
return NULL;
}
diff --git a/src/nvim/lua/converter.c b/src/nvim/lua/converter.c
index 8303ecdd37..61cb428923 100644
--- a/src/nvim/lua/converter.c
+++ b/src/nvim/lua/converter.c
@@ -212,19 +212,27 @@ bool nlua_pop_typval(lua_State *lstate, typval_T *ret_tv)
const char *s = lua_tolstring(lstate, -2, &len);
if (cur.special) {
list_T *const kv_pair = tv_list_alloc();
- tv_list_append_list(cur.tv->vval.v_list, kv_pair);
- listitem_T *const key = tv_list_item_alloc();
- *TV_LIST_ITEM_TV(key) = decode_string(s, len, kTrue, false, false);
- tv_list_append(kv_pair, key);
- if (TV_LIST_ITEM_TV(key)->v_type == VAR_UNKNOWN) {
+
+ typval_T s_tv = decode_string(s, len, kTrue, false, false);
+ if (s_tv.v_type == VAR_UNKNOWN) {
ret = false;
tv_list_unref(kv_pair);
continue;
}
- listitem_T *const val = tv_list_item_alloc();
- tv_list_append(kv_pair, val);
+ tv_list_append_owned_tv(kv_pair, s_tv);
+
+ // Value: not populated yet, need to create list item to push.
+ tv_list_append_owned_tv(kv_pair, (typval_T) {
+ .v_type = VAR_UNKNOWN,
+ });
kv_push(stack, cur);
- cur = (TVPopStackItem) { TV_LIST_ITEM_TV(val), false, false, 0 };
+ tv_list_append_list(cur.tv->vval.v_list, kv_pair);
+ cur = (TVPopStackItem) {
+ .tv = TV_LIST_ITEM_TV(tv_list_last(kv_pair)),
+ .container = false,
+ .special = false,
+ .idx = 0,
+ };
} else {
dictitem_T *const di = tv_dict_item_alloc_len(s, len);
if (tv_dict_add(cur.tv->vval.v_dict, di) == FAIL) {
@@ -244,10 +252,18 @@ bool nlua_pop_typval(lua_State *lstate, typval_T *ret_tv)
lua_pop(lstate, 2);
continue;
}
- listitem_T *const li = tv_list_item_alloc();
- tv_list_append(cur.tv->vval.v_list, li);
+ // Not populated yet, need to create list item to push.
+ tv_list_append_owned_tv(cur.tv->vval.v_list, (typval_T) {
+ .v_type = VAR_UNKNOWN,
+ });
kv_push(stack, cur);
- cur = (TVPopStackItem) { TV_LIST_ITEM_TV(li), false, false, 0 };
+ // TODO(ZyX-I): Use indexes, here list item *will* be reallocated.
+ cur = (TVPopStackItem) {
+ .tv = TV_LIST_ITEM_TV(tv_list_last(cur.tv->vval.v_list)),
+ .container = false,
+ .special = false,
+ .idx = 0,
+ };
}
}
assert(!cur.container);
diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c
index f85009dca8..224e43008d 100644
--- a/src/nvim/quickfix.c
+++ b/src/nvim/quickfix.c
@@ -76,18 +76,25 @@ struct qfline_S {
*/
#define LISTCOUNT 10
+/// Quickfix/Location list definition
+///
+/// Usually the list contains one or more entries. But an empty list can be
+/// created using setqflist()/setloclist() with a title and/or user context
+/// information and entries can be added later using setqflist()/setloclist().
typedef struct qf_list_S {
- qfline_T *qf_start; // pointer to the first error
- qfline_T *qf_last; // pointer to the last error
- qfline_T *qf_ptr; // pointer to the current error
- int qf_count; // number of errors (0 means no error list)
- int qf_index; // current index in the error list
- int qf_nonevalid; // TRUE if not a single valid entry found
- char_u *qf_title; // title derived from the command that created
- // the error list
- typval_T *qf_ctx; // context set by setqflist/setloclist
+ qfline_T *qf_start; ///< pointer to the first error
+ qfline_T *qf_last; ///< pointer to the last error
+ qfline_T *qf_ptr; ///< pointer to the current error
+ int qf_count; ///< number of errors (0 means empty list)
+ int qf_index; ///< current index in the error list
+ int qf_nonevalid; ///< TRUE if not a single valid entry found
+ char_u *qf_title; ///< title derived from the command that created
+ ///< the error list or set by setqflist
+ typval_T *qf_ctx; ///< context set by setqflist/setloclist
} qf_list_T;
+/// Quickfix/Location list stack definition
+/// Contains a list of quickfix/location lists (qf_list_T)
struct qf_info_S {
/*
* Count of references to this list. Used only for location lists.
@@ -1121,6 +1128,7 @@ qf_init_ext(
}
if (qf_add_entry(qi,
+ qi->qf_curlist,
qi->qf_directory,
(*fields.namebuf || qi->qf_directory)
? fields.namebuf : ((qi->qf_currfile && fields.valid)
@@ -1182,13 +1190,17 @@ qf_init_end:
return retval;
}
-static void qf_store_title(qf_info_T *qi, char_u *title)
+static void qf_store_title(qf_info_T *qi, int qf_idx, char_u *title)
{
+ xfree(qi->qf_lists[qf_idx].qf_title);
+ qi->qf_lists[qf_idx].qf_title = NULL;
+
if (title != NULL) {
- char_u *p = xmalloc(STRLEN(title) + 2);
+ size_t len = STRLEN(title) + 1;
+ char_u *p = xmallocz(len);
- qi->qf_lists[qi->qf_curlist].qf_title = p;
- sprintf((char *)p, ":%s", (char *)title);
+ qi->qf_lists[qf_idx].qf_title = p;
+ snprintf((char *)p, len + 1, ":%s", (char *)title);
}
}
@@ -1217,7 +1229,7 @@ static void qf_new_list(qf_info_T *qi, char_u *qf_title)
} else
qi->qf_curlist = qi->qf_listcount++;
memset(&qi->qf_lists[qi->qf_curlist], 0, (size_t)(sizeof(qf_list_T)));
- qf_store_title(qi, qf_title);
+ qf_store_title(qi, qi->qf_curlist, qf_title);
}
/*
@@ -1260,6 +1272,7 @@ void qf_free_all(win_T *wp)
/// Add an entry to the end of the list of errors.
///
/// @param qi quickfix list
+/// @param qf_idx list index
/// @param dir optional directory name
/// @param fname file name or NULL
/// @param bufnum buffer number or zero
@@ -1273,9 +1286,10 @@ void qf_free_all(win_T *wp)
/// @param valid valid entry
///
/// @returns OK or FAIL.
-static int qf_add_entry(qf_info_T *qi, char_u *dir, char_u *fname, int bufnum,
- char_u *mesg, long lnum, int col, char_u vis_col,
- char_u *pattern, int nr, char_u type, char_u valid)
+static int qf_add_entry(qf_info_T *qi, int qf_idx, char_u *dir, char_u *fname,
+ int bufnum, char_u *mesg, long lnum, int col,
+ char_u vis_col, char_u *pattern, int nr, char_u type,
+ char_u valid)
{
qfline_T *qfp = xmalloc(sizeof(qfline_T));
qfline_T **lastp; // pointer to qf_last or NULL
@@ -1306,12 +1320,12 @@ static int qf_add_entry(qf_info_T *qi, char_u *dir, char_u *fname, int bufnum,
qfp->qf_type = (char_u)type;
qfp->qf_valid = valid;
- lastp = &qi->qf_lists[qi->qf_curlist].qf_last;
- if (qi->qf_lists[qi->qf_curlist].qf_count == 0) {
- /* first element in the list */
- qi->qf_lists[qi->qf_curlist].qf_start = qfp;
- qi->qf_lists[qi->qf_curlist].qf_ptr = qfp;
- qi->qf_lists[qi->qf_curlist].qf_index = 0;
+ lastp = &qi->qf_lists[qf_idx].qf_last;
+ if (qi->qf_lists[qf_idx].qf_count == 0) {
+ // first element in the list
+ qi->qf_lists[qf_idx].qf_start = qfp;
+ qi->qf_lists[qf_idx].qf_ptr = qfp;
+ qi->qf_lists[qf_idx].qf_index = 0;
qfp->qf_prev = NULL;
} else {
assert(*lastp);
@@ -1321,12 +1335,11 @@ static int qf_add_entry(qf_info_T *qi, char_u *dir, char_u *fname, int bufnum,
qfp->qf_next = NULL;
qfp->qf_cleared = false;
*lastp = qfp;
- qi->qf_lists[qi->qf_curlist].qf_count++;
- if (qi->qf_lists[qi->qf_curlist].qf_index == 0 && qfp->qf_valid) {
- /* first valid entry */
- qi->qf_lists[qi->qf_curlist].qf_index =
- qi->qf_lists[qi->qf_curlist].qf_count;
- qi->qf_lists[qi->qf_curlist].qf_ptr = qfp;
+ qi->qf_lists[qf_idx].qf_count++;
+ if (qi->qf_lists[qf_idx].qf_index == 0 && qfp->qf_valid) {
+ // first valid entry
+ qi->qf_lists[qf_idx].qf_index = qi->qf_lists[qf_idx].qf_count;
+ qi->qf_lists[qf_idx].qf_ptr = qfp;
}
return OK;
@@ -1429,6 +1442,7 @@ void copy_loclist(win_T *from, win_T *to)
i < from_qfl->qf_count && from_qfp != NULL;
i++, from_qfp = from_qfp->qf_next) {
if (qf_add_entry(to->w_llist,
+ to->w_llist->qf_curlist,
NULL,
NULL,
0,
@@ -2392,8 +2406,9 @@ void qf_history(exarg_T *eap)
}
}
-/// Free all the entries in the error list "idx".
-static void qf_free(qf_info_T *qi, int idx)
+/// Free all the entries in the error list "idx". Note that other information
+/// associated with the list like context and title are not freed.
+static void qf_free_items(qf_info_T *qi, int idx)
{
qfline_T *qfp;
qfline_T *qfpnext;
@@ -2417,12 +2432,9 @@ static void qf_free(qf_info_T *qi, int idx)
qi->qf_lists[idx].qf_start = qfpnext;
qi->qf_lists[idx].qf_count--;
}
- xfree(qi->qf_lists[idx].qf_title);
+
qi->qf_lists[idx].qf_start = NULL;
qi->qf_lists[idx].qf_ptr = NULL;
- qi->qf_lists[idx].qf_title = NULL;
- tv_free(qi->qf_lists[idx].qf_ctx);
- qi->qf_lists[idx].qf_ctx = NULL;
qi->qf_lists[idx].qf_index = 0;
qi->qf_lists[idx].qf_start = NULL;
qi->qf_lists[idx].qf_last = NULL;
@@ -2438,6 +2450,18 @@ static void qf_free(qf_info_T *qi, int idx)
qi->qf_multiscan = false;
}
+/// Free error list "idx". Frees all the entries in the quickfix list,
+/// associated context information and the title.
+static void qf_free(qf_info_T *qi, int idx)
+{
+ qf_free_items(qi, idx);
+
+ xfree(qi->qf_lists[idx].qf_title);
+ qi->qf_lists[idx].qf_title = NULL;
+ tv_free(qi->qf_lists[idx].qf_ctx);
+ qi->qf_lists[idx].qf_ctx = NULL;
+}
+
/*
* qf_mark_adjust: adjust marks
*/
@@ -3704,6 +3728,7 @@ void ex_vimgrep(exarg_T *eap)
// dummy buffer, unless duplicate_name is set, then the
// buffer will be wiped out below.
if (qf_add_entry(qi,
+ qi->qf_curlist,
NULL, // dir
fname,
duplicate_name ? 0 : buf->b_fnum,
@@ -4083,16 +4108,22 @@ enum {
int get_errorlist_properties(win_T *wp, dict_T *what, dict_T *retdict)
{
qf_info_T *qi = &ql_info;
+ dictitem_T *di;
if (wp != NULL) {
qi = GET_LOC_LIST(wp);
if (qi == NULL) {
+ // If querying for the size of the location list, return 0
+ if (((di = tv_dict_find(what, S_LEN("nr"))) != NULL)
+ && (di->di_tv.v_type == VAR_STRING)
+ && strequal((const char *)di->di_tv.vval.v_string, "$")) {
+ return tv_dict_add_nr(retdict, S_LEN("nr"), 0);
+ }
return FAIL;
}
}
int status = OK;
- dictitem_T *di;
int flags = QF_GETLIST_NONE;
int qf_idx = qi->qf_curlist; // default is the current list
@@ -4105,6 +4136,17 @@ int get_errorlist_properties(win_T *wp, dict_T *what, dict_T *retdict)
if (qf_idx < 0 || qf_idx >= qi->qf_listcount) {
return FAIL;
}
+ } else if (qi->qf_listcount == 0) { // stack is empty
+ return FAIL;
+ }
+ flags |= QF_GETLIST_NR;
+ } else if (di->di_tv.v_type == VAR_STRING
+ && strequal((const char *)di->di_tv.vval.v_string, "$")) {
+ // Get the last quickfix list number
+ if (qi->qf_listcount > 0) {
+ qf_idx = qi->qf_listcount - 1;
+ } else {
+ qf_idx = -1; // Quickfix stack is empty
}
flags |= QF_GETLIST_NR;
} else {
@@ -4112,20 +4154,26 @@ int get_errorlist_properties(win_T *wp, dict_T *what, dict_T *retdict)
}
}
- if (tv_dict_find(what, S_LEN("all")) != NULL) {
- flags |= QF_GETLIST_ALL;
- }
+ if (qf_idx != -1) {
+ if (tv_dict_find(what, S_LEN("all")) != NULL) {
+ flags |= QF_GETLIST_ALL;
+ }
- if (tv_dict_find(what, S_LEN("title")) != NULL) {
- flags |= QF_GETLIST_TITLE;
- }
+ if (tv_dict_find(what, S_LEN("title")) != NULL) {
+ flags |= QF_GETLIST_TITLE;
+ }
- if (tv_dict_find(what, S_LEN("winid")) != NULL) {
- flags |= QF_GETLIST_WINID;
- }
+ if (tv_dict_find(what, S_LEN("winid")) != NULL) {
+ flags |= QF_GETLIST_WINID;
+ }
- if (tv_dict_find(what, S_LEN("context")) != NULL) {
- flags |= QF_GETLIST_CONTEXT;
+ if (tv_dict_find(what, S_LEN("context")) != NULL) {
+ flags |= QF_GETLIST_CONTEXT;
+ }
+
+ if (tv_dict_find(what, S_LEN("items")) != NULL) {
+ flags |= QF_GETLIST_ITEMS;
+ }
}
if (flags & QF_GETLIST_TITLE) {
@@ -4144,6 +4192,11 @@ int get_errorlist_properties(win_T *wp, dict_T *what, dict_T *retdict)
status = tv_dict_add_nr(retdict, S_LEN("winid"), win->handle);
}
}
+ if ((status == OK) && (flags & QF_GETLIST_ITEMS)) {
+ list_T *l = tv_list_alloc();
+ (void)get_errorlist(wp, qf_idx, l);
+ tv_dict_add_list(retdict, S_LEN("items"), l);
+ }
if ((status == OK) && (flags & QF_GETLIST_CONTEXT)) {
if (qi->qf_lists[qf_idx].qf_ctx != NULL) {
@@ -4164,23 +4217,24 @@ int get_errorlist_properties(win_T *wp, dict_T *what, dict_T *retdict)
/// Add list of entries to quickfix/location list. Each list entry is
/// a dictionary with item information.
-static int qf_add_entries(qf_info_T *qi, list_T *list, char_u *title,
- int action)
+static int qf_add_entries(qf_info_T *qi, int qf_idx, list_T *list,
+ char_u *title, int action)
{
dict_T *d;
qfline_T *old_last = NULL;
int retval = OK;
bool did_bufnr_emsg = false;
- if (action == ' ' || qi->qf_curlist == qi->qf_listcount) {
+ if (action == ' ' || qf_idx == qi->qf_listcount) {
// make place for a new list
qf_new_list(qi, title);
- } else if (action == 'a' && qi->qf_lists[qi->qf_curlist].qf_count > 0) {
+ qf_idx = qi->qf_curlist;
+ } else if (action == 'a' && qi->qf_lists[qf_idx].qf_count > 0) {
// Adding to existing list, use last entry.
- old_last = qi->qf_lists[qi->qf_curlist].qf_last;
+ old_last = qi->qf_lists[qf_idx].qf_last;
} else if (action == 'r') {
- qf_free(qi, qi->qf_curlist);
- qf_store_title(qi, title);
+ qf_free_items(qi, qf_idx);
+ qf_store_title(qi, qf_idx, title);
}
TV_LIST_ITER_CONST(list, li, {
@@ -4228,6 +4282,7 @@ static int qf_add_entries(qf_info_T *qi, list_T *list, char_u *title,
}
int status = qf_add_entry(qi,
+ qf_idx,
NULL, // dir
(char_u *)filename,
bufnum,
@@ -4250,16 +4305,16 @@ static int qf_add_entries(qf_info_T *qi, list_T *list, char_u *title,
}
});
- if (qi->qf_lists[qi->qf_curlist].qf_index == 0) {
+ if (qi->qf_lists[qf_idx].qf_index == 0) {
// no valid entry
- qi->qf_lists[qi->qf_curlist].qf_nonevalid = true;
+ qi->qf_lists[qf_idx].qf_nonevalid = true;
} else {
- qi->qf_lists[qi->qf_curlist].qf_nonevalid = false;
+ qi->qf_lists[qf_idx].qf_nonevalid = false;
}
if (action != 'a') {
- qi->qf_lists[qi->qf_curlist].qf_ptr = qi->qf_lists[qi->qf_curlist].qf_start;
- if (qi->qf_lists[qi->qf_curlist].qf_count > 0) {
- qi->qf_lists[qi->qf_curlist].qf_index = 1;
+ qi->qf_lists[qf_idx].qf_ptr = qi->qf_lists[qf_idx].qf_start;
+ if (qi->qf_lists[qf_idx].qf_count > 0) {
+ qi->qf_lists[qf_idx].qf_index = 1;
}
}
@@ -4286,13 +4341,24 @@ static int qf_set_properties(qf_info_T *qi, dict_T *what, int action)
if (di->di_tv.vval.v_number != 0) {
qf_idx = (int)di->di_tv.vval.v_number - 1;
}
- if (qf_idx < 0 || qf_idx >= qi->qf_listcount) {
+
+ if ((action == ' ' || action == 'a') && qf_idx == qi->qf_listcount) {
+ // When creating a new list, accept qf_idx pointing to the next
+ // non-available list
+ newlist = true;
+ } else if (qf_idx < 0 || qf_idx >= qi->qf_listcount) {
return FAIL;
+ } else {
+ newlist = false; // use the specified list
}
+ } else if (di->di_tv.v_type == VAR_STRING
+ && strequal((const char *)di->di_tv.vval.v_string, "$")
+ && qi->qf_listcount > 0) {
+ qf_idx = qi->qf_listcount - 1;
+ newlist = false;
} else {
return FAIL;
}
- newlist = false; // use the specified list
}
if (newlist) {
@@ -4311,6 +4377,15 @@ static int qf_set_properties(qf_info_T *qi, dict_T *what, int action)
retval = OK;
}
}
+ if ((di = tv_dict_find(what, S_LEN("items"))) != NULL) {
+ if (di->di_tv.v_type == VAR_LIST) {
+ char_u *title_save = vim_strsave(qi->qf_lists[qf_idx].qf_title);
+
+ retval = qf_add_entries(qi, qf_idx, di->di_tv.vval.v_list,
+ title_save, action == ' ' ? 'a' : action);
+ xfree(title_save);
+ }
+ }
if ((di = tv_dict_find(what, S_LEN("context"))) != NULL) {
tv_free(qi->qf_lists[qf_idx].qf_ctx);
@@ -4400,7 +4475,7 @@ int set_errorlist(win_T *wp, list_T *list, int action, char_u *title,
} else if (what != NULL) {
retval = qf_set_properties(qi, what, action);
} else {
- retval = qf_add_entries(qi, list, title, action);
+ retval = qf_add_entries(qi, qi->qf_curlist, list, title, action);
}
return retval;
@@ -4718,6 +4793,7 @@ void ex_helpgrep(exarg_T *eap)
line[--l] = NUL;
if (qf_add_entry(qi,
+ qi->qf_curlist,
NULL, // dir
fnames[fi],
0,
diff --git a/src/nvim/regexp_nfa.c b/src/nvim/regexp_nfa.c
index 93ba9ce097..c520ef5fb9 100644
--- a/src/nvim/regexp_nfa.c
+++ b/src/nvim/regexp_nfa.c
@@ -1263,7 +1263,7 @@ static int nfa_regatom(void)
rc_did_emsg = TRUE;
return FAIL;
}
- EMSGN("INTERNAL: Unknown character class char: %" PRId64, c);
+ IEMSGN("INTERNAL: Unknown character class char: %" PRId64, c);
return FAIL;
}
/* When '.' is followed by a composing char ignore the dot, so that
@@ -4413,8 +4413,8 @@ static int check_char_class(int class, int c)
break;
default:
- /* should not be here :P */
- EMSGN(_(e_ill_char_class), class);
+ // should not be here :P
+ IEMSGN(_(e_ill_char_class), class);
return FAIL;
}
return FAIL;
@@ -5992,8 +5992,9 @@ static int nfa_regmatch(nfa_regprog_T *prog, nfa_state_T *start,
int c = t->state->c;
#ifdef REGEXP_DEBUG
- if (c < 0)
- EMSGN("INTERNAL: Negative state char: %" PRId64, c);
+ if (c < 0) {
+ IEMSGN("INTERNAL: Negative state char: %" PRId64, c);
+ }
#endif
result = (c == curc);
@@ -6462,12 +6463,13 @@ static regprog_T *nfa_regcomp(char_u *expr, int re_flags)
* (and count its size). */
postfix = re2post();
if (postfix == NULL) {
- /* TODO: only give this error for debugging? */
- if (post_ptr >= post_end)
- EMSGN("Internal error: estimated max number "
- "of states insufficient: %" PRId64,
- post_end - post_start);
- goto fail; /* Cascaded (syntax?) error */
+ // TODO(vim): only give this error for debugging?
+ if (post_ptr >= post_end) {
+ IEMSGN("Internal error: estimated max number "
+ "of states insufficient: %" PRId64,
+ post_end - post_start);
+ }
+ goto fail; // Cascaded (syntax?) error
}
/*
diff --git a/src/nvim/search.c b/src/nvim/search.c
index 387614fd09..1eb1a25a19 100644
--- a/src/nvim/search.c
+++ b/src/nvim/search.c
@@ -3669,6 +3669,11 @@ current_quote (
/* Correct cursor when 'selection' is exclusive */
if (VIsual_active) {
+ // this only works within one line
+ if (VIsual.lnum != curwin->w_cursor.lnum) {
+ return false;
+ }
+
vis_bef_curs = lt(VIsual, curwin->w_cursor);
if (*p_sel == 'e' && vis_bef_curs)
dec_cursor();
diff --git a/src/nvim/testdir/Makefile b/src/nvim/testdir/Makefile
index 1f8cf8a0e7..5af8dd20cd 100644
--- a/src/nvim/testdir/Makefile
+++ b/src/nvim/testdir/Makefile
@@ -42,6 +42,7 @@ SCRIPTS ?= $(SCRIPTS_DEFAULT)
NEW_TESTS ?= \
test_autocmd.res \
test_bufwintabinfo.res \
+ test_changedtick.res \
test_charsearch.res \
test_cmdline.res \
test_command_count.res \
diff --git a/src/nvim/testdir/test_alot.vim b/src/nvim/testdir/test_alot.vim
index c1f6405579..5ce6799b99 100644
--- a/src/nvim/testdir/test_alot.vim
+++ b/src/nvim/testdir/test_alot.vim
@@ -2,9 +2,10 @@
" This makes testing go faster, since Vim doesn't need to restart.
source test_assign.vim
+source test_changedtick.vim
source test_cursor_func.vim
-source test_execute_func.vim
source test_ex_undo.vim
+source test_execute_func.vim
source test_expr.vim
source test_expr_utf8.vim
source test_feedkeys.vim
diff --git a/src/nvim/testdir/test_changedtick.vim b/src/nvim/testdir/test_changedtick.vim
new file mode 100644
index 0000000000..3a91bb54aa
--- /dev/null
+++ b/src/nvim/testdir/test_changedtick.vim
@@ -0,0 +1,57 @@
+" 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
diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim
index ac44e09a5a..dc9790a39c 100644
--- a/src/nvim/testdir/test_cmdline.vim
+++ b/src/nvim/testdir/test_cmdline.vim
@@ -330,4 +330,36 @@ func Test_cmdline_search_range()
bwipe!
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
+
+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>\<Esc>", "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>
+endfunc
+
set cpo&
diff --git a/src/nvim/testdir/test_expr.vim b/src/nvim/testdir/test_expr.vim
index d32facaa98..ad967c528c 100644
--- a/src/nvim/testdir/test_expr.vim
+++ b/src/nvim/testdir/test_expr.vim
@@ -439,3 +439,8 @@ func Test_funcref()
call assert_equal(2, OneByRef())
call assert_fails('echo funcref("{")', 'E475:')
endfunc
+
+func Test_empty_concatenate()
+ call assert_equal('b', 'a'[4:0] . 'b')
+ call assert_equal('b', 'b' . 'a'[4:0])
+endfunc
diff --git a/src/nvim/testdir/test_functions.vim b/src/nvim/testdir/test_functions.vim
index 0ce034b63e..398e9ab331 100644
--- a/src/nvim/testdir/test_functions.vim
+++ b/src/nvim/testdir/test_functions.vim
@@ -311,3 +311,45 @@ func! Test_mode()
bwipe!
iunmap <F2>
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))
+
+ " 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
+
+ set fileformats&
+endfunc
diff --git a/src/nvim/testdir/test_quickfix.vim b/src/nvim/testdir/test_quickfix.vim
index 30023dddc9..95a7d29089 100644
--- a/src/nvim/testdir/test_quickfix.vim
+++ b/src/nvim/testdir/test_quickfix.vim
@@ -1632,12 +1632,12 @@ func XbottomTests(cchar)
call assert_fails('lbottom', 'E776:')
endif
- call g:Xsetlist([{'filename': 'foo', 'lnum': 42}])
+ 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')
+ call g:Xsetlist([{'filename': 'var', 'lnum': 24}], 'a')
Xbottom
call win_gotoid(wid)
call assert_equal(2, line('.'))
@@ -1817,6 +1817,73 @@ func Xproperty_tests(cchar)
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})
+ call g:Xsetlist([], ' ', {'title':'Green',
+ \ 'items' : [{'filename':'F1', 'lnum':10}]})
+ 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))
+
+ " 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 l1.nr=2
+ let l2.nr=1
+ 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')
endfunc
func Test_qf_property()
@@ -2102,3 +2169,43 @@ func Test_bufoverflow()
set efm&vim
endfunc
+func Test_cclose_from_copen()
+ augroup QF_Test
+ au!
+ au FileType qf :cclose
+ augroup END
+ copen
+ augroup QF_Test
+ au!
+ augroup END
+ augroup! QF_Test
+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(1, len(g:Xgetlist({'nr':'$', 'all':1})))
+ call assert_equal(0, len(g:Xgetlist({'nr':0})))
+
+ 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
diff --git a/src/nvim/testdir/test_stat.vim b/src/nvim/testdir/test_stat.vim
index dee0d13e84..1239fe9427 100644
--- a/src/nvim/testdir/test_stat.vim
+++ b/src/nvim/testdir/test_stat.vim
@@ -1,20 +1,41 @@
" Tests for stat functions and checktime
-func Test_existent_file()
+func CheckFileTime(doSleep)
let fname = 'Xtest.tmp'
+ let result = 0
let ts = localtime()
+ if a:doSleep
+ sleep 1
+ endif
let fl = ['Hello World!']
call writefile(fl, fname)
let tf = getftime(fname)
+ if a:doSleep
+ sleep 1
+ endif
let te = localtime()
- call assert_true(ts <= tf && tf <= te)
- call assert_equal(strlen(fl[0] . "\n"), getfsize(fname))
- call assert_equal('file', getftype(fname))
- call assert_equal('rw-', getfperm(fname)[0:2])
+ let time_correct = (ts <= tf && tf <= te)
+ if a:doSleep || time_correct
+ call assert_true(time_correct)
+ call assert_equal(strlen(fl[0] . "\n"), getfsize(fname))
+ call assert_equal('file', getftype(fname))
+ call assert_equal('rw-', getfperm(fname)[0:2])
+ let result = 1
+ endif
call delete(fname)
+ 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()
diff --git a/src/nvim/testdir/test_substitute.vim b/src/nvim/testdir/test_substitute.vim
index e2b6de03c3..a3bc04dcd0 100644
--- a/src/nvim/testdir/test_substitute.vim
+++ b/src/nvim/testdir/test_substitute.vim
@@ -39,3 +39,70 @@ function! Test_multiline_subst()
call assert_equal('xxxxx', getline(13))
enew!
endfunction
+
+function! 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/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/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' },
+ \]
+
+ 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
+endfunction
diff --git a/src/nvim/testdir/test_visual.vim b/src/nvim/testdir/test_visual.vim
index 1694adbd32..69607e642c 100644
--- a/src/nvim/testdir/test_visual.vim
+++ b/src/nvim/testdir/test_visual.vim
@@ -43,3 +43,10 @@ func Test_dotregister_paste()
call assert_equal('hello world world', getline(1))
q!
endfunc
+
+func Test_Visual_inner_quote()
+ new
+ normal oxX
+ normal vki'
+ bwipe!
+endfunc
diff --git a/src/nvim/tui/terminfo.c b/src/nvim/tui/terminfo.c
index 492c1c5e9c..2f07e83158 100644
--- a/src/nvim/tui/terminfo.c
+++ b/src/nvim/tui/terminfo.c
@@ -90,8 +90,8 @@ bool terminfo_is_term_family(const char *term, const char *family)
size_t tlen = strlen(term);
size_t flen = strlen(family);
return tlen >= flen
- && 0 == memcmp(term, family, flen) \
- // Per the commentary in terminfo, minus sign is the suffix separator.
+ && 0 == memcmp(term, family, flen)
+ // Per commentary in terminfo, minus is the only valid suffix separator.
&& ('\0' == term[flen] || '-' == term[flen]);
}
diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c
index dbe1222dc0..df5b41a64b 100644
--- a/src/nvim/tui/tui.c
+++ b/src/nvim/tui/tui.c
@@ -222,7 +222,8 @@ static void terminfo_start(UI *ui)
const char *vte_version_env = os_getenv("VTE_VERSION");
long vte_version = vte_version_env ? strtol(vte_version_env, NULL, 10) : 0;
bool iterm_env = termprg && strstr(termprg, "iTerm.app");
- bool konsole = os_getenv("KONSOLE_PROFILE_NAME")
+ bool konsole = terminfo_is_term_family(term, "konsole")
+ || os_getenv("KONSOLE_PROFILE_NAME")
|| os_getenv("KONSOLE_DBUS_SESSION");
patch_terminfo_bugs(data, term, colorterm, vte_version, konsole, iterm_env);
diff --git a/src/nvim/version.c b/src/nvim/version.c
index e35b803b4e..996c06c902 100644
--- a/src/nvim/version.c
+++ b/src/nvim/version.c
@@ -480,7 +480,7 @@ static const int included_patches[] = {
// 958,
// 957,
// 956,
- // 955,
+ 955,
// 954,
// 953,
// 952,
@@ -778,7 +778,7 @@ static const int included_patches[] = {
// 660,
// 659,
// 658,
- // 657,
+ 657,
// 656,
// 655,
// 654,
@@ -794,14 +794,14 @@ static const int included_patches[] = {
// 644,
// 643,
// 642,
- // 641,
+ 641,
// 640,
// 639,
// 638,
// 637,
// 636,
// 635,
- // 634,
+ 634,
// 633,
// 632,
// 631,
@@ -827,7 +827,7 @@ static const int included_patches[] = {
// 611,
// 610,
// 609,
- // 608,
+ 608,
607,
606,
605,
@@ -844,7 +844,7 @@ static const int included_patches[] = {
// 594,
// 593,
// 592,
- // 591,
+ 591,
590,
// 589,
// 588,
@@ -1096,12 +1096,12 @@ static const int included_patches[] = {
// 342,
341,
// 340,
- // 339,
+ 339,
// 338,
// 337,
- // 336,
- // 335,
- // 334,
+ 336,
+ 335,
+ 334,
333,
// 332,
331,
@@ -1120,8 +1120,8 @@ static const int included_patches[] = {
// 318,
// 317,
// 316,
- // 315,
- // 314,
+ 315,
+ 314,
// 313,
// 312,
311,
@@ -1275,7 +1275,7 @@ static const int included_patches[] = {
163,
162,
161,
- // 160,
+ 160,
159,
158,
157,
diff --git a/src/nvim/window.c b/src/nvim/window.c
index 5e85a9bede..b687781dfb 100644
--- a/src/nvim/window.c
+++ b/src/nvim/window.c
@@ -1724,7 +1724,6 @@ void close_windows(buf_T *buf, int keep_curwin)
{
tabpage_T *tp, *nexttp;
int h = tabline_height();
- int count = tabpage_index(NULL);
++RedrawingDisabled;
@@ -1762,10 +1761,6 @@ void close_windows(buf_T *buf, int keep_curwin)
--RedrawingDisabled;
- if (count != tabpage_index(NULL)) {
- apply_autocmds(EVENT_TABCLOSED, NULL, NULL, false, curbuf);
- }
-
redraw_tabline = true;
if (h != tabline_height()) {
shell_new_rows();
@@ -1848,7 +1843,6 @@ static bool close_last_window_tabpage(win_T *win, bool free_buf,
// Since goto_tabpage_tp above did not trigger *Enter autocommands, do
// that now.
- apply_autocmds(EVENT_TABCLOSED, prev_idx, prev_idx, false, curbuf);
apply_autocmds(EVENT_WINENTER, NULL, NULL, false, curbuf);
apply_autocmds(EVENT_TABENTER, NULL, NULL, false, curbuf);
if (old_curbuf != curbuf) {
@@ -2108,19 +2102,29 @@ void win_close_othertab(win_T *win, int free_buf, tabpage_T *tp)
/* When closing the last window in a tab page remove the tab page. */
if (tp->tp_firstwin == tp->tp_lastwin) {
- if (tp == first_tabpage)
+ char_u prev_idx[NUMBUFLEN];
+ if (has_event(EVENT_TABCLOSED)) {
+ vim_snprintf((char *)prev_idx, NUMBUFLEN, "%i", tabpage_index(tp));
+ }
+
+ if (tp == first_tabpage) {
first_tabpage = tp->tp_next;
- else {
+ } else {
for (ptp = first_tabpage; ptp != NULL && ptp->tp_next != tp;
- ptp = ptp->tp_next)
- ;
+ ptp = ptp->tp_next) {
+ // loop
+ }
if (ptp == NULL) {
internal_error("win_close_othertab()");
return;
}
ptp->tp_next = tp->tp_next;
}
- free_tp = TRUE;
+ free_tp = true;
+
+ if (has_event(EVENT_TABCLOSED)) {
+ apply_autocmds(EVENT_TABCLOSED, prev_idx, prev_idx, false, win->w_buffer);
+ }
}
/* Free the memory used for the window. */
diff --git a/test/functional/autocmd/tabclose_spec.lua b/test/functional/autocmd/tabclose_spec.lua
index 1431c69589..fb777e7eea 100644
--- a/test/functional/autocmd/tabclose_spec.lua
+++ b/test/functional/autocmd/tabclose_spec.lua
@@ -2,32 +2,67 @@ local helpers = require('test.functional.helpers')(after_each)
local clear, nvim, eq = helpers.clear, helpers.nvim, helpers.eq
describe('TabClosed', function()
- describe('au TabClosed', function()
- describe('with * as <afile>', function()
- it('matches when closing any tab', function()
- clear()
- nvim('command', 'au! TabClosed * echom "tabclosed:".expand("<afile>").":".expand("<amatch>").":".tabpagenr()')
- repeat
- nvim('command', 'tabnew')
- until nvim('eval', 'tabpagenr()') == 6 -- current tab is now 6
- eq("\ntabclosed:6:6:5", nvim('command_output', 'tabclose')) -- close last 6, current tab is now 5
- eq("\ntabclosed:5:5:4", nvim('command_output', 'close')) -- close last window on tab, closes tab
- eq("\ntabclosed:2:2:3", nvim('command_output', '2tabclose')) -- close tab 2, current tab is now 3
- eq("\ntabclosed:1:1:2\ntabclosed:1:1:1", nvim('command_output', 'tabonly')) -- close tabs 1 and 2
- end)
- end)
- describe('with NR as <afile>', function()
- it('matches when closing a tab whose index is NR', function()
- nvim('command', 'au! TabClosed 2 echom "tabclosed:match"')
- repeat
- nvim('command', 'tabnew')
- until nvim('eval', 'tabpagenr()') == 5 -- current tab is now 5
- -- sanity check, we shouldn't match on tabs with numbers other than 2
- eq("\ntabclosed:5:5:4", nvim('command_output', 'tabclose'))
- -- close tab page 2, current tab is now 3
- eq("\ntabclosed:2:2:3\ntabclosed:match", nvim('command_output', '2tabclose'))
- end)
- end)
+ before_each(clear)
+
+ describe('au TabClosed', function()
+ describe('with * as <afile>', function()
+ it('matches when closing any tab', function()
+ nvim('command', 'au! TabClosed * echom "tabclosed:".expand("<afile>").":".expand("<amatch>").":".tabpagenr()')
+ repeat
+ nvim('command', 'tabnew')
+ until nvim('eval', 'tabpagenr()') == 6 -- current tab is now 6
+ eq("\ntabclosed:6:6:5", nvim('command_output', 'tabclose')) -- close last 6, current tab is now 5
+ eq("\ntabclosed:5:5:4", nvim('command_output', 'close')) -- close last window on tab, closes tab
+ eq("\ntabclosed:2:2:3", nvim('command_output', '2tabclose')) -- close tab 2, current tab is now 3
+ eq("\ntabclosed:1:1:2\ntabclosed:1:1:1", nvim('command_output', 'tabonly')) -- close tabs 1 and 2
+ end)
+
+ it('is triggered when closing a window via bdelete from another tab', function()
+ nvim('command', 'au! TabClosed * echom "tabclosed:".expand("<afile>").":".expand("<amatch>").":".tabpagenr()')
+ nvim('command', '1tabedit Xtestfile')
+ nvim('command', '1tabedit Xtestfile')
+ nvim('command', 'normal! 1gt')
+ eq({1, 3}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
+ eq("\ntabclosed:2:2:1\ntabclosed:2:2:1", nvim('command_output', 'bdelete Xtestfile'))
+ eq({1, 1}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
+ end)
+
+ it('is triggered when closing a window via bdelete from current tab', function()
+ nvim('command', 'au! TabClosed * echom "tabclosed:".expand("<afile>").":".expand("<amatch>").":".tabpagenr()')
+ nvim('command', 'file Xtestfile1')
+ nvim('command', '1tabedit Xtestfile2')
+ nvim('command', '1tabedit Xtestfile2')
+
+ -- Only one tab is closed, and the alternate file is used for the other.
+ eq({2, 3}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
+ eq("\ntabclosed:2:2:2", nvim('command_output', 'bdelete Xtestfile2'))
+ eq('Xtestfile1', nvim('eval', 'bufname("")'))
+ end)
+ end)
+
+ describe('with NR as <afile>', function()
+ it('matches when closing a tab whose index is NR', function()
+ nvim('command', 'au! TabClosed * echom "tabclosed:".expand("<afile>").":".expand("<amatch>").":".tabpagenr()')
+ nvim('command', 'au! TabClosed 2 echom "tabclosed:match"')
+ repeat
+ nvim('command', 'tabnew')
+ until nvim('eval', 'tabpagenr()') == 7 -- current tab is now 7
+ -- sanity check, we shouldn't match on tabs with numbers other than 2
+ eq("\ntabclosed:7:7:6", nvim('command_output', 'tabclose'))
+ -- close tab page 2, current tab is now 5
+ eq("\ntabclosed:2:2:5\ntabclosed:match", nvim('command_output', '2tabclose'))
+ end)
+ end)
+
+ describe('with close', function()
+ it('is triggered', function()
+ nvim('command', 'au! TabClosed * echom "tabclosed:".expand("<afile>").":".expand("<amatch>").":".tabpagenr()')
+ nvim('command', 'tabedit Xtestfile')
+ eq({2, 2}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
+ eq("\ntabclosed:2:2:1", nvim('command_output', 'close'))
+ eq({1, 1}, nvim('eval', '[tabpagenr(), tabpagenr("$")]'))
+ end)
end)
+ end)
end)
diff --git a/test/functional/autocmd/termclose_spec.lua b/test/functional/autocmd/termclose_spec.lua
index c6c30494dd..e64df502a6 100644
--- a/test/functional/autocmd/termclose_spec.lua
+++ b/test/functional/autocmd/termclose_spec.lua
@@ -4,6 +4,7 @@ local clear, command, nvim, nvim_dir =
helpers.clear, helpers.command, helpers.nvim, helpers.nvim_dir
local eval, eq, retry =
helpers.eval, helpers.eq, helpers.retry
+local ok = helpers.ok
if helpers.pending_win32(pending) then return end
@@ -41,7 +42,9 @@ describe('TermClose event', function()
command('call jobstop(g:test_job)')
retry(nil, nil, function() eq(1, eval('get(g:, "test_job_exited", 0)')) end)
local duration = os.time() - start
- eq(2, duration)
+ -- nvim starts sending SIGTERM after KILL_TIMEOUT_MS
+ ok(duration >= 2)
+ ok(duration <= 4) -- <= 2 + delta because of slow CI
end)
it('kills pty job trapping SIGHUP and SIGTERM', function()
@@ -58,8 +61,8 @@ describe('TermClose event', function()
retry(nil, nil, function() eq(1, eval('get(g:, "test_job_exited", 0)')) end)
local duration = os.time() - start
-- nvim starts sending kill after 2*KILL_TIMEOUT_MS
- helpers.ok(4 <= duration)
- helpers.ok(duration <= 7) -- <= 4 + delta because of slow CI
+ ok(duration >= 4)
+ ok(duration <= 7) -- <= 4 + delta because of slow CI
end)
it('reports the correct <abuf>', function()
diff --git a/test/functional/eval/system_spec.lua b/test/functional/eval/system_spec.lua
index 7e213e2156..e2b12b6bc9 100644
--- a/test/functional/eval/system_spec.lua
+++ b/test/functional/eval/system_spec.lua
@@ -89,7 +89,9 @@ describe('system()', function()
end)
it('does NOT run in shell', function()
- if not iswin() then
+ if iswin() then
+ eq("%PATH%\n", eval("system(['powershell', '-NoProfile', '-NoLogo', '-ExecutionPolicy', 'RemoteSigned', '-Command', 'echo', '%PATH%'])"))
+ else
eq("* $PATH %PATH%\n", eval("system(['echo', '*', '$PATH', '%PATH%'])"))
end
end)
@@ -185,6 +187,7 @@ describe('system()', function()
end)
it('`yes` and is interrupted with CTRL-C', function()
+ if helpers.pending_win32(pending) then return end
feed(':call system("yes")<cr>')
screen:expect([[
|
@@ -442,11 +445,13 @@ describe('systemlist()', function()
describe('with output containing NULs', function()
local fname = 'Xtest'
- before_each(create_file_with_nuls(fname))
+ before_each(function()
+ command('set ff=unix')
+ create_file_with_nuls(fname)()
+ end)
after_each(delete_file(fname))
it('replaces NULs by newline characters', function()
- if helpers.pending_win32(pending) then return end
eq({'part1\npart2\npart3'}, eval('systemlist("cat '..fname..'")'))
end)
end)
diff --git a/test/functional/helpers.lua b/test/functional/helpers.lua
index bff8d065f8..31a2c3b3ff 100644
--- a/test/functional/helpers.lua
+++ b/test/functional/helpers.lua
@@ -383,9 +383,8 @@ end
local function set_shell_powershell()
source([[
- set shell=powershell shellquote=\" shellpipe=\| shellredir=>
- set shellcmdflag=\ -NoLogo\ -NoProfile\ -ExecutionPolicy\ RemoteSigned\ -Command
- let &shellxquote=' '
+ set shell=powershell shellquote=( shellpipe=\| shellredir=> shellxquote=
+ set shellcmdflag=-NoLogo\ -NoProfile\ -ExecutionPolicy\ RemoteSigned\ -Command
]])
end
diff --git a/test/functional/normal/K_spec.lua b/test/functional/normal/K_spec.lua
index 43e598633c..174313d80e 100644
--- a/test/functional/normal/K_spec.lua
+++ b/test/functional/normal/K_spec.lua
@@ -2,8 +2,6 @@ local helpers = require('test.functional.helpers')(after_each)
local eq, clear, eval, feed =
helpers.eq, helpers.clear, helpers.eval, helpers.feed
-if helpers.pending_win32(pending) then return end
-
describe('K', function()
local test_file = 'K_spec_out'
before_each(function()
@@ -29,7 +27,7 @@ describe('K', function()
it("invokes non-prefixed 'keywordprg' as shell command", function()
helpers.source([[
let @a='fnord'
- set keywordprg=echo\ fnord\ >>]])
+ set keywordprg=echo\ fnord>>]])
-- K on the text "K_spec_out" resolves to `!echo fnord >> K_spec_out`.
feed('i'..test_file..'<ESC>K')
diff --git a/test/functional/options/autochdir_spec.lua b/test/functional/options/autochdir_spec.lua
index 209531515c..2fce0a5ed9 100644
--- a/test/functional/options/autochdir_spec.lua
+++ b/test/functional/options/autochdir_spec.lua
@@ -3,8 +3,6 @@ local clear = helpers.clear
local eq = helpers.eq
local getcwd = helpers.funcs.getcwd
-if helpers.pending_win32(pending) then return end
-
describe("'autochdir'", function()
it('given on the shell gets processed properly', function()
local targetdir = 'test/functional/fixtures'
@@ -12,9 +10,10 @@ describe("'autochdir'", function()
-- By default 'autochdir' is off, thus getcwd() returns the repo root.
clear(targetdir..'/tty-test.c')
local rootdir = getcwd()
+ local expected = rootdir .. '/' .. targetdir
-- With 'autochdir' on, we should get the directory of tty-test.c.
clear('--cmd', 'set autochdir', targetdir..'/tty-test.c')
- eq(rootdir..'/'..targetdir, getcwd())
+ eq(helpers.iswin() and expected:gsub('/', '\\') or expected, getcwd())
end)
end)
diff --git a/test/functional/options/defaults_spec.lua b/test/functional/options/defaults_spec.lua
index b83b7b8eee..89d4e56d04 100644
--- a/test/functional/options/defaults_spec.lua
+++ b/test/functional/options/defaults_spec.lua
@@ -11,19 +11,8 @@ local neq = helpers.neq
local mkdir = helpers.mkdir
local rmdir = helpers.rmdir
-local function init_session(...)
- local args = { helpers.nvim_prog, '-i', 'NONE', '--embed',
- '--cmd', helpers.nvim_set }
- for _, v in ipairs({...}) do
- table.insert(args, v)
- end
- helpers.set_session(helpers.spawn(args))
-end
-
describe('startup defaults', function()
describe(':filetype', function()
- if helpers.pending_win32(pending) then return end
-
local function expect_filetype(expected)
local screen = Screen.new(50, 4)
screen:attach()
@@ -36,50 +25,70 @@ describe('startup defaults', function()
)
end
- it('enabled by `-u NORC`', function()
- init_session('-u', 'NORC')
+ it('all ON after `-u NORC`', function()
+ clear('-u', 'NORC')
expect_filetype(
'filetype detection:ON plugin:ON indent:ON |')
end)
- it('disabled by `-u NONE`', function()
- init_session('-u', 'NONE')
+ it('all ON after `:syntax …` #7765', function()
+ clear('-u', 'NORC', '--cmd', 'syntax on')
expect_filetype(
- 'filetype detection:OFF plugin:OFF indent:OFF |')
+ 'filetype detection:ON plugin:ON indent:ON |')
+ clear('-u', 'NORC', '--cmd', 'syntax off')
+ expect_filetype(
+ 'filetype detection:ON plugin:ON indent:ON |')
end)
- it('overridden by early `filetype on`', function()
- init_session('-u', 'NORC', '--cmd', 'filetype on')
+ it('all OFF after `-u NONE`', function()
+ clear('-u', 'NONE')
expect_filetype(
- 'filetype detection:ON plugin:OFF indent:OFF |')
+ 'filetype detection:OFF plugin:OFF indent:OFF |')
end)
- it('overridden by early `filetype plugin on`', function()
- init_session('-u', 'NORC', '--cmd', 'filetype plugin on')
+ it('explicit OFF stays OFF', function()
+ clear('-u', 'NORC', '--cmd',
+ 'syntax off | filetype off | filetype plugin indent off')
+ expect_filetype(
+ 'filetype detection:OFF plugin:OFF indent:OFF |')
+ clear('-u', 'NORC', '--cmd', 'syntax off | filetype plugin indent off')
+ expect_filetype(
+ 'filetype detection:ON plugin:OFF indent:OFF |')
+ clear('-u', 'NORC', '--cmd', 'filetype indent off')
expect_filetype(
'filetype detection:ON plugin:ON indent:OFF |')
+ clear('-u', 'NORC', '--cmd', 'syntax off | filetype off')
+ expect_filetype(
+ 'filetype detection:OFF plugin:(on) indent:(on) |')
+ -- Swap the order.
+ clear('-u', 'NORC', '--cmd', 'filetype off | syntax off')
+ expect_filetype(
+ 'filetype detection:OFF plugin:(on) indent:(on) |')
end)
- it('overridden by early `filetype indent on`', function()
- init_session('-u', 'NORC', '--cmd', 'filetype indent on')
+ it('all ON after early `:filetype … on`', function()
+ -- `:filetype … on` should not change the defaults. #7765
+ -- Only an explicit `:filetype … off` sets OFF.
+
+ clear('-u', 'NORC', '--cmd', 'filetype on')
expect_filetype(
- 'filetype detection:ON plugin:OFF indent:ON |')
+ 'filetype detection:ON plugin:ON indent:ON |')
+ clear('-u', 'NORC', '--cmd', 'filetype plugin on')
+ expect_filetype(
+ 'filetype detection:ON plugin:ON indent:ON |')
+ clear('-u', 'NORC', '--cmd', 'filetype indent on')
+ expect_filetype(
+ 'filetype detection:ON plugin:ON indent:ON |')
end)
- it('adjusted by late `filetype off`', function()
- init_session('-u', 'NORC', '-c', 'filetype off')
+ it('late `:filetype … off` stays OFF', function()
+ clear('-u', 'NORC', '-c', 'filetype off')
expect_filetype(
'filetype detection:OFF plugin:(on) indent:(on) |')
- end)
-
- it('adjusted by late `filetype plugin off`', function()
- init_session('-u', 'NORC', '-c', 'filetype plugin off')
+ clear('-u', 'NORC', '-c', 'filetype plugin off')
expect_filetype(
'filetype detection:ON plugin:OFF indent:ON |')
- end)
-
- it('adjusted by late `filetype indent off`', function()
- init_session('-u', 'NORC', '-c', 'filetype indent off')
+ clear('-u', 'NORC', '-c', 'filetype indent off')
expect_filetype(
'filetype detection:ON plugin:ON indent:OFF |')
end)
@@ -87,22 +96,21 @@ describe('startup defaults', function()
describe('syntax', function()
it('enabled by `-u NORC`', function()
- init_session('-u', 'NORC')
+ clear('-u', 'NORC')
eq(1, eval('g:syntax_on'))
end)
it('disabled by `-u NONE`', function()
- init_session('-u', 'NONE')
+ clear('-u', 'NONE')
eq(0, eval('exists("g:syntax_on")'))
end)
- it('overridden by early `syntax off`', function()
- init_session('-u', 'NORC', '--cmd', 'syntax off')
+ it('`:syntax off` stays off', function()
+ -- early
+ clear('-u', 'NORC', '--cmd', 'syntax off')
eq(0, eval('exists("g:syntax_on")'))
- end)
-
- it('adjusted by late `syntax off`', function()
- init_session('-u', 'NORC', '-c', 'syntax off')
+ -- late
+ clear('-u', 'NORC', '-c', 'syntax off')
eq(0, eval('exists("g:syntax_on")'))
end)
end)
diff --git a/test/functional/plugin/man_spec.lua b/test/functional/plugin/man_spec.lua
index 479fd6e7a5..dc189b8f8e 100644
--- a/test/functional/plugin/man_spec.lua
+++ b/test/functional/plugin/man_spec.lua
@@ -12,8 +12,8 @@ before_each(function()
command('set filetype=man')
end)
-describe('In autoload/man.vim', function()
- describe('function man#highlight_formatted_text', function()
+describe(':Man', function()
+ describe('man.lua: highlight_line()', function()
local screen
before_each(function()
diff --git a/test/functional/plugin/msgpack_spec.lua b/test/functional/plugin/msgpack_spec.lua
index 5ba19708cf..4b014cbc73 100644
--- a/test/functional/plugin/msgpack_spec.lua
+++ b/test/functional/plugin/msgpack_spec.lua
@@ -8,7 +8,7 @@ local NIL = helpers.NIL
local plugin_helpers = require('test.functional.plugin.helpers')
local reset = plugin_helpers.reset
-describe('In autoload/msgpack.vim', function()
+describe('autoload/msgpack.vim', function()
before_each(reset)
local sp = function(typ, val)
diff --git a/test/functional/plugin/shada_spec.lua b/test/functional/plugin/shada_spec.lua
index dbc78e63f0..5a064a759f 100644
--- a/test/functional/plugin/shada_spec.lua
+++ b/test/functional/plugin/shada_spec.lua
@@ -43,9 +43,7 @@ local wshada, _, fname = get_shada_rw('Xtest-functional-plugin-shada.shada')
local wshada_tmp, _, fname_tmp =
get_shada_rw('Xtest-functional-plugin-shada.shada.tmp.f')
-if helpers.pending_win32(pending) then return end
-
-describe('In autoload/shada.vim', function()
+describe('autoload/shada.vim', function()
local epoch = os.date('%Y-%m-%dT%H:%M:%S', 0)
before_each(function()
reset()
@@ -2138,8 +2136,9 @@ describe('In autoload/shada.vim', function()
end)
end)
-describe('In plugin/shada.vim', function()
+describe('plugin/shada.vim', function()
local epoch = os.date('%Y-%m-%dT%H:%M:%S', 0)
+ local eol = helpers.iswin() and '\r\n' or '\n'
before_each(function()
reset()
os.remove(fname)
@@ -2279,7 +2278,7 @@ describe('In plugin/shada.vim', function()
' + f file name ["foo"]',
' + l line number 2',
' + c column -200',
- }, '\n') .. '\n', io.open(fname .. '.tst'):read('*a'))
+ }, eol) .. eol, io.open(fname .. '.tst'):read('*a'))
shada_eq({{
timestamp=0,
type=8,
@@ -2303,6 +2302,7 @@ describe('In plugin/shada.vim', function()
describe('event FileWriteCmd', function()
it('works', function()
+ if helpers.pending_win32(pending) then return end
nvim('set_var', 'shada#add_own_header', 0)
curbuf('set_lines', 0, 1, true, {
'Jump with timestamp ' .. epoch .. ':',
@@ -2326,7 +2326,7 @@ describe('In plugin/shada.vim', function()
'Jump with timestamp ' .. epoch .. ':',
' % Key________ Description Value',
' + n name \'A\'',
- }, '\n') .. '\n', io.open(fname .. '.tst'):read('*a'))
+ }, eol) .. eol, io.open(fname .. '.tst'):read('*a'))
shada_eq({{
timestamp=0,
type=8,
@@ -2383,7 +2383,7 @@ describe('In plugin/shada.vim', function()
' + f file name ["foo"]',
' + l line number 2',
' + c column -200',
- }, '\n') .. '\n', io.open(fname .. '.tst'):read('*a'))
+ }, eol) .. eol, io.open(fname .. '.tst'):read('*a'))
shada_eq({{
timestamp=0,
type=8,
diff --git a/test/functional/shada/helpers.lua b/test/functional/shada/helpers.lua
index b77e59682f..1312d762d8 100644
--- a/test/functional/shada/helpers.lua
+++ b/test/functional/shada/helpers.lua
@@ -37,7 +37,6 @@ local function add_argv(...)
end
local clear = function()
- os.execute('cp ' .. tmpname .. ' /tmp/test.shada')
os.remove(tmpname)
append_argv = nil
end
diff --git a/test/functional/terminal/ex_terminal_spec.lua b/test/functional/terminal/ex_terminal_spec.lua
index e015df10db..ee92ba6865 100644
--- a/test/functional/terminal/ex_terminal_spec.lua
+++ b/test/functional/terminal/ex_terminal_spec.lua
@@ -7,7 +7,6 @@ local retry = helpers.retry
local iswin = helpers.iswin
describe(':terminal', function()
- if helpers.pending_win32(pending) then return end
local screen
before_each(function()
@@ -24,7 +23,11 @@ describe(':terminal', function()
echomsg "msg3"
]])
-- Invoke a command that emits frequent terminal activity.
- feed_command([[terminal while true; do echo X; done]])
+ if iswin() then
+ feed_command([[terminal for /L \\%I in (1,0,2) do echo \\%I]])
+ else
+ feed_command([[terminal while true; do echo X; done]])
+ end
helpers.feed([[<C-\><C-N>]])
wait()
screen:sleep(10) -- Let some terminal activity happen.
@@ -38,7 +41,11 @@ describe(':terminal', function()
end)
it("in normal-mode :split does not move cursor", function()
- feed_command([[terminal while true; do echo foo; sleep .1; done]])
+ if iswin() then
+ feed_command([[terminal for /L \\%I in (1,0,2) do ( echo foo & ping -w 100 -n 1 127.0.0.1 > nul )]])
+ else
+ feed_command([[terminal while true; do echo foo; sleep .1; done]])
+ end
helpers.feed([[<C-\><C-N>M]]) -- move cursor away from last line
wait()
eq(3, eval("line('$')")) -- window height
diff --git a/test/functional/ui/bufhl_spec.lua b/test/functional/ui/bufhl_spec.lua
index 2143c01139..091c45596d 100644
--- a/test/functional/ui/bufhl_spec.lua
+++ b/test/functional/ui/bufhl_spec.lua
@@ -4,8 +4,6 @@ local Screen = require('test.functional.ui.screen')
local clear, feed, insert = helpers.clear, helpers.feed, helpers.insert
local command, request, neq = helpers.command, helpers.request, helpers.neq
-if helpers.pending_win32(pending) then return end
-
describe('Buffer highlighting', function()
local screen
local curbuf
diff --git a/test/functional/ui/inccommand_spec.lua b/test/functional/ui/inccommand_spec.lua
index 53fd17c309..4a8ebf6212 100644
--- a/test/functional/ui/inccommand_spec.lua
+++ b/test/functional/ui/inccommand_spec.lua
@@ -121,8 +121,6 @@ describe(":substitute, inccommand=split does not trigger preview", function()
end)
describe(":substitute, 'inccommand' preserves", function()
- if helpers.pending_win32(pending) then return end
-
before_each(clear)
it('listed buffers (:ls)', function()
@@ -285,8 +283,6 @@ describe(":substitute, 'inccommand' preserves", function()
end)
describe(":substitute, 'inccommand' preserves undo", function()
- if helpers.pending_win32(pending) then return end
-
local cases = { "", "split", "nosplit" }
local substrings = {
@@ -700,8 +696,6 @@ describe(":substitute, 'inccommand' preserves undo", function()
end)
describe(":substitute, inccommand=split", function()
- if helpers.pending_win32(pending) then return end
-
local screen = Screen.new(30,15)
before_each(function()
@@ -1169,8 +1163,6 @@ describe(":substitute, inccommand=split", function()
end)
describe("inccommand=nosplit", function()
- if helpers.pending_win32(pending) then return end
-
local screen = Screen.new(20,10)
before_each(function()
@@ -1356,8 +1348,6 @@ describe("inccommand=nosplit", function()
end)
describe(":substitute, 'inccommand' with a failing expression", function()
- if helpers.pending_win32(pending) then return end
-
local screen = Screen.new(20,10)
local cases = { "", "split", "nosplit" }
@@ -1621,8 +1611,6 @@ describe("'inccommand' autocommands", function()
end)
describe("'inccommand' split windows", function()
- if helpers.pending_win32(pending) then return end
-
local screen
local function refresh()
clear()
diff --git a/test/functional/ui/input_spec.lua b/test/functional/ui/input_spec.lua
index 29d974b709..f8842901c1 100644
--- a/test/functional/ui/input_spec.lua
+++ b/test/functional/ui/input_spec.lua
@@ -4,8 +4,6 @@ local feed, next_message, eq = helpers.feed, helpers.next_message, helpers.eq
local expect = helpers.expect
local Screen = require('test.functional.ui.screen')
-if helpers.pending_win32(pending) then return end
-
describe('mappings', function()
local cid
diff --git a/test/functional/ui/mouse_spec.lua b/test/functional/ui/mouse_spec.lua
index 3daf92eea0..3fdedeb073 100644
--- a/test/functional/ui/mouse_spec.lua
+++ b/test/functional/ui/mouse_spec.lua
@@ -4,8 +4,6 @@ local clear, feed, meths = helpers.clear, helpers.feed, helpers.meths
local insert, feed_command = helpers.insert, helpers.feed_command
local eq, funcs = helpers.eq, helpers.funcs
-if helpers.pending_win32(pending) then return end
-
describe('ui/mouse/input', function()
local screen
diff --git a/test/functional/ui/searchhl_spec.lua b/test/functional/ui/searchhl_spec.lua
index 11b18d015f..5af8b83a36 100644
--- a/test/functional/ui/searchhl_spec.lua
+++ b/test/functional/ui/searchhl_spec.lua
@@ -3,8 +3,6 @@ local Screen = require('test.functional.ui.screen')
local clear, feed, insert = helpers.clear, helpers.feed, helpers.insert
local feed_command = helpers.feed_command
-if helpers.pending_win32(pending) then return end
-
describe('search highlighting', function()
local screen
local colors = Screen.colors
diff --git a/test/functional/ui/sign_spec.lua b/test/functional/ui/sign_spec.lua
index e5c96f2ec0..c00d99cf90 100644
--- a/test/functional/ui/sign_spec.lua
+++ b/test/functional/ui/sign_spec.lua
@@ -2,8 +2,6 @@ local helpers = require('test.functional.helpers')(after_each)
local Screen = require('test.functional.ui.screen')
local clear, feed, command = helpers.clear, helpers.feed, helpers.command
-if helpers.pending_win32(pending) then return end
-
describe('Signs', function()
local screen
diff --git a/test/functional/ui/syntax_conceal_spec.lua b/test/functional/ui/syntax_conceal_spec.lua
index 28a104360d..e7a7004c1e 100644
--- a/test/functional/ui/syntax_conceal_spec.lua
+++ b/test/functional/ui/syntax_conceal_spec.lua
@@ -3,8 +3,6 @@ local Screen = require('test.functional.ui.screen')
local clear, feed, command = helpers.clear, helpers.feed, helpers.command
local insert = helpers.insert
-if helpers.pending_win32(pending) then return end
-
describe('Screen', function()
local screen
diff --git a/test/functional/viml/completion_spec.lua b/test/functional/viml/completion_spec.lua
index b70ef724b7..fbc7a527f8 100644
--- a/test/functional/viml/completion_spec.lua
+++ b/test/functional/viml/completion_spec.lua
@@ -5,8 +5,6 @@ local eval, eq, neq = helpers.eval, helpers.eq, helpers.neq
local feed_command, source, expect = helpers.feed_command, helpers.source, helpers.expect
local meths = helpers.meths
-if helpers.pending_win32(pending) then return end
-
describe('completion', function()
local screen
diff --git a/test/unit/eval/helpers.lua b/test/unit/eval/helpers.lua
index d7399182f7..6babd4be77 100644
--- a/test/unit/eval/helpers.lua
+++ b/test/unit/eval/helpers.lua
@@ -7,7 +7,7 @@ local ffi = helpers.ffi
local eq = helpers.eq
local eval = cimport('./src/nvim/eval.h', './src/nvim/eval/typval.h',
- './src/nvim/hashtab.h')
+ './src/nvim/hashtab.h', './src/nvim/memory.h')
local null_string = {[true]='NULL string'}
local null_list = {[true]='NULL list'}
@@ -24,10 +24,19 @@ local nil_value = {[true]='nil'}
local lua2typvalt
+local function tv_list_item_alloc()
+ return ffi.cast('listitem_T*', eval.xmalloc(ffi.sizeof('listitem_T')))
+end
+
+local function tv_list_item_free(li)
+ eval.tv_clear(li.li_tv)
+ eval.xfree(li)
+end
+
local function li_alloc(nogc)
- local gcfunc = eval.tv_list_item_free
+ local gcfunc = tv_list_item_free
if nogc then gcfunc = nil end
- local li = ffi.gc(eval.tv_list_item_alloc(), gcfunc)
+ local li = ffi.gc(tv_list_item_alloc(), gcfunc)
li.li_next = nil
li.li_prev = nil
li.li_tv = {v_type=eval.VAR_UNKNOWN, v_lock=eval.VAR_UNLOCKED}
@@ -41,7 +50,7 @@ local function populate_list(l, lua_l, processed)
processed[lua_l] = l
for i = 1, #lua_l do
local item_tv = ffi.gc(lua2typvalt(lua_l[i], processed), nil)
- local item_li = eval.tv_list_item_alloc()
+ local item_li = tv_list_item_alloc()
item_li.li_tv = item_tv
eval.tv_list_append(l, item_li)
end
@@ -533,6 +542,7 @@ return {
typvalt=typvalt,
li_alloc=li_alloc,
+ tv_list_item_free=tv_list_item_free,
dict_iter=dict_iter,
list_iter=list_iter,
diff --git a/test/unit/eval/typval_spec.lua b/test/unit/eval/typval_spec.lua
index bec74f05fc..b668144175 100644
--- a/test/unit/eval/typval_spec.lua
+++ b/test/unit/eval/typval_spec.lua
@@ -41,6 +41,7 @@ local tbl2callback = eval_helpers.tbl2callback
local dict_watchers = eval_helpers.dict_watchers
local concat_tables = global_helpers.concat_tables
+local map = global_helpers.map
local lib = cimport('./src/nvim/eval/typval.h', './src/nvim/memory.h',
'./src/nvim/mbyte.h', './src/nvim/garray.h',
@@ -80,8 +81,6 @@ local function get_alloc_rets(exp_log, res)
return exp_log
end
-local to_cstr_nofree = function(v) return lib.xstrdup(v) end
-
local alloc_log = alloc_log_new()
before_each(function()
@@ -121,118 +120,76 @@ end
describe('typval.c', function()
describe('list', function()
describe('item', function()
- describe('alloc()/free()', function()
+ describe('remove()', function()
itp('works', function()
- local li = li_alloc(true)
- neq(nil, li)
- lib.tv_list_item_free(li)
- alloc_log:check({
- a.li(li),
- a.freed(li),
- })
- end)
- itp('also frees the value', function()
- local li
- local s
- local l
- local tv
- li = li_alloc(true)
- li.li_tv.v_type = lib.VAR_NUMBER
- li.li_tv.vval.v_number = 10
- lib.tv_list_item_free(li)
- alloc_log:check({
- a.li(li),
- a.freed(li),
- })
-
- li = li_alloc(true)
- li.li_tv.v_type = lib.VAR_FLOAT
- li.li_tv.vval.v_float = 10.5
- lib.tv_list_item_free(li)
- alloc_log:check({
- a.li(li),
- a.freed(li),
- })
-
- li = li_alloc(true)
- li.li_tv.v_type = lib.VAR_STRING
- li.li_tv.vval.v_string = nil
- lib.tv_list_item_free(li)
+ local l = list(1, 2, 3, 4, 5, 6, 7)
+ neq(nil, l)
+ local lis = list_items(l)
alloc_log:check({
- a.li(li),
- a.freed(alloc_log.null),
- a.freed(li),
+ a.list(l),
+ a.li(lis[1]),
+ a.li(lis[2]),
+ a.li(lis[3]),
+ a.li(lis[4]),
+ a.li(lis[5]),
+ a.li(lis[6]),
+ a.li(lis[7]),
})
- li = li_alloc(true)
- li.li_tv.v_type = lib.VAR_STRING
- s = to_cstr_nofree('test')
- li.li_tv.vval.v_string = s
- lib.tv_list_item_free(li)
+ eq(lis[2], lib.tv_list_item_remove(l, lis[1]))
alloc_log:check({
- a.li(li),
- a.str(s, #('test')),
- a.freed(s),
- a.freed(li),
+ a.freed(table.remove(lis, 1)),
})
+ eq(lis, list_items(l))
- li = li_alloc(true)
- li.li_tv.v_type = lib.VAR_LIST
- l = ffi.gc(list(), nil)
- l.lv_refcount = 2
- li.li_tv.vval.v_list = l
- lib.tv_list_item_free(li)
+ eq(lis[7], lib.tv_list_item_remove(l, lis[6]))
alloc_log:check({
- a.li(li),
- a.list(l),
- a.freed(li),
+ a.freed(table.remove(lis)),
})
- eq(1, l.lv_refcount)
+ eq(lis, list_items(l))
- li = li_alloc(true)
- tv = lua2typvalt({})
- tv.vval.v_dict.dv_refcount = 2
- li.li_tv = tv
- lib.tv_list_item_free(li)
+ eq(lis[4], lib.tv_list_item_remove(l, lis[3]))
alloc_log:check({
- a.li(li),
- a.dict(tv.vval.v_dict),
- a.freed(li),
+ a.freed(table.remove(lis, 3)),
})
- eq(1, tv.vval.v_dict.dv_refcount)
+ eq(lis, list_items(l))
end)
- end)
- describe('remove()', function()
- itp('works', function()
- local l = list(1, 2, 3, 4, 5, 6, 7)
+ itp('also frees the value', function()
+ local l = list('a', 'b', 'c', 'd')
neq(nil, l)
local lis = list_items(l)
alloc_log:check({
a.list(l),
+ a.str(lis[1].li_tv.vval.v_string, 1),
a.li(lis[1]),
+ a.str(lis[2].li_tv.vval.v_string, 1),
a.li(lis[2]),
+ a.str(lis[3].li_tv.vval.v_string, 1),
a.li(lis[3]),
+ a.str(lis[4].li_tv.vval.v_string, 1),
a.li(lis[4]),
- a.li(lis[5]),
- a.li(lis[6]),
- a.li(lis[7]),
})
+ local strings = map(function(li) return li.li_tv.vval.v_string end,
+ lis)
- lib.tv_list_item_remove(l, lis[1])
+ eq(lis[2], lib.tv_list_item_remove(l, lis[1]))
alloc_log:check({
+ a.freed(table.remove(strings, 1)),
a.freed(table.remove(lis, 1)),
})
eq(lis, list_items(l))
- lib.tv_list_item_remove(l, lis[6])
+ eq(lis[3], lib.tv_list_item_remove(l, lis[2]))
alloc_log:check({
- a.freed(table.remove(lis)),
+ a.freed(table.remove(strings, 2)),
+ a.freed(table.remove(lis, 2)),
})
eq(lis, list_items(l))
- lib.tv_list_item_remove(l, lis[3])
+ eq(nil, lib.tv_list_item_remove(l, lis[2]))
alloc_log:check({
- a.freed(table.remove(lis, 3)),
+ a.freed(table.remove(strings, 2)),
+ a.freed(table.remove(lis, 2)),
})
eq(lis, list_items(l))
end)
@@ -257,19 +214,19 @@ describe('typval.c', function()
a.li(lis[7]),
})
- lib.tv_list_item_remove(l, lis[4])
+ eq(lis[5], lib.tv_list_item_remove(l, lis[4]))
alloc_log:check({a.freed(lis[4])})
eq({lis[1], lis[5], lis[7]}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item})
- lib.tv_list_item_remove(l, lis[2])
+ eq(lis[3], lib.tv_list_item_remove(l, lis[2]))
alloc_log:check({a.freed(lis[2])})
eq({lis[1], lis[5], lis[7]}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item})
- lib.tv_list_item_remove(l, lis[7])
+ eq(nil, lib.tv_list_item_remove(l, lis[7]))
alloc_log:check({a.freed(lis[7])})
eq({lis[1], lis[5], nil}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item == nil and nil})
- lib.tv_list_item_remove(l, lis[1])
+ eq(lis[3], lib.tv_list_item_remove(l, lis[1]))
alloc_log:check({a.freed(lis[1])})
eq({lis[3], lis[5], nil}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item == nil and nil})
@@ -449,7 +406,7 @@ describe('typval.c', function()
})
end)
end)
- describe('remove_items()', function()
+ describe('drop_items()', function()
itp('works', function()
local l_tv = lua2typvalt({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13})
local l = l_tv.vval.v_list
@@ -462,21 +419,92 @@ describe('typval.c', function()
}
alloc_log:clear()
- lib.tv_list_remove_items(l, lis[1], lis[3])
+ lib.tv_list_drop_items(l, lis[1], lis[3])
eq({4, 5, 6, 7, 8, 9, 10, 11, 12, 13}, typvalt2lua(l_tv))
eq({lis[4], lis[7], lis[13]}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item})
- lib.tv_list_remove_items(l, lis[11], lis[13])
+ lib.tv_list_drop_items(l, lis[11], lis[13])
eq({4, 5, 6, 7, 8, 9, 10}, typvalt2lua(l_tv))
eq({lis[4], lis[7], nil}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item == nil and nil})
- lib.tv_list_remove_items(l, lis[6], lis[8])
+ lib.tv_list_drop_items(l, lis[6], lis[8])
eq({4, 5, 9, 10}, typvalt2lua(l_tv))
eq({lis[4], lis[9], nil}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item == nil and nil})
+ lib.tv_list_drop_items(l, lis[4], lis[10])
+ eq(empty_list, typvalt2lua(l_tv))
+ eq({true, true, true}, {lws[1].lw_item == nil, lws[2].lw_item == nil, lws[3].lw_item == nil})
+
+ lib.tv_list_watch_remove(l, lws[1])
+ lib.tv_list_watch_remove(l, lws[2])
+ lib.tv_list_watch_remove(l, lws[3])
+
+ alloc_log:check({})
+ end)
+ end)
+ describe('remove_items()', function()
+ itp('works', function()
+ local l_tv = lua2typvalt({'1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13'})
+ local l = l_tv.vval.v_list
+ local lis = list_items(l)
+ local strings = map(function(li) return li.li_tv.vval.v_string end, lis)
+ -- Three watchers: pointing to first, middle and last elements.
+ local lws = {
+ list_watch(l, lis[1]),
+ list_watch(l, lis[7]),
+ list_watch(l, lis[13]),
+ }
+ alloc_log:clear()
+
+ lib.tv_list_remove_items(l, lis[1], lis[3])
+ eq({'4', '5', '6', '7', '8', '9', '10', '11', '12', '13'}, typvalt2lua(l_tv))
+ eq({lis[4], lis[7], lis[13]}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item})
+ alloc_log:check({
+ a.freed(strings[1]),
+ a.freed(lis[1]),
+ a.freed(strings[2]),
+ a.freed(lis[2]),
+ a.freed(strings[3]),
+ a.freed(lis[3]),
+ })
+
+ lib.tv_list_remove_items(l, lis[11], lis[13])
+ eq({'4', '5', '6', '7', '8', '9', '10'}, typvalt2lua(l_tv))
+ eq({lis[4], lis[7], nil}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item == nil and nil})
+ alloc_log:check({
+ a.freed(strings[11]),
+ a.freed(lis[11]),
+ a.freed(strings[12]),
+ a.freed(lis[12]),
+ a.freed(strings[13]),
+ a.freed(lis[13]),
+ })
+
+ lib.tv_list_remove_items(l, lis[6], lis[8])
+ eq({'4', '5', '9', '10'}, typvalt2lua(l_tv))
+ eq({lis[4], lis[9], nil}, {lws[1].lw_item, lws[2].lw_item, lws[3].lw_item == nil and nil})
+ alloc_log:check({
+ a.freed(strings[6]),
+ a.freed(lis[6]),
+ a.freed(strings[7]),
+ a.freed(lis[7]),
+ a.freed(strings[8]),
+ a.freed(lis[8]),
+ })
+
lib.tv_list_remove_items(l, lis[4], lis[10])
eq(empty_list, typvalt2lua(l_tv))
eq({true, true, true}, {lws[1].lw_item == nil, lws[2].lw_item == nil, lws[3].lw_item == nil})
+ alloc_log:check({
+ a.freed(strings[4]),
+ a.freed(lis[4]),
+ a.freed(strings[5]),
+ a.freed(lis[5]),
+ a.freed(strings[9]),
+ a.freed(lis[9]),
+ a.freed(strings[10]),
+ a.freed(lis[10]),
+ })
lib.tv_list_watch_remove(l, lws[1])
lib.tv_list_watch_remove(l, lws[2])
@@ -678,6 +706,66 @@ describe('typval.c', function()
eq({int(-100500), int(100500)}, typvalt2lua(l_tv))
end)
end)
+ describe('tv()', function()
+ itp('works', function()
+ local l_tv = lua2typvalt(empty_list)
+ local l = l_tv.vval.v_list
+
+ local l_l_tv = lua2typvalt(empty_list)
+ alloc_log:clear()
+ local l_l = l_l_tv.vval.v_list
+ eq(1, l_l.lv_refcount)
+ lib.tv_list_append_tv(l, l_l_tv)
+ eq(2, l_l.lv_refcount)
+ eq(l_l, l.lv_first.li_tv.vval.v_list)
+ alloc_log:check({
+ a.li(l.lv_first),
+ })
+
+ local l_s_tv = lua2typvalt('test')
+ alloc_log:check({
+ a.str(l_s_tv.vval.v_string, 'test'),
+ })
+ lib.tv_list_append_tv(l, l_s_tv)
+ alloc_log:check({
+ a.li(l.lv_last),
+ a.str(l.lv_last.li_tv.vval.v_string, 'test'),
+ })
+
+ eq({empty_list, 'test'}, typvalt2lua(l_tv))
+ end)
+ end)
+ describe('owned tv()', function()
+ itp('works', function()
+ local l_tv = lua2typvalt(empty_list)
+ local l = l_tv.vval.v_list
+
+ local l_l_tv = lua2typvalt(empty_list)
+ alloc_log:clear()
+ local l_l = l_l_tv.vval.v_list
+ eq(1, l_l.lv_refcount)
+ lib.tv_list_append_owned_tv(l, l_l_tv)
+ eq(1, l_l.lv_refcount)
+ l_l.lv_refcount = l_l.lv_refcount + 1
+ eq(l_l, l.lv_first.li_tv.vval.v_list)
+ alloc_log:check({
+ a.li(l.lv_first),
+ })
+
+ local l_s_tv = ffi.gc(lua2typvalt('test'), nil)
+ alloc_log:check({
+ a.str(l_s_tv.vval.v_string, 'test'),
+ })
+ lib.tv_list_append_owned_tv(l, l_s_tv)
+ eq(l_s_tv.vval.v_string, l.lv_last.li_tv.vval.v_string)
+ l_s_tv.vval.v_string = nil
+ alloc_log:check({
+ a.li(l.lv_last),
+ })
+
+ eq({empty_list, 'test'}, typvalt2lua(l_tv))
+ end)
+ end)
end)
describe('copy()', function()
local function tv_list_copy(...)
diff --git a/test/unit/helpers.lua b/test/unit/helpers.lua
index b1e709c444..87c838dece 100644
--- a/test/unit/helpers.lua
+++ b/test/unit/helpers.lua
@@ -650,8 +650,6 @@ local function itp_child(wr, func)
collectgarbage('stop')
child_sethook(wr)
err, emsg = pcall(func)
- collectgarbage('restart')
- collectgarbage()
debug.sethook()
end
emsg = tostring(emsg)
@@ -662,14 +660,15 @@ local function itp_child(wr, func)
end
sc.write(wr, ('-\n%05u\n%s'):format(#emsg, emsg))
deinit()
- sc.close(wr)
- sc.exit(1)
else
sc.write(wr, '+\n')
deinit()
- sc.close(wr)
- sc.exit(0)
end
+ collectgarbage('restart')
+ collectgarbage()
+ sc.write(wr, '$\n')
+ sc.close(wr)
+ sc.exit(err and 0 or 1)
end
local function check_child_err(rd)
@@ -690,44 +689,48 @@ local function check_child_err(rd)
break
end
trace[#trace + 1] = traceline
- table.remove(trace, maxtrace + 1)
+ if #trace > maxtrace then
+ table.remove(trace, 1)
+ end
end
local res = sc.read(rd, 2)
- if #res ~= 2 then
- local error
- if #trace == 0 then
- error = '\nTest crashed, no trace available\n'
- else
- error = '\nTest crashed, trace:\n' .. tracehelp
- for i = 1, #trace do
- error = error .. trace[i]
+ if #res == 2 then
+ local err = ''
+ if res ~= '+\n' then
+ eq('-\n', res)
+ local len_s = sc.read(rd, 5)
+ local len = tonumber(len_s)
+ neq(0, len)
+ if os.getenv('NVIM_TEST_TRACE_ON_ERROR') == '1' and #trace ~= 0 then
+ err = '\nTest failed, trace:\n' .. tracehelp
+ for _, traceline in ipairs(trace) do
+ err = err .. traceline
+ end
end
+ err = err .. sc.read(rd, len + 1)
end
- if not did_traceline then
- error = error .. '\nNo end of trace occurred'
- end
- local cc_err, cc_emsg = pcall(check_cores, Paths.test_luajit_prg, true)
- if not cc_err then
- error = error .. '\ncheck_cores failed: ' .. cc_emsg
+ local eres = sc.read(rd, 2)
+ if eres ~= '$\n' then
+ if #trace == 0 then
+ err = '\nTest crashed, no trace available\n'
+ else
+ err = '\nTest crashed, trace:\n' .. tracehelp
+ for i = 1, #trace do
+ err = err .. trace[i]
+ end
+ end
+ if not did_traceline then
+ err = err .. '\nNo end of trace occurred'
+ end
+ local cc_err, cc_emsg = pcall(check_cores, Paths.test_luajit_prg, true)
+ if not cc_err then
+ err = err .. '\ncheck_cores failed: ' .. cc_emsg
+ end
end
- assert.just_fail(error)
- end
- if res == '+\n' then
- return
- end
- eq('-\n', res)
- local len_s = sc.read(rd, 5)
- local len = tonumber(len_s)
- neq(0, len)
- local err = ''
- if os.getenv('NVIM_TEST_TRACE_ON_ERROR') == '1' and #trace ~= 0 then
- err = '\nTest failed, trace:\n' .. tracehelp
- for _, traceline in ipairs(trace) do
- err = err .. traceline
+ if err ~= '' then
+ assert.just_fail(err)
end
end
- err = err .. sc.read(rd, len + 1)
- assert.just_fail(err)
end
local function itp_parent(rd, pid, allow_failure)
diff --git a/third-party/CMakeLists.txt b/third-party/CMakeLists.txt
index 66f921ffcc..537059afdd 100644
--- a/third-party/CMakeLists.txt
+++ b/third-party/CMakeLists.txt
@@ -90,18 +90,18 @@ include(ExternalProject)
set(LIBUV_URL https://github.com/libuv/libuv/archive/v1.12.0.tar.gz)
set(LIBUV_SHA256 41ce914a88da21d3b07a76023beca57576ca5b376c6ac440c80bc581cbca1250)
-set(MSGPACK_URL https://github.com/msgpack/msgpack-c/archive/cpp-2.1.3.tar.gz)
-set(MSGPACK_SHA256 42ff5c213fd24bd4388c45c1f21d84b476678ce6366ea4d4f4086618a1d2cd23)
+set(MSGPACK_URL https://github.com/msgpack/msgpack-c/releases/download/cpp-2.1.5/msgpack-2.1.5.tar.gz)
+set(MSGPACK_SHA256 6126375af9b204611b9d9f154929f4f747e4599e6ae8443b337915dcf2899d2b)
-set(LUAJIT_URL https://github.com/LuaJIT/LuaJIT/archive/82151a4514e6538086f3f5e01cb8d4b22287b14f.tar.gz)
-set(LUAJIT_SHA256 8bc4e96ebab74e12ab84e751360e864714289bb089b51b6f396fa9a97df69798)
+set(LUAJIT_URL https://github.com/LuaJIT/LuaJIT/archive/7dbf0b05f1228c1c719866db5e5f3d58f87f74c8.tar.gz)
+set(LUAJIT_SHA256 cbae019b5e396164eb5f0d07777b55cc03931bb944f83c61a010c053c9f5fd5b)
set(LUA_URL https://www.lua.org/ftp/lua-5.1.5.tar.gz)
set(LUA_SHA256 2640fc56a795f29d28ef15e13c34a47e223960b0240e8cb0a82d9b0738695333)
# NOTE: Version must match LUAROCKS_VERSION in third-party/cmake/BuildLuarocks.cmake
-set(LUAROCKS_URL https://github.com/luarocks/luarocks/archive/v2.4.2.tar.gz)
-set(LUAROCKS_SHA256 eef88c2429c715a7beb921e4b1ba571dddb7c74a250fbb0d3cc0d4be7a5865d9)
+set(LUAROCKS_URL https://github.com/luarocks/luarocks/archive/v2.4.3.tar.gz)
+set(LUAROCKS_SHA256 ea1881d6954f2a98c34f93674571c8f0cbdbc28dedb3fa3cb56b6a91886d1a99)
set(UNIBILIUM_URL https://github.com/mauke/unibilium/archive/v1.2.1.tar.gz)
set(UNIBILIUM_SHA256 6045b4f6adca7b1123284007675ca71f718f70942d3a93d8b9fa5bd442006ec1)
@@ -139,8 +139,8 @@ set(WIN32YANK_X86_SHA256 62f34e5a46c5d4a7b3f3b512e1ff7b77fedd432f42581cbe825233a
set(WIN32YANK_X86_64_URL https://github.com/equalsraf/win32yank/releases/download/v0.0.4/win32yank-x64.zip)
set(WIN32YANK_X86_64_SHA256 33a747a92da60fb65e668edbf7661d3d902411a2d545fe9dc08623cecd142a20)
-set(WINPTY_URL https://github.com/rprichard/winpty/releases/download/0.4.2/winpty-0.4.2-msvc2015.zip)
-set(WINPTY_SHA256 b465f2584ff394b3fe27c01aa1dcfc679583c1ee951d0e83de3f859d8b8305b8)
+set(WINPTY_URL https://github.com/rprichard/winpty/releases/download/0.4.3/winpty-0.4.3-msvc2015.zip)
+set(WINPTY_SHA256 35a48ece2ff4acdcbc8299d4920de53eb86b1fb41e64d2fe5ae7898931bcee89)
if(USE_BUNDLED_UNIBILIUM)
include(BuildUnibilium)