aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.editorconfig3
-rw-r--r--.github/ISSUE_TEMPLATE/lsp_bug_report.yml7
-rw-r--r--.github/workflows/api-docs.yml4
-rw-r--r--.github/workflows/ci.yml59
-rw-r--r--.github/workflows/commitlint.yml6
-rwxr-xr-x.github/workflows/env.sh3
-rw-r--r--.github/workflows/labeler.yml16
-rw-r--r--.github/workflows/release.yml2
-rw-r--r--.github/workflows/squash-typos.yml33
-rw-r--r--.github/workflows/vim-patches.yml2
-rw-r--r--.luacheckrc4
-rw-r--r--CMakeLists.txt40
-rw-r--r--CONTRIBUTING.md4
-rwxr-xr-xci/before_install.sh46
-rwxr-xr-xci/before_script.sh13
-rw-r--r--ci/common/suite.sh121
-rwxr-xr-xci/install.sh11
-rwxr-xr-xci/run_lint.sh7
-rwxr-xr-xci/run_tests.sh4
-rwxr-xr-xci/script.sh9
-rw-r--r--cmake/RunTests.cmake4
-rw-r--r--config/CMakeLists.txt13
-rw-r--r--config/config.h.in1
-rw-r--r--runtime/autoload/dist/ft.vim62
-rw-r--r--runtime/autoload/health.vim36
-rw-r--r--runtime/autoload/health/provider.vim2
-rw-r--r--runtime/autoload/man.vim109
-rw-r--r--runtime/autoload/msgpack.vim6
-rw-r--r--runtime/doc/api.txt116
-rw-r--r--runtime/doc/autocmd.txt49
-rw-r--r--runtime/doc/change.txt3
-rw-r--r--runtime/doc/channel.txt2
-rw-r--r--runtime/doc/cmdline.txt5
-rw-r--r--runtime/doc/develop.txt2
-rw-r--r--runtime/doc/diagnostic.txt41
-rw-r--r--runtime/doc/diff.txt7
-rw-r--r--runtime/doc/editing.txt13
-rw-r--r--runtime/doc/eval.txt88
-rw-r--r--runtime/doc/filetype.txt76
-rw-r--r--runtime/doc/fold.txt4
-rw-r--r--runtime/doc/helphelp.txt4
-rw-r--r--runtime/doc/if_cscop.txt2
-rw-r--r--runtime/doc/indent.txt4
-rw-r--r--runtime/doc/index.txt2
-rw-r--r--runtime/doc/insert.txt9
-rw-r--r--runtime/doc/intro.txt5
-rw-r--r--runtime/doc/lsp-extension.txt2
-rw-r--r--runtime/doc/lsp.txt74
-rw-r--r--runtime/doc/lua.txt274
-rw-r--r--runtime/doc/map.txt23
-rw-r--r--runtime/doc/mbyte.txt4
-rw-r--r--runtime/doc/message.txt12
-rw-r--r--runtime/doc/nvim_terminal_emulator.txt11
-rw-r--r--runtime/doc/options.txt18
-rw-r--r--runtime/doc/pattern.txt6
-rw-r--r--runtime/doc/quickfix.txt2
-rw-r--r--runtime/doc/quickref.txt4
-rw-r--r--runtime/doc/repeat.txt6
-rw-r--r--runtime/doc/sign.txt5
-rw-r--r--runtime/doc/starting.txt39
-rw-r--r--runtime/doc/syntax.txt12
-rw-r--r--runtime/doc/term.txt2
-rw-r--r--runtime/doc/treesitter.txt23
-rw-r--r--runtime/doc/usr_05.txt25
-rw-r--r--runtime/doc/usr_41.txt1
-rw-r--r--runtime/doc/usr_toc.txt13
-rw-r--r--runtime/doc/various.txt21
-rw-r--r--runtime/doc/vim_diff.txt11
-rw-r--r--runtime/doc/windows.txt16
-rw-r--r--runtime/filetype.lua26
-rw-r--r--runtime/filetype.vim65
-rw-r--r--runtime/ftplugin/checkhealth.vim20
-rw-r--r--runtime/ftplugin/git.vim41
-rw-r--r--runtime/ftplugin/gitcommit.vim47
-rw-r--r--runtime/ftplugin/gitrebase.vim15
-rw-r--r--runtime/ftplugin/i3config.vim13
-rw-r--r--runtime/ftplugin/solution.vim37
-rw-r--r--runtime/ftplugin/zsh.vim8
-rw-r--r--runtime/indent/sh.vim2
-rw-r--r--runtime/indent/xml.vim8
-rw-r--r--runtime/lua/vim/diagnostic.lua147
-rw-r--r--runtime/lua/vim/filetype.lua1579
-rw-r--r--runtime/lua/vim/highlight.lua19
-rw-r--r--runtime/lua/vim/keymap.lua135
-rw-r--r--runtime/lua/vim/lsp.lua313
-rw-r--r--runtime/lua/vim/lsp/buf.lua26
-rw-r--r--runtime/lua/vim/lsp/diagnostic.lua46
-rw-r--r--runtime/lua/vim/lsp/handlers.lua102
-rw-r--r--runtime/lua/vim/lsp/log.lua4
-rw-r--r--runtime/lua/vim/lsp/rpc.lua5
-rw-r--r--runtime/lua/vim/lsp/sync.lua17
-rw-r--r--runtime/lua/vim/lsp/util.lua184
-rw-r--r--runtime/lua/vim/shared.lua54
-rw-r--r--runtime/lua/vim/treesitter/languagetree.lua2
-rw-r--r--runtime/lua/vim/treesitter/query.lua27
-rw-r--r--runtime/lua/vim/uri.lua4
-rw-r--r--runtime/nvim.appdata.xml2
-rw-r--r--runtime/optwin.vim4
-rw-r--r--runtime/pack/dist/opt/matchit/autoload/matchit.vim251
-rw-r--r--runtime/pack/dist/opt/matchit/doc/matchit.txt10
-rw-r--r--runtime/pack/dist/opt/matchit/plugin/matchit.vim42
-rw-r--r--runtime/pack/dist/opt/termdebug/plugin/termdebug.vim76
-rw-r--r--runtime/scripts.vim8
-rw-r--r--runtime/syntax/c.vim3
-rw-r--r--runtime/syntax/checkhealth.vim30
-rw-r--r--runtime/syntax/css.vim29
-rw-r--r--runtime/syntax/debcontrol.vim20
-rw-r--r--runtime/syntax/dep3patch.vim57
-rw-r--r--runtime/syntax/dtd.vim6
-rw-r--r--runtime/syntax/git.vim93
-rw-r--r--runtime/syntax/gitcommit.vim86
-rw-r--r--runtime/syntax/gitrebase.vim15
-rw-r--r--runtime/syntax/i3config.vim257
-rw-r--r--runtime/syntax/python.vim5
-rw-r--r--runtime/syntax/rc.vim21
-rw-r--r--runtime/syntax/scala.vim110
-rw-r--r--runtime/syntax/texinfo.vim406
-rw-r--r--runtime/syntax/xml.vim12
-rw-r--r--runtime/syntax/zsh.vim223
-rw-r--r--scripts/gen_filetype.lua201
-rwxr-xr-xscripts/gen_vimdoc.py6
-rw-r--r--scripts/squash_typos.py263
-rwxr-xr-xscripts/vim-patch.sh57
-rw-r--r--src/mpack/lmpack.c3
-rw-r--r--src/nvim/CMakeLists.txt8
-rw-r--r--src/nvim/api/buffer.c67
-rw-r--r--src/nvim/api/deprecated.c11
-rw-r--r--src/nvim/api/extmark.c159
-rw-r--r--src/nvim/api/keysets.lua16
-rw-r--r--src/nvim/api/private/converter.c21
-rw-r--r--src/nvim/api/private/helpers.c245
-rw-r--r--src/nvim/api/vim.c112
-rw-r--r--src/nvim/api/window.c2
-rw-r--r--src/nvim/auevents.lua4
-rw-r--r--src/nvim/autocmd.c6
-rw-r--r--src/nvim/buffer.c4
-rw-r--r--src/nvim/buffer_defs.h5
-rw-r--r--src/nvim/decoration.c161
-rw-r--r--src/nvim/decoration.h7
-rw-r--r--src/nvim/diff.c219
-rw-r--r--src/nvim/edit.c32
-rw-r--r--src/nvim/eval.c17
-rw-r--r--src/nvim/eval.lua2
-rw-r--r--src/nvim/eval/funcs.c112
-rw-r--r--src/nvim/eval/typval.c2
-rw-r--r--src/nvim/event/loop.c2
-rw-r--r--src/nvim/ex_cmds.c12
-rw-r--r--src/nvim/ex_cmds2.c4
-rw-r--r--src/nvim/ex_cmds_defs.h2
-rw-r--r--src/nvim/ex_docmd.c285
-rw-r--r--src/nvim/ex_docmd.h21
-rw-r--r--src/nvim/ex_getln.c38
-rw-r--r--src/nvim/extmark.c286
-rw-r--r--src/nvim/extmark.h3
-rw-r--r--src/nvim/extmark_defs.h12
-rw-r--r--src/nvim/file_search.c19
-rw-r--r--src/nvim/fold.c2
-rw-r--r--src/nvim/generators/gen_api_dispatch.lua4
-rw-r--r--src/nvim/generators/gen_char_blob.lua52
-rw-r--r--src/nvim/generators/gen_keysets.lua15
-rw-r--r--src/nvim/getchar.c434
-rw-r--r--src/nvim/getchar.h4
-rw-r--r--src/nvim/globals.h5
-rw-r--r--src/nvim/indent_c.c19
-rw-r--r--src/nvim/input.c2
-rw-r--r--src/nvim/keymap.c2
-rw-r--r--src/nvim/keymap.h5
-rw-r--r--src/nvim/lua/converter.c15
-rw-r--r--src/nvim/lua/executor.c107
-rw-r--r--src/nvim/lua/executor.h1
-rw-r--r--src/nvim/lua/spell.c101
-rw-r--r--src/nvim/lua/spell.h12
-rw-r--r--src/nvim/lua/stdlib.c5
-rw-r--r--src/nvim/lua/treesitter.c4
-rw-r--r--src/nvim/lua/vim.lua63
-rw-r--r--src/nvim/main.c19
-rw-r--r--src/nvim/map.c7
-rw-r--r--src/nvim/map.h10
-rw-r--r--src/nvim/marktree.c196
-rw-r--r--src/nvim/marktree.h89
-rw-r--r--src/nvim/mbyte.c18
-rw-r--r--src/nvim/memfile.c6
-rw-r--r--src/nvim/memline.c6
-rw-r--r--src/nvim/menu.c2
-rw-r--r--src/nvim/message.c6
-rw-r--r--src/nvim/move.c8
-rw-r--r--src/nvim/normal.c45
-rw-r--r--src/nvim/ops.c57
-rw-r--r--src/nvim/option.c39
-rw-r--r--src/nvim/option.h1
-rw-r--r--src/nvim/option_defs.h1
-rw-r--r--src/nvim/options.lua20
-rw-r--r--src/nvim/os/input.c14
-rw-r--r--src/nvim/os/pty_process_unix.c120
-rw-r--r--src/nvim/plines.c2
-rw-r--r--src/nvim/po/ja.euc-jp.po9
-rw-r--r--src/nvim/po/ja.po9
-rw-r--r--src/nvim/popupmnu.c43
-rw-r--r--src/nvim/quickfix.c2
-rw-r--r--src/nvim/regexp_nfa.c40
-rw-r--r--src/nvim/screen.c43
-rw-r--r--src/nvim/sign.c3
-rw-r--r--src/nvim/spell.c10
-rw-r--r--src/nvim/spellfile.c4
-rw-r--r--src/nvim/state.c2
-rw-r--r--src/nvim/terminal.c49
-rwxr-xr-xsrc/nvim/testdir/runnvim.sh4
-rw-r--r--src/nvim/testdir/runtest.vim6
-rw-r--r--src/nvim/testdir/setup.vim2
-rw-r--r--src/nvim/testdir/test_alot.vim1
-rw-r--r--src/nvim/testdir/test_autocmd.vim90
-rw-r--r--src/nvim/testdir/test_blob.vim8
-rw-r--r--src/nvim/testdir/test_cmdline.vim37
-rw-r--r--src/nvim/testdir/test_compiler.vim3
-rw-r--r--src/nvim/testdir/test_display.vim25
-rw-r--r--src/nvim/testdir/test_edit.vim3
-rw-r--r--src/nvim/testdir/test_ex_mode.vim2
-rw-r--r--src/nvim/testdir/test_excmd.vim44
-rw-r--r--src/nvim/testdir/test_filechanged.vim149
-rw-r--r--src/nvim/testdir/test_fileformat.vim246
-rw-r--r--src/nvim/testdir/test_filetype.vim227
-rw-r--r--src/nvim/testdir/test_filetype_lua.vim2
-rw-r--r--src/nvim/testdir/test_listchars.vim16
-rw-r--r--src/nvim/testdir/test_messages.vim8
-rw-r--r--src/nvim/testdir/test_options.vim21
-rw-r--r--src/nvim/testdir/test_put.vim22
-rw-r--r--src/nvim/testdir/test_regexp_utf8.vim8
-rw-r--r--src/nvim/testdir/test_registers.vim51
-rw-r--r--src/nvim/testdir/test_search_stat.vim1
-rw-r--r--src/nvim/testdir/test_signs.vim25
-rw-r--r--src/nvim/testdir/test_spell.vim8
-rw-r--r--src/nvim/testdir/test_substitute.vim2
-rw-r--r--src/nvim/testdir/test_timers.vim2
-rw-r--r--src/nvim/testdir/test_usercommands.vim4
-rw-r--r--src/nvim/testdir/test_virtualedit.vim42
-rw-r--r--src/nvim/testdir/test_visual.vim15
-rw-r--r--src/nvim/tui/tui.c45
-rw-r--r--src/nvim/types.h2
-rw-r--r--src/nvim/vim.h1
-rw-r--r--src/nvim/viml/parser/expressions.c2
-rw-r--r--src/nvim/viml/parser/expressions.h2
-rw-r--r--src/nvim/window.c4
-rw-r--r--test/README.md10
-rw-r--r--test/functional/api/command_spec.lua135
-rw-r--r--test/functional/api/extmark_spec.lua59
-rw-r--r--test/functional/api/keymap_spec.lua223
-rw-r--r--test/functional/api/vim_spec.lua82
-rw-r--r--test/functional/autocmd/cursormoved_spec.lua8
-rw-r--r--test/functional/autocmd/recording_spec.lua72
-rw-r--r--test/functional/core/startup_spec.lua23
-rw-r--r--test/functional/editor/K_spec.lua23
-rw-r--r--test/functional/editor/macro_spec.lua27
-rw-r--r--test/functional/editor/meta_key_spec.lua17
-rw-r--r--test/functional/editor/mode_insert_spec.lua11
-rw-r--r--test/functional/editor/mode_visual_spec.lua27
-rw-r--r--test/functional/editor/put_spec.lua16
-rw-r--r--test/functional/ex_cmds/append_spec.lua70
-rw-r--r--test/functional/helpers.lua1
-rw-r--r--test/functional/legacy/memory_usage_spec.lua4
-rw-r--r--test/functional/legacy/options_spec.lua5
-rw-r--r--test/functional/lua/api_spec.lua13
-rw-r--r--test/functional/lua/commands_spec.lua18
-rw-r--r--test/functional/lua/diagnostic_spec.lua29
-rw-r--r--test/functional/lua/filetype_spec.lua98
-rw-r--r--test/functional/lua/spell_spec.lua53
-rw-r--r--test/functional/lua/uri_spec.lua6
-rw-r--r--test/functional/lua/vim_spec.lua334
-rw-r--r--test/functional/plugin/health_spec.lua6
-rw-r--r--test/functional/plugin/lsp/incremental_sync_spec.lua269
-rw-r--r--test/functional/plugin/lsp_spec.lua223
-rw-r--r--test/functional/terminal/buffer_spec.lua7
-rw-r--r--test/functional/terminal/channel_spec.lua28
-rw-r--r--test/functional/terminal/mouse_spec.lua122
-rw-r--r--test/functional/terminal/tui_spec.lua8
-rw-r--r--test/functional/treesitter/parser_spec.lua21
-rw-r--r--test/functional/ui/bufhl_spec.lua16
-rw-r--r--test/functional/ui/input_spec.lua21
-rw-r--r--test/functional/ui/popupmenu_spec.lua187
-rw-r--r--test/functional/vimscript/screenpos_spec.lua51
-rw-r--r--test/unit/charset/vim_str2nr_spec.lua2
-rw-r--r--test/unit/garray_spec.lua2
-rw-r--r--test/unit/marktree_spec.lua44
-rw-r--r--test/unit/os/env_spec.lua2
-rw-r--r--test/unit/os/fs_spec.lua4
-rw-r--r--third-party/CMakeLists.txt8
-rw-r--r--third-party/cmake/BuildLuajit.cmake10
286 files changed, 10169 insertions, 3889 deletions
diff --git a/.editorconfig b/.editorconfig
index bb6a1423ef..22fee54b22 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -8,6 +8,9 @@ end_of_line = lf
insert_final_newline = true
charset = utf-8
+[*.{c,h,in,lua}]
+max_line_length = 100
+
[{Makefile,**/Makefile,runtime/doc/*.txt}]
indent_style = tab
indent_size = 8
diff --git a/.github/ISSUE_TEMPLATE/lsp_bug_report.yml b/.github/ISSUE_TEMPLATE/lsp_bug_report.yml
index b5b7687bf8..0ed163c9be 100644
--- a/.github/ISSUE_TEMPLATE/lsp_bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/lsp_bug_report.yml
@@ -29,13 +29,6 @@ body:
- type: textarea
attributes:
- label: ':checkhealth'
- description: |
- Paste the results from `nvim -c ":checkhealth nvim lspconfig"`
- render: markdown
-
- - type: textarea
- attributes:
label: 'Steps to reproduce using "nvim -u minimal_init.lua"'
description: |
- Download the minimal config with `curl -LO https://raw.githubusercontent.com/neovim/nvim-lspconfig/master/test/minimal_init.lua` and modify it to include any specific commands or servers pertaining to your issues.
diff --git a/.github/workflows/api-docs.yml b/.github/workflows/api-docs.yml
index ee72cf5f01..39d85e967d 100644
--- a/.github/workflows/api-docs.yml
+++ b/.github/workflows/api-docs.yml
@@ -48,6 +48,6 @@ jobs:
if: ${{ steps.docs.outputs.UPDATED_DOCS != 0 }}
run: |
git add -u
- git commit -m 'docs: regenerate'
+ git commit -m 'docs: regenerate [skip ci]'
git push --force https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY} ${DOC_BRANCH}
- gh pr create --fill --base ${GITHUB_REF#refs/heads/} --head ${DOC_BRANCH} || true
+ gh pr create --draft --fill --base ${GITHUB_REF#refs/heads/} --head ${DOC_BRANCH} || true
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6a81ee4238..b650c5dd85 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -10,7 +10,50 @@ on:
- 'master'
- 'release-[0-9]+.[0-9]+'
+# Cancel any in-progress CI runs for a PR if it is updated
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }}
+ cancel-in-progress: true
+
jobs:
+ lint:
+ if: (github.event_name == 'pull_request' && github.base_ref == 'master' && !github.event.pull_request.draft) || (github.event_name == 'push' && github.ref == 'refs/heads/master')
+ runs-on: ubuntu-20.04
+ env:
+ CC: gcc
+ steps:
+ - uses: actions/checkout@v2
+
+ - name: Setup common environment variables
+ run: ./.github/workflows/env.sh lint
+
+ - name: Install apt packages
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y autoconf automake build-essential ccache cmake cpanminus gettext gperf language-pack-tr libtool-bin locales ninja-build pkg-config python3 python3-pip python3-setuptools unzip flake8
+
+ - name: Setup interpreter packages
+ run: |
+ ./ci/install.sh
+
+ - name: Cache dependencies
+ uses: actions/cache@v2
+ with:
+ path: |
+ ${{ env.CACHE_NVIM_DEPS_DIR }}
+ ~/.ccache
+ key: ${{ matrix.runner }}-lint-${{ matrix.cc }}-${{ hashFiles('cmake/*', 'third-party/**', '**/CMakeLists.txt') }}-${{ github.base_ref }}
+
+ - name: Build third-party
+ run: ./ci/before_script.sh
+
+ - name: Run lint
+ run: ./ci/script.sh
+
+ - name: Cache dependencies
+ if: ${{ success() }}
+ run: ./ci/before_cache.sh
+
unixish:
name: ${{ matrix.runner }} ${{ matrix.flavor }} (cc=${{ matrix.cc }})
strategy:
@@ -18,15 +61,11 @@ jobs:
matrix:
include:
- flavor: asan
- cc: clang-12
- runner: ubuntu-20.04
- os: linux
- - flavor: lint
- cc: gcc
+ cc: clang-13
runner: ubuntu-20.04
os: linux
- flavor: tsan
- cc: clang-12
+ cc: clang-13
runner: ubuntu-20.04
os: linux
- cc: clang
@@ -58,20 +97,17 @@ jobs:
run: |
wget https://apt.llvm.org/llvm.sh
chmod a+x llvm.sh
- sudo ./llvm.sh 12
+ sudo ./llvm.sh 13
rm llvm.sh
- name: Install brew packages
if: matrix.os == 'osx'
run: |
- # Workaround brew issues
- rm -f /usr/local/bin/2to3
brew update >/dev/null
brew install automake ccache perl cpanminus ninja
- name: Setup interpreter packages
run: |
- ./ci/before_install.sh
./ci/install.sh
- name: Cache dependencies
@@ -135,7 +171,7 @@ jobs:
steps:
- uses: actions/checkout@v2
- - name: Setup commom environment variables
+ - name: Setup common environment variables
run: ./.github/workflows/env.sh ${{ matrix.flavor }}
- name: Install apt packages
@@ -162,7 +198,6 @@ jobs:
- name: Setup interpreter packages
run: |
- ./ci/before_install.sh
./ci/install.sh
- name: Cache dependencies
diff --git a/.github/workflows/commitlint.yml b/.github/workflows/commitlint.yml
index 6c74ec99d3..5044b7dcab 100644
--- a/.github/workflows/commitlint.yml
+++ b/.github/workflows/commitlint.yml
@@ -1,13 +1,13 @@
name: "Commit Linter"
on:
- pull_request:
+ # Only pull_request and push honor [skip ci]. Since this workflow must pass
+ # to merge a PR, it can't be skipped, so use pull_request_target
+ pull_request_target:
types: [opened, synchronize, reopened, ready_for_review]
jobs:
lint-commits:
runs-on: ubuntu-latest
if: github.event.pull_request.draft == false
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- uses: actions/checkout@v2
with:
diff --git a/.github/workflows/env.sh b/.github/workflows/env.sh
index a30e06ae26..acdbc5da1e 100755
--- a/.github/workflows/env.sh
+++ b/.github/workflows/env.sh
@@ -34,7 +34,7 @@ case "$FLAVOR" in
BUILD_FLAGS="$BUILD_FLAGS -DPREFER_LUA=ON"
cat <<EOF >> "$GITHUB_ENV"
CLANG_SANITIZER=ASAN_UBSAN
-SYMBOLIZER=asan_symbolize-12
+SYMBOLIZER=asan_symbolize-13
ASAN_OPTIONS=detect_leaks=1:check_initialization_order=1:log_path=$GITHUB_WORKSPACE/build/log/asan
UBSAN_OPTIONS=print_stacktrace=1 log_path=$GITHUB_WORKSPACE/build/log/ubsan
EOF
@@ -42,6 +42,7 @@ EOF
tsan)
cat <<EOF >> "$GITHUB_ENV"
TSAN_OPTIONS=log_path=$GITHUB_WORKSPACE/build/log/tsan
+CLANG_SANITIZER=TSAN
EOF
;;
lint)
diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml
index 76fc8793fa..3de0c453a5 100644
--- a/.github/workflows/labeler.yml
+++ b/.github/workflows/labeler.yml
@@ -1,8 +1,9 @@
name: "Pull Request Labeler"
on:
pull_request_target:
- types: opened
+ types: [opened]
jobs:
+
triage:
runs-on: ubuntu-latest
permissions:
@@ -12,8 +13,10 @@ jobs:
- uses: actions/labeler@main
with:
repo-token: "${{ secrets.GITHUB_TOKEN }}"
+
type-scope:
runs-on: ubuntu-latest
+ needs: ["triage"]
permissions:
contents: write
pull-requests: write
@@ -23,8 +26,9 @@ jobs:
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_TITLE: ${{ github.event.pull_request.title }}
steps:
- # Extract type and try to add it as a label
- - run: gh pr edit "$PR_NUMBER" --add-label "$(echo "$PR_TITLE" | sed -E 's|([[:alpha:]]+)(\(.*\))?!?:.*|\1|')" || true
-
- # Extract scope and try to add it as a label
- - run: gh pr edit "$PR_NUMBER" --add-label "$(echo "$PR_TITLE" | sed -E 's|[[:alpha:]]+\((.+)\)!?:.*|\1|')" || true
+ - name: "Extract commit type and add as label"
+ continue-on-error: true
+ run: gh pr edit "$PR_NUMBER" --add-label "$(echo "$PR_TITLE" | sed -E 's|([[:alpha:]]+)(\(.*\))?!?:.*|\1|')"
+ - name: "Extract commit scope and add as label"
+ continue-on-error: true
+ run: gh pr edit "$PR_NUMBER" --add-label "$(echo "$PR_TITLE" | sed -E 's|[[:alpha:]]+\((.+)\)!?:.*|\1|')"
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 5839be2944..b72c2ab71d 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -80,7 +80,6 @@ jobs:
fetch-depth: 0
- name: Install brew packages
run: |
- rm -f /usr/local/bin/2to3
brew update >/dev/null
brew install automake ninja
- if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.tag_name != 'nightly')
@@ -213,6 +212,7 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NVIM_VERSION: ${{ needs.linux.outputs.version }}
+ DEBUG: api
run: |
envsubst < "$GITHUB_WORKSPACE/.github/workflows/notes.md" > "$RUNNER_TEMP/notes.md"
gh release create $TAG_NAME $PRERELEASE --notes-file "$RUNNER_TEMP/notes.md" --title "$SUBJECT" --target $GITHUB_SHA nvim-macos/* nvim-linux64/* appimage/* nvim-win64/*
diff --git a/.github/workflows/squash-typos.yml b/.github/workflows/squash-typos.yml
deleted file mode 100644
index 6779589dc6..0000000000
--- a/.github/workflows/squash-typos.yml
+++ /dev/null
@@ -1,33 +0,0 @@
-name: Squash Typo Pull Requests
-
-on:
- pull_request_target:
- types: labeled
-concurrency:
- group: ${{ github.workflow }}
-jobs:
- build:
- if: github.event.label.name == 'typo'
- runs-on: ubuntu-latest
-
- permissions:
- contents: write
- pull-requests: write
-
- env:
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-
- steps:
- - uses: actions/checkout@v2
- with:
- fetch-depth: 0
- - uses: actions/setup-python@v2
-
- - name: Setup git config
- run: |
- git config --global user.name 'marvim'
- git config --global user.email 'marvim@users.noreply.github.com'
-
- - run: python scripts/squash_typos.py
- env:
- PR_NUMBER: ${{ github.event.number }}
diff --git a/.github/workflows/vim-patches.yml b/.github/workflows/vim-patches.yml
index 5742b51158..453d293b0e 100644
--- a/.github/workflows/vim-patches.yml
+++ b/.github/workflows/vim-patches.yml
@@ -49,4 +49,4 @@ jobs:
git add -u
git commit -m 'version.c: update [skip ci]'
git push --force https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY} ${VERSION_BRANCH}
- gh pr create --fill --label vim-patch --base ${GITHUB_REF#refs/heads/} --head ${VERSION_BRANCH} || true
+ gh pr create --draft --fill --label vim-patch --base ${GITHUB_REF#refs/heads/} --head ${VERSION_BRANCH} || true
diff --git a/.luacheckrc b/.luacheckrc
index 487f5ab552..9bbd323e84 100644
--- a/.luacheckrc
+++ b/.luacheckrc
@@ -26,6 +26,10 @@ read_globals = {
"vim",
}
+globals = {
+ "vim.g",
+}
+
exclude_files = {
'test/functional/fixtures/lua/syntax_error.lua',
}
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4b62ca8556..e0f05e1205 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -408,6 +408,19 @@ main(void)
if(TS_HAS_SET_MATCH_LIMIT)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DNVIM_TS_HAS_SET_MATCH_LIMIT")
endif()
+check_c_source_compiles("
+#include <stdlib.h>
+#include <tree_sitter/api.h>
+int
+main(void)
+{
+ ts_set_allocator(malloc, calloc, realloc, free);
+ return 0;
+}
+" TS_HAS_SET_ALLOCATOR)
+if(TS_HAS_SET_ALLOCATOR)
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DNVIM_TS_HAS_SET_ALLOCATOR")
+endif()
# Note: The test lib requires LuaJIT; it will be skipped if LuaJIT is missing.
option(PREFER_LUA "Prefer Lua over LuaJIT in the nvim executable." OFF)
@@ -543,6 +556,33 @@ endif()
message(STATUS "Using Lua interpreter: ${LUA_PRG}")
+if(DEBUG)
+ option(COMPILE_LUA "Pre-compile Lua sources into bytecode (for sources that are included in the binary)" OFF)
+else()
+ option(COMPILE_LUA "Pre-compile Lua sources into bytecode (for sources that are included in the binary)" ON)
+endif()
+
+if(COMPILE_LUA AND NOT WIN32)
+ if(PREFER_LUA)
+ foreach(CURRENT_LUAC_PRG luac5.1 luac)
+ find_program(_CHECK_LUAC_PRG ${CURRENT_LUAC_PRG})
+ if(_CHECK_LUAC_PRG)
+ set(LUAC_PRG "${_CHECK_LUAC_PRG} -s -o - %s" CACHE STRING "Format for compiling to Lua bytecode")
+ break()
+ endif()
+ endforeach()
+ elseif(LUA_PRG MATCHES "luajit")
+ check_lua_module(${LUA_PRG} "jit.bcsave" LUAJIT_HAS_JIT_BCSAVE)
+ if(LUAJIT_HAS_JIT_BCSAVE)
+ set(LUAC_PRG "${LUA_PRG} -b -s %s -" CACHE STRING "Format for compiling to Lua bytecode")
+ endif()
+ endif()
+endif()
+
+if(LUAC_PRG)
+ message(STATUS "Using Lua compiler: ${LUAC_PRG}")
+endif()
+
# Setup busted.
find_program(BUSTED_PRG NAMES busted busted.bat)
find_program(BUSTED_LUA_PRG busted-lua)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index faf9181a2c..5e04f33b15 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -7,11 +7,11 @@ Getting started
If you want to help but don't know where to start, here are some
low-risk/isolated tasks:
-- [Merge a Vim patch].
-- Try a [good first issue](../../labels/good-first-issue) or [complexity:low] issue.
+- Try a [complexity:low] issue.
- Fix bugs found by [Clang](#clang-scan-build), [PVS](#pvs-studio) or
[Coverity](#coverity).
- [Improve documentation][wiki-contribute-help]
+- [Merge a Vim patch] (Familiarity with Vim is *strongly* recommended)
Reporting problems
------------------
diff --git a/ci/before_install.sh b/ci/before_install.sh
deleted file mode 100755
index f12f972fe0..0000000000
--- a/ci/before_install.sh
+++ /dev/null
@@ -1,46 +0,0 @@
-#!/usr/bin/env bash
-
-set -e
-set -o pipefail
-
-echo 'Python info:'
-(
- set -x
- python3 --version
- python2 --version
- python --version
- pip3 --version
- pip2 --version
- pip --version
-
- pyenv --version
- pyenv versions
-) 2>&1 | sed 's/^/ /' || true
-
-# Use pyenv, but not for OSX on Travis, where it only has the "system" version.
-if [[ "${TRAVIS_OS_NAME}" != osx ]] && command -v pyenv; then
- echo 'Setting Python versions via pyenv'
-
- # Prefer Python 2 over 3 (more conservative).
- pyenv global 2.7:3.8
-
- echo 'Updated Python info:'
- (
- set -x
- python3 --version
- python2 --version
- python --version
-
- python3 -m pip --version
- python2 -m pip --version
- ) 2>&1 | sed 's/^/ /'
-fi
-
-echo "Install node (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 10
diff --git a/ci/before_script.sh b/ci/before_script.sh
index 701fe1d9eb..f7216338d4 100755
--- a/ci/before_script.sh
+++ b/ci/before_script.sh
@@ -6,12 +6,6 @@ set -o pipefail
CI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${CI_DIR}/common/build.sh"
-# Enable ipv6 on Travis. ref: a39c8b7ce30d
-if test -n "${TRAVIS_OS_NAME}" && ! test "${TRAVIS_OS_NAME}" = osx ; then
- echo "before_script.sh: enable ipv6"
- sudo sysctl -w net.ipv6.conf.lo.disable_ipv6=0
-fi
-
# Test some of the configuration variables.
if [[ -n "${GCOV}" ]] && [[ ! $(type -P "${GCOV}") ]]; then
echo "\$GCOV: '${GCOV}' is not executable."
@@ -27,13 +21,6 @@ ccache -s
# Reset ccache stats for real results in before_cache.
ccache --zero-stats
-if [[ "${TRAVIS_OS_NAME}" == osx ]]; then
- # Adds user to a dummy group.
- # That allows to test changing the group of the file by `os_fchown`.
- sudo dscl . -create /Groups/chown_test
- sudo dscl . -append /Groups/chown_test GroupMembership "${USER}"
-fi
-
# Compile dependencies.
build_deps
diff --git a/ci/common/suite.sh b/ci/common/suite.sh
index 038b116c5a..561849ce2d 100644
--- a/ci/common/suite.sh
+++ b/ci/common/suite.sh
@@ -11,22 +11,10 @@ FAIL_SUMMARY=""
END_MARKER="$BUILD_DIR/.tests_finished"
FAIL_SUMMARY_FILE="$BUILD_DIR/.test_errors"
-ANSI_CLEAR="\033[0K"
-
-if test "$TRAVIS" = "true"; then
- ci_fold() {
- local action="$1"
- local name="$2"
- name="$(echo -n "$name" | tr '\n\0' '--' | sed 's/[^A-Za-z0-9]\{1,\}/-/g')"
- name="$(echo -n "$name" | sed 's/-$//')"
- echo -en "travis_fold:${action}:${name}\r${ANSI_CLEAR}"
- }
-elif test "$GITHUB_ACTIONS" = "true"; then
- ci_fold() {
+ci_fold() {
+ if test "$GITHUB_ACTIONS" = "true"; then
local action="$1"
local name="$2"
- name="$(echo -n "$name" | tr '\n\0' '--' | sed 's/[^A-Za-z0-9]\{1,\}/-/g')"
- name="$(echo -n "$name" | sed 's/-$//')"
case "$action" in
start)
echo "::group::${name}"
@@ -37,12 +25,8 @@ elif test "$GITHUB_ACTIONS" = "true"; then
*)
:;;
esac
- }
-else
- ci_fold() {
- return 0
- }
-fi
+ fi
+}
enter_suite() {
set +x
@@ -50,7 +34,7 @@ enter_suite() {
rm -f "${END_MARKER}"
local suite_name="$1"
export NVIM_TEST_CURRENT_SUITE="${NVIM_TEST_CURRENT_SUITE}/$suite_name"
- ci_fold start "${NVIM_TEST_CURRENT_SUITE}"
+ ci_fold "start" "$suite_name"
set -x
}
@@ -60,7 +44,7 @@ exit_suite() {
echo "Suite ${NVIM_TEST_CURRENT_SUITE} failed, summary:"
echo "${FAIL_SUMMARY}"
else
- ci_fold end "${NVIM_TEST_CURRENT_SUITE}"
+ ci_fold "end" ""
fi
export NVIM_TEST_CURRENT_SUITE="${NVIM_TEST_CURRENT_SUITE%/*}"
if test "$1" != "--continue" ; then
@@ -98,99 +82,6 @@ run_test() {
fi
}
-run_test_wd() {
- local hang_ok=
- if test "$1" = "--allow-hang" ; then
- hang_ok=1
- shift
- fi
-
- local timeout="$1"
- test $# -gt 0 && shift
-
- local cmd="$1"
- test $# -gt 0 && shift
-
- local restart_cmd="$1"
- : ${restart_cmd:=true}
- test $# -gt 0 && shift
-
- local test_name="$1"
- : ${test_name:=$cmd}
- test $# -gt 0 && shift
-
- local output_file="$(mktemp)"
- local status_file="$(mktemp)"
- local sid_file="$(mktemp)"
-
- local restarts=5
- local prev_tmpsize=-1
- while test $restarts -gt 0 ; do
- : > "$status_file"
- : > "$sid_file"
- setsid \
- env \
- output_file="$output_file" \
- status_file="$status_file" \
- sid_file="$sid_file" \
- cmd="$cmd" \
- CI_DIR="$CI_DIR" \
- sh -c '
- . "${CI_DIR}/common/test.sh"
- ps -o sid= > "$sid_file"
- (
- ret=0
- if ! eval "$cmd" 2>&1 ; then
- ret=1
- fi
- echo "$ret" > "$status_file"
- ) | tee -a "$output_file"
- '
- while test "$(stat -c "%s" "$status_file")" -eq 0 ; do
- prev_tmpsize=$tmpsize
- sleep $timeout
- tmpsize="$(stat -c "%s" "$output_file")"
- if test $tempsize -eq $prev_temsize ; then
- # no output, assuming either hang or exit
- break
- fi
- done
- restarts=$(( restarts - 1 ))
- if test "$(stat -c "%s" "$status_file")" -eq 0 ; then
- # Status file not updated, assuming hang
-
- # SID not known, this should not ever happen
- if test "$(stat -c "%s" "$sid_file")" -eq 0 ; then
- fail "$test_name" E "Shell did not run"
- break
- fi
-
- # Kill all processes which belong to one session: should get rid of test
- # processes as well as sh itself.
- pkill -KILL -s$(cat "$sid_file")
-
- if test $restarts -eq 0 ; then
- if test -z "$hang_ok" ; then
- fail "$test_name" E "Test hang up"
- fi
- else
- echo "Test ${test_name} hang up, restarting"
- eval "$restart_cmd"
- fi
- else
- local new_failed="$(cat "$status_file")"
- if test "$new_failed" != "0" ; then
- fail "$test_name" F "Test failed in run_test_wd"
- fi
- break
- fi
- done
-
- rm -f "$output_file"
- rm -f "$status_file"
- rm -f "$sid_file"
-}
-
ended_successfully() {
if test -f "${FAIL_SUMMARY_FILE}" ; then
echo 'Test failed, complete summary:'
diff --git a/ci/install.sh b/ci/install.sh
index 1edc1138ee..bd42274b49 100755
--- a/ci/install.sh
+++ b/ci/install.sh
@@ -3,15 +3,6 @@
set -e
set -o pipefail
-if [[ "${CI_TARGET}" == lint ]]; then
- python3 -m pip -q install --user --upgrade flake8
- exit
-fi
-
-if [[ "${TRAVIS_OS_NAME}" == osx ]]; then
- export PATH="/usr/local/opt/ccache/libexec:$PATH"
-fi
-
# Use default CC to avoid compilation problems when installing Python modules.
echo "Install neovim module for Python 3."
CC=cc python3 -m pip -q install --user --upgrade pynvim
@@ -24,8 +15,6 @@ echo "Install neovim RubyGem."
gem install --no-document --bindir "$HOME/.local/bin" --user-install --pre neovim
echo "Install neovim npm package"
-source ~/.nvm/nvm.sh
-nvm use 10
npm install -g neovim
npm link neovim
diff --git a/ci/run_lint.sh b/ci/run_lint.sh
index 8373a3cb36..314976edc2 100755
--- a/ci/run_lint.sh
+++ b/ci/run_lint.sh
@@ -25,12 +25,7 @@ run_test 'make shlint' shlint
exit_suite --continue
enter_suite single-includes
-CLICOLOR_FORCE=1 run_test_wd \
- --allow-hang \
- 10s \
- 'make check-single-includes' \
- 'csi_clean' \
- single-includes
+run_test 'make check-single-includes' single-includes
exit_suite --continue
end_tests
diff --git a/ci/run_tests.sh b/ci/run_tests.sh
index d91ac5589e..c175910da5 100755
--- a/ci/run_tests.sh
+++ b/ci/run_tests.sh
@@ -17,10 +17,6 @@ build_nvim
exit_suite --continue
-source ~/.nvm/nvm.sh
-nvm use 10
-
-
enter_suite tests
if test "$CLANG_SANITIZER" != "TSAN" ; then
diff --git a/ci/script.sh b/ci/script.sh
index c8025ce34d..74fc4eda6c 100755
--- a/ci/script.sh
+++ b/ci/script.sh
@@ -3,14 +3,7 @@
set -e
set -o pipefail
-# This will pass the environment variables down to a bash process which runs
-# as $USER, while retaining the environment variables defined and belonging
-# to secondary groups given above in usermod.
-if [[ "${TRAVIS_OS_NAME}" == osx ]]; then
- sudo -E su "${USER}" -c "ci/run_${CI_TARGET}.sh"
-else
- ci/run_${CI_TARGET}.sh
-fi
+ci/run_${CI_TARGET}.sh
if [[ -s "${GCOV_ERROR_FILE}" ]]; then
echo '=== Unexpected gcov errors: ==='
diff --git a/cmake/RunTests.cmake b/cmake/RunTests.cmake
index e78392562f..3adbcbbfc5 100644
--- a/cmake/RunTests.cmake
+++ b/cmake/RunTests.cmake
@@ -46,6 +46,10 @@ if(DEFINED ENV{TEST_FILTER} AND NOT "$ENV{TEST_FILTER}" STREQUAL "")
list(APPEND BUSTED_ARGS --filter $ENV{TEST_FILTER})
endif()
+if(DEFINED ENV{TEST_FILTER_OUT} AND NOT "$ENV{TEST_FILTER_OUT}" STREQUAL "")
+ list(APPEND BUSTED_ARGS --filter-out $ENV{TEST_FILTER_OUT})
+endif()
+
# TMPDIR: use relative test path (for parallel test runs / isolation).
set(ENV{TMPDIR} "${BUILD_DIR}/Xtest_tmpdir/${TEST_PATH}")
execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory $ENV{TMPDIR})
diff --git a/config/CMakeLists.txt b/config/CMakeLists.txt
index 30f08c5297..8f93e1eb27 100644
--- a/config/CMakeLists.txt
+++ b/config/CMakeLists.txt
@@ -50,6 +50,19 @@ check_function_exists(strcasecmp HAVE_STRCASECMP)
check_function_exists(strncasecmp HAVE_STRNCASECMP)
check_function_exists(strptime HAVE_STRPTIME)
+if(CMAKE_SYSTEM_NAME STREQUAL "SunOS")
+ check_c_source_compiles("
+#include <termios.h>
+int
+main(void)
+{
+ return forkpty(0, NULL, NULL, NULL);
+}
+" HAVE_FORKPTY)
+else()
+ set(HAVE_FORKPTY 1)
+endif()
+
# Symbols
check_symbol_exists(FD_CLOEXEC "fcntl.h" HAVE_FD_CLOEXEC)
if(HAVE_LANGINFO_H)
diff --git a/config/config.h.in b/config/config.h.in
index b0635fb52b..b44b7238d2 100644
--- a/config/config.h.in
+++ b/config/config.h.in
@@ -50,6 +50,7 @@
# undef HAVE_SYS_UIO_H
# endif
#endif
+#cmakedefine HAVE_FORKPTY
#cmakedefine FEAT_TUI
diff --git a/runtime/autoload/dist/ft.vim b/runtime/autoload/dist/ft.vim
index a3db4ae87a..69712046a5 100644
--- a/runtime/autoload/dist/ft.vim
+++ b/runtime/autoload/dist/ft.vim
@@ -1,7 +1,7 @@
" Vim functions for file type detection
"
" Maintainer: Bram Moolenaar <Bram@vim.org>
-" Last Change: 2021 Nov 27
+" Last Change: 2022 Jan 11
" These functions are moved here from runtime/filetype.vim to make startup
" faster.
@@ -67,13 +67,29 @@ func dist#ft#FTasmsyntax()
endif
endfunc
-" Check if one of the first five lines contains "VB_Name". In that case it is
-" probably a Visual Basic file. Otherwise it's assumed to be "alt" filetype.
-func dist#ft#FTVB(alt)
- if getline(1).getline(2).getline(3).getline(4).getline(5) =~? 'VB_Name\|Begin VB\.\(Form\|MDIForm\|UserControl\)'
+func dist#ft#FTbas()
+ if exists("g:filetype_bas")
+ exe "setf " . g:filetype_bas
+ return
+ endif
+
+ " most frequent FreeBASIC-specific keywords in distro files
+ let fb_keywords = '\c^\s*\%(extern\|var\|enum\|private\|scope\|union\|byref\|operator\|constructor\|delete\|namespace\|public\|property\|with\|destructor\|using\)\>\%(\s*[:=(]\)\@!'
+ let fb_preproc = '\c^\s*\%(#\a\+\|option\s\+\%(byval\|dynamic\|escape\|\%(no\)\=gosub\|nokeyword\|private\|static\)\>\)'
+ let fb_comment = "^\\s*/'"
+ " OPTION EXPLICIT, without the leading underscore, is common to many dialects
+ let qb64_preproc = '\c^\s*\%($\a\+\|option\s\+\%(_explicit\|_\=explicitarray\)\>\)'
+
+ let lines = getline(1, min([line("$"), 100]))
+
+ if match(lines, fb_preproc) > -1 || match(lines, fb_comment) > -1 || match(lines, fb_keywords) > -1
+ setf freebasic
+ elseif match(lines, qb64_preproc) > -1
+ setf qb64
+ elseif match(lines, '\cVB_Name\|Begin VB\.\(Form\|MDIForm\|UserControl\)') > -1
setf vb
else
- exe "setf " . a:alt
+ setf basic
endif
endfunc
@@ -811,6 +827,40 @@ func dist#ft#Redif()
endwhile
endfunc
+" This function is called for all files under */debian/patches/*, make sure not
+" to non-dep3patch files, such as README and other text files.
+func dist#ft#Dep3patch()
+ if expand('%:t') ==# 'series'
+ return
+ endif
+
+ for ln in getline(1, 100)
+ if ln =~# '^\%(Description\|Subject\|Origin\|Bug\|Forwarded\|Author\|From\|Reviewed-by\|Acked-by\|Last-Updated\|Applied-Upstream\):'
+ setf dep3patch
+ return
+ elseif ln =~# '^---'
+ " end of headers found. stop processing
+ return
+ endif
+ endfor
+endfunc
+
+" This function checks the first 15 lines for appearance of 'FoamFile'
+" and then 'object' in a following line.
+" In that case, it's probably an OpenFOAM file
+func dist#ft#FTfoam()
+ let ffile = 0
+ let lnum = 1
+ while lnum <= 15
+ if getline(lnum) =~# '^FoamFile'
+ let ffile = 1
+ elseif ffile == 1 && getline(lnum) =~# '^\s*object'
+ setf foam
+ return
+ endif
+ let lnum = lnum + 1
+ endwhile
+endfunc
" Restore 'cpoptions'
let &cpo = s:cpo_save
diff --git a/runtime/autoload/health.vim b/runtime/autoload/health.vim
index 73c1459f86..1d462ad02c 100644
--- a/runtime/autoload/health.vim
+++ b/runtime/autoload/health.vim
@@ -1,27 +1,3 @@
-function! s:enhance_syntax() abort
- syntax case match
-
- syntax keyword healthError ERROR[:]
- \ containedin=markdownCodeBlock,mkdListItemLine
- highlight default link healthError Error
-
- syntax keyword healthWarning WARNING[:]
- \ containedin=markdownCodeBlock,mkdListItemLine
- highlight default link healthWarning WarningMsg
-
- syntax keyword healthSuccess OK[:]
- \ containedin=markdownCodeBlock,mkdListItemLine
- highlight default healthSuccess guibg=#5fff00 guifg=#080808 ctermbg=82 ctermfg=232
-
- syntax match healthHelp "|.\{-}|" contains=healthBar
- \ containedin=markdownCodeBlock,mkdListItemLine
- syntax match healthBar "|" contained conceal
- highlight default link healthHelp Identifier
-
- " We do not care about markdown syntax errors in :checkhealth output.
- highlight! link markdownError Normal
-endfunction
-
" Runs the specified healthchecks.
" Runs all discovered healthchecks if a:plugin_names is empty.
function! health#check(plugin_names) abort
@@ -29,13 +5,9 @@ function! health#check(plugin_names) abort
\ ? s:discover_healthchecks()
\ : s:get_healthcheck(a:plugin_names)
- tabnew
- setlocal wrap breakindent linebreak
- setlocal filetype=markdown
- setlocal conceallevel=2 concealcursor=nc
- setlocal keywordprg=:help
- let &l:iskeyword='!-~,^*,^|,^",192-255'
- call s:enhance_syntax()
+ " create scratch-buffer
+ execute 'tab sbuffer' nvim_create_buf(v:true, v:true)
+ setfiletype checkhealth
if empty(healthchecks)
call setline(1, 'ERROR: No healthchecks found.')
@@ -70,8 +42,6 @@ function! health#check(plugin_names) abort
" needed for plasticboy/vim-markdown, because it uses fdm=expr
normal! zR
- setlocal nomodified
- setlocal bufhidden=hide
redraw|echo ''
endfunction
diff --git a/runtime/autoload/health/provider.vim b/runtime/autoload/health/provider.vim
index 7b4dce3441..e6523aa215 100644
--- a/runtime/autoload/health/provider.vim
+++ b/runtime/autoload/health/provider.vim
@@ -523,7 +523,7 @@ function! s:check_virtualenv() abort
let hint = '$PATH ambiguities in subshells typically are '
\.'caused by your shell config overriding the $PATH previously set by the '
\.'virtualenv. Either prevent them from doing so, or use this workaround: '
- \.'https://vi.stackexchange.com/a/7654'
+ \.'https://vi.stackexchange.com/a/34996'
let hints[hint] = v:true
endif
endfor
diff --git a/runtime/autoload/man.vim b/runtime/autoload/man.vim
index 90d353f9de..b28170b7a1 100644
--- a/runtime/autoload/man.vim
+++ b/runtime/autoload/man.vim
@@ -7,7 +7,6 @@ let s:loaded_man = 1
let s:find_arg = '-w'
let s:localfile_arg = v:true " Always use -l if possible. #6683
-let s:section_arg = '-S'
function! man#init() abort
try
@@ -216,16 +215,42 @@ endfunction
function! s:get_path(sect, name) abort
" Some man implementations (OpenBSD) return all available paths from the
- " search command, so we get() the first one. #8341
+ " search command. Previously, this function would simply select the first one.
+ "
+ " However, some searches will report matches that are incorrect:
+ " man -w strlen may return string.3 followed by strlen.3, and therefore
+ " selecting the first would get us the wrong page. Thus, we must find the
+ " first matching one.
+ "
+ " There's yet another special case here. Consider the following:
+ " If you run man -w strlen and string.3 comes up first, this is a problem. We
+ " should search for a matching named one in the results list.
+ " However, if you search for man -w clock_gettime, you will *only* get
+ " clock_getres.2, which is the right page. Searching the resuls for
+ " clock_gettime will no longer work. In this case, we should just use the
+ " first one that was found in the correct section.
+ "
+ " Finally, we can avoid relying on -S or -s here since they are very
+ " inconsistently supported. Instead, call -w with a section and a name.
if empty(a:sect)
- return substitute(get(split(s:system(['man', s:find_arg, a:name])), 0, ''), '\n\+$', '', '')
+ let results = split(s:system(['man', s:find_arg, a:name]))
+ else
+ let results = split(s:system(['man', s:find_arg, a:sect, a:name]))
+ endif
+
+ if empty(results)
+ return ''
endif
- " '-s' flag handles:
- " - tokens like 'printf(echo)'
- " - sections starting with '-'
- " - 3pcap section (found on macOS)
- " - commas between sections (for section priority)
- return substitute(get(split(s:system(['man', s:find_arg, s:section_arg, a:sect, a:name])), 0, ''), '\n\+$', '', '')
+
+ " find any that match the specified name
+ let namematches = filter(copy(results), 'fnamemodify(v:val, ":t") =~ a:name')
+ let sectmatches = []
+
+ if !empty(namematches) && !empty(a:sect)
+ let sectmatches = filter(copy(namematches), 'fnamemodify(v:val, ":e") == a:sect')
+ endif
+
+ return substitute(get(sectmatches, 0, get(namematches, 0, results[0])), '\n\+$', '', '')
endfunction
" s:verify_exists attempts to find the path to a manpage
@@ -243,40 +268,72 @@ endfunction
" then we don't do it again in step 2.
function! s:verify_exists(sect, name) abort
let sect = a:sect
- if empty(sect)
- let sect = get(b:, 'man_default_sects', '')
- endif
- try
- return s:get_path(sect, a:name)
- catch /^command error (/
- endtry
-
- if !empty(get(b:, 'man_default_sects', '')) && sect !=# b:man_default_sects
+ if empty(sect)
+ " no section specified, so search with b:man_default_sects
+ if exists('b:man_default_sects')
+ let sects = split(b:man_default_sects, ',')
+ for sec in sects
+ try
+ let res = s:get_path(sec, a:name)
+ if !empty(res)
+ return res
+ endif
+ catch /^command error (/
+ endtry
+ endfor
+ endif
+ else
+ " try with specified section
try
- return s:get_path(b:man_default_sects, a:name)
+ let res = s:get_path(sect, a:name)
+ if !empty(res)
+ return res
+ endif
catch /^command error (/
endtry
- endif
- if !empty(sect)
- try
- return s:get_path('', a:name)
- catch /^command error (/
- endtry
+ " try again with b:man_default_sects
+ if exists('b:man_default_sects')
+ let sects = split(b:man_default_sects, ',')
+ for sec in sects
+ try
+ let res = s:get_path(sec, a:name)
+ if !empty(res)
+ return res
+ endif
+ catch /^command error (/
+ endtry
+ endfor
+ endif
endif
+ " if none of the above worked, we will try with no section
+ try
+ let res = s:get_path('', a:name)
+ if !empty(res)
+ return res
+ endif
+ catch /^command error (/
+ endtry
+
+ " if that still didn't work, we will check for $MANSECT and try again with it
+ " unset
if !empty($MANSECT)
try
let MANSECT = $MANSECT
call setenv('MANSECT', v:null)
- return s:get_path('', a:name)
+ let res = s:get_path('', a:name)
+ if !empty(res)
+ return res
+ endif
catch /^command error (/
finally
call setenv('MANSECT', MANSECT)
endtry
endif
+ " finally, if that didn't work, there is no hope
throw 'no manual entry for ' . a:name
endfunction
diff --git a/runtime/autoload/msgpack.vim b/runtime/autoload/msgpack.vim
index 7dd225e3d9..7f98a5b230 100644
--- a/runtime/autoload/msgpack.vim
+++ b/runtime/autoload/msgpack.vim
@@ -56,6 +56,7 @@ function s:msgpack_init_python() abort
\. " time = datetime.datetime.fromtimestamp(timestamp)\n"
\. " return time.strftime(fmt)\n"
\. "def shada_dict_strptime():\n"
+ \. " import calendar\n"
\. " import datetime\n"
\. " import vim\n"
\. " fmt = vim.eval('a:format')\n"
@@ -64,7 +65,10 @@ function s:msgpack_init_python() abort
\. " try:\n"
\. " timestamp = int(timestamp.timestamp())\n"
\. " except:\n"
- \. " timestamp = int(timestamp.strftime('%s'))\n"
+ \. " try:\n"
+ \. " timestamp = int(timestamp.strftime('%s'))\n"
+ \. " except:\n"
+ \. " timestamp = calendar.timegm(timestamp.utctimetuple())\n"
\. " if timestamp > 2 ** 31:\n"
\. " tsabs = abs(timestamp)\n"
\. " return ('{\"_TYPE\": v:msgpack_types.integer,'\n"
diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt
index 8fb6290e50..2da1f5e40d 100644
--- a/runtime/doc/api.txt
+++ b/runtime/doc/api.txt
@@ -45,7 +45,7 @@ start with a TCP/IP socket instead, use |--listen| with a TCP-style address: >
More endpoints can be started with |serverstart()|.
Note that localhost TCP sockets are generally less secure than named pipes,
-and can lead to vunerabilities like remote code execution.
+and can lead to vulnerabilities like remote code execution.
Connecting to the socket is the easiest way a programmer can test the API,
which can be done through any msgpack-rpc client library or full-featured
@@ -198,7 +198,7 @@ any of these approaches:
2. Start Nvim with |--api-info|. Useful for statically-compiled clients.
Example (requires Python "pyyaml" and "msgpack-python" modules): >
- nvim --api-info | python -c 'import msgpack, sys, yaml; print yaml.dump(msgpack.unpackb(sys.stdin.read()))'
+ nvim --api-info | python -c 'import msgpack, sys, yaml; yaml.dump(msgpack.unpackb(sys.stdin.buffer.read()), sys.stdout)'
<
3. Use the |api_info()| Vimscript function. >
:lua print(vim.inspect(vim.fn.api_info()))
@@ -361,7 +361,7 @@ UTF-32 and UTF-16 sizes of the deleted region is also passed as additional
arguments {old_utf32_size} and {old_utf16_size}.
"on_changedtick" is invoked when |b:changedtick| was incremented but no text
-was changed. The parameters recieved are ("changedtick", {buf}, {changedtick}).
+was changed. The parameters received are ("changedtick", {buf}, {changedtick}).
*api-lua-detach*
In-process Lua callbacks can detach by returning `true`. This will detach all
@@ -468,7 +468,7 @@ extmark position and enter some text, the extmark migrates forward. >
f o o z|b a r line (| = cursor)
4 extmark (after typing "z")
-If an extmark is on the last index of a line and you inputsa newline at that
+If an extmark is on the last index of a line and you inputs a newline at that
point, the extmark will accordingly migrate to the next line: >
f o o z b a r| line (| = cursor)
@@ -626,6 +626,59 @@ nvim__stats() *nvim__stats()*
Return: ~
Map of various internal stats.
+ *nvim_add_user_command()*
+nvim_add_user_command({name}, {command}, {*opts})
+ Create a new user command |user-commands|
+
+ {name} is the name of the new command. The name must begin
+ with an uppercase letter.
+
+ {command} is the replacement text or Lua function to execute.
+
+ Example: >
+ :call nvim_add_user_command('SayHello', 'echo "Hello world!"', {})
+ :SayHello
+ Hello world!
+<
+
+ Parameters: ~
+ {name} Name of the new user command. Must begin with
+ an uppercase letter.
+ {command} Replacement command to execute when this user
+ command is executed. When called from Lua, the
+ command can also be a Lua function. The
+ function is called with a single table argument
+ that contains the following keys:
+ • args: (string) The args passed to the
+ command, if any |<args>|
+ • bang: (boolean) "true" if the command was
+ executed with a ! modifier |<bang>|
+ • line1: (number) The starting line of the
+ command range |<line1>|
+ • line2: (number) The final line of the command
+ range |<line2>|
+ • range: (number) The number of items in the
+ command range: 0, 1, or 2 |<range>|
+ • count: (number) Any count supplied |<count>|
+ • reg: (string) The optional register, if
+ specified |<reg>|
+ • mods: (string) Command modifiers, if any
+ |<mods>|
+ {opts} Optional command attributes. See
+ |command-attributes| for more details. To use
+ boolean attributes (such as |:command-bang| or
+ |:command-bar|) set the value to "true". In
+ addition to the string options listed in
+ |:command-complete|, the "complete" key also
+ accepts a Lua function which works like the
+ "customlist" completion mode
+ |:command-completion-customlist|. Additional
+ parameters:
+ • desc: (string) Used for listing the command
+ when a Lua function is used for {command}.
+ • force: (boolean, default true) Override any
+ previous definition.
+
nvim_call_atomic({calls}) *nvim_call_atomic()*
Calls many API methods atomically.
@@ -634,7 +687,7 @@ nvim_call_atomic({calls}) *nvim_call_atomic()*
atomically, i.e. without interleaving redraws, RPC requests
from other clients, or user interactions (however API
methods may trigger autocommands or event processing which
- have such side-effects, e.g. |:sleep| may wake timers).
+ have such side effects, e.g. |:sleep| may wake timers).
2. To minimize RPC overhead (roundtrips) of a sequence of many
requests.
@@ -656,8 +709,8 @@ nvim_chan_send({chan}, {data}) *nvim_chan_send()*
Send data to channel `id` . For a job, it writes it to the
stdin of the process. For the stdio channel |channel-stdio|,
it writes to Nvim's stdout. For an internal terminal instance
- (|nvim_open_term()|) it writes directly to terimal output. See
- |channel-bytes| for more information.
+ (|nvim_open_term()|) it writes directly to terminal output.
+ See |channel-bytes| for more information.
This function writes raw data, not RPC messages. If the
channel was created with `rpc=true` then the channel expects
@@ -698,7 +751,7 @@ nvim_del_keymap({mode}, {lhs}) *nvim_del_keymap()*
|nvim_set_keymap()|
nvim_del_mark({name}) *nvim_del_mark()*
- Deletes a uppercase/file named mark. See |mark-motions|.
+ Deletes an uppercase/file named mark. See |mark-motions|.
Note:
fails with error if a lowercase or buffer local named mark
@@ -714,6 +767,12 @@ nvim_del_mark({name}) *nvim_del_mark()*
|nvim_buf_del_mark()|
|nvim_get_mark()|
+nvim_del_user_command({name}) *nvim_del_user_command()*
+ Delete a user-defined command.
+
+ Parameters: ~
+ {name} Name of the command to delete.
+
nvim_del_var({name}) *nvim_del_var()*
Removes a global (g:) variable.
@@ -1061,7 +1120,7 @@ nvim_get_option_value({name}, {*opts}) *nvim_get_option_value()*
Parameters: ~
{name} Option name
{opts} Optional parameters
- • scope: One of 'global' or 'local'. Analagous to
+ • scope: One of 'global' or 'local'. Analogous to
|:setglobal| and |:setlocal|, respectively.
Return: ~
@@ -1346,7 +1405,7 @@ nvim_replace_termcodes({str}, {from_part}, {do_lt}, {special})
{from_part} Legacy Vim parameter. Usually true.
{do_lt} Also translate <lt>. Ignored if `special` is
false.
- {special} Replace |keycodes|, e.g. <CR> becomes a "\n"
+ {special} Replace |keycodes|, e.g. <CR> becomes a "\r"
char.
See also: ~
@@ -1524,8 +1583,11 @@ nvim_set_keymap({mode}, {lhs}, {rhs}, {*opts}) *nvim_set_keymap()*
{rhs} Right-hand-side |{rhs}| of the mapping.
{opts} Optional parameters map. Accepts all
|:map-arguments| as keys excluding |<buffer>| but
- including |noremap|. Values are Booleans. Unknown
- key is an error.
+ including |noremap| and "desc". |desc| can be used
+ to give a description to keymap. When called from
+ Lua, also accepts a "callback" key that takes a
+ Lua function to call when the mapping is executed.
+ Values are Booleans. Unknown key is an error.
nvim_set_option({name}, {value}) *nvim_set_option()*
Sets the global value of an option.
@@ -1545,7 +1607,7 @@ nvim_set_option_value({name}, {value}, {*opts})
{name} Option name
{value} New option value
{opts} Optional parameters
- • scope: One of 'global' or 'local'. Analagous to
+ • scope: One of 'global' or 'local'. Analogous to
|:setglobal| and |:setlocal|, respectively.
nvim_set_var({name}, {value}) *nvim_set_var()*
@@ -1790,6 +1852,16 @@ nvim__buf_redraw_range({buffer}, {first}, {last})
nvim__buf_stats({buffer}) *nvim__buf_stats()*
TODO: Documentation
+ *nvim_buf_add_user_command()*
+nvim_buf_add_user_command({buffer}, {name}, {command}, {*opts})
+ Create a new user command |user-commands| in the given buffer.
+
+ Parameters: ~
+ {buffer} Buffer handle, or 0 for current buffer.
+
+ See also: ~
+ nvim_add_user_command
+
nvim_buf_attach({buffer}, {send_buffer}, {opts}) *nvim_buf_attach()*
Activates buffer-update events on a channel, or as Lua
callbacks.
@@ -1925,6 +1997,18 @@ nvim_buf_del_mark({buffer}, {name}) *nvim_buf_del_mark()*
|nvim_buf_set_mark()|
|nvim_del_mark()|
+ *nvim_buf_del_user_command()*
+nvim_buf_del_user_command({buffer}, {name})
+ Delete a buffer-local user-defined command.
+
+ Only commands created with |:command-buffer| or
+ |nvim_buf_add_user_command()| can be deleted with this
+ function.
+
+ Parameters: ~
+ {buffer} Buffer handle, or 0 for current buffer.
+ {name} Name of the command to delete.
+
nvim_buf_del_var({buffer}, {name}) *nvim_buf_del_var()*
Removes a buffer-scoped (b:) variable
@@ -2464,6 +2548,10 @@ nvim_buf_set_extmark({buffer}, {ns_id}, {line}, {col}, {*opts})
• priority: a priority value for the highlight
group. For example treesitter highlighting
uses a value of 100.
+ • strict: boolean that indicates extmark should
+ not be placed if the line or column value is
+ past the end of the buffer or end of the line
+ respectively. Defaults to true.
Return: ~
Id of the created/updated extmark
@@ -2687,7 +2775,7 @@ nvim_win_is_valid({window}) *nvim_win_is_valid()*
true if the window is valid, false otherwise
nvim_win_set_buf({window}, {buffer}) *nvim_win_set_buf()*
- Sets the current buffer in a window, without side-effects
+ Sets the current buffer in a window, without side effects
Attributes: ~
not allowed when |textlock| is active
diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt
index 242631d98c..5e50f9c1f8 100644
--- a/runtime/doc/autocmd.txt
+++ b/runtime/doc/autocmd.txt
@@ -40,10 +40,10 @@ effects. Be careful not to destroy your text.
2. Defining autocommands *autocmd-define*
*:au* *:autocmd*
-:au[tocmd] [group] {event} {pat} [++once] [++nested] {cmd}
+:au[tocmd] [group] {event} {aupat} [++once] [++nested] {cmd}
Add {cmd} to the list of commands that Vim will
execute automatically on {event} for a file matching
- {pat} |autocmd-pattern|.
+ {aupat} |autocmd-pattern|.
Note: A quote character is seen as argument to the
:autocmd and won't start a comment.
Nvim always adds {cmd} after existing autocommands so
@@ -119,19 +119,19 @@ prompt. When one command outputs two messages this can happen anyway.
==============================================================================
3. Removing autocommands *autocmd-remove*
-:au[tocmd]! [group] {event} {pat} [++once] [++nested] {cmd}
+:au[tocmd]! [group] {event} {aupat} [++once] [++nested] {cmd}
Remove all autocommands associated with {event} and
- {pat}, and add the command {cmd}.
+ {aupat}, and add the command {cmd}.
See |autocmd-once| for [++once].
See |autocmd-nested| for [++nested].
-:au[tocmd]! [group] {event} {pat}
+:au[tocmd]! [group] {event} {aupat}
Remove all autocommands associated with {event} and
- {pat}.
+ {aupat}.
-:au[tocmd]! [group] * {pat}
- Remove all autocommands associated with {pat} for all
- events.
+:au[tocmd]! [group] * {aupat}
+ Remove all autocommands associated with {aupat} for
+ all events.
:au[tocmd]! [group] {event}
Remove ALL autocommands for {event}.
@@ -151,12 +151,12 @@ with ":augroup"); otherwise, Vim uses the group defined with [group].
==============================================================================
4. Listing autocommands *autocmd-list*
-:au[tocmd] [group] {event} {pat}
+:au[tocmd] [group] {event} {aupat}
Show the autocommands associated with {event} and
- {pat}.
+ {aupat}.
-:au[tocmd] [group] * {pat}
- Show the autocommands associated with {pat} for all
+:au[tocmd] [group] * {aupat}
+ Show the autocommands associated with {aupat} for all
events.
:au[tocmd] [group] {event}
@@ -828,6 +828,21 @@ RemoteReply When a reply from a Vim that functions as
SearchWrapped After making a search with |n| or |N| if the
search wraps around the document back to
the start/finish respectively.
+ *RecordingEnter*
+RecordingEnter When a macro starts recording.
+ The pattern is the current file name, and
+ |reg_recording()| is the current register that
+ is used.
+ *RecordingLeave*
+RecordingLeave When a macro stops recording.
+ The pattern is the current file name, and
+ |reg_recording()| is the recorded
+ register.
+ |reg_recorded()| is only updated after this
+ event.
+ Sets these |v:event| keys:
+ regcontents
+ regname
*SessionLoadPost*
SessionLoadPost After loading the session file created using
the |:mksession| command.
@@ -1060,16 +1075,16 @@ WinScrolled After scrolling the viewport of the current
==============================================================================
-6. Patterns *autocmd-pattern* *{pat}*
+6. Patterns *autocmd-pattern* *{aupat}*
-The {pat} argument can be a comma separated list. This works as if the
-command was given with each pattern separately. Thus this command: >
+The {aupat} argument of `:autocmd` can be a comma separated list. This works
+as if the command was given with each pattern separately. Thus this command: >
:autocmd BufRead *.txt,*.info set et
Is equivalent to: >
:autocmd BufRead *.txt set et
:autocmd BufRead *.info set et
-The file pattern {pat} is tested for a match against the file name in one of
+The file pattern {aupat} is tested for a match against the file name in one of
two ways:
1. When there is no '/' in the pattern, Vim checks for a match against only
the tail part of the file name (without its leading directory path).
diff --git a/runtime/doc/change.txt b/runtime/doc/change.txt
index ffdd8427f9..953f097a92 100644
--- a/runtime/doc/change.txt
+++ b/runtime/doc/change.txt
@@ -1595,7 +1595,8 @@ r Automatically insert the current comment leader after hitting
<Enter> in Insert mode.
*fo-o*
o Automatically insert the current comment leader after hitting 'o' or
- 'O' in Normal mode.
+ 'O' in Normal mode. In case comment is unwanted in a specific place
+ use CTRL-U to quickly delete it. |i_CTRL-U|
*fo-q*
q Allow formatting of comments with "gq".
Note that formatting will not change blank lines or lines containing
diff --git a/runtime/doc/channel.txt b/runtime/doc/channel.txt
index 5f376a600e..e14427494d 100644
--- a/runtime/doc/channel.txt
+++ b/runtime/doc/channel.txt
@@ -44,7 +44,7 @@ functions like |chansend()| consume channel ids.
2. Reading and writing raw bytes *channel-bytes*
Channels opened by Vimscript functions operate with raw bytes by default. For
-a job channel using RPC, bytes can still be read over its stderr. Similarily,
+a job channel using RPC, bytes can still be read over its stderr. Similarly,
only bytes can be written to Nvim's own stderr.
*channel-callback*
diff --git a/runtime/doc/cmdline.txt b/runtime/doc/cmdline.txt
index 7716af25bd..641cd93386 100644
--- a/runtime/doc/cmdline.txt
+++ b/runtime/doc/cmdline.txt
@@ -697,7 +697,8 @@ Line numbers may be specified with: *:range* *{address}*
Each may be followed (several times) by '+' or '-' and an optional number.
This number is added or subtracted from the preceding line number. If the
-number is omitted, 1 is used.
+number is omitted, 1 is used. If there is nothing before the '+' or '-' then
+the current line is used.
The "/" and "?" after {pattern} are required to separate the pattern from
anything that follows.
@@ -727,7 +728,7 @@ Some commands allow for a count after the command. This count is used as the
number of lines to be used, starting with the line given in the last line
specifier (the default is the cursor line). The commands that accept a count
are the ones that use a range but do not have a file name argument (because
-a file name can also be a number).
+a file name can also be a number). The count cannot be negative.
Examples: >
:s/x/X/g 5 substitute 'x' by 'X' in the current line and four
diff --git a/runtime/doc/develop.txt b/runtime/doc/develop.txt
index 7127c74134..178b0dc62b 100644
--- a/runtime/doc/develop.txt
+++ b/runtime/doc/develop.txt
@@ -105,7 +105,7 @@ in eval.c:
- eval_call_provider(name, method, arguments, discard): calls
provider#{name}#Call with the method and arguments. If discard is true, any
- value returned by the provider will be discarded and and empty value be
+ value returned by the provider will be discarded and empty value will be
returned.
- eval_has_provider(name): Checks the `g:loaded_{name}_provider` variable
which must be set to 2 by the provider script to indicate that it is
diff --git a/runtime/doc/diagnostic.txt b/runtime/doc/diagnostic.txt
index 0893f1f343..19db3158be 100644
--- a/runtime/doc/diagnostic.txt
+++ b/runtime/doc/diagnostic.txt
@@ -132,7 +132,7 @@ with |vim.notify()|: >
In this example, there is nothing to do when diagnostics are hidden, so we
omit the "hide" function.
-Existing handlers can be overriden. For example, use the following to only
+Existing handlers can be overridden. For example, use the following to only
show a sign for the highest severity diagnostic on a given line: >
-- Create a custom namespace. This will aggregate signs from all other
@@ -177,8 +177,9 @@ All highlights defined for diagnostics begin with `Diagnostic` followed by
the type of highlight (e.g., `Sign`, `Underline`, etc.) and the severity (e.g.
`Error`, `Warn`, etc.)
-Sign, underline and virtual text highlights (by default) are linked to their
-corresponding default highlight.
+By default, highlights for signs, floating windows, and virtual text are linked to the
+corresponding default highlight. Underline highlights are not linked and use their
+own default highlight groups.
For example, the default highlighting for |hl-DiagnosticSignError| is linked
to |hl-DiagnosticError|. To change the default (and therefore the linked
@@ -298,7 +299,6 @@ Example: >
autocmd DiagnosticChanged * lua vim.diagnostic.setqflist({open = false })
<
==============================================================================
-==============================================================================
Lua module: vim.diagnostic *diagnostic-api*
config({opts}, {namespace}) *vim.diagnostic.config()*
@@ -334,8 +334,9 @@ config({opts}, {namespace}) *vim.diagnostic.config()*
that returns any of the above.
Parameters: ~
- {opts} table Configuration table with the following
- keys:
+ {opts} table|nil When omitted or "nil", retrieve the
+ current configuration. Otherwise, a
+ configuration table with the following keys:
• underline: (default true) Use underline for
diagnostics. Options:
• severity: Only underline diagnostics
@@ -343,13 +344,24 @@ config({opts}, {namespace}) *vim.diagnostic.config()*
|diagnostic-severity|
• virtual_text: (default true) Use virtual
- text for diagnostics. Options:
+ text for diagnostics. If multiple
+ diagnostics are set for a namespace, one
+ prefix per diagnostic + the last diagnostic
+ message are shown. Options:
• severity: Only show virtual text for
diagnostics matching the given severity
|diagnostic-severity|
- • source: (string) Include the diagnostic
- source in virtual text. One of "always"
- or "if_many".
+ • source: (boolean or string) Include the
+ diagnostic source in virtual text. Use
+ "if_many" to only show sources if there
+ is more than one diagnostic source in the
+ buffer. Otherwise, any truthy value means
+ to always show the diagnostic source.
+ • spacing: (number) Amount of empty spaces
+ inserted at the beginning of the virtual
+ text.
+ • prefix: (string) Prepend diagnostic
+ message with prefix.
• format: (function) A function that takes
a diagnostic as input and returns a
string. The return value is the text used
@@ -608,9 +620,12 @@ open_float({opts}, {...}) *vim.diagnostic.open_float()*
is interpreted as a [text, hl_group] tuple.
Overrides the setting from
|vim.diagnostic.config()|.
- • source: (string) Include the diagnostic source
- in the message. One of "always" or "if_many".
- Overrides the setting from
+ • source: (boolean or string) Include the
+ diagnostic source in the message. Use "if_many"
+ to only show sources if there is more than one
+ source of diagnostics in the buffer. Otherwise,
+ any truthy value means to always show the
+ diagnostic source. Overrides the setting from
|vim.diagnostic.config()|.
• format: (function) A function that takes a
diagnostic as input and returns a string. The
diff --git a/runtime/doc/diff.txt b/runtime/doc/diff.txt
index 6115a5d235..abe99102ee 100644
--- a/runtime/doc/diff.txt
+++ b/runtime/doc/diff.txt
@@ -324,8 +324,9 @@ After setting this variable, reload the syntax script: >
FINDING THE DIFFERENCES *diff-diffexpr*
-The 'diffexpr' option can be set to use something else than the standard
-"diff" program to compare two files and find the differences. *E959*
+The 'diffexpr' option can be set to use something else than the internal diff
+support or the standard "diff" program to compare two files and find the
+differences.
When 'diffexpr' is empty, Vim uses this command to find the differences
between file1 and file2: >
@@ -358,7 +359,7 @@ format mentioned. These variables are set to the file names used:
v:fname_in original file
v:fname_new new version of the same file
- v:fname_out resulting diff file
+ v:fname_out where to write the resulting diff file
Additionally, 'diffexpr' should take care of "icase" and "iwhite" in the
'diffopt' option. 'diffexpr' cannot change the value of 'lines' and
diff --git a/runtime/doc/editing.txt b/runtime/doc/editing.txt
index 4e3173cfa9..44987f3b7b 100644
--- a/runtime/doc/editing.txt
+++ b/runtime/doc/editing.txt
@@ -845,7 +845,7 @@ Note: When the 'write' option is off, you are not able to write any file.
*:w* *:write*
*E502* *E503* *E504* *E505*
- *E512* *E514* *E667* *E796* *E949*
+ *E512* *E514* *E667* *E949*
:w[rite] [++opt] Write the whole buffer to the current file. This is
the normal way to save changes to a file. It fails
when the 'readonly' option is set or when there is
@@ -1253,10 +1253,12 @@ working directory. If a local working directory (tab or window) does not
exist, the next-higher scope in the hierarchy applies.
*:cd* *E747* *E472*
-:cd[!] On non-Unix systems: Print the current directory
- name. On Unix systems: Change the current directory
- to the home directory. Use |:pwd| to print the
- current directory on all systems.
+:cd[!] On non-Unix systems when 'cdhome' is off: Print the
+ current directory name.
+ Otherwise: Change the current directory to the home
+ directory. Clear any window-local directory.
+ Use |:pwd| to print the current directory on all
+ systems.
:cd[!] {path} Change the current directory to {path}.
If {path} is relative, it is searched for in the
@@ -1329,6 +1331,7 @@ current directory for that window. Windows where the |:lcd| command has not
been used stick to the global or tab-local directory. When jumping to another
window the current directory is changed to the last specified local current
directory. If none was specified, the global or tab-local directory is used.
+When creating a new window it inherits the local directory of the current window.
When changing tabs the same behaviour applies. If the current tab has no
local working directory the global working directory is used.
diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt
index 75b782fbff..fa75ead9a3 100644
--- a/runtime/doc/eval.txt
+++ b/runtime/doc/eval.txt
@@ -111,7 +111,7 @@ When mixing Number and Float the Number is converted to Float. Otherwise
there is no automatic conversion of Float. You can use str2float() for String
to Float, printf() for Float to String and float2nr() for Float to Number.
- *E891* *E892* *E893* *E894*
+ *E362* *E891* *E892* *E893* *E894* *E907*
When expecting a Float a Number can also be used, but nothing else.
*no-type-checking*
@@ -1195,6 +1195,7 @@ When expr8 is a |Funcref| type variable, invoke the function it refers to.
expr8->name([args]) method call *method* *->*
expr8->{lambda}([args])
+ *E260* *E276*
For methods that are also available as global functions this is the same as: >
name(expr8 [, args])
There can also be methods specifically for the type of "expr8".
@@ -2278,7 +2279,7 @@ USAGE RESULT DESCRIPTION ~
abs({expr}) Float or Number absolute value of {expr}
acos({expr}) Float arc cosine of {expr}
add({object}, {item}) List/Blob append {item} to {object}
-and({expr}, {expr}) Number bitwise AND
+and({expr}, {expr}) Number bitwise AND
api_info() Dict api metadata
append({lnum}, {string}) Number append {string} below line {lnum}
append({lnum}, {list}) Number append lines {list} below line {lnum}
@@ -2310,7 +2311,7 @@ assert_notmatch({pat}, {text} [, {msg}])
assert_report({msg}) Number report a test failure
assert_true({actual} [, {msg}]) Number assert {actual} is true
atan({expr}) Float arc tangent of {expr}
-atan2({expr}, {expr}) Float arc tangent of {expr1} / {expr2}
+atan2({expr}, {expr}) Float arc tangent of {expr1} / {expr2}
browse({save}, {title}, {initdir}, {default})
String put up a file requester
browsedir({title}, {initdir}) String put up a directory requester
@@ -2336,7 +2337,7 @@ char2nr({expr}[, {utf8}]) Number ASCII/UTF-8 value of first char in {expr}
charidx({string}, {idx} [, {countcc}])
Number char index of byte {idx} in {string}
chdir({dir}) String change current working directory
-cindent({lnum}) Number C indent for line {lnum}
+cindent({lnum}) Number C indent for line {lnum}
clearmatches([{win}]) none clear all matches
col({expr}) Number column nr of cursor or mark
complete({startcol}, {matches}) none set Insert mode completion
@@ -2349,7 +2350,7 @@ copy({expr}) any make a shallow copy of {expr}
cos({expr}) Float cosine of {expr}
cosh({expr}) Float hyperbolic cosine of {expr}
count({list}, {expr} [, {ic} [, {start}]])
- Number count how many {expr} are in {list}
+ Number count how many {expr} are in {list}
cscope_connection([{num}, {dbpath} [, {prepend}]])
Number checks existence of cscope connection
ctxget([{index}]) Dict return the |context| dict at {index}
@@ -2362,7 +2363,7 @@ ctxsize() Number return |context-stack| size
cursor({lnum}, {col} [, {off}])
Number move cursor to {lnum}, {col}, {off}
cursor({list}) Number move cursor to position in {list}
-debugbreak({pid}) Number interrupt process being debugged
+debugbreak({pid}) Number interrupt process being debugged
deepcopy({expr} [, {noref}]) any make a full copy of {expr}
delete({fname} [, {flags}]) Number delete the file or directory {fname}
deletebufline({buf}, {first}[, {last}])
@@ -2381,7 +2382,7 @@ eval({string}) any evaluate {string} into its value
eventhandler() Number |TRUE| if inside an event handler
executable({expr}) Number 1 if executable {expr} exists
execute({command}) String execute and capture output of {command}
-exepath({expr}) String full path of the command {expr}
+exepath({expr}) String full path of the command {expr}
exists({expr}) Number |TRUE| if {expr} exists
extend({expr1}, {expr2} [, {expr3}])
List/Dict insert items of {expr2} into {expr1}
@@ -2410,10 +2411,11 @@ foldlevel({lnum}) Number fold level at {lnum}
foldtext() String line displayed for closed fold
foldtextresult({lnum}) String text for closed fold at {lnum}
foreground() Number bring the Vim window to the foreground
+fullcommand({name}) String get full command from {name}
funcref({name} [, {arglist}] [, {dict}])
- Funcref reference to function {name}
+ Funcref reference to function {name}
function({name} [, {arglist}] [, {dict}])
- Funcref named reference to function {name}
+ Funcref named reference to function {name}
garbagecollect([{atexit}]) none free memory, breaking cyclic references
get({list}, {idx} [, {def}]) any get item {idx} from {list} or {def}
get({dict}, {key} [, {def}]) any get item {key} from {dict} or {def}
@@ -2501,11 +2503,11 @@ inputlist({textlist}) Number let the user pick from a choice list
inputrestore() Number restore typeahead
inputsave() Number save and clear typeahead
inputsecret({prompt} [, {text}])
- String like input() but hiding the text
+ String like input() but hiding the text
insert({object}, {item} [, {idx}])
List insert {item} in {object} [before {idx}]
interrupt() none interrupt script execution
-invert({expr}) Number bitwise invert
+invert({expr}) Number bitwise invert
isdirectory({directory}) Number |TRUE| if {directory} is a directory
isinf({expr}) Number determine if {expr} is infinity value
(positive or negative)
@@ -2525,7 +2527,7 @@ json_encode({expr}) String Convert {expr} to JSON
keys({dict}) List keys in {dict}
len({expr}) Number the length of {expr}
libcall({lib}, {func}, {arg}) String call {func} in library {lib} with {arg}
-libcallnr({lib}, {func}, {arg}) Number idem, but return a Number
+libcallnr({lib}, {func}, {arg}) Number idem, but return a Number
line({expr} [, {winid}]) Number line nr of cursor, last line or mark
line2byte({lnum}) Number byte count of line {lnum}
lispindent({lnum}) Number Lisp indent for line {lnum}
@@ -2567,7 +2569,7 @@ msgpackparse({data}) List parse msgpack to a list of objects
nextnonblank({lnum}) Number line nr of non-blank line >= {lnum}
nr2char({expr}[, {utf8}]) String single char with ASCII/UTF-8 value {expr}
nvim_...({args}...) any call nvim |api| functions
-or({expr}, {expr}) Number bitwise OR
+or({expr}, {expr}) Number bitwise OR
pathshorten({expr}) String shorten directory names in a path
perleval({expr}) any evaluate |perl| expression
pow({x}, {y}) Float {x} to the power of {y}
@@ -2588,6 +2590,7 @@ readdir({dir} [, {expr}]) List file names in {dir} selected by {expr}
readfile({fname} [, {type} [, {max}]])
List get list of lines from file {fname}
reg_executing() String get the executing register name
+reg_recorded() String get the last recorded register name
reg_recording() String get the recording register name
reltime([{start} [, {end}]]) List get time value
reltimefloat({time}) Float turn the time value into a Float
@@ -2626,7 +2629,7 @@ screenrow() Number current cursor row
screenstring({row}, {col}) String characters at screen position
search({pattern} [, {flags} [, {stopline} [, {timeout}]]])
Number search for {pattern}
-searchcount([{options}]) Dict Get or update the last search count
+searchcount([{options}]) Dict Get or update the last search count
searchdecl({name} [, {global} [, {thisblock}]])
Number search for variable declaration
searchpair({start}, {middle}, {end} [, {flags} [, {skip} [...]]])
@@ -2698,7 +2701,7 @@ split({expr} [, {pat} [, {keepempty}]])
List make |List| from {pat} separated {expr}
sqrt({expr}) Float square root of {expr}
stdioopen({dict}) Number open stdio in a headless instance.
-stdpath({what}) String/List returns the standard path(s) for {what}
+stdpath({what}) String/List returns the standard path(s) for {what}
str2float({expr} [, {quoted}]) Float convert String to Float
str2list({expr} [, {utf8}]) List convert each character of {expr} to
ASCII/UTF-8 value
@@ -2734,7 +2737,7 @@ synID({lnum}, {col}, {trans}) Number syntax ID at {lnum} and {col}
synIDattr({synID}, {what} [, {mode}])
String attribute {what} of syntax ID {synID}
synIDtrans({synID}) Number translated syntax ID of {synID}
-synconcealed({lnum}, {col}) List info about concealing
+synconcealed({lnum}, {col}) List info about concealing
synstack({lnum}, {col}) List stack of syntax IDs at {lnum} and {col}
system({cmd} [, {input}]) String output of shell command/filter {cmd}
systemlist({cmd} [, {input}]) List output of shell command/filter {cmd}
@@ -2770,7 +2773,7 @@ values({dict}) List values in {dict}
virtcol({expr}) Number screen column of cursor or mark
visualmode([expr]) String last visual mode used
wait({timeout}, {condition}[, {interval}])
- Number Wait until {condition} is satisfied
+ Number Wait until {condition} is satisfied
wildmenumode() Number whether 'wildmenu' mode is active
win_execute({id}, {command} [, {silent}])
String execute {command} in window {id}
@@ -4161,11 +4164,12 @@ expand({string} [, {nosuf} [, {list}]]) *expand()*
Can also be used as a |method|: >
Getpattern()->expand()
-expandcmd({expr}) *expandcmd()*
- Expand special items in {expr} like what is done for an Ex
- command such as `:edit`. This expands special keywords, like
- with |expand()|, and environment variables, anywhere in
- {expr}. "~user" and "~/path" are only expanded at the start.
+expandcmd({string}) *expandcmd()*
+ Expand special items in String {string} like what is done for
+ an Ex command such as `:edit`. This expands special keywords,
+ like with |expand()|, and environment variables, anywhere in
+ {string}. "~user" and "~/path" are only expanded at the
+ start.
Returns the expanded string. Example: >
:echo expandcmd('make %<.o')
@@ -4549,6 +4553,21 @@ foreground() Move the Vim window to the foreground. Useful when sent from
|remote_foreground()| instead.
{only in the Win32 GUI and console version}
+fullcommand({name}) *fullcommand()*
+ Get the full command name from a short abbreviated command
+ name; see |20.2| for details on command abbreviations.
+
+ The string argument {name} may start with a `:` and can
+ include a [range], these are skipped and not returned.
+ Returns an empty string if a command doesn't exist or if it's
+ ambiguous (for user-defined commands).
+
+ For example `fullcommand('s')`, `fullcommand('sub')`,
+ `fullcommand(':%substitute')` all return "substitute".
+
+ Can also be used as a |method|: >
+ GetName()->fullcommand()
+<
*funcref()*
funcref({name} [, {arglist}] [, {dict}])
Just like |function()|, but the returned Funcref will lookup
@@ -4556,8 +4575,10 @@ funcref({name} [, {arglist}] [, {dict}])
function {name} is redefined later.
Unlike |function()|, {name} must be an existing user function.
- Also for autoloaded functions. {name} cannot be a builtin
- function.
+ It only works for an autoloaded function if it has already
+ been loaded (to avoid mistakenly loading the autoload script
+ when only intending to use the function name, use |function()|
+ instead). {name} cannot be a builtin function.
Can also be used as a |method|: >
GetFuncname()->funcref([arg])
@@ -5419,8 +5440,9 @@ getreg([{regname} [, 1 [, {list}]]]) *getreg()*
The result is a String, which is the contents of register
{regname}. Example: >
:let cliptext = getreg('*')
-< When {regname} was not set the result is an empty string.
- The {regname} argument is a string.
+< When register {regname} was not set the result is an empty
+ string.
+ The {regname} argument must be a string.
getreg('=') returns the last evaluated value of the expression
register. (For use in maps.)
@@ -6873,7 +6895,7 @@ match({expr}, {pat} [, {start} [, {count}]]) *match()*
GetText()->match('word')
GetList()->match('word')
<
- *matchadd()* *E798* *E799* *E801* *E957*
+ *matchadd()* *E798* *E799* *E801* *E957*
matchadd({group}, {pattern}[, {priority}[, {id} [, {dict}]]])
Defines a pattern to be highlighted in the current window (a
"match"). It will be highlighted with {group}. Returns an
@@ -7201,7 +7223,7 @@ mode([expr]) Return a string that indicates the current mode.
Rvc Virtual Replace mode completion |compl-generic|
Rvx Virtual Replace mode |i_CTRL-X| completion
c Command-line editing
- cv Vim Ex mode |Q| or |gQ|
+ cv Vim Ex mode |gQ|
r Hit-enter prompt
rm The -- more -- prompt
r? A |:confirm| query of some sort
@@ -7825,6 +7847,11 @@ reg_executing() *reg_executing()*
Returns an empty string when no register is being executed.
See |@|.
+reg_recorded() *reg_recorded()*
+ Returns the single letter name of the last recorded register.
+ Returns an empty string string when nothing was recorded yet.
+ See |q| and |Q|.
+
reg_recording() *reg_recording()*
Returns the single letter name of the register being recorded.
Returns an empty string string when not recording. See |q|.
@@ -11039,7 +11066,7 @@ See |:verbose-cmd| for more information.
command, use line breaks instead of |:bar|: >
:exe "func Foo()\necho 'foo'\nendfunc"
<
- *:delf* *:delfunction* *E130* *E131* *E933*
+ *:delf* *:delfunction* *E131* *E933*
:delf[unction][!] {name}
Delete function {name}.
{name} can also be a |Dictionary| entry that is a
@@ -13129,7 +13156,7 @@ code can be used: >
unlet scriptnames_output
==============================================================================
-The sandbox *eval-sandbox* *sandbox* *E48*
+The sandbox *eval-sandbox* *sandbox*
The 'foldexpr', 'formatexpr', 'includeexpr', 'indentexpr', 'statusline' and
'foldtext' options may be evaluated in a sandbox. This means that you are
@@ -13138,6 +13165,7 @@ safety for when these options are set from a modeline. It is also used when
the command from a tags file is executed and for CTRL-R = in the command line.
The sandbox is also used for the |:sandbox| command.
+ *E48*
These items are not allowed in the sandbox:
- changing the buffer text
- defining or changing mapping, autocommands, user commands
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt
index bbbe71ec3a..5486c87af9 100644
--- a/runtime/doc/filetype.txt
+++ b/runtime/doc/filetype.txt
@@ -24,12 +24,21 @@ 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 this file:
+Detail: The ":filetype on" command will load these files:
+ $VIMRUNTIME/filetype.lua
$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
- contents of the file.
+ filetype.lua creates an autocommand that fires for all BufNewFile and
+ BufRead events. It tries to detect the filetype based off of the
+ file's extension or name.
+
+ filetype.vim is a Vim script that defines autocommands for the
+ BufNewFile and BufRead events. In contrast to filetype.lua, this
+ file creates separate BufNewFile and BufRead events for each filetype
+ pattern.
+
+ If the file type is not found by the name, the file
+ $VIMRUNTIME/scripts.vim is used to detect it from the contents of the
+ file.
When the GUI is running or will start soon, the |menu.vim| script is
also sourced. See |'go-M'| about avoiding that.
@@ -122,14 +131,15 @@ shell script: "#!/bin/csh".
argument was used.
*filetype-overrule*
-When the same extension is used for two filetypes, Vim tries to guess what
-kind of file it is. This doesn't always work. A number of global variables
-can be used to overrule the filetype used for certain extensions:
+When the same extension is used for multiple filetypes, Vim tries to guess
+what kind of file it is. This doesn't always work. A number of global
+variables can be used to overrule the filetype used for certain extensions:
file name variable ~
*.asa g:filetype_asa |ft-aspvbs-syntax| |ft-aspperl-syntax|
*.asm g:asmsyntax |ft-asm-syntax|
*.asp g:filetype_asp |ft-aspvbs-syntax| |ft-aspperl-syntax|
+ *.bas g:filetype_bas |ft-basic-syntax|
*.fs g:filetype_fs |ft-forth-syntax|
*.i g:filetype_i |ft-progress-syntax|
*.inc g:filetype_inc
@@ -149,9 +159,10 @@ is used. The default value is set like this: >
This means that the contents of compressed files are not inspected.
*new-filetype*
-If a file type that you want to use is not detected yet, there are four ways
-to add it. In any way, it's better not to modify the $VIMRUNTIME/filetype.vim
-file. It will be overwritten when installing a new version of Vim.
+If a file type that you want to use is not detected yet, there are a few ways
+to add it. In any way, it's better not to modify the $VIMRUNTIME/filetype.lua
+or $VIMRUNTIME/filetype.vim files. They will be overwritten when installing a
+new version of Nvim.
A. If you want to overrule all default file type checks.
This works by writing one file for each filetype. The disadvantage is that
@@ -191,7 +202,7 @@ B. If you want to detect your file after the default file type checks.
au BufRead,BufNewFile * if &ft == 'pascal' | set ft=mypascal
| endif
-C. If your file type can be detected by the file name.
+C. If your file type can be detected by the file name or extension.
1. Create your user runtime directory. You would normally use the first
item of the 'runtimepath' option. Example for Unix: >
:!mkdir -p ~/.config/nvim
@@ -206,9 +217,38 @@ C. If your file type can be detected by the file name.
au! BufRead,BufNewFile *.mine setfiletype mine
au! BufRead,BufNewFile *.xyz setfiletype drawing
augroup END
-< Write this file as "filetype.vim" in your user runtime directory. For
+<
+ Write this file as "filetype.vim" in your user runtime directory. For
example, for Unix: >
:w ~/.config/nvim/filetype.vim
+<
+ Alternatively, create a file called "filetype.lua" that adds new
+ filetypes.
+ Example: >
+ vim.filetype.add({
+ extension = {
+ foo = "fooscript",
+ },
+ filename = {
+ [".foorc"] = "foorc",
+ },
+ pattern = {
+ [".*/etc/foo/.*%.conf"] = "foorc",
+ },
+ })
+<
+ See |vim.filetype.add()|.
+ *g:do_filetype_lua*
+ For now, Lua filetype detection is opt-in. You can enable it by adding
+ the following to your |init.vim|: >
+ let g:do_filetype_lua = 1
+< *g:did_load_filetypes*
+ In either case, the builtin filetype detection provided by Nvim can be
+ disabled by setting the did_load_filetypes global variable. If this
+ variable exists, $VIMRUNTIME/filetype.vim will not run.
+ Example: >
+ " Disable filetype.vim
+ let g:did_load_filetypes = 1
< 3. To use the new filetype detection you must restart Vim.
@@ -245,9 +285,9 @@ D. If your filetype can only be detected by inspecting the contents of the
$VIMRUNTIME/scripts.vim.
*remove-filetype*
-If a file type is detected that is wrong for you, install a filetype.vim or
-scripts.vim to catch it (see above). You can set 'filetype' to a non-existing
-name to avoid that it will be set later anyway: >
+If a file type is detected that is wrong for you, install a filetype.lua,
+filetype.vim or scripts.vim to catch it (see above). You can set 'filetype' to
+a non-existing name to avoid that it will be set later anyway: >
:set filetype=ignored
If you are setting up a system with many users, and you don't want each user
@@ -314,12 +354,12 @@ define yourself. There are a few ways to avoid this:
You need to define your own mapping before the plugin is loaded (before
editing a file of that type). The plugin will then skip installing the
default mapping.
- *no_mail_maps*
+ *no_mail_maps* *g:no_mail_maps*
3. Disable defining mappings for a specific filetype by setting a variable,
which contains the name of the filetype. For the "mail" filetype this
would be: >
:let no_mail_maps = 1
-< *no_plugin_maps*
+< *no_plugin_maps* *g:no_plugin_maps*
4. Disable defining mappings for all filetypes by setting a variable: >
:let no_plugin_maps = 1
<
diff --git a/runtime/doc/fold.txt b/runtime/doc/fold.txt
index 80c934d13b..8bc47a3b10 100644
--- a/runtime/doc/fold.txt
+++ b/runtime/doc/fold.txt
@@ -501,7 +501,9 @@ Note the use of backslashes to avoid some characters to be interpreted by the
:endfunction
Evaluating 'foldtext' is done in the |sandbox|. The current window is set to
-the window that displays the line. Errors are ignored.
+the window that displays the line.
+
+Errors are ignored. For debugging set the 'debug' option to "throw".
The default value is |foldtext()|. This returns a reasonable text for most
types of folding. If you don't like it, you can specify your own 'foldtext'
diff --git a/runtime/doc/helphelp.txt b/runtime/doc/helphelp.txt
index e7b489d6e1..03ec8966d4 100644
--- a/runtime/doc/helphelp.txt
+++ b/runtime/doc/helphelp.txt
@@ -164,7 +164,7 @@ If you would like to open the help in the current window, see this tip:
The initial height of the help window can be set with the 'helpheight' option
(default 20).
-
+ *help-buffer-options*
When the help buffer is created, several local options are set to make sure
the help text is displayed as it was intended:
'iskeyword' nearly all ASCII chars except ' ', '*', '"' and '|'
@@ -219,7 +219,7 @@ command: >
<
*:helpt* *:helptags*
- *E154* *E150* *E151* *E152* *E153* *E670* *E856*
+ *E150* *E151* *E152* *E153* *E154* *E670* *E856*
:helpt[ags] [++t] {dir}
Generate the help tags file(s) for directory {dir}.
When {dir} is ALL then all "doc" directories in
diff --git a/runtime/doc/if_cscop.txt b/runtime/doc/if_cscop.txt
index f05b3bb8ed..8947aefc1b 100644
--- a/runtime/doc/if_cscop.txt
+++ b/runtime/doc/if_cscop.txt
@@ -40,7 +40,7 @@ See |cscope-usage| to get started.
==============================================================================
Cscope commands *cscope-commands*
- *:cscope* *:cs* *:scs* *:scscope* *E259* *E262* *E561* *E560*
+ *:cscope* *:cs* *:scs* *:scscope* *E259* *E262* *E560* *E561*
All cscope commands are accessed through suboptions to the cscope commands.
`:cscope` or `:cs` is the main command
`:scscope` or `:scs` does the same and splits the window
diff --git a/runtime/doc/indent.txt b/runtime/doc/indent.txt
index 1b42092616..a76f8636f8 100644
--- a/runtime/doc/indent.txt
+++ b/runtime/doc/indent.txt
@@ -872,7 +872,7 @@ For example, with N = 1, this will give:
*PHP_outdentphpescape*
To indent PHP escape tags as the surrounding non-PHP code (only affects the
PHP escape tags): >
-:let g:PHP_outdentphpescape = 0
+ :let g:PHP_outdentphpescape = 0
-------------
*PHP_removeCRwhenUnix*
@@ -1199,7 +1199,7 @@ comments will be indented according to the correctly indented code.
VIM *ft-vim-indent*
-
+ *g:vim_indent_cont*
For indenting Vim scripts there is one variable that specifies the amount of
indent for a continuation line, a line that starts with a backslash: >
diff --git a/runtime/doc/index.txt b/runtime/doc/index.txt
index baa7bc1992..d8689e2c65 100644
--- a/runtime/doc/index.txt
+++ b/runtime/doc/index.txt
@@ -339,7 +339,6 @@ tag char note action in Normal mode ~
insert text, repeat N times
|P| ["x]P 2 put the text [from register x] before the
cursor N times
-|Q| Q switch to "Ex" mode
|R| R 2 enter replace mode: overtype existing
characters, repeat the entered text N-1
times
@@ -401,6 +400,7 @@ tag char note action in Normal mode ~
|q| q{0-9a-zA-Z"} record typed characters into named register
{0-9a-zA-Z"} (uppercase to append)
|q| q (while recording) stops recording
+|Q| Q replay last recorded macro
|q:| q: edit : command-line in command-line window
|q/| q/ edit / command-line in command-line window
|q?| q? edit ? command-line in command-line window
diff --git a/runtime/doc/insert.txt b/runtime/doc/insert.txt
index fd1d0f8ea6..ae2b9c4418 100644
--- a/runtime/doc/insert.txt
+++ b/runtime/doc/insert.txt
@@ -76,6 +76,8 @@ CTRL-U Delete all entered characters before the cursor in the current
line. If there are no newly entered characters and
'backspace' is not empty, delete all characters before the
cursor in the current line.
+ If C-indenting is enabled the indent will be adjusted if the
+ line becomes blank.
See |i_backspacing| about joining lines.
*i_CTRL-U-default*
By default, sets a new undo point before deleting.
@@ -828,7 +830,7 @@ space is preferred). Maximum line length is 510 bytes.
For an example, imagine the 'thesaurus' file has a line like this: >
angry furious mad enraged
-<Placing the cursor after the letters "ang" and typing CTRL-X CTRL-T would
+Placing the cursor after the letters "ang" and typing CTRL-X CTRL-T would
complete the word "angry"; subsequent presses would change the word to
"furious", "mad" etc.
@@ -840,7 +842,7 @@ https://github.com/vim/vim/issues/629#issuecomment-443293282
Unpack thesaurus_pkg.zip, put the thesaurus.txt file somewhere, e.g.
~/.vim/thesaurus/english.txt, and the 'thesaurus' option to this file name.
-
+
Completing keywords with 'thesaurusfunc' *compl-thesaurusfunc*
If the 'thesaurusfunc' option is set, then the user specified function is
@@ -1878,6 +1880,9 @@ When 'autoindent' is on, the indent for a new line is obtained from the
previous line. When 'smartindent' or 'cindent' is on, the indent for a line
is automatically adjusted for C programs.
+'formatoptions' can be set to copy the comment leader when opening a new
+line.
+
'textwidth' can be set to the maximum width for a line. When a line becomes
too long when appending characters a line break is automatically inserted.
diff --git a/runtime/doc/intro.txt b/runtime/doc/intro.txt
index a89263861b..54999fa163 100644
--- a/runtime/doc/intro.txt
+++ b/runtime/doc/intro.txt
@@ -322,7 +322,6 @@ notation meaning equivalent decimal value(s) ~
<Bar> vertical bar | 124 *<Bar>*
<Del> delete 127
<CSI> command sequence intro ALT-Esc 155 *<CSI>*
-<xCSI> CSI when typed in the GUI *<xCSI>*
<EOL> end-of-line (can be <CR>, <NL> or <CR><NL>,
depends on system and 'fileformat') *<EOL>*
@@ -563,8 +562,8 @@ The command CTRL-\ CTRL-G or <C-\><C-G> can be used to go to Insert mode when
make sure Vim is in the mode indicated by 'insertmode', without knowing in
what mode Vim currently is.
- *gQ* *Q* *mode-Ex* *Ex-mode* *Ex* *EX* *E501*
-Q or gQ Switch to Ex mode. This is like typing ":" commands
+ *gQ* *mode-Ex* *Ex-mode* *Ex* *EX* *E501*
+gQ Switch to Ex mode. This is like typing ":" commands
one after another, except:
- You don't have to keep pressing ":".
- The screen doesn't get updated after each command.
diff --git a/runtime/doc/lsp-extension.txt b/runtime/doc/lsp-extension.txt
index d13303ada6..6e9ad940c7 100644
--- a/runtime/doc/lsp-extension.txt
+++ b/runtime/doc/lsp-extension.txt
@@ -60,7 +60,7 @@ The example will:
return nil
end
local dir = bufname
- -- Just in case our algo is buggy, don't infinite loop.
+ -- Just in case our algorithm is buggy, don't infinite loop.
for _ = 1, 100 do
local did_change
dir, did_change = dirname(dir)
diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt
index 3793a21f36..f6fcbe8fb9 100644
--- a/runtime/doc/lsp.txt
+++ b/runtime/doc/lsp.txt
@@ -214,7 +214,7 @@ For |lsp-request|, each |lsp-handler| has this signature: >
request, a table with information about the error
is sent. Otherwise, it is `nil`. See |lsp-response|.
{result} (Result | Params | nil)
- When the language server is able to succesfully
+ When the language server is able to successfully
complete a request, this contains the `result` key
of the response. See |lsp-response|.
{ctx} (table)
@@ -236,7 +236,7 @@ For |lsp-request|, each |lsp-handler| has this signature: >
{config} (table)
Configuration for the handler.
- Each handler can define it's own configuration
+ Each handler can define its own configuration
table that allows users to customize the behavior
of a particular handler.
@@ -274,7 +274,7 @@ For |lsp-notification|, each |lsp-handler| has this signature: >
{config} (table)
Configuration for the handler.
- Each handler can define it's own configuration
+ Each handler can define its own configuration
table that allows users to customize the behavior
of a particular handler.
@@ -369,7 +369,7 @@ Handlers can be set by:
For example: >
vim.lsp.start_client {
- ..., -- Other configuration ommitted.
+ ..., -- Other configuration omitted.
handlers = {
["textDocument/definition"] = my_custom_server_definition
},
@@ -394,6 +394,9 @@ in the following order:
2. Handler defined in |vim.lsp.start_client()|, if any.
3. Handler defined in |vim.lsp.handlers|, if any.
+ *vim.lsp.log_levels*
+Log levels are defined in |vim.log.levels|
+
VIM.LSP.PROTOCOL *vim.lsp.protocol*
@@ -444,7 +447,7 @@ LspCodeLens
|nvim_buf_set_extmark()|.
LspCodeLensSeparator *hl-LspCodeLensSeparator*
- Used to color the seperator between two or more code lens.
+ Used to color the separator between two or more code lens.
*lsp-highlight-signature*
@@ -485,6 +488,16 @@ buf_attach_client({bufnr}, {client_id}) *vim.lsp.buf_attach_client()*
{bufnr} (number) Buffer handle, or 0 for current
{client_id} (number) Client id
+buf_detach_client({bufnr}, {client_id}) *vim.lsp.buf_detach_client()*
+ Detaches client from the specified buffer. Note: While the
+ server is notified that the text document (buffer) was closed,
+ it is still able to send notifications should it ignore this
+ notification.
+
+ Parameters: ~
+ {bufnr} number Buffer handle, or 0 for current
+ {client_id} number Client id
+
buf_get_clients({bufnr}) *vim.lsp.buf_get_clients()*
Gets a map of client_id:client pairs for the given buffer,
where each value is a |vim.lsp.client| object.
@@ -736,8 +749,8 @@ omnifunc({findstart}, {base}) *vim.lsp.omnifunc()*
set_log_level({level}) *vim.lsp.set_log_level()*
Sets the global log level for LSP logging.
- Levels by name: "trace", "debug", "info", "warn", "error"
- Level numbers begin with "trace" at 0
+ Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR"
+ Level numbers begin with "TRACE" at 0
Use `lsp.log_levels` for reverse lookup.
@@ -825,10 +838,10 @@ start_client({config}) *vim.lsp.start_client()*
throws an error. `code` is a number
describing the error. Other arguments
may be passed depending on the error
- kind. See |vim.lsp.client_errors| for
- possible errors. Use
- `vim.lsp.client_errors[code]` to get
- human-friendly name.
+ kind. See |vim.lsp.rpc.client_errors|
+ for possible errors. Use
+ `vim.lsp.rpc.client_errors[code]` to
+ get human-friendly name.
{before_init} Callback with parameters
(initialize_params, config) invoked
before the LSP "initialize" phase,
@@ -995,7 +1008,7 @@ document_highlight() *vim.lsp.buf.document_highlight()*
Send request to the server to resolve document highlights for
the current text document position. This request can be
triggered by a key mapping or by events such as `CursorHold` ,
- eg:
+ e.g.:
>
autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
autocmd CursorHoldI <buffer> lua vim.lsp.buf.document_highlight()
@@ -1011,11 +1024,12 @@ document_symbol() *vim.lsp.buf.document_symbol()*
Lists all symbols in the current buffer in the quickfix
window.
-execute_command({command}) *vim.lsp.buf.execute_command()*
+execute_command({command_params}) *vim.lsp.buf.execute_command()*
Executes an LSP server command.
Parameters: ~
- {command} A valid `ExecuteCommandParams` object
+ {command_params} table A valid `ExecuteCommandParams`
+ object
See also: ~
https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand
@@ -1291,7 +1305,7 @@ hover({_}, {result}, {ctx}, {config}) *vim.lsp.handlers.hover()*
{config} table Configuration table.
• border: (default=nil)
• Add borders to the floating window
- • See |vim.api.nvim_open_win()|
+ • See |nvim_open_win()|
*vim.lsp.handlers.signature_help()*
signature_help({_}, {result}, {ctx}, {config})
@@ -1318,7 +1332,7 @@ signature_help({_}, {result}, {ctx}, {config})
Lua module: vim.lsp.util *lsp-util*
*vim.lsp.util.apply_text_document_edit()*
-apply_text_document_edit({text_document_edit}, {index})
+apply_text_document_edit({text_document_edit}, {index}, {offset_encoding})
Applies a `TextDocumentEdit` , which is a list of changes to a
single document.
@@ -1338,18 +1352,19 @@ apply_text_edits({text_edits}, {bufnr}, {offset_encoding})
Parameters: ~
{text_edits} table list of `TextEdit` objects
{bufnr} number Buffer id
- {offset_encoding} string utf-8|utf-16|utf-32|nil defaults
- to encoding of first client of `bufnr`
+ {offset_encoding} string utf-8|utf-16|utf-32 defaults to
+ encoding of first client of `bufnr`
See also: ~
https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit
*vim.lsp.util.apply_workspace_edit()*
-apply_workspace_edit({workspace_edit})
+apply_workspace_edit({workspace_edit}, {offset_encoding})
Applies a `WorkspaceEdit` .
Parameters: ~
- {workspace_edit} (table) `WorkspaceEdit`
+ {workspace_edit} table `WorkspaceEdit`
+ {offset_encoding} string utf-8|utf-16|utf-32 (required)
buf_clear_references({bufnr}) *vim.lsp.util.buf_clear_references()*
Removes document highlights from a buffer.
@@ -1366,9 +1381,7 @@ buf_highlight_references({bufnr}, {references}, {offset_encoding})
{references} table List of `DocumentHighlight`
objects to highlight
{offset_encoding} string One of "utf-8", "utf-16",
- "utf-32", or nil. Defaults to
- `offset_encoding` of first client of
- `bufnr`
+ "utf-32".
See also: ~
https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#documentHighlight
@@ -1457,16 +1470,19 @@ get_effective_tabstop({bufnr}) *vim.lsp.util.get_effective_tabstop()*
See also: ~
|softtabstop|
-jump_to_location({location}) *vim.lsp.util.jump_to_location()*
+ *vim.lsp.util.jump_to_location()*
+jump_to_location({location}, {offset_encoding})
Jumps to a location.
Parameters: ~
- {location} ( `Location` | `LocationLink` )
+ {location} table ( `Location` | `LocationLink` )
+ {offset_encoding} string utf-8|utf-16|utf-32 (required)
Return: ~
`true` if the jump succeeded
-locations_to_items({locations}) *vim.lsp.util.locations_to_items()*
+ *vim.lsp.util.locations_to_items()*
+locations_to_items({locations}, {offset_encoding})
Returns the items with the byte position calculated correctly
and in sorted order, for display in quickfix and location
lists.
@@ -1475,8 +1491,10 @@ locations_to_items({locations}) *vim.lsp.util.locations_to_items()*
|setqflist()| or |setloclist()|.
Parameters: ~
- {locations} (table) list of `Location` s or
- `LocationLink` s
+ {locations} table list of `Location` s or
+ `LocationLink` s
+ {offset_encoding} string offset_encoding for locations
+ utf-8|utf-16|utf-32
Return: ~
(table) list of items
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt
index 630df16e79..3d4abed550 100644
--- a/runtime/doc/lua.txt
+++ b/runtime/doc/lua.txt
@@ -249,13 +249,15 @@ arguments separated by " " (space) instead of "\t" (tab).
*:lua*
:[range]lua {chunk}
Executes Lua chunk {chunk}.
-
+ if {chunk} starts with "=" the rest of the chunk is
+ evaluated as an expression and printed. `:lua =expr`
+ is equivalent to `:lua print(vim.inspect(expr))`
Examples: >
:lua vim.api.nvim_command('echo "Hello, Nvim!"')
< To see the Lua version: >
:lua print(_VERSION)
< To see the LuaJIT version: >
- :lua print(jit.version)
+ :lua =jit.version
<
*:lua-heredoc*
:[range]lua << [endmarker]
@@ -272,7 +274,7 @@ arguments separated by " " (space) instead of "\t" (tab).
lua << EOF
local linenr = vim.api.nvim_win_get_cursor(0)[1]
local curline = vim.api.nvim_buf_get_lines(
- 0, linenr, linenr + 1, false)[1]
+ 0, linenr - 1, linenr, false)[1]
print(string.format("Current line [%d] has %d bytes",
linenr, #curline))
EOF
@@ -708,6 +710,38 @@ vim.mpack.decode({str}) *vim.mpack.decode*
Decodes (or "unpacks") the msgpack-encoded {str} to a Lua object.
------------------------------------------------------------------------------
+VIM.SPELL *lua-spell*
+
+vim.spell.check({str}) *vim.spell.check()*
+ Check {str} for spelling errors. Similar to the Vimscript function
+ |spellbadword()|.
+
+ Note: The behaviour of this function is dependent on: 'spelllang',
+ 'spellfile', 'spellcapcheck' and 'spelloptions' which can all be local
+ to the buffer. Consider calling this with |nvim_buf_call()|.
+
+ Example: >
+ vim.spell.check("the quik brown fox")
+ -->
+ {
+ {'quik', 'bad', 4}
+ }
+<
+
+ Parameters: ~
+ {str} String to spell check.
+
+ Return: ~
+ List of tuples with three items:
+ - The badly spelled word.
+ - The type of the spelling error:
+ "bad" spelling mistake
+ "rare" rare word
+ "local" word only valid in another region
+ "caps" word should start with Capital
+ - The position in {str} where the word begins.
+
+------------------------------------------------------------------------------
VIM *lua-builtin*
vim.api.{func}({...}) *vim.api*
@@ -759,9 +793,9 @@ vim.stricmp({a}, {b}) *vim.stricmp()*
respectively.
vim.str_utfindex({str}[, {index}]) *vim.str_utfindex()*
- Convert byte index to UTF-32 and UTF-16 indicies. If {index} is not
- supplied, the length of the string is used. All indicies are zero-based.
- Returns two values: the UTF-32 and UTF-16 indicies respectively.
+ Convert byte index to UTF-32 and UTF-16 indices. If {index} is not
+ supplied, the length of the string is used. All indices are zero-based.
+ Returns two values: the UTF-32 and UTF-16 indices respectively.
Embedded NUL bytes are treated as terminating the string. Invalid
UTF-8 bytes, and embedded surrogates are counted as one code
@@ -881,6 +915,15 @@ vim.types *vim.types*
`vim.types.dictionary` will not change or that `vim.types` table will
only contain values for these three types.
+ *log_levels* *vim.log.levels*
+Log levels are one of the values defined in `vim.log.levels`:
+
+ vim.log.levels.DEBUG
+ vim.log.levels.ERROR
+ vim.log.levels.INFO
+ vim.log.levels.TRACE
+ vim.log.levels.WARN
+
------------------------------------------------------------------------------
LUA-VIMSCRIPT BRIDGE *lua-vimscript*
@@ -1197,19 +1240,32 @@ inspect({object}, {options}) *vim.inspect()*
https://github.com/kikito/inspect.lua
https://github.com/mpeterv/vinspect
-notify({msg}, {log_level}, {opts}) *vim.notify()*
- Notification provider
+notify({msg}, {level}, {opts}) *vim.notify()*
+ Display a notification to the user.
- Without a runtime, writes to :Messages
+ This function can be overridden by plugins to display
+ notifications using a custom provider (such as the system
+ notification provider). By default, writes to |:messages|.
Parameters: ~
- {msg} string Content of the notification to show to
- the user
- {log_level} number|nil enum from vim.log.levels
- {opts} table|nil additional options (timeout, etc)
+ {msg} string Content of the notification to show to the
+ user.
+ {level} number|nil One of the values from
+ |vim.log.levels|.
+ {opts} table|nil Optional parameters. Unused by default.
- See also: ~
- :help nvim_notify
+notify_once({msg}, {level}, {opts}) *vim.notify_once()*
+ Display a notification only one time.
+
+ Like |vim.notify()|, but subsequent calls with the same
+ message will not display a notification.
+
+ Parameters: ~
+ {msg} string Content of the notification to show to the
+ user.
+ {level} number|nil One of the values from
+ |vim.log.levels|.
+ {opts} table|nil Optional parameters. Unused by default.
on_key({fn}, {ns_id}) *vim.on_key()*
Adds Lua function {fn} with namespace id {ns_id} as a listener
@@ -1273,6 +1329,18 @@ paste({lines}, {phase}) *vim.paste()*
See also: ~
|paste|
+pretty_print({...}) *vim.pretty_print()*
+ Prints given arguments in human-readable format. Example: >
+ -- Print highlight group Normal and store it's contents in a variable.
+ local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true))
+<
+
+ Return: ~
+ given arguments.
+
+ See also: ~
+ |vim.inspect()|
+
region({bufnr}, {pos1}, {pos2}, {regtype}, {inclusive}) *vim.region()*
Get a table of lines with start, end columns for a region
marked by two points
@@ -1615,16 +1683,25 @@ validate({opt}) *vim.validate()*
=> error('arg1: expected even number, got 3')
<
+ If multiple types are valid they can be given as a list. >
+
+ vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
+ => NOP (success)
+
+ vim.validate{arg1={1, {'string', table'}}}
+ => error('arg1: expected string|table, got number')
+<
+
Parameters: ~
- {opt} Map of parameter names to validations. Each key is
- a parameter name; each value is a tuple in one of
- these forms:
+ {opt} table of parameter names to validations. Each key
+ is a parameter name; each value is a tuple in one
+ of these forms:
1. (arg_value, type_name, optional)
• arg_value: argument value
- • type_name: string type name, one of: ("table",
- "t", "string", "s", "number", "n", "boolean",
- "b", "function", "f", "nil", "thread",
- "userdata")
+ • type_name: string|table type name, one of:
+ ("table", "t", "string", "s", "number", "n",
+ "boolean", "b", "function", "f", "nil",
+ "thread", "userdata") or list of them.
• optional: (optional) boolean, if true, `nil`
is valid
@@ -1728,4 +1805,157 @@ select({items}, {opts}, {on_choice}) *vim.ui.select()*
1-based index of `item` within `item` . `nil`
if the user aborted the dialog.
+
+==============================================================================
+Lua module: filetype *lua-filetype*
+
+add({filetypes}) *vim.filetype.add()*
+ Add new filetype mappings.
+
+ Filetype mappings can be added either by extension or by
+ filename (either the "tail" or the full file path). The full
+ file path is checked first, followed by the file name. If a
+ match is not found using the filename, then the filename is
+ matched against the list of patterns (sorted by priority)
+ until a match is found. Lastly, if pattern matching does not
+ find a filetype, then the file extension is used.
+
+ The filetype can be either a string (in which case it is used
+ as the filetype directly) or a function. If a function, it
+ takes the full path and buffer number of the file as arguments
+ (along with captures from the matched pattern, if any) and
+ should return a string that will be used as the buffer's
+ filetype.
+
+ Filename patterns can specify an optional priority to resolve
+ cases when a file path matches multiple patterns. Higher
+ priorities are matched first. When omitted, the priority
+ defaults to 0.
+
+ See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
+
+ Note that Lua filetype detection is only enabled when
+ |g:do_filetype_lua| is set to 1.
+
+ Example: >
+
+ vim.filetype.add({
+ extension = {
+ foo = "fooscript",
+ bar = function(path, bufnr)
+ if some_condition() then
+ return "barscript"
+ end
+ return "bar"
+ end,
+ },
+ filename = {
+ [".foorc"] = "toml",
+ ["/etc/foo/config"] = "toml",
+ },
+ pattern = {
+ [".*&zwj;/etc/foo/.*"] = "fooscript",
+ -- Using an optional priority
+ [".*&zwj;/etc/foo/.*%.conf"] = { "dosini", { priority = 10 } },
+ ["README.(%a+)$"] = function(path, bufnr, ext)
+ if ext == "md" then
+ return "markdown"
+ elseif ext == "rst" then
+ return "rst"
+ end
+ end,
+ },
+ })
+<
+
+ Parameters: ~
+ {filetypes} table A table containing new filetype maps
+ (see example).
+
+match({name}, {bufnr}) *vim.filetype.match()*
+ Set the filetype for the given buffer from a file name.
+
+ Parameters: ~
+ {name} string File name (can be an absolute or relative
+ path)
+ {bufnr} number|nil The buffer to set the filetype for.
+ Defaults to the current buffer.
+
+
+==============================================================================
+Lua module: keymap *lua-keymap*
+
+del({modes}, {lhs}, {opts}) *vim.keymap.del()*
+ Remove an existing mapping. Examples: >
+
+ vim.keymap.del('n', 'lhs')
+
+ vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
+<
+
+ Parameters: ~
+ {opts} table A table of optional arguments:
+ • buffer: (number or boolean) Remove a mapping
+ from the given buffer. When "true" or 0, use the
+ current buffer.
+
+ See also: ~
+ |vim.keymap.set()|
+
+set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
+ Add a new |mapping|. Examples: >
+
+ -- Can add mapping to Lua functions
+ vim.keymap.set('n', 'lhs', function() print("real lua function") end)
+
+ -- Can use it to map multiple modes
+ vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer=true })
+
+ -- Can add mapping for specific buffer
+ vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 })
+
+ -- Expr mappings
+ vim.keymap.set('i', '<Tab>', function()
+ return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
+ end, { expr = true })
+ -- <Plug> mappings
+ vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)')
+<
+
+ Note that in a mapping like: >
+
+ vim.keymap.set('n', 'asdf', require('jkl').my_fun)
+<
+
+ the require('jkl') gets evaluated during this call in order to
+ access the function. If you want to avoid this cost at startup
+ you can wrap it in a function, for example: >
+
+ vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end)
+<
+
+ Parameters: ~
+ {mode} string|table Same mode short names as
+ |nvim_set_keymap()|. Can also be list of modes to
+ create mapping on multiple modes.
+ {lhs} string Left-hand side |{lhs}| of the mapping.
+ {rhs} string|function Right-hand side |{rhs}| of the
+ mapping. Can also be a Lua function.
+ {opts} table A table of |:map-arguments| such as
+ "silent". In addition to the options listed in
+ |nvim_set_keymap()|, this table also accepts the
+ following keys:
+ • replace_keycodes: (boolean, default true) When
+ both this and expr is "true",
+ |nvim_replace_termcodes()| is applied to the
+ result of Lua expr maps.
+ • remap: (boolean) Make the mapping recursive.
+ This is the inverse of the "noremap" option from
+ |nvim_set_keymap()|. Default `true` if `lhs` is
+ a string starting with `<plug>`
+ (case-insensitive), `false` otherwise.
+
+ See also: ~
+ |nvim_set_keymap()|
+
vim:tw=78:ts=8:ft=help:norl:
diff --git a/runtime/doc/map.txt b/runtime/doc/map.txt
index 0ea2565694..9244638788 100644
--- a/runtime/doc/map.txt
+++ b/runtime/doc/map.txt
@@ -82,8 +82,7 @@ modes.
map command applies. The mapping may remain defined
for other modes where it applies.
It also works when {lhs} matches the {rhs} of a
- mapping. This is for when when an abbreviation
- applied.
+ mapping. This is for when an abbreviation applied.
Note: Trailing spaces are included in the {lhs}. This
unmap does NOT work: >
:map @@ foo
@@ -158,7 +157,7 @@ type "a", then "bar" will get inserted.
"<unique>" can be used in any order. They must appear right after the
command, before any other arguments.
- *:map-local* *:map-<buffer>* *E224* *E225*
+ *:map-local* *:map-<buffer>* *:map-buffer* *E224* *E225*
If the first argument to one of these commands is "<buffer>" the mapping will
be effective in the current buffer only. Example: >
:map <buffer> ,w /[.,;]<CR>
@@ -211,7 +210,7 @@ Note: ":map <script>" and ":noremap <script>" do the same thing. The
"<script>" overrules the command name. Using ":noremap <script>" is
preferred, because it's clearer that remapping is (mostly) disabled.
- *:map-<unique>* *E226* *E227*
+ *:map-<unique>* *:map-unique* *E226* *E227*
If the first argument to one of these commands is "<unique>" and it is used to
define a new mapping or abbreviation, the command will fail if the mapping or
abbreviation already exists. Example: >
@@ -245,7 +244,7 @@ go through the main loop (e.g. to update the display), return "\<Ignore>".
This is similar to "nothing" but makes Vim return from the loop that waits for
input.
-Also, keep in mind that the expression may be evaluated when looking for
+Keep in mind that the expression may be evaluated when looking for
typeahead, before the previous command has been executed. For example: >
func StoreColumn()
let g:column = col('.')
@@ -837,8 +836,7 @@ g@{motion} Call the function set by the 'operatorfunc' option.
"line" {motion} was |linewise|
"char" {motion} was |charwise|
"block" {motion} was |blockwise-visual|
- Although "block" would rarely appear, since it can
- only result from Visual mode where "g@" is not useful.
+ The type can be forced, see |forced-motion|.
Here is an example that counts the number of spaces with <F4>: >
@@ -1219,7 +1217,7 @@ scripts.
*:command-verbose*
When 'verbose' is non-zero, listing a command will also display where it was
-last defined. Example: >
+last defined and any completion argument. Example: >
:verbose command TOhtml
< Name Args Range Complete Definition ~
@@ -1248,8 +1246,8 @@ See |:verbose-cmd| for more information.
Command attributes ~
-
-User-defined commands are treated by Vim just like any other Ex commands. They
+ *command-attributes*
+User-defined commands are treated by Nvim just like any other Ex commands. They
can have arguments, or have a range specified. Arguments are subject to
completion as filenames, buffers, etc. Exactly how this works depends upon the
command's attributes, which are specified when the command is defined.
@@ -1334,6 +1332,8 @@ completion can be enabled:
-complete=custom,{func} custom completion, defined via {func}
-complete=customlist,{func} custom completion, defined via {func}
+If you specify completion while there is nothing to complete (-nargs=0, the
+default) then you get error *E1208* .
Note: That some completion methods might expand environment variables.
@@ -1436,6 +1436,9 @@ There are some special cases as well:
-register The first argument to the command can be an optional
register name (like :del, :put, :yank).
-buffer The command will only be available in the current buffer.
+ -keepscript Do not use the location of where the user command was
+ defined for verbose messages, use the location of where
+ the user command was invoked.
In the cases of the -count and -register attributes, if the optional argument
is supplied, it is removed from the argument list and is available to the
diff --git a/runtime/doc/mbyte.txt b/runtime/doc/mbyte.txt
index 3bbf36c642..2aa49cee1e 100644
--- a/runtime/doc/mbyte.txt
+++ b/runtime/doc/mbyte.txt
@@ -489,8 +489,8 @@ Use the RPM or port for your system.
window specific to the input method.
-USING XIM *multibyte-input* *E284* *E286* *E287* *E288*
- *E285* *E289*
+USING XIM *multibyte-input* *E284* *E285* *E286* *E287*
+ *E288* *E289*
Note that Display and Input are independent. It is possible to see your
language even though you have no input method for it. But when your Display
diff --git a/runtime/doc/message.txt b/runtime/doc/message.txt
index 6fbd9ec922..950028d9cc 100644
--- a/runtime/doc/message.txt
+++ b/runtime/doc/message.txt
@@ -112,7 +112,8 @@ wiped out a buffer which contains a mark or is referenced in another way.
*E95* >
Buffer with this name already exists
-You cannot have two buffers with the same name.
+You cannot have two buffers with exactly the same name. This includes the
+path leading to the file.
*E72* >
Close error on swap file
@@ -513,10 +514,10 @@ If you type "gq", it will execute this mapping, which will call "gq" again.
*E22* >
Scripts nested too deep
-Scripts can be read with the "-s" command-line argument and with the ":source"
-command. The script can then again read another script. This can continue
-for about 14 levels. When more nesting is done, Vim assumes that there is a
-recursive loop somewhere and stops with this error message.
+Scripts can be read with the "-s" command-line argument and with the
+`:source!` command. The script can then again read another script. This can
+continue for about 14 levels. When more nesting is done, Vim assumes that
+there is a recursive loop and stops with this error message.
*E300* >
Swap file already exists (symlink attack?)
@@ -686,6 +687,7 @@ Ex command or function was given an invalid argument. Or |jobstart()| or
Trailing characters
An argument was given to an Ex command that does not permit one.
+Or the argument has invalid characters and has not been recognized.
*E477* *E478* >
No ! allowed
diff --git a/runtime/doc/nvim_terminal_emulator.txt b/runtime/doc/nvim_terminal_emulator.txt
index e83b17f9a0..f322764ecf 100644
--- a/runtime/doc/nvim_terminal_emulator.txt
+++ b/runtime/doc/nvim_terminal_emulator.txt
@@ -90,7 +90,7 @@ Mouse input has the following behavior:
- If another window is clicked, terminal focus will be lost and nvim will jump
to the clicked window
- If the mouse wheel is used while the mouse is positioned in another window,
- the terminal wont lose focus and the hovered window will be scrolled.
+ the terminal won't lose focus and the hovered window will be scrolled.
==============================================================================
Configuration *terminal-config*
@@ -162,12 +162,11 @@ command name, for example: >
This opens two windows:
gdb window A terminal window in which "gdb vim" is executed. Here you
- can directly interact with gdb. The buffer name is "!gdb".
+ can directly interact with gdb.
program window A terminal window for the executed program. When "run" is
used in gdb the program I/O will happen in this window, so
- that it does not interfere with controlling gdb. The buffer
- name is "gdb program".
+ that it does not interfere with controlling gdb.
The current window is used to show the source code. When gdb pauses the
source file location will be displayed, if possible. A sign is used to
@@ -391,6 +390,8 @@ GDB command *termdebug-customizing*
To change the name of the gdb command, set the "termdebugger" variable before
invoking `:Termdebug`: >
let termdebugger = "mygdb"
+If the command needs an argument use a List: >
+ let g:termdebugger = ['rr', 'replay', '--']
To not use neovim floating windows for previewing variable evaluation, set the
`g:termdebug_useFloatingHover` variable like this: >
@@ -426,7 +427,7 @@ When 'background' is "dark":
hi debugBreakpoint term=reverse ctermbg=red guibg=red
-Shorcuts *termdebug_shortcuts*
+Shortcuts *termdebug_shortcuts*
You can define your own shortcuts (mappings) to control gdb, that can work in
any window, using the TermDebugSendCommand() function. Example: >
diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt
index 097cd38400..06236741c2 100644
--- a/runtime/doc/options.txt
+++ b/runtime/doc/options.txt
@@ -304,7 +304,7 @@ value to the local value, it doesn't switch back to using the global value
This will make the local value of 'path' empty, so that the global value is
used. Thus it does the same as: >
:setlocal path=
-Note: In the future more global options can be made global-local. Using
+Note: In the future more global options can be made |global-local|. Using
":setlocal" on a global option might work differently then.
@@ -686,10 +686,10 @@ A jump table for the options with a short description can be found at |Q_op|.
Write the contents of the file, if it has been modified, on each
`:next`, `:rewind`, `:last`, `:first`, `:previous`, `:stop`,
`:suspend`, `:tag`, `:!`, `:make`, CTRL-] and CTRL-^ command; and when
- a :buffer, CTRL-O, CTRL-I, '{A-Z0-9}, or `{A-Z0-9} command takes one
+ a `:buffer`, CTRL-O, CTRL-I, '{A-Z0-9}, or `{A-Z0-9} command takes one
to another file.
A buffer is not written if it becomes hidden, e.g. when 'bufhidden' is
- set to "hide" and `:next` is used
+ set to "hide" and `:next` is used.
Note that for some commands the 'autowrite' option is not used, see
'autowriteall' for that.
Some buffers will not be written, specifically when 'buftype' is
@@ -953,7 +953,6 @@ A jump table for the options with a short description can be found at |Q_op|.
error Other Error occurred (e.g. try to join last line)
(mostly used in |Normal-mode| or |Cmdline-mode|).
esc hitting <Esc> in |Normal-mode|.
- ex In |Visual-mode|, hitting |Q| results in an error.
hangul Ignored.
insertmode Pressing <Esc> in 'insertmode'.
lang Calling the beep module for Lua/Mzscheme/TCL.
@@ -1160,6 +1159,14 @@ A jump table for the options with a short description can be found at |Q_op|.
case mapping, the current locale is not effective.
This probably only matters for Turkish.
+ *'cdhome'* *'cdh'*
+'cdhome' 'cdh' boolean (default: off)
+ global
+ When on, |:cd|, |:tcd| and |:lcd| without an argument changes the
+ current working directory to the |$HOME| directory like in Unix.
+ When off, those commands just print the current directory name.
+ On Unix this option has no effect.
+
*'cdpath'* *'cd'* *E344* *E346*
'cdpath' 'cd' string (default: equivalent to $CDPATH or ",,")
global
@@ -5124,7 +5131,8 @@ A jump table for the options with a short description can be found at |Q_op|.
Don't include both "curdir" and "sesdir". When neither is included
filenames are stored as absolute paths.
-
+ If you leave out "options" many things won't work well after restoring
+ the session.
*'shada'* *'sd'* *E526* *E527* *E528*
'shada' 'sd' string (Vim default for
Win32: !,'100,<50,s10,h,rA:,rB:
diff --git a/runtime/doc/pattern.txt b/runtime/doc/pattern.txt
index dfed39dba6..634145da3e 100644
--- a/runtime/doc/pattern.txt
+++ b/runtime/doc/pattern.txt
@@ -304,7 +304,7 @@ the pattern.
==============================================================================
2. The definition of a pattern *search-pattern* *pattern* *[pattern]*
*regular-expression* *regexp* *Pattern*
- *E76* *E383* *E476*
+ *E383* *E476*
For starters, read chapter 27 of the user manual |usr_27.txt|.
@@ -1036,6 +1036,8 @@ match ASCII characters, as indicated by the range.
\(\) A pattern enclosed by escaped parentheses. */\(* */\(\)* */\)*
E.g., "\(^a\)" matches 'a' at the start of a line.
+ There can only be ten of these. You can use "\%(" to add more, but
+ not counting it as a sub-expression.
*E51* *E54* *E55* *E872* *E873*
\1 Matches the same string that was matched by */\1* *E65*
@@ -1058,7 +1060,7 @@ x A single character, with no special meaning, matches itself
\x A backslash followed by a single character, with no special meaning,
is reserved for future expansions
-[] (with 'nomagic': \[]) */[]* */\[]* */\_[]* */collection*
+[] (with 'nomagic': \[]) */[]* */\[]* */\_[]* */collection* *E76*
\_[]
A collection. This is a sequence of characters enclosed in square
brackets. It matches any single character in the collection.
diff --git a/runtime/doc/quickfix.txt b/runtime/doc/quickfix.txt
index ba1da209f7..873fbd8971 100644
--- a/runtime/doc/quickfix.txt
+++ b/runtime/doc/quickfix.txt
@@ -232,7 +232,7 @@ processing a quickfix or location list command, it will be aborted.
":qall!" |:qall|, except that Nvim exits non-zero or
[count].
- *:cf* *:cfile*
+ *:cf* *:cfi* *:cfile*
:cf[ile][!] [errorfile] Read the error file and jump to the first error.
This is done automatically when Vim is started with
the -q option. You can use this command when you
diff --git a/runtime/doc/quickref.txt b/runtime/doc/quickref.txt
index 8cabf05053..af8301f1a0 100644
--- a/runtime/doc/quickref.txt
+++ b/runtime/doc/quickref.txt
@@ -489,6 +489,7 @@ In Insert or Command-line mode:
|q| q{a-z} record typed characters into register {a-z}
|q| q{A-Z} record typed characters, appended to register {a-z}
|q| q stop recording
+|Q| Q replay last recorded macro
|@| N @{a-z} execute the contents of register {a-z} (N times)
|@@| N @@ repeat previous @{a-z} (N times)
|:@| :@{a-z} execute the contents of register {a-z} as an Ex
@@ -628,6 +629,7 @@ Short explanation of each option: *option-list*
'buflisted' 'bl' whether the buffer shows up in the buffer list
'buftype' 'bt' special type of buffer
'casemap' 'cmp' specifies how case of letters is changed
+'cdhome' 'cdh' change directory to the home directory by ":cd"
'cdpath' 'cd' list of directories searched with ":cd"
'cedit' key used to open the command-line window
'charconvert' 'ccv' expression for character encoding conversion
@@ -997,7 +999,7 @@ Short explanation of each option: *option-list*
|:version| :ve[rsion] show version information
|:normal| :norm[al][!] {commands}
execute Normal mode commands
-|Q| Q switch to "Ex" mode
+|gQ| gQ switch to "Ex" mode
|:redir| :redir >{file} redirect messages to {file}
|:silent| :silent[!] {command} execute {command} silently
diff --git a/runtime/doc/repeat.txt b/runtime/doc/repeat.txt
index 7e8d93aa71..c7481ad290 100644
--- a/runtime/doc/repeat.txt
+++ b/runtime/doc/repeat.txt
@@ -103,7 +103,7 @@ Which is two characters shorter!
When using "global" in Ex mode, a special case is using ":visual" as a
command. This will move to a matching line, go to Normal mode to let you
-execute commands there until you use |Q| to return to Ex mode. This will be
+execute commands there until you use |gQ| to return to Ex mode. This will be
repeated for each matching line. While doing this you cannot use ":global".
To abort this type CTRL-C twice.
@@ -147,6 +147,10 @@ q Stops recording.
*@@* *E748*
@@ Repeat the previous @{0-9a-z":*} [count] times.
+ *Q*
+Q Repeat the last recorded register [count] times.
+ See |reg_recorded()|.
+
*:@*
:[addr]@{0-9a-z".=*+} Execute the contents of register {0-9a-z".=*+} as an Ex
command. First set cursor at line [addr] (default is
diff --git a/runtime/doc/sign.txt b/runtime/doc/sign.txt
index 68165f3d3d..5cfa06c33c 100644
--- a/runtime/doc/sign.txt
+++ b/runtime/doc/sign.txt
@@ -122,8 +122,9 @@ See |sign_define()| for the equivalent Vim script function.
in. Most useful is defining a background color.
numhl={group}
- Highlighting group used for 'number' column at the associated
- line. Overrides |hl-LineNr|, |hl-CursorLineNr|.
+ Highlighting group used for the line number on the line where
+ the sign is placed. Overrides |hl-LineNr|, |hl-LineNrAbove|,
+ |hl-LineNrBelow|, and |hl-CursorLineNr|.
text={text} *E239*
Define the text that is displayed when there is no icon or the
diff --git a/runtime/doc/starting.txt b/runtime/doc/starting.txt
index bb775ec884..978142a1e0 100644
--- a/runtime/doc/starting.txt
+++ b/runtime/doc/starting.txt
@@ -188,7 +188,7 @@ argument.
changes and writing.
-e *-e* *-E*
--E Start Nvim in Ex mode |gQ|.
+-E Start Nvim in Ex mode |gQ|, see |Ex-mode|.
If stdin is not a TTY:
-e reads/executes stdin as Ex commands.
@@ -409,7 +409,12 @@ accordingly, proceeding as follows:
4. Setup |default-mappings| and |default-autocmds|.
-5. Load user config (execute Ex commands from files, environment, …).
+5. Enable filetype and indent plugins.
+ This does the same as the command: >
+ :runtime! ftplugin.vim indent.vim
+< Skipped if the "-u NONE" command line argument was given.
+
+6. Load user config (execute Ex commands from files, environment, …).
$VIMINIT environment variable is read as one Ex command line (separate
multiple commands with '|' or <NL>).
*config* *init.vim* *init.lua* *vimrc* *exrc*
@@ -453,21 +458,19 @@ accordingly, proceeding as follows:
- The file ".nvimrc"
- The file ".exrc"
-6. Enable filetype and indent plugins.
- This does the same as the commands: >
- :runtime! filetype.vim
- :runtime! ftplugin.vim
- :runtime! indent.vim
-< Skipped if ":filetype … off" was called or if the "-u NONE" command
- line argument was given.
+7. Enable filetype detection.
+ This does the same as the command: >
+ :runtime! filetype.lua filetype.vim
+< Skipped if ":filetype off" was called or if the "-u NONE" command line
+ argument was given.
-7. Enable syntax highlighting.
+8. Enable syntax highlighting.
This does the same as the command: >
:runtime! syntax/syntax.vim
< Skipped if ":syntax off" was called or if the "-u NONE" command
line argument was given.
-8. Load the plugin scripts. *load-plugins*
+9. Load the plugin scripts. *load-plugins*
This does the same as the command: >
:runtime! plugin/**/*.vim
:runtime! plugin/**/*.lua
@@ -497,21 +500,21 @@ accordingly, proceeding as follows:
if packages have been found, but that should not add a directory
ending in "after".
-9. Set 'shellpipe' and 'shellredir'
+10. Set 'shellpipe' and 'shellredir'
The 'shellpipe' and 'shellredir' options are set according to the
value of the 'shell' option, unless they have been set before.
This means that Nvim will figure out the values of 'shellpipe' and
'shellredir' for you, unless you have set them yourself.
-10. Set 'updatecount' to zero, if "-n" command argument used
+11. Set 'updatecount' to zero, if "-n" command argument used
-11. Set binary options if the |-b| flag was given.
+12. Set binary options if the |-b| flag was given.
-12. Read the |shada-file|.
+13. Read the |shada-file|.
-13. Read the quickfix file if the |-q| flag was given, or exit on failure.
+14. Read the quickfix file if the |-q| flag was given, or exit on failure.
-14. Open all windows
+15. Open all windows
When the |-o| flag was given, windows will be opened (but not
displayed yet).
When the |-p| flag was given, tab pages will be created (but not
@@ -521,7 +524,7 @@ accordingly, proceeding as follows:
Buffers for all windows will be loaded, without triggering |BufAdd|
autocommands.
-15. Execute startup commands
+16. Execute startup commands
If a |-t| flag was given, the tag is jumped to.
Commands given with |-c| and |+cmd| are executed.
If the 'insertmode' option is set, Insert mode is entered.
diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt
index d49809599d..be1586ab41 100644
--- a/runtime/doc/syntax.txt
+++ b/runtime/doc/syntax.txt
@@ -920,12 +920,16 @@ in .../after/syntax/baan.vim (see |after-directory|). Eg: >
BASIC *basic.vim* *vb.vim* *ft-basic-syntax* *ft-vb-syntax*
-Both Visual Basic and "normal" basic use the extension ".bas". To detect
+Both Visual Basic and "normal" BASIC use the extension ".bas". To detect
which one should be used, Vim checks for the string "VB_Name" in the first
five lines of the file. If it is not found, filetype will be "basic",
otherwise "vb". Files with the ".frm" extension will always be seen as Visual
Basic.
+If the automatic detection doesn't work for you or you only edit, for
+example, FreeBASIC files, use this in your startup vimrc: >
+ :let filetype_bas = "freebasic"
+
C *c.vim* *ft-c-syntax*
@@ -1406,7 +1410,7 @@ add the following line to your startup file: >
:let g:filetype_euphoria = "euphoria4"
-Elixir and Euphoria share the *.ex file extension. If the filetype is
+Elixir and Euphoria share the *.ex file extension. If the filetype is
specifically set as Euphoria with the g:filetype_euphoria variable, or the
file is determined to be Euphoria based on keywords in the file, then the
filetype will be set as Euphoria. Otherwise, the filetype will default to
@@ -1437,7 +1441,7 @@ The following file extensions are auto-detected as Elixir file types:
*.ex, *.exs, *.eex, *.leex, *.lock
-Elixir and Euphoria share the *.ex file extension. If the filetype is
+Elixir and Euphoria share the *.ex file extension. If the filetype is
specifically set as Euphoria with the g:filetype_euphoria variable, or the
file is determined to be Euphoria based on keywords in the file, then the
filetype will be set as Euphoria. Otherwise, the filetype will default to
@@ -4455,7 +4459,7 @@ it marks the "\(\I\i*\)" sub-expression as external; in the end pattern, it
changes the \z1 back-reference into an external reference referring to the
first external sub-expression in the start pattern. External references can
also be used in skip patterns: >
- :syn region foo start="start \(\I\i*\)" skip="not end \z1" end="end \z1"
+ :syn region foo start="start \z(\I\i*\)" skip="not end \z1" end="end \z1"
Note that normal and external sub-expressions are completely orthogonal and
indexed separately; for instance, if the pattern "\z(..\)\(..\)" is applied
diff --git a/runtime/doc/term.txt b/runtime/doc/term.txt
index 935d958729..62e13285f5 100644
--- a/runtime/doc/term.txt
+++ b/runtime/doc/term.txt
@@ -133,7 +133,7 @@ capabilities as if they had been in the terminfo definition.
If terminfo does not (yet) have this flag, Nvim will fall back to $TERM and
other environment variables. It will add constructed "setrgbf" and "setrgbb"
-capabilities in the case of the the "rxvt", "linux", "st", "tmux", and "iterm"
+capabilities in the case of the "rxvt", "linux", "st", "tmux", and "iterm"
terminal types, or when Konsole, genuine Xterm, a libvte terminal emulator
version 0.36 or later, or a terminal emulator that sets the COLORTERM
environment variable to "truecolor" is detected.
diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt
index 8f7241dd46..5829dbdd6b 100644
--- a/runtime/doc/treesitter.txt
+++ b/runtime/doc/treesitter.txt
@@ -100,7 +100,7 @@ tsnode:prev_named_sibling() *tsnode:prev_named_sibling()*
tsnode:iter_children() *tsnode:iter_children()*
Iterates over all the direct children of {tsnode}, regardless of
- wether they are named or not.
+ whether they are named or not.
Returns the child node plus the eventual field name corresponding to
this child node.
@@ -155,9 +155,9 @@ tsnode:sexpr() *tsnode:sexpr()*
Get an S-expression representing the node as a string.
tsnode:id() *tsnode:id()*
- Get an unique identier for the node inside its own tree.
+ Get an unique identifier for the node inside its own tree.
- No guarantees are made about this identifer's internal representation,
+ No guarantees are made about this identifier's internal representation,
except for being a primitive lua type with value equality (so not a table).
Presently it is a (non-printable) string.
@@ -195,7 +195,7 @@ to a match.
Treesitter Query Predicates *lua-treesitter-predicates*
When writing queries for treesitter, one might use `predicates`, that is,
-special scheme nodes that are evaluted to verify things on a captured node for
+special scheme nodes that are evaluated to verify things on a captured node for
example, the |eq?| predicate : >
((identifier) @foo (#eq? @foo "foo"))
@@ -203,16 +203,16 @@ This will only match identifier corresponding to the `"foo"` text.
Here is a list of built-in predicates :
`eq?` *ts-predicate-eq?*
- This predicate will check text correspondance between nodes or
+ This predicate will check text correspondence between nodes or
strings : >
((identifier) @foo (#eq? @foo "foo"))
((node1) @left (node2) @right (#eq? @left @right))
<
`match?` *ts-predicate-match?*
`vim-match?` *ts-predicate-vim-match?*
- This will match if the provived vim regex matches the text
+ This will match if the provided vim regex matches the text
corresponding to a node : >
- ((idenfitier) @constant (#match? @constant "^[A-Z_]+$"))
+ ((identifier) @constant (#match? @constant "^[A-Z_]+$"))
< Note: the `^` and `$` anchors will respectively match the
start and end of the node's text.
@@ -267,7 +267,7 @@ Here is a list of built-in directives:
`offset!` *ts-predicate-offset!*
Takes the range of the captured node and applies the offsets
to it's range : >
- ((idenfitier) @constant (#offset! @constant 0 1 0 -1))
+ ((identifier) @constant (#offset! @constant 0 1 0 -1))
< This will generate a range object for the captured node with the
offsets applied. The arguments are
`({capture_id}, {start_row}, {start_col}, {end_row}, {end_col}, {key?})`
@@ -467,8 +467,9 @@ parse_query({lang}, {query}) *parse_query()*
• `info.patterns` contains information about predicates.
Parameters: ~
- {lang} The language
- {query} A string containing the query (s-expr syntax)
+ {lang} string The language
+ {query} string A string containing the query (s-expr
+ syntax)
Return: ~
The query
@@ -665,7 +666,7 @@ LanguageTree:invalidate({self}, {reload}) *LanguageTree:invalidate()*
{self}
LanguageTree:is_valid({self}) *LanguageTree:is_valid()*
- Determines whether this tree is valid. If the tree is invalid, `parse()` must be called to get the an updated tree.
+ Determines whether this tree is valid. If the tree is invalid, `parse()` must be called to get the updated tree.
Parameters: ~
{self}
diff --git a/runtime/doc/usr_05.txt b/runtime/doc/usr_05.txt
index 2edef0ca23..f93a221e43 100644
--- a/runtime/doc/usr_05.txt
+++ b/runtime/doc/usr_05.txt
@@ -11,13 +11,12 @@ Vim's capabilities. Or define your own macros.
|05.1| The vimrc file
|05.2| The example vimrc file explained
-|05.3| The defaults.vim file explained
-|05.4| Simple mappings
-|05.5| Adding a package
-|05.6| Adding a plugin
-|05.7| Adding a help file
-|05.8| The option window
-|05.9| Often used options
+|05.3| Simple mappings
+|05.4| Adding a package
+|05.5| Adding a plugin
+|05.6| Adding a help file
+|05.7| The option window
+|05.8| Often used options
Next chapter: |usr_06.txt| Using syntax highlighting
Previous chapter: |usr_04.txt| Making small changes
@@ -200,7 +199,7 @@ mapping. If set (default), this may break plugins (but it's backward
compatible). See 'langremap'.
==============================================================================
-*05.4* Simple mappings
+*05.3* Simple mappings
A mapping enables you to bind a set of Vim commands to a single key. Suppose,
for example, that you need to surround certain words with curly braces. In
@@ -247,7 +246,7 @@ The ":map" command (with no arguments) lists your current mappings. At
least the ones for Normal mode. More about mappings in section |40.1|.
==============================================================================
-*05.5* Adding a package *add-package* *vimball-install*
+*05.4* Adding a package *add-package* *vimball-install*
A package is a set of files that you can add to Vim. There are two kinds of
packages: optional and automatically loaded on startup.
@@ -287,7 +286,7 @@ an archive or as a repository. For an archive you can follow these steps:
More information about packages can be found here: |packages|.
==============================================================================
-*05.6* Adding a plugin *add-plugin* *plugin*
+*05.5* Adding a plugin *add-plugin* *plugin*
Vim's functionality can be extended by adding plugins. A plugin is nothing
more than a Vim script file that is loaded automatically when Vim starts. You
@@ -423,7 +422,7 @@ Further reading:
|new-filetype| How to detect a new file type.
==============================================================================
-*05.7* Adding a help file *add-local-help*
+*05.6* Adding a help file *add-local-help*
If you are lucky, the plugin you installed also comes with a help file. We
will explain how to install the help file, so that you can easily find help
@@ -456,7 +455,7 @@ them through the tag.
For writing a local help file, see |write-local-help|.
==============================================================================
-*05.8* The option window
+*05.7* The option window
If you are looking for an option that does what you want, you can search in
the help files here: |options|. Another way is by using this command: >
@@ -495,7 +494,7 @@ border. This is what the 'scrolloff' option does, it specifies an offset
from the window border where scrolling starts.
==============================================================================
-*05.9* Often used options
+*05.8* Often used options
There are an awful lot of options. Most of them you will hardly ever use.
Some of the more useful ones will be mentioned here. Don't forget you can
diff --git a/runtime/doc/usr_41.txt b/runtime/doc/usr_41.txt
index 6a9284dac9..7e611a47f3 100644
--- a/runtime/doc/usr_41.txt
+++ b/runtime/doc/usr_41.txt
@@ -852,6 +852,7 @@ Command line: *command-line-functions*
getcmdtype() return the current command-line type
getcmdwintype() return the current command-line window type
getcompletion() list of command-line completion matches
+ fullcommand() get full command name
Quickfix and location lists: *quickfix-functions*
getqflist() list of quickfix errors
diff --git a/runtime/doc/usr_toc.txt b/runtime/doc/usr_toc.txt
index f466a8ece9..bf9c02882c 100644
--- a/runtime/doc/usr_toc.txt
+++ b/runtime/doc/usr_toc.txt
@@ -99,13 +99,12 @@ Read this from start to end to learn the essential commands.
|usr_05.txt| Set your settings
|05.1| The vimrc file
|05.2| The example vimrc file explained
- |05.3| The defaults.vim file explained
- |05.4| Simple mappings
- |05.5| Adding a package
- |05.6| Adding a plugin
- |05.7| Adding a help file
- |05.8| The option window
- |05.9| Often used options
+ |05.3| Simple mappings
+ |05.4| Adding a package
+ |05.5| Adding a plugin
+ |05.6| Adding a help file
+ |05.7| The option window
+ |05.8| Often used options
|usr_06.txt| Using syntax highlighting
|06.1| Switching it on
diff --git a/runtime/doc/various.txt b/runtime/doc/various.txt
index b0e0bdcb84..fc0230c62d 100644
--- a/runtime/doc/various.txt
+++ b/runtime/doc/various.txt
@@ -249,7 +249,7 @@ g8 Print the hex values of the bytes used in the
To enter |Terminal-mode| automatically: >
autocmd TermOpen * startinsert
<
- *:!cmd* *:!* *E34*
+ *:!cmd* *:!*
:!{cmd} Execute {cmd} with 'shell'. See also |:terminal|.
The command runs in a non-interactive shell connected
@@ -261,6 +261,7 @@ g8 Print the hex values of the bytes used in the
Use |jobstart()| instead. >
:call jobstart('foo', {'detach':1})
<
+ *E34*
Any "!" in {cmd} is replaced with the previous
external command (see also 'cpoptions'), unless
escaped by a backslash. Example: ":!ls" followed by
@@ -357,19 +358,19 @@ g8 Print the hex values of the bytes used in the
:redi[r] END End redirecting messages.
*:filt* *:filter*
-:filt[er][!] {pat} {command}
-:filt[er][!] /{pat}/ {command}
+:filt[er][!] {pattern} {command}
+:filt[er][!] /{pattern}/ {command}
Restrict the output of {command} to lines matching
- with {pat}. For example, to list only xml files: >
+ with {pattern}. For example, to list only xml files: >
:filter /\.xml$/ oldfiles
< If the [!] is given, restrict the output of {command}
- to lines that do NOT match {pat}.
+ to lines that do NOT match {pattern}.
- {pat} is a Vim search pattern. Instead of enclosing
+ {pattern} is a Vim search pattern. Instead of enclosing
it in / any non-ID character (see |'isident'|) can be
- used, so long as it does not appear in {pat}. Without
- the enclosing character the pattern cannot include the
- bar character. 'ignorecase' is not used.
+ used, so long as it does not appear in {pattern}.
+ Without the enclosing character the pattern cannot
+ include the bar character. 'ignorecase' is not used.
The pattern is matched against the relevant part of
the output, not necessarily the whole line. Only some
@@ -387,7 +388,7 @@ g8 Print the hex values of the bytes used in the
|:marks| - filter by text in the current file,
or file name for other files
|:oldfiles| - filter by file name
- |:set| - filter by variable name
+ |:set| - filter by option name
Only normal messages are filtered, error messages are
not.
diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt
index bc59ea785e..7e61eac404 100644
--- a/runtime/doc/vim_diff.txt
+++ b/runtime/doc/vim_diff.txt
@@ -23,8 +23,10 @@ centralized reference of the differences.
==============================================================================
2. Defaults *nvim-defaults*
-- Syntax highlighting is enabled by default
-- ":filetype plugin indent on" is enabled by default
+- Filetype detection is enabled by default. This can be disabled by adding
+ ":filetype off" to |init.vim|.
+- Syntax highlighting is enabled by default. This can be disabled by adding
+ ":syntax off" to |init.vim|.
- 'autoindent' is enabled
- 'autoread' is enabled
@@ -180,6 +182,8 @@ Commands:
|:match| can be invoked before highlight group is defined
Events:
+ |RecordingEnter|
+ |RecordingLeave|
|SearchWrapped|
|Signal|
|TabNewEntered|
@@ -356,7 +360,8 @@ Motion:
The |jumplist| avoids useless/phantom jumps.
Normal commands:
- |Q| is the same as |gQ|
+ |Q| replays the last recorded macro instead of switching to Ex mode.
+ Instead |gQ| can be used to enter Ex mode.
Options:
'ttimeout', 'ttimeoutlen' behavior was simplified
diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt
index e0c33fa2c9..5b91321c40 100644
--- a/runtime/doc/windows.txt
+++ b/runtime/doc/windows.txt
@@ -116,13 +116,15 @@ other windows. If 'mouse' is enabled, a status line can be dragged to resize
windows.
*filler-lines*
-The lines after the last buffer line in a window are called filler lines.
-These lines start with a tilde (~) character. By default, these are
-highlighted as NonText (|hl-NonText|). The EndOfBuffer highlight group
-(|hl-EndOfBuffer|) can be used to change the highlighting of filler lines.
+The lines after the last buffer line in a window are called filler lines. By
+default, these lines start with a tilde (~) character. The 'eob' item in the
+'fillchars' option can be used to change this character. By default, these
+characters are highlighted as NonText (|hl-NonText|). The EndOfBuffer
+highlight group (|hl-EndOfBuffer|) can be used to change the highlighting of
+the filler characters.
==============================================================================
-3. Opening and closing a window *opening-window* *E36*
+3. Opening and closing a window *opening-window*
CTRL-W s *CTRL-W_s*
CTRL-W S *CTRL-W_S*
@@ -221,6 +223,10 @@ CTRL-W ge *CTRL-W_ge*
Note that the 'splitbelow' and 'splitright' options influence where a new
window will appear.
+ *E36*
+Creating a window will fail if there is not enough room. Every window needs
+at least one screen line and column, sometimes more. Options 'winminheight'
+and 'winminwidth' are relevant.
*:vert* *:vertical*
:vert[ical] {cmd}
diff --git a/runtime/filetype.lua b/runtime/filetype.lua
new file mode 100644
index 0000000000..fcfc5701f0
--- /dev/null
+++ b/runtime/filetype.lua
@@ -0,0 +1,26 @@
+if vim.g.did_load_filetypes and vim.g.did_load_filetypes ~= 0 then
+ return
+end
+
+-- For now, make this opt-in with a global variable
+if vim.g.do_filetype_lua ~= 1 then
+ return
+end
+
+vim.cmd [[
+augroup filetypedetect
+au BufRead,BufNewFile * call v:lua.vim.filetype.match(expand('<afile>'))
+
+" These *must* be sourced after the autocommand above is created
+runtime! ftdetect/*.vim
+runtime! ftdetect/*.lua
+
+" Set a marker so that the ftdetect scripts are not sourced a second time by filetype.vim
+let g:did_load_ftdetect = 1
+
+augroup END
+]]
+
+if not vim.g.ft_ignore_pat then
+ vim.g.ft_ignore_pat = "\\.\\(Z\\|gz\\|bz2\\|zip\\|tgz\\)$"
+end
diff --git a/runtime/filetype.vim b/runtime/filetype.vim
index 806748b7cb..f58658a73b 100644
--- a/runtime/filetype.vim
+++ b/runtime/filetype.vim
@@ -1,7 +1,7 @@
" Vim support file to detect file types
"
" Maintainer: Bram Moolenaar <Bram@vim.org>
-" Last Change: 2021 Dec 03
+" Last Change: 2022 Jan 23
" Listen very carefully, I will say this only once
if exists("did_load_filetypes")
@@ -189,7 +189,8 @@ au BufNewFile,BufRead *.awk,*.gawk setf awk
au BufNewFile,BufRead *.mch,*.ref,*.imp setf b
" BASIC or Visual Basic
-au BufNewFile,BufRead *.bas call dist#ft#FTVB("basic")
+au BufNewFile,BufRead *.bas call dist#ft#FTbas()
+au BufNewFile,BufRead *.bi,*.bm call dist#ft#FTbas()
" Visual Basic Script (close to Visual Basic) or Visual Basic .NET
au BufNewFile,BufRead *.vb,*.vbs,*.dsm,*.ctl setf vb
@@ -198,7 +199,7 @@ au BufNewFile,BufRead *.vb,*.vbs,*.dsm,*.ctl setf vb
au BufNewFile,BufRead *.iba,*.ibi setf ibasic
" FreeBasic file (similar to QBasic)
-au BufNewFile,BufRead *.fb,*.bi setf freebasic
+au BufNewFile,BufRead *.fb setf freebasic
" Batch file for MSDOS.
au BufNewFile,BufRead *.bat,*.sys setf dosbatch
@@ -392,7 +393,8 @@ au BufNewFile,BufRead configure.in,configure.ac setf config
" CUDA Compute Unified Device Architecture
au BufNewFile,BufRead *.cu,*.cuh setf cuda
-" Dockerfilb; Podman uses the same syntax with name Containerfile
+" Dockerfile; Podman uses the same syntax with name Containerfile
+" Also see Dockerfile.* below.
au BufNewFile,BufRead Containerfile,Dockerfile,*.Dockerfile setf dockerfile
" WildPackets EtherPeek Decoder
@@ -486,10 +488,13 @@ au BufNewFile,BufRead dict.conf,.dictrc setf dictconf
" Dictd config
au BufNewFile,BufRead dictd*.conf setf dictdconf
+" DEP3 formatted patch files
+au BufNewFile,BufRead */debian/patches/* call dist#ft#Dep3patch()
+
" Diff files
au BufNewFile,BufRead *.diff,*.rej setf diff
au BufNewFile,BufRead *.patch
- \ if getline(1) =~ '^From [0-9a-f]\{40\} Mon Sep 17 00:00:00 2001$' |
+ \ if getline(1) =~# '^From [0-9a-f]\{40,\} Mon Sep 17 00:00:00 2001$' |
\ setf gitsendemail |
\ else |
\ setf diff |
@@ -668,20 +673,19 @@ autocmd BufRead,BufNewFile *.gift setf gift
" Git
au BufNewFile,BufRead COMMIT_EDITMSG,MERGE_MSG,TAG_EDITMSG setf gitcommit
-au BufNewFile,BufRead *.git/config,.gitconfig,/etc/gitconfig setf gitconfig
+au BufNewFile,BufRead NOTES_EDITMSG,EDIT_DESCRIPTION setf gitcommit
+au BufNewFile,BufRead *.git/config,.gitconfig,*/etc/gitconfig setf gitconfig
au BufNewFile,BufRead */.config/git/config setf gitconfig
+au BufNewFile,BufRead *.git/config.worktree setf gitconfig
+au BufNewFile,BufRead *.git/worktrees/*/config.worktree setf gitconfig
au BufNewFile,BufRead .gitmodules,*.git/modules/*/config setf gitconfig
if !empty($XDG_CONFIG_HOME)
au BufNewFile,BufRead $XDG_CONFIG_HOME/git/config setf gitconfig
endif
au BufNewFile,BufRead git-rebase-todo setf gitrebase
au BufRead,BufNewFile .gitsendemail.msg.?????? setf gitsendemail
-au BufNewFile,BufRead .msg.[0-9]*
- \ if getline(1) =~ '^From.*# This line is ignored.$' |
- \ setf gitsendemail |
- \ endif
au BufNewFile,BufRead *.git/*
- \ if getline(1) =~ '^\x\{40\}\>\|^ref: ' |
+ \ if getline(1) =~# '^\x\{40,\}\>\|^ref: ' |
\ setf git |
\ endif
@@ -708,7 +712,7 @@ au BufNewFile,BufRead gitolite.conf setf gitolite
au BufNewFile,BufRead {,.}gitolite.rc,example.gitolite.rc setf perl
" Gnuplot scripts
-au BufNewFile,BufRead *.gpi setf gnuplot
+au BufNewFile,BufRead *.gpi,.gnuplot setf gnuplot
" Go (Google)
au BufNewFile,BufRead *.go setf go
@@ -880,6 +884,9 @@ au BufNewFile,BufRead *.jov,*.j73,*.jovial setf jovial
" JSON
au BufNewFile,BufRead *.json,*.jsonp,*.webmanifest setf json
+" JSON5
+au BufNewFile,BufRead *.json5 setf json5
+
" JSON Patch (RFC 6902)
au BufNewFile,BufRead *.json-patch setf json
@@ -955,9 +962,9 @@ au BufNewFile,BufRead lilo.conf setf lilo
" Lisp (*.el = ELisp, *.cl = Common Lisp)
" *.jl was removed, it's also used for Julia, better skip than guess wrong.
if has("fname_case")
- au BufNewFile,BufRead *.lsp,*.lisp,*.el,*.cl,*.L,.emacs,.sawfishrc setf lisp
+ au BufNewFile,BufRead *.lsp,*.lisp,*.asd,*.el,*.cl,*.L,.emacs,.sawfishrc setf lisp
else
- au BufNewFile,BufRead *.lsp,*.lisp,*.el,*.cl,.emacs,.sawfishrc setf lisp
+ au BufNewFile,BufRead *.lsp,*.lisp,*.asd,*.el,*.cl,.emacs,.sawfishrc setf lisp
endif
" SBCL implementation of Common Lisp
@@ -1084,7 +1091,9 @@ au BufNewFile,BufRead *.mmp setf mmp
" Modsim III (or LambdaProlog)
au BufNewFile,BufRead *.mod
- \ if getline(1) =~ '\<module\>' |
+ \ if expand("<afile>") =~ '\<go.mod$' |
+ \ setf gomod |
+ \ elseif getline(1) =~ '\<module\>' |
\ setf lprolog |
\ else |
\ setf modsim3 |
@@ -1207,6 +1216,9 @@ au BufNewFile,BufRead *.xom,*.xin setf omnimark
" OPAM
au BufNewFile,BufRead opam,*.opam,*.opam.template setf opam
+" OpenFOAM
+au BufNewFile,BufRead [a-zA-Z0-9]*Dict\(.*\)\=,[a-zA-Z]*Properties\(.*\)\=,*Transport\(.*\),fvSchemes,fvSolution,fvConstrains,fvModels,*/constant/g,*/0\(\.orig\)\=/* call dist#ft#FTfoam()
+
" OpenROAD
au BufNewFile,BufRead *.or setf openroad
@@ -1659,7 +1671,7 @@ au BufNewFile,BufRead .zshrc,.zshenv,.zlogin,.zlogout,.zcompdump setf zsh
au BufNewFile,BufRead *.zsh setf zsh
" Scheme
-au BufNewFile,BufRead *.scm,*.ss,*.rkt,*.rktd,*.rktl setf scheme
+au BufNewFile,BufRead *.scm,*.ss,*.sld,*.rkt,*.rktd,*.rktl setf scheme
" Screen RC
au BufNewFile,BufRead .screenrc,screenrc setf screen
@@ -1741,6 +1753,7 @@ au BufNewFile,BufRead *.ice setf slice
" Microsoft Visual Studio Solution
au BufNewFile,BufRead *.sln setf solution
+au BufNewFile,BufRead *.slnf setf json
" Spice
au BufNewFile,BufRead *.sp,*.spice setf spice
@@ -1767,8 +1780,8 @@ au BufNewFile,BufRead *.sqr,*.sqi setf sqr
au BufNewFile,BufRead *.nut setf squirrel
" OpenSSH configuration
-au BufNewFile,BufRead ssh_config,*/.ssh/config setf sshconfig
-au BufNewFile,BufRead */etc/ssh/ssh_config.d/*.conf setf sshconfig
+au BufNewFile,BufRead ssh_config,*/.ssh/config,*/.ssh/*.conf setf sshconfig
+au BufNewFile,BufRead */etc/ssh/ssh_config.d/*.conf setf sshconfig
" OpenSSH server configuration
au BufNewFile,BufRead sshd_config setf sshdconfig
@@ -2231,6 +2244,9 @@ au BufNewFile,BufRead crontab,crontab.*,*/etc/cron.d/* call s:StarSetf('crontab
" dnsmasq(8) configuration
au BufNewFile,BufRead */etc/dnsmasq.d/* call s:StarSetf('dnsmasq')
+" Dockerfile
+au BufNewFile,BufRead Dockerfile.*,Containerfile.* call s:StarSetf('dockerfile')
+
" Dracula
au BufNewFile,BufRead drac.* call s:StarSetf('dracula')
@@ -2275,6 +2291,9 @@ au BufNewFile,BufRead Kconfig.* call s:StarSetf('kconfig')
" Lilo: Linux loader
au BufNewFile,BufRead lilo.conf* call s:StarSetf('lilo')
+" Libsensors
+au BufNewFile,BufRead */etc/sensors.d/[^.]* call s:StarSetf('sensors')
+
" Logcheck
au BufNewFile,BufRead */etc/logcheck/*.d*/* call s:StarSetf('logcheck')
@@ -2397,10 +2416,12 @@ au BufNewFile,BufRead *.txt
\| setf text
\| endif
-" Use the filetype detect plugins. They may overrule any of the previously
-" detected filetypes.
-runtime! ftdetect/*.vim
-runtime! ftdetect/*.lua
+if !exists('g:did_load_ftdetect')
+ " Use the filetype detect plugins. They may overrule any of the previously
+ " detected filetypes.
+ runtime! ftdetect/*.vim
+ runtime! ftdetect/*.lua
+endif
" NOTE: The above command could have ended the filetypedetect autocmd group
" and started another one. Let's make sure it has ended to get to a consistent
diff --git a/runtime/ftplugin/checkhealth.vim b/runtime/ftplugin/checkhealth.vim
new file mode 100644
index 0000000000..3d8e9ace1a
--- /dev/null
+++ b/runtime/ftplugin/checkhealth.vim
@@ -0,0 +1,20 @@
+" Vim filetype plugin
+" Language: Neovim checkhealth buffer
+" Last Change: 2021 Dec 15
+
+if exists("b:did_ftplugin")
+ finish
+endif
+
+runtime! ftplugin/markdown.vim ftplugin/markdown_*.vim ftplugin/markdown/*.vim
+
+setlocal wrap breakindent linebreak
+setlocal conceallevel=2 concealcursor=nc
+setlocal keywordprg=:help
+let &l:iskeyword='!-~,^*,^|,^",192-255'
+
+if exists("b:undo_ftplugin")
+ let b:undo_ftplugin .= "|setl wrap< bri< lbr< cole< cocu< kp< isk<"
+else
+ let b:undo_ftplugin = "setl wrap< bri< lbr< cole< cocu< kp< isk<"
+endif
diff --git a/runtime/ftplugin/git.vim b/runtime/ftplugin/git.vim
deleted file mode 100644
index 75b20f021e..0000000000
--- a/runtime/ftplugin/git.vim
+++ /dev/null
@@ -1,41 +0,0 @@
-" Vim filetype plugin
-" Language: generic git output
-" Maintainer: Tim Pope <vimNOSPAM@tpope.org>
-" Last Change: 2019 Dec 05
-
-" Only do this when not done yet for this buffer
-if (exists("b:did_ftplugin"))
- finish
-endif
-let b:did_ftplugin = 1
-
-if !exists('b:git_dir')
- if expand('%:p') =~# '[\/]\.git[\/]modules[\/]\|:[\/][\/]\|^\a\a\+:'
- " Stay out of the way
- elseif expand('%:p') =~# '[\/]\.git[\/]worktrees'
- let b:git_dir = matchstr(expand('%:p'),'.*\.git[\/]worktrees[\/][^\/]\+\>')
- elseif expand('%:p') =~# '\.git\>'
- let b:git_dir = matchstr(expand('%:p'),'.*\.git\>')
- elseif $GIT_DIR != ''
- let b:git_dir = $GIT_DIR
- endif
- if (has('win32') || has('win64')) && exists('b:git_dir')
- let b:git_dir = substitute(b:git_dir,'\\','/','g')
- endif
-endif
-
-if exists('*shellescape') && exists('b:git_dir') && b:git_dir != ''
- if b:git_dir =~# '/\.git$' " Not a bare repository
- let &l:path = escape(fnamemodify(b:git_dir,':h'),'\, ').','.&l:path
- endif
- let &l:path = escape(b:git_dir,'\, ').','.&l:path
- let &l:keywordprg = 'git --git-dir='.shellescape(b:git_dir).' show'
-else
- setlocal keywordprg=git\ show
-endif
-if has('gui_running')
- let &l:keywordprg = substitute(&l:keywordprg,'^git\>','git --no-pager','')
-endif
-
-setlocal includeexpr=substitute(v:fname,'^[^/]\\+/','','')
-let b:undo_ftplugin = "setl keywordprg< path< includeexpr<"
diff --git a/runtime/ftplugin/gitcommit.vim b/runtime/ftplugin/gitcommit.vim
index 9b1998acaa..9342799b56 100644
--- a/runtime/ftplugin/gitcommit.vim
+++ b/runtime/ftplugin/gitcommit.vim
@@ -1,66 +1,57 @@
" Vim filetype plugin
" Language: git commit file
" Maintainer: Tim Pope <vimNOSPAM@tpope.org>
-" Last Change: 2019 Dec 05
+" Last Change: 2022 Jan 05
" Only do this when not done yet for this buffer
if (exists("b:did_ftplugin"))
finish
endif
-runtime! ftplugin/git.vim
let b:did_ftplugin = 1
-setlocal comments=:# commentstring=#\ %s
setlocal nomodeline tabstop=8 formatoptions+=tl textwidth=72
setlocal formatoptions-=c formatoptions-=r formatoptions-=o formatoptions-=q formatoptions+=n
setlocal formatlistpat+=\\\|^\\s*[-*+]\\s\\+
+setlocal include=^+++
+setlocal includeexpr=substitute(v:fname,'^[bi]/','','')
-let b:undo_ftplugin = 'setl modeline< tabstop< formatoptions< tw< com< cms< formatlistpat<'
+let b:undo_ftplugin = 'setl modeline< tabstop< formatoptions< tw< com< cms< formatlistpat< inc< inex<'
-if exists("g:no_gitcommit_commands") || v:version < 700
- finish
-endif
+let s:l = search('\C\m^[#;@!$%^&|:] -\{24,\} >8 -\{24,\}$', 'cnW', '', 100)
+let &l:comments = ':' . (matchstr(getline(s:l ? s:l : '$'), '^[#;@!$%^&|:]\S\@!') . '#')[0]
+let &l:commentstring = &l:comments[1] . ' %s'
+unlet s:l
-if !exists("b:git_dir")
- let b:git_dir = expand("%:p:h")
+if exists("g:no_gitcommit_commands")
+ finish
endif
-command! -bang -bar -buffer -complete=custom,s:diffcomplete -nargs=* DiffGitCached :call s:gitdiffcached(<bang>0,b:git_dir,<f-args>)
+command! -bang -bar -buffer -complete=custom,s:diffcomplete -nargs=* DiffGitCached :call s:gitdiffcached(<bang>0, <f-args>)
let b:undo_ftplugin = b:undo_ftplugin . "|delc DiffGitCached"
-function! s:diffcomplete(A,L,P)
+function! s:diffcomplete(A, L, P) abort
let args = ""
if a:P <= match(a:L." -- "," -- ")+3
let args = args . "-p\n--stat\n--shortstat\n--summary\n--patch-with-stat\n--no-renames\n-B\n-M\n-C\n"
end
- if exists("b:git_dir") && a:A !~ '^-'
- let tree = fnamemodify(b:git_dir,':h')
- if strpart(getcwd(),0,strlen(tree)) == tree
- let args = args."\n".system("git diff --cached --name-only")
- endif
+ if a:A !~ '^-' && !empty(getftype('.git'))
+ let args = args."\n".system("git diff --cached --name-only")
endif
return args
endfunction
-function! s:gitdiffcached(bang,gitdir,...)
- let tree = fnamemodify(a:gitdir,':h')
+function! s:gitdiffcached(bang, ...) abort
let name = tempname()
- let git = "git"
- if strpart(getcwd(),0,strlen(tree)) != tree
- let git .= " --git-dir=".(exists("*shellescape") ? shellescape(a:gitdir) : '"'.a:gitdir.'"')
- endif
if a:0
- let extra = join(map(copy(a:000),exists("*shellescape") ? 'shellescape(v:val)' : "'\"'.v:val.'\"'"))
+ let extra = join(map(copy(a:000), 'shellescape(v:val)'))
else
let extra = "-p --stat=".&columns
endif
- call system(git." diff --cached --no-color --no-ext-diff ".extra." > ".(exists("*shellescape") ? shellescape(name) : name))
- exe "pedit ".(exists("*fnameescape") ? fnameescape(name) : name)
+ call system("git diff --cached --no-color --no-ext-diff ".extra." > ".shellescape(name))
+ exe "pedit " . fnameescape(name)
wincmd P
- let b:git_dir = a:gitdir
- command! -bang -bar -buffer -complete=custom,s:diffcomplete -nargs=* DiffGitCached :call s:gitdiffcached(<bang>0,b:git_dir,<f-args>)
- nnoremap <buffer> <silent> q :q<CR>
+ command! -bang -bar -buffer -complete=custom,s:diffcomplete -nargs=* DiffGitCached :call s:gitdiffcached(<bang>0, <f-args>)
setlocal buftype=nowrite nobuflisted noswapfile nomodifiable filetype=git
endfunction
diff --git a/runtime/ftplugin/gitrebase.vim b/runtime/ftplugin/gitrebase.vim
index 2fed53c829..143f86a251 100644
--- a/runtime/ftplugin/gitrebase.vim
+++ b/runtime/ftplugin/gitrebase.vim
@@ -1,22 +1,20 @@
" Vim filetype plugin
" Language: git rebase --interactive
" Maintainer: Tim Pope <vimNOSPAM@tpope.org>
-" Last Change: 2019 Dec 05
+" Last Change: 2022 Jan 05
" Only do this when not done yet for this buffer
if (exists("b:did_ftplugin"))
finish
endif
-runtime! ftplugin/git.vim
let b:did_ftplugin = 1
-setlocal comments=:# commentstring=#\ %s formatoptions-=t
+let &l:comments = ':' . (matchstr(getline('$'), '^[#;@!$%^&|:]\S\@!') . '#')[0]
+let &l:commentstring = &l:comments[1] . ' %s'
+setlocal formatoptions-=t
setlocal nomodeline
-if !exists("b:undo_ftplugin")
- let b:undo_ftplugin = ""
-endif
-let b:undo_ftplugin = b:undo_ftplugin."|setl com< cms< fo< ml<"
+let b:undo_ftplugin = "setl com< cms< fo< ml<"
function! s:choose(word) abort
s/^\(\w\+\>\)\=\(\s*\)\ze\x\{4,40\}\>/\=(strlen(submatch(1)) == 1 ? a:word[0] : a:word) . substitute(submatch(2),'^$',' ','')/e
@@ -41,8 +39,7 @@ if exists("g:no_plugin_maps") || exists("g:no_gitrebase_maps")
finish
endif
-nnoremap <buffer> <expr> K col('.') < 7 && expand('<Lt>cword>') =~ '\X' && getline('.') =~ '^\w\+\s\+\x\+\>' ? 'wK' : 'K'
nnoremap <buffer> <silent> <C-A> :<C-U><C-R>=v:count1<CR>Cycle<CR>
nnoremap <buffer> <silent> <C-X> :<C-U><C-R>=v:count1<CR>Cycle!<CR>
-let b:undo_ftplugin = b:undo_ftplugin . "|exe 'nunmap <buffer> K'|exe 'nunmap <buffer> <C-A>'|exe 'nunmap <buffer> <C-X>'"
+let b:undo_ftplugin = b:undo_ftplugin . "|exe 'nunmap <buffer> <C-A>'|exe 'nunmap <buffer> <C-X>'"
diff --git a/runtime/ftplugin/i3config.vim b/runtime/ftplugin/i3config.vim
new file mode 100644
index 0000000000..4204510e64
--- /dev/null
+++ b/runtime/ftplugin/i3config.vim
@@ -0,0 +1,13 @@
+" Vim filetype plugin file
+" Language: i3 config file
+" Original Author: Mohamed Boughaba <mohamed dot bgb at gmail dot com>
+" Maintainer: Quentin Hibon
+" Version: 0.4
+" Last Change: 2021 Dec 14
+
+if exists("b:did_ftplugin") | finish | endif
+let b:did_ftplugin = 1
+
+let b:undo_ftplugin = "setlocal cms<"
+
+setlocal commentstring=#\ %s
diff --git a/runtime/ftplugin/solution.vim b/runtime/ftplugin/solution.vim
new file mode 100644
index 0000000000..bd30c7bb19
--- /dev/null
+++ b/runtime/ftplugin/solution.vim
@@ -0,0 +1,37 @@
+" Vim filetype plugin file
+" Language: Microsoft Visual Studio Solution
+" Maintainer: Doug Kearns <dougkearns@gmail.com>
+" Last Change: 2021 Dec 15
+
+if exists("b:did_ftplugin")
+ finish
+endif
+let b:did_ftplugin = 1
+
+let s:cpo_save = &cpo
+set cpo&vim
+
+setlocal comments=:#
+setlocal commentstring=#\ %s
+
+let b:undo_ftplugin = "setl com< cms<"
+
+if exists("loaded_matchit") && !exists("b:match_words")
+ let b:match_words =
+ \ '\<Project\>:\<EndProject\>,' ..
+ \ '\<ProjectSection\>:\<EndProjectSection\>,' ..
+ \ '\<Global\>:\<EndGlobal\>,' ..
+ \ '\<GlobalSection\>:\<EndGlobalSection\>'
+ let b:undo_ftplugin ..= " | unlet! b:match_words"
+endif
+
+if (has("gui_win32") || has("gui_gtk")) && !exists("b:browsefilter")
+ let b:browsefilter = "Microsoft Visual Studio Solution Files\t*.sln\n" ..
+ \ "All Files (*.*)\t*.*\n"
+ let b:undo_ftplugin ..= " | unlet! b:browsefilter"
+endif
+
+let &cpo = s:cpo_save
+unlet s:cpo_save
+
+" vim: nowrap sw=2 sts=2 ts=8 noet:
diff --git a/runtime/ftplugin/zsh.vim b/runtime/ftplugin/zsh.vim
index 53ce1417dd..34410f1c62 100644
--- a/runtime/ftplugin/zsh.vim
+++ b/runtime/ftplugin/zsh.vim
@@ -18,13 +18,13 @@ setlocal comments=:# commentstring=#\ %s formatoptions-=t formatoptions+=croql
let b:undo_ftplugin = "setl com< cms< fo< "
-if executable('zsh')
+if executable('zsh') && &shell !~# '/\%(nologin\|false\)$'
if !has('gui_running') && executable('less')
- command! -buffer -nargs=1 RunHelp silent exe '!MANPAGER= zsh -ic "autoload -Uz run-help; run-help <args> 2>/dev/null | LESS= less"' | redraw!
+ command! -buffer -nargs=1 RunHelp silent exe '!MANPAGER= zsh -c "autoload -Uz run-help; run-help <args> 2>/dev/null | LESS= less"' | redraw!
elseif has('terminal')
- command! -buffer -nargs=1 RunHelp silent exe ':term zsh -ic "autoload -Uz run-help; run-help <args>"'
+ command! -buffer -nargs=1 RunHelp silent exe ':term zsh -c "autoload -Uz run-help; run-help <args>"'
else
- command! -buffer -nargs=1 RunHelp echo system('zsh -ic "autoload -Uz run-help; run-help <args> 2>/dev/null"')
+ command! -buffer -nargs=1 RunHelp echo system('zsh -c "autoload -Uz run-help; run-help <args> 2>/dev/null"')
endif
if !exists('current_compiler')
compiler zsh
diff --git a/runtime/indent/sh.vim b/runtime/indent/sh.vim
index d2fb1ba452..aa47c6d1bd 100644
--- a/runtime/indent/sh.vim
+++ b/runtime/indent/sh.vim
@@ -109,7 +109,7 @@ function! GetShIndent()
let ind += s:indent_value('continuation-line')
endif
elseif s:end_block(line) && !s:start_block(line)
- let ind -= s:indent_value('default')
+ let ind = indent(lnum)
elseif pnum != 0 &&
\ s:is_continuation_line(pline) &&
\ !s:end_block(curline) &&
diff --git a/runtime/indent/xml.vim b/runtime/indent/xml.vim
index da65417939..5bf53ad1f8 100644
--- a/runtime/indent/xml.vim
+++ b/runtime/indent/xml.vim
@@ -39,6 +39,8 @@ setlocal indentkeys=o,O,*<Return>,<>>,<<>,/,{,},!^F
" autoindent: used when the indentexpr returns -1
setlocal autoindent
+let b:undo_indent = "setl ai< inde< indk<"
+
if !exists('b:xml_indent_open')
let b:xml_indent_open = '.\{-}<[:A-Z_a-z]'
" pre tag, e.g. <address>
@@ -51,6 +53,10 @@ if !exists('b:xml_indent_close')
" let b:xml_indent_close = '.\{-}</\(address\)\@!'
endif
+if !exists('b:xml_indent_continuation_filetype')
+ let b:xml_indent_continuation_filetype = 'xml'
+endif
+
let &cpo = s:keepcpo
unlet s:keepcpo
@@ -162,7 +168,7 @@ endfun
func! <SID>IsXMLContinuation(line)
" Checks, whether or not the line matches a start-of-tag
- return a:line !~ '^\s*<' && &ft is# 'xml'
+ return a:line !~ '^\s*<' && &ft =~# b:xml_indent_continuation_filetype
endfunc
func! <SID>HasNoTagEnd(line)
diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua
index 59cb9f8c5b..b4537c2882 100644
--- a/runtime/lua/vim/diagnostic.lua
+++ b/runtime/lua/vim/diagnostic.lua
@@ -30,7 +30,7 @@ M.handlers = setmetatable({}, {
__newindex = function(t, name, handler)
vim.validate { handler = {handler, "t" } }
rawset(t, name, handler)
- if not global_diagnostic_options[name] then
+ if global_diagnostic_options[name] == nil then
global_diagnostic_options[name] = true
end
end,
@@ -91,23 +91,22 @@ local function filter_by_severity(severity, diagnostics)
end
---@private
-local function prefix_source(source, diagnostics)
- vim.validate { source = {source, function(v)
- return v == "always" or v == "if_many"
- end, "'always' or 'if_many'" } }
-
- if source == "if_many" then
- local sources = {}
- for _, d in pairs(diagnostics) do
- if d.source then
- sources[d.source] = true
+local function count_sources(bufnr)
+ local seen = {}
+ local count = 0
+ for _, namespace_diagnostics in pairs(diagnostic_cache[bufnr]) do
+ for _, diagnostic in ipairs(namespace_diagnostics) do
+ if diagnostic.source and not seen[diagnostic.source] then
+ seen[diagnostic.source] = true
+ count = count + 1
end
end
- if #vim.tbl_keys(sources) <= 1 then
- return diagnostics
- end
end
+ return count
+end
+---@private
+local function prefix_source(diagnostics)
return vim.tbl_map(function(d)
if not d.source then
return d
@@ -272,6 +271,8 @@ end
---@private
local function set_diagnostic_cache(namespace, bufnr, diagnostics)
for _, diagnostic in ipairs(diagnostics) do
+ assert(diagnostic.lnum, "Diagnostic line number is required")
+ assert(diagnostic.col, "Diagnostic column is required")
diagnostic.severity = diagnostic.severity and to_severity(diagnostic.severity) or M.severity.ERROR
diagnostic.end_lnum = diagnostic.end_lnum or diagnostic.lnum
diagnostic.end_col = diagnostic.end_col or diagnostic.col
@@ -297,11 +298,6 @@ local function restore_extmarks(bufnr, last)
if not found[extmark[1]] then
local opts = extmark[4]
opts.id = extmark[1]
- -- HACK: end_row should be end_line
- if opts.end_row then
- opts.end_line = opts.end_row
- opts.end_row = nil
- end
pcall(vim.api.nvim_buf_set_extmark, bufnr, ns, extmark[2], extmark[3], opts)
end
end
@@ -556,15 +552,24 @@ end
--- - `table`: Enable this feature with overrides. Use an empty table to use default values.
--- - `function`: Function with signature (namespace, bufnr) that returns any of the above.
---
----@param opts table Configuration table with the following keys:
+---@param opts table|nil When omitted or "nil", retrieve the current configuration. Otherwise, a
+--- configuration table with the following keys:
--- - underline: (default true) Use underline for diagnostics. Options:
--- * severity: Only underline diagnostics matching the given severity
--- |diagnostic-severity|
---- - virtual_text: (default true) Use virtual text for diagnostics. Options:
+--- - virtual_text: (default true) Use virtual text for diagnostics. If multiple diagnostics
+--- are set for a namespace, one prefix per diagnostic + the last diagnostic
+--- message are shown.
+--- Options:
--- * severity: Only show virtual text for diagnostics matching the given
--- severity |diagnostic-severity|
---- * source: (string) Include the diagnostic source in virtual
---- text. One of "always" or "if_many".
+--- * source: (boolean or string) Include the diagnostic source in virtual
+--- text. Use "if_many" to only show sources if there is more than
+--- one diagnostic source in the buffer. Otherwise, any truthy value
+--- means to always show the diagnostic source.
+--- * spacing: (number) Amount of empty spaces inserted at the beginning
+--- of the virtual text.
+--- * prefix: (string) Prepend diagnostic message with prefix.
--- * format: (function) A function that takes a diagnostic as input and
--- returns a string. The return value is the text used to display
--- the diagnostic. Example:
@@ -595,7 +600,7 @@ end
--- global diagnostic options.
function M.config(opts, namespace)
vim.validate {
- opts = { opts, 't' },
+ opts = { opts, 't', true },
namespace = { namespace, 'n', true },
}
@@ -607,10 +612,13 @@ function M.config(opts, namespace)
t = global_diagnostic_options
end
- for opt in pairs(global_diagnostic_options) do
- if opts[opt] ~= nil then
- t[opt] = opts[opt]
- end
+ if not opts then
+ -- Return current config
+ return vim.deepcopy(t)
+ end
+
+ for k, v in pairs(opts) do
+ t[k] = v
end
if namespace then
@@ -640,7 +648,11 @@ function M.set(namespace, bufnr, diagnostics, opts)
vim.validate {
namespace = {namespace, 'n'},
bufnr = {bufnr, 'n'},
- diagnostics = {diagnostics, 't'},
+ diagnostics = {
+ diagnostics,
+ vim.tbl_islist,
+ "a list of diagnostics",
+ },
opts = {opts, 't', true},
}
@@ -806,11 +818,16 @@ M.handlers.signs = {
vim.validate {
namespace = {namespace, 'n'},
bufnr = {bufnr, 'n'},
- diagnostics = {diagnostics, 't'},
+ diagnostics = {
+ diagnostics,
+ vim.tbl_islist,
+ "a list of diagnostics",
+ },
opts = {opts, 't', true},
}
bufnr = get_bufnr(bufnr)
+ opts = opts or {}
if opts.signs and opts.signs.severity then
diagnostics = filter_by_severity(opts.signs.severity, diagnostics)
@@ -869,11 +886,16 @@ M.handlers.underline = {
vim.validate {
namespace = {namespace, 'n'},
bufnr = {bufnr, 'n'},
- diagnostics = {diagnostics, 't'},
+ diagnostics = {
+ diagnostics,
+ vim.tbl_islist,
+ "a list of diagnostics",
+ },
opts = {opts, 't', true},
}
bufnr = get_bufnr(bufnr)
+ opts = opts or {}
if opts.underline and opts.underline.severity then
diagnostics = filter_by_severity(opts.underline.severity, diagnostics)
@@ -917,19 +939,27 @@ M.handlers.virtual_text = {
vim.validate {
namespace = {namespace, 'n'},
bufnr = {bufnr, 'n'},
- diagnostics = {diagnostics, 't'},
+ diagnostics = {
+ diagnostics,
+ vim.tbl_islist,
+ "a list of diagnostics",
+ },
opts = {opts, 't', true},
}
bufnr = get_bufnr(bufnr)
+ opts = opts or {}
local severity
if opts.virtual_text then
if opts.virtual_text.format then
diagnostics = reformat_diagnostics(opts.virtual_text.format, diagnostics)
end
- if opts.virtual_text.source then
- diagnostics = prefix_source(opts.virtual_text.source, diagnostics)
+ if
+ opts.virtual_text.source
+ and (opts.virtual_text.source ~= "if_many" or count_sources(bufnr) > 1)
+ then
+ diagnostics = prefix_source(diagnostics)
end
if opts.virtual_text.severity then
severity = opts.virtual_text.severity
@@ -1074,7 +1104,11 @@ function M.show(namespace, bufnr, diagnostics, opts)
vim.validate {
namespace = { namespace, 'n', true },
bufnr = { bufnr, 'n', true },
- diagnostics = { diagnostics, 't', true },
+ diagnostics = {
+ diagnostics,
+ function(v) return v == nil or vim.tbl_islist(v) end,
+ "a list of diagnostics",
+ },
opts = { opts, 't', true },
}
@@ -1154,8 +1188,11 @@ end
--- - header: (string or table) String to use as the header for the floating window. If a
--- table, it is interpreted as a [text, hl_group] tuple. Overrides the setting
--- from |vim.diagnostic.config()|.
---- - source: (string) Include the diagnostic source in the message. One of "always" or
---- "if_many". Overrides the setting from |vim.diagnostic.config()|.
+--- - source: (boolean or string) Include the diagnostic source in the message.
+--- Use "if_many" to only show sources if there is more than one source of
+--- diagnostics in the buffer. Otherwise, any truthy value means to always show
+--- the diagnostic source. Overrides the setting from
+--- |vim.diagnostic.config()|.
--- - format: (function) A function that takes a diagnostic as input and returns a
--- string. The return value is the text used to display the diagnostic.
--- Overrides the setting from |vim.diagnostic.config()|.
@@ -1267,8 +1304,8 @@ function M.open_float(opts, ...)
diagnostics = reformat_diagnostics(opts.format, diagnostics)
end
- if opts.source then
- diagnostics = prefix_source(opts.source, diagnostics)
+ if opts.source and (opts.source ~= "if_many" or count_sources(bufnr) > 1) then
+ diagnostics = prefix_source(diagnostics)
end
local prefix_opt = if_nil(opts.prefix, (scope == "cursor" and #diagnostics <= 1) and "" or function(_, i)
@@ -1342,16 +1379,16 @@ function M.reset(namespace, bufnr)
diagnostic_cache[iter_bufnr][iter_namespace] = nil
M.hide(iter_namespace, iter_bufnr)
end
- end
- vim.api.nvim_buf_call(bufnr, function()
- vim.api.nvim_command(
- string.format(
- "doautocmd <nomodeline> DiagnosticChanged %s",
- vim.fn.fnameescape(vim.api.nvim_buf_get_name(bufnr))
+ vim.api.nvim_buf_call(iter_bufnr, function()
+ vim.api.nvim_command(
+ string.format(
+ "doautocmd <nomodeline> DiagnosticChanged %s",
+ vim.fn.fnameescape(vim.api.nvim_buf_get_name(iter_bufnr))
+ )
)
- )
- end)
+ end)
+ end
end
--- Add all diagnostics to the quickfix list.
@@ -1516,7 +1553,13 @@ local errlist_type_map = {
---@param diagnostics table List of diagnostics |diagnostic-structure|.
---@return array of quickfix list items |setqflist-what|
function M.toqflist(diagnostics)
- vim.validate { diagnostics = {diagnostics, 't'} }
+ vim.validate {
+ diagnostics = {
+ diagnostics,
+ vim.tbl_islist,
+ "a list of diagnostics",
+ },
+ }
local list = {}
for _, v in ipairs(diagnostics) do
@@ -1547,7 +1590,13 @@ end
--- |getloclist()|.
---@return array of diagnostics |diagnostic-structure|
function M.fromqflist(list)
- vim.validate { list = {list, 't'} }
+ vim.validate {
+ list = {
+ list,
+ vim.tbl_islist,
+ "a list of quickfix items",
+ },
+ }
local diagnostics = {}
for _, item in ipairs(list) do
diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua
new file mode 100644
index 0000000000..736ecc1ff7
--- /dev/null
+++ b/runtime/lua/vim/filetype.lua
@@ -0,0 +1,1579 @@
+local api = vim.api
+
+local M = {}
+
+---@private
+local function starsetf(ft)
+ return {function(path)
+ if not vim.g.fg_ignore_pat then
+ return ft
+ end
+
+ local re = vim.regex(vim.g.fg_ignore_pat)
+ if re:match_str(path) then
+ return ft
+ end
+ end, {
+ -- Starset matches should always have lowest priority
+ priority = -math.huge,
+ }}
+end
+
+---@private
+local function getline(bufnr, lnum)
+ return api.nvim_buf_get_lines(bufnr, lnum-1, lnum, false)[1]
+end
+
+-- Filetypes based on file extension
+-- luacheck: push no unused args
+local extension = {
+ -- BEGIN EXTENSION
+ ["8th"] = "8th",
+ ["a65"] = "a65",
+ aap = "aap",
+ abap = "abap",
+ abc = "abc",
+ abl = "abel",
+ wrm = "acedb",
+ ads = "ada",
+ ada = "ada",
+ gpr = "ada",
+ adb = "ada",
+ tdf = "ahdl",
+ aidl = "aidl",
+ aml = "aml",
+ run = "ampl",
+ scpt = "applescript",
+ ino = "arduino",
+ pde = "arduino",
+ art = "art",
+ asciidoc = "asciidoc",
+ adoc = "asciidoc",
+ ["asn1"] = "asn",
+ asn = "asn",
+ atl = "atlas",
+ as = "atlas",
+ ahk = "autohotkey",
+ ["au3"] = "autoit",
+ ave = "ave",
+ gawk = "awk",
+ awk = "awk",
+ ref = "b",
+ imp = "b",
+ mch = "b",
+ bc = "bc",
+ bdf = "bdf",
+ beancount = "beancount",
+ bib = "bib",
+ bl = "blank",
+ bsdl = "bsdl",
+ bst = "bst",
+ bzl = "bzl",
+ bazel = "bzl",
+ BUILD = "bzl",
+ qc = "c",
+ cabal = "cabal",
+ cdl = "cdl",
+ toc = "cdrtoc",
+ cfc = "cf",
+ cfm = "cf",
+ cfi = "cf",
+ cfg = "cfg",
+ hgrc = "cfg",
+ chf = "ch",
+ chai = "chaiscript",
+ chs = "chaskell",
+ chopro = "chordpro",
+ crd = "chordpro",
+ crdpro = "chordpro",
+ cho = "chordpro",
+ chordpro = "chordpro",
+ eni = "cl",
+ dcl = "clean",
+ icl = "clean",
+ cljx = "clojure",
+ clj = "clojure",
+ cljc = "clojure",
+ cljs = "clojure",
+ cmake = "cmake",
+ cmod = "cmod",
+ lib = "cobol",
+ cob = "cobol",
+ cbl = "cobol",
+ atg = "coco",
+ recipe = "conaryrecipe",
+ mklx = "context",
+ mkiv = "context",
+ mkii = "context",
+ mkxl = "context",
+ mkvi = "context",
+ moc = "cpp",
+ hh = "cpp",
+ tlh = "cpp",
+ inl = "cpp",
+ ipp = "cpp",
+ ["c++"] = "cpp",
+ C = "cpp",
+ cxx = "cpp",
+ H = "cpp",
+ tcc = "cpp",
+ hxx = "cpp",
+ hpp = "cpp",
+ cpp = function(path, bufnr)
+ if vim.g.cynlib_syntax_for_cc then
+ return "cynlib"
+ end
+ return "cpp"
+ end,
+ cc = function(path, bufnr)
+ if vim.g.cynlib_syntax_for_cc then
+ return "cynlib"
+ end
+ return "cpp"
+ end,
+ crm = "crm",
+ csx = "cs",
+ cs = "cs",
+ csc = "csc",
+ csdl = "csdl",
+ fdr = "csp",
+ csp = "csp",
+ css = "css",
+ con = "cterm",
+ feature = "cucumber",
+ cuh = "cuda",
+ cu = "cuda",
+ pld = "cupl",
+ si = "cuplsim",
+ cyn = "cynpp",
+ dart = "dart",
+ drt = "dart",
+ ds = "datascript",
+ dcd = "dcd",
+ def = "def",
+ desc = "desc",
+ directory = "desktop",
+ desktop = "desktop",
+ diff = "diff",
+ rej = "diff",
+ Dockerfile = "dockerfile",
+ sys = "dosbatch",
+ bat = "dosbatch",
+ wrap = "dosini",
+ ini = "dosini",
+ dot = "dot",
+ gv = "dot",
+ drac = "dracula",
+ drc = "dracula",
+ dtd = "dtd",
+ dts = "dts",
+ dtsi = "dts",
+ dylan = "dylan",
+ intr = "dylanintr",
+ lid = "dylanlid",
+ ecd = "ecd",
+ eex = "eelixir",
+ leex = "eelixir",
+ exs = "elixir",
+ elm = "elm",
+ epp = "epuppet",
+ erl = "erlang",
+ hrl = "erlang",
+ yaws = "erlang",
+ erb = "eruby",
+ rhtml = "eruby",
+ ec = "esqlc",
+ EC = "esqlc",
+ strl = "esterel",
+ exp = "expect",
+ factor = "factor",
+ fal = "falcon",
+ fan = "fan",
+ fwt = "fan",
+ fnl = "fennel",
+ ["m4gl"] = "fgl",
+ ["4gl"] = "fgl",
+ ["4gh"] = "fgl",
+ fish = "fish",
+ focexec = "focexec",
+ fex = "focexec",
+ fth = "forth",
+ ft = "forth",
+ FOR = "fortran",
+ ["f77"] = "fortran",
+ ["f03"] = "fortran",
+ fortran = "fortran",
+ ["F95"] = "fortran",
+ ["f90"] = "fortran",
+ ["F03"] = "fortran",
+ fpp = "fortran",
+ FTN = "fortran",
+ ftn = "fortran",
+ ["for"] = "fortran",
+ ["F90"] = "fortran",
+ ["F77"] = "fortran",
+ ["f95"] = "fortran",
+ FPP = "fortran",
+ f = "fortran",
+ F = "fortran",
+ ["F08"] = "fortran",
+ ["f08"] = "fortran",
+ fpc = "fpcmake",
+ fsl = "framescript",
+ fb = "freebasic",
+ fsi = "fsharp",
+ fsx = "fsharp",
+ gdmo = "gdmo",
+ mo = "gdmo",
+ ged = "gedcom",
+ gmi = "gemtext",
+ gemini = "gemtext",
+ gift = "gift",
+ gpi = "gnuplot",
+ gnuplot = "gnuplot",
+ go = "go",
+ gp = "gp",
+ gs = "grads",
+ gretl = "gretl",
+ gradle = "groovy",
+ groovy = "groovy",
+ gsp = "gsp",
+ haml = "haml",
+ hsm = "hamster",
+ ["hs-boot"] = "haskell",
+ hsig = "haskell",
+ hsc = "haskell",
+ hs = "haskell",
+ ht = "haste",
+ htpp = "hastepreproc",
+ hb = "hb",
+ sum = "hercules",
+ errsum = "hercules",
+ ev = "hercules",
+ vc = "hercules",
+ hex = "hex",
+ ["h32"] = "hex",
+ hog = "hog",
+ hws = "hollywood",
+ htt = "httest",
+ htb = "httest",
+ iba = "ibasic",
+ ibi = "ibasic",
+ icn = "icon",
+ inf = "inform",
+ INF = "inform",
+ ii = "initng",
+ iss = "iss",
+ mst = "ist",
+ ist = "ist",
+ ijs = "j",
+ JAL = "jal",
+ jal = "jal",
+ jpr = "jam",
+ jpl = "jam",
+ jav = "java",
+ java = "java",
+ jj = "javacc",
+ jjt = "javacc",
+ es = "javascript",
+ mjs = "javascript",
+ javascript = "javascript",
+ js = "javascript",
+ cjs = "javascript",
+ jsx = "javascriptreact",
+ clp = "jess",
+ jgr = "jgraph",
+ ["j73"] = "jovial",
+ jov = "jovial",
+ jovial = "jovial",
+ properties = "jproperties",
+ slnf = "json",
+ json = "json",
+ jsonp = "json",
+ webmanifest = "json",
+ ipynb = "json",
+ ["json-patch"] = "json",
+ json5 = "json5",
+ jsonc = "jsonc",
+ jsp = "jsp",
+ jl = "julia",
+ kv = "kivy",
+ kix = "kix",
+ kts = "kotlin",
+ kt = "kotlin",
+ ktm = "kotlin",
+ ks = "kscript",
+ k = "kwt",
+ ACE = "lace",
+ ace = "lace",
+ latte = "latte",
+ lte = "latte",
+ ld = "ld",
+ ldif = "ldif",
+ less = "less",
+ lex = "lex",
+ lxx = "lex",
+ ["l++"] = "lex",
+ l = "lex",
+ lhs = "lhaskell",
+ ll = "lifelines",
+ liquid = "liquid",
+ cl = "lisp",
+ L = "lisp",
+ lisp = "lisp",
+ el = "lisp",
+ lsp = "lisp",
+ asd = "lisp",
+ lt = "lite",
+ lite = "lite",
+ lgt = "logtalk",
+ lotos = "lotos",
+ lot = "lotos",
+ lout = "lout",
+ lou = "lout",
+ ulpc = "lpc",
+ lpc = "lpc",
+ sig = "lprolog",
+ lsl = "lsl",
+ lss = "lss",
+ nse = "lua",
+ rockspec = "lua",
+ lua = "lua",
+ quake = "m3quake",
+ at = "m4",
+ eml = "mail",
+ mk = "make",
+ mak = "make",
+ dsp = "make",
+ page = "mallard",
+ map = "map",
+ mws = "maple",
+ mpl = "maple",
+ mv = "maple",
+ mkdn = "markdown",
+ md = "markdown",
+ mdwn = "markdown",
+ mkd = "markdown",
+ markdown = "markdown",
+ mdown = "markdown",
+ mhtml = "mason",
+ comp = "mason",
+ mason = "mason",
+ master = "master",
+ mas = "master",
+ mel = "mel",
+ mf = "mf",
+ mgl = "mgl",
+ mgp = "mgp",
+ my = "mib",
+ mib = "mib",
+ mix = "mix",
+ mixal = "mix",
+ nb = "mma",
+ mmp = "mmp",
+ DEF = "modula2",
+ ["m2"] = "modula2",
+ MOD = "modula2",
+ mi = "modula2",
+ ssc = "monk",
+ monk = "monk",
+ tsc = "monk",
+ isc = "monk",
+ moo = "moo",
+ mp = "mp",
+ mof = "msidl",
+ odl = "msidl",
+ msql = "msql",
+ mu = "mupad",
+ mush = "mush",
+ mysql = "mysql",
+ ["n1ql"] = "n1ql",
+ nql = "n1ql",
+ nanorc = "nanorc",
+ ncf = "ncf",
+ nginx = "nginx",
+ ninja = "ninja",
+ nqc = "nqc",
+ roff = "nroff",
+ tmac = "nroff",
+ man = "nroff",
+ mom = "nroff",
+ nr = "nroff",
+ tr = "nroff",
+ nsi = "nsis",
+ nsh = "nsis",
+ obj = "obj",
+ mlt = "ocaml",
+ mly = "ocaml",
+ mll = "ocaml",
+ mlp = "ocaml",
+ mlip = "ocaml",
+ mli = "ocaml",
+ ml = "ocaml",
+ occ = "occam",
+ xom = "omnimark",
+ xin = "omnimark",
+ opam = "opam",
+ ["or"] = "openroad",
+ ora = "ora",
+ pxsl = "papp",
+ papp = "papp",
+ pxml = "papp",
+ pas = "pascal",
+ lpr = "pascal",
+ dpr = "pascal",
+ pbtxt = "pbtxt",
+ g = "pccts",
+ pcmk = "pcmk",
+ pdf = "pdf",
+ plx = "perl",
+ psgi = "perl",
+ al = "perl",
+ ctp = "php",
+ php = "php",
+ phtml = "php",
+ pike = "pike",
+ pmod = "pike",
+ rcp = "pilrc",
+ pli = "pli",
+ ["pl1"] = "pli",
+ ["p36"] = "plm",
+ plm = "plm",
+ pac = "plm",
+ plp = "plp",
+ pls = "plsql",
+ plsql = "plsql",
+ po = "po",
+ pot = "po",
+ pod = "pod",
+ pk = "poke",
+ ps = "postscr",
+ epsi = "postscr",
+ afm = "postscr",
+ epsf = "postscr",
+ eps = "postscr",
+ pfa = "postscr",
+ ai = "postscr",
+ pov = "pov",
+ ppd = "ppd",
+ it = "ppwiz",
+ ih = "ppwiz",
+ action = "privoxy",
+ pc = "proc",
+ pdb = "prolog",
+ pml = "promela",
+ proto = "proto",
+ ["psd1"] = "ps1",
+ ["psm1"] = "ps1",
+ ["ps1"] = "ps1",
+ pssc = "ps1",
+ ["ps1xml"] = "ps1xml",
+ psf = "psf",
+ psl = "psl",
+ arr = "pyret",
+ pxd = "pyrex",
+ pyx = "pyrex",
+ pyw = "python",
+ py = "python",
+ pyi = "python",
+ ptl = "python",
+ rad = "radiance",
+ mat = "radiance",
+ ["pod6"] = "raku",
+ rakudoc = "raku",
+ rakutest = "raku",
+ rakumod = "raku",
+ ["pm6"] = "raku",
+ raku = "raku",
+ ["t6"] = "raku",
+ ["p6"] = "raku",
+ raml = "raml",
+ rbs = "rbs",
+ rego = "rego",
+ rem = "remind",
+ remind = "remind",
+ frt = "reva",
+ testUnit = "rexx",
+ rex = "rexx",
+ orx = "rexx",
+ rexx = "rexx",
+ jrexx = "rexx",
+ rxj = "rexx",
+ rexxj = "rexx",
+ testGroup = "rexx",
+ rxo = "rexx",
+ Rd = "rhelp",
+ rd = "rhelp",
+ rib = "rib",
+ Rmd = "rmd",
+ rmd = "rmd",
+ smd = "rmd",
+ Smd = "rmd",
+ rnc = "rnc",
+ rng = "rng",
+ rnw = "rnoweb",
+ snw = "rnoweb",
+ Rnw = "rnoweb",
+ Snw = "rnoweb",
+ rsc = "routeros",
+ x = "rpcgen",
+ rpl = "rpl",
+ Srst = "rrst",
+ srst = "rrst",
+ Rrst = "rrst",
+ rrst = "rrst",
+ rst = "rst",
+ rtf = "rtf",
+ rjs = "ruby",
+ rxml = "ruby",
+ rb = "ruby",
+ rant = "ruby",
+ ru = "ruby",
+ rbw = "ruby",
+ gemspec = "ruby",
+ builder = "ruby",
+ rake = "ruby",
+ rs = "rust",
+ sas = "sas",
+ sass = "sass",
+ sa = "sather",
+ sbt = "sbt",
+ scala = "scala",
+ sc = "scala",
+ scd = "scdoc",
+ ss = "scheme",
+ scm = "scheme",
+ sld = "scheme",
+ rkt = "scheme",
+ rktd = "scheme",
+ rktl = "scheme",
+ sce = "scilab",
+ sci = "scilab",
+ scss = "scss",
+ sd = "sd",
+ sdc = "sdc",
+ pr = "sdl",
+ sdl = "sdl",
+ sed = "sed",
+ sexp = "sexplib",
+ sieve = "sieve",
+ siv = "sieve",
+ sil = "sil",
+ sim = "simula",
+ ["s85"] = "sinda",
+ sin = "sinda",
+ ssm = "sisu",
+ sst = "sisu",
+ ssi = "sisu",
+ ["_sst"] = "sisu",
+ ["-sst"] = "sisu",
+ il = "skill",
+ ils = "skill",
+ cdf = "skill",
+ sl = "slang",
+ ice = "slice",
+ score = "slrnsc",
+ tpl = "smarty",
+ ihlp = "smcl",
+ smcl = "smcl",
+ hlp = "smcl",
+ smith = "smith",
+ smt = "smith",
+ sml = "sml",
+ spt = "snobol4",
+ sno = "snobol4",
+ sln = "solution",
+ sparql = "sparql",
+ rq = "sparql",
+ spec = "spec",
+ spice = "spice",
+ sp = "spice",
+ spd = "spup",
+ spdata = "spup",
+ speedup = "spup",
+ spi = "spyce",
+ spy = "spyce",
+ tyc = "sql",
+ typ = "sql",
+ pkb = "sql",
+ tyb = "sql",
+ pks = "sql",
+ sqlj = "sqlj",
+ sqi = "sqr",
+ sqr = "sqr",
+ nut = "squirrel",
+ ["s28"] = "srec",
+ ["s37"] = "srec",
+ srec = "srec",
+ mot = "srec",
+ ["s19"] = "srec",
+ st = "st",
+ imata = "stata",
+ ["do"] = "stata",
+ mata = "stata",
+ ado = "stata",
+ stp = "stp",
+ svelte = "svelte",
+ svg = "svg",
+ swift = "swift",
+ svh = "systemverilog",
+ sv = "systemverilog",
+ tak = "tak",
+ task = "taskedit",
+ tm = "tcl",
+ tcl = "tcl",
+ itk = "tcl",
+ itcl = "tcl",
+ tk = "tcl",
+ jacl = "tcl",
+ tmpl = "template",
+ ti = "terminfo",
+ dtx = "tex",
+ ltx = "tex",
+ bbl = "tex",
+ latex = "tex",
+ sty = "tex",
+ texi = "texinfo",
+ txi = "texinfo",
+ texinfo = "texinfo",
+ text = "text",
+ tf = "tf",
+ tli = "tli",
+ toml = "toml",
+ tpp = "tpp",
+ treetop = "treetop",
+ slt = "tsalt",
+ tsscl = "tsscl",
+ tssgm = "tssgm",
+ tssop = "tssop",
+ tutor = "tutor",
+ twig = "twig",
+ ts = function(path, bufnr)
+ if getline(bufnr, 1):find("<%?xml") then
+ return "xml"
+ else
+ return "typescript"
+ end
+ end,
+ tsx = "typescriptreact",
+ uc = "uc",
+ uit = "uil",
+ uil = "uil",
+ sba = "vb",
+ vb = "vb",
+ dsm = "vb",
+ ctl = "vb",
+ vbs = "vb",
+ vr = "vera",
+ vri = "vera",
+ vrh = "vera",
+ v = "verilog",
+ va = "verilogams",
+ vams = "verilogams",
+ vhdl = "vhdl",
+ vst = "vhdl",
+ vhd = "vhdl",
+ hdl = "vhdl",
+ vho = "vhdl",
+ vbe = "vhdl",
+ vim = "vim",
+ vba = "vim",
+ mar = "vmasm",
+ cm = "voscm",
+ wrl = "vrml",
+ vroom = "vroom",
+ vue = "vue",
+ wat = "wast",
+ wast = "wast",
+ wm = "webmacro",
+ wbt = "winbatch",
+ wml = "wml",
+ wsml = "wsml",
+ ad = "xdefaults",
+ xhtml = "xhtml",
+ xht = "xhtml",
+ msc = "xmath",
+ msf = "xmath",
+ ["psc1"] = "xml",
+ tpm = "xml",
+ xliff = "xml",
+ atom = "xml",
+ xul = "xml",
+ cdxml = "xml",
+ mpd = "xml",
+ rss = "xml",
+ fsproj = "xml",
+ ui = "xml",
+ vbproj = "xml",
+ xlf = "xml",
+ wsdl = "xml",
+ csproj = "xml",
+ wpl = "xml",
+ xmi = "xml",
+ ["xpm2"] = "xpm2",
+ xqy = "xquery",
+ xqm = "xquery",
+ xquery = "xquery",
+ xq = "xquery",
+ xql = "xquery",
+ xs = "xs",
+ xsd = "xsd",
+ xsl = "xslt",
+ xslt = "xslt",
+ yy = "yacc",
+ ["y++"] = "yacc",
+ yxx = "yacc",
+ yml = "yaml",
+ yaml = "yaml",
+ ["z8a"] = "z8a",
+ zig = "zig",
+ zu = "zimbu",
+ zut = "zimbutempl",
+ zsh = "zsh",
+ E = function() vim.fn["dist#ft#FTe"]() end,
+ EU = function() vim.fn["dist#ft#EuphoriaCheck"]() end,
+ EW = function() vim.fn["dist#ft#EuphoriaCheck"]() end,
+ EX = function() vim.fn["dist#ft#EuphoriaCheck"]() end,
+ EXU = function() vim.fn["dist#ft#EuphoriaCheck"]() end,
+ EXW = function() vim.fn["dist#ft#EuphoriaCheck"]() end,
+ PL = function() vim.fn["dist#ft#FTpl"]() end,
+ R = function() vim.fn["dist#ft#FTr"]() end,
+ asm = function() vim.fn["dist#ft#FTasm"]() end,
+ bas = function() vim.fn["dist#ft#FTbas"]() end,
+ bi = function() vim.fn["dist#ft#FTbas"]() end,
+ bm = function() vim.fn["dist#ft#FTbas"]() end,
+ bash = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ btm = function() vim.fn["dist#ft#FTbtm"]() end,
+ c = function() vim.fn["dist#ft#FTlpc"]() end,
+ ch = function() vim.fn["dist#ft#FTchange"]() end,
+ com = function() vim.fn["dist#ft#BindzoneCheck"]('dcl') end,
+ cpt = function() vim.fn["dist#ft#FThtml"]() end,
+ csh = function() vim.fn["dist#ft#CSH"]() end,
+ d = function() vim.fn["dist#ft#DtraceCheck"]() end,
+ db = function() vim.fn["dist#ft#BindzoneCheck"]('') end,
+ dtml = function() vim.fn["dist#ft#FThtml"]() end,
+ e = function() vim.fn["dist#ft#FTe"]() end,
+ ebuild = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ eclass = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ ent = function() vim.fn["dist#ft#FTent"]() end,
+ env = function() vim.fn["dist#ft#SetFileTypeSH"](vim.fn.getline(1)) end,
+ eu = function() vim.fn["dist#ft#EuphoriaCheck"]() end,
+ ew = function() vim.fn["dist#ft#EuphoriaCheck"]() end,
+ ex = function() vim.fn["dist#ft#ExCheck"]() end,
+ exu = function() vim.fn["dist#ft#EuphoriaCheck"]() end,
+ exw = function() vim.fn["dist#ft#EuphoriaCheck"]() end,
+ frm = function() vim.fn["dist#ft#FTVB"]("form") end,
+ fs = function() vim.fn["dist#ft#FTfs"]() end,
+ h = function() vim.fn["dist#ft#FTheader"]() end,
+ htm = function() vim.fn["dist#ft#FThtml"]() end,
+ html = function() vim.fn["dist#ft#FThtml"]() end,
+ i = function() vim.fn["dist#ft#FTprogress_asm"]() end,
+ idl = function() vim.fn["dist#ft#FTidl"]() end,
+ inc = function() vim.fn["dist#ft#FTinc"]() end,
+ inp = function() vim.fn["dist#ft#Check_inp"]() end,
+ ksh = function() vim.fn["dist#ft#SetFileTypeSH"]("ksh") end,
+ lst = function() vim.fn["dist#ft#FTasm"]() end,
+ m = function() vim.fn["dist#ft#FTm"]() end,
+ mac = function() vim.fn["dist#ft#FTasm"]() end,
+ mc = function() vim.fn["dist#ft#McSetf"]() end,
+ mm = function() vim.fn["dist#ft#FTmm"]() end,
+ mms = function() vim.fn["dist#ft#FTmms"]() end,
+ p = function() vim.fn["dist#ft#FTprogress_pascal"]() end,
+ patch = function(path, bufnr)
+ local firstline = getline(bufnr, 1)
+ if string.find(firstline, "^From " .. string.rep("%x", 40) .. "+ Mon Sep 17 00:00:00 2001$") then
+ return "gitsendemail"
+ else
+ return "diff"
+ end
+ end,
+ pl = function() vim.fn["dist#ft#FTpl"]() end,
+ pp = function() vim.fn["dist#ft#FTpp"]() end,
+ pro = function() vim.fn["dist#ft#ProtoCheck"]('idlang') end,
+ pt = function() vim.fn["dist#ft#FThtml"]() end,
+ r = function() vim.fn["dist#ft#FTr"]() end,
+ rdf = function() vim.fn["dist#ft#Redif"]() end,
+ rules = function() vim.fn["dist#ft#FTRules"]() end,
+ sh = function() vim.fn["dist#ft#SetFileTypeSH"](vim.fn.getline(1)) end,
+ shtml = function() vim.fn["dist#ft#FThtml"]() end,
+ sql = function() vim.fn["dist#ft#SQL"]() end,
+ stm = function() vim.fn["dist#ft#FThtml"]() end,
+ tcsh = function() vim.fn["dist#ft#SetFileTypeShell"]("tcsh") end,
+ tex = function() vim.fn["dist#ft#FTtex"]() end,
+ w = function() vim.fn["dist#ft#FTprogress_cweb"]() end,
+ xml = function() vim.fn["dist#ft#FTxml"]() end,
+ y = function() vim.fn["dist#ft#FTy"]() end,
+ zsql = function() vim.fn["dist#ft#SQL"]() end,
+ txt = function(path, bufnr)
+ --helpfiles match *.txt, but should have a modeline as last line
+ if not getline(bufnr, -1):match("vim:.*ft=help") then
+ return "text"
+ end
+ end,
+ -- END EXTENSION
+}
+
+local filename = {
+ -- BEGIN FILENAME
+ ["a2psrc"] = "a2ps",
+ ["/etc/a2ps.cfg"] = "a2ps",
+ [".a2psrc"] = "a2ps",
+ [".asoundrc"] = "alsaconf",
+ ["/usr/share/alsa/alsa.conf"] = "alsaconf",
+ ["/etc/asound.conf"] = "alsaconf",
+ ["build.xml"] = "ant",
+ [".htaccess"] = "apache",
+ ["apt.conf"] = "aptconf",
+ ["/.aptitude/config"] = "aptconf",
+ ["=tagging-method"] = "arch",
+ [".arch-inventory"] = "arch",
+ ["GNUmakefile.am"] = "automake",
+ ["named.root"] = "bindzone",
+ WORKSPACE = "bzl",
+ BUILD = "bzl",
+ ["cabal.config"] = "cabalconfig",
+ ["cabal.project"] = "cabalproject",
+ calendar = "calendar",
+ catalog = "catalog",
+ ["/etc/cdrdao.conf"] = "cdrdaoconf",
+ [".cdrdao"] = "cdrdaoconf",
+ ["/etc/default/cdrdao"] = "cdrdaoconf",
+ ["/etc/defaults/cdrdao"] = "cdrdaoconf",
+ ["cfengine.conf"] = "cfengine",
+ ["CMakeLists.txt"] = "cmake",
+ ["auto.master"] = "conf",
+ ["configure.in"] = "config",
+ ["configure.ac"] = "config",
+ [".cvsrc"] = "cvsrc",
+ ["/debian/changelog"] = "debchangelog",
+ ["changelog.dch"] = "debchangelog",
+ ["changelog.Debian"] = "debchangelog",
+ ["NEWS.dch"] = "debchangelog",
+ ["NEWS.Debian"] = "debchangelog",
+ ["/debian/control"] = "debcontrol",
+ ["/debian/copyright"] = "debcopyright",
+ ["/etc/apt/sources.list"] = "debsources",
+ ["denyhosts.conf"] = "denyhosts",
+ ["dict.conf"] = "dictconf",
+ [".dictrc"] = "dictconf",
+ ["/etc/DIR_COLORS"] = "dircolors",
+ [".dir_colors"] = "dircolors",
+ [".dircolors"] = "dircolors",
+ ["/etc/dnsmasq.conf"] = "dnsmasq",
+ Containerfile = "dockerfile",
+ Dockerfile = "dockerfile",
+ npmrc = "dosini",
+ ["/etc/yum.conf"] = "dosini",
+ ["/etc/pacman.conf"] = "dosini",
+ [".npmrc"] = "dosini",
+ [".editorconfig"] = "dosini",
+ dune = "dune",
+ jbuild = "dune",
+ ["dune-workspace"] = "dune",
+ ["dune-project"] = "dune",
+ ["elinks.conf"] = "elinks",
+ ["mix.lock"] = "elixir",
+ ["filter-rules"] = "elmfilt",
+ ["exim.conf"] = "exim",
+ exports = "exports",
+ [".fetchmailrc"] = "fetchmail",
+ fvSchemes = function() vim.fn["dist#ft#FTfoam"]() end,
+ fvSolution = function() vim.fn["dist#ft#FTfoam"]() end,
+ fvConstraints = function() vim.fn["dist#ft#FTfoam"]() end,
+ fvModels = function() vim.fn["dist#ft#FTfoam"]() end,
+ fstab = "fstab",
+ mtab = "fstab",
+ [".gdbinit"] = "gdb",
+ gdbinit = "gdb",
+ ["lltxxxxx.txt"] = "gedcom",
+ ["TAG_EDITMSG"] = "gitcommit",
+ ["MERGE_MSG"] = "gitcommit",
+ ["COMMIT_EDITMSG"] = "gitcommit",
+ ["NOTES_EDITMSG"] = "gitcommit",
+ ["EDIT_DESCRIPTION"] = "gitcommit",
+ [".gitconfig"] = "gitconfig",
+ [".gitmodules"] = "gitconfig",
+ ["gitolite.conf"] = "gitolite",
+ ["git-rebase-todo"] = "gitrebase",
+ gkrellmrc = "gkrellmrc",
+ [".gnashrc"] = "gnash",
+ [".gnashpluginrc"] = "gnash",
+ gnashpluginrc = "gnash",
+ gnashrc = "gnash",
+ [".gprc"] = "gp",
+ ["/.gnupg/gpg.conf"] = "gpg",
+ ["/.gnupg/options"] = "gpg",
+ ["/var/backups/gshadow.bak"] = "group",
+ ["/etc/gshadow"] = "group",
+ ["/etc/group-"] = "group",
+ ["/etc/gshadow.edit"] = "group",
+ ["/etc/gshadow-"] = "group",
+ ["/etc/group"] = "group",
+ ["/var/backups/group.bak"] = "group",
+ ["/etc/group.edit"] = "group",
+ ["/boot/grub/menu.lst"] = "grub",
+ ["/etc/grub.conf"] = "grub",
+ ["/boot/grub/grub.conf"] = "grub",
+ [".gtkrc"] = "gtkrc",
+ gtkrc = "gtkrc",
+ ["snort.conf"] = "hog",
+ ["vision.conf"] = "hog",
+ ["/etc/host.conf"] = "hostconf",
+ ["/etc/hosts.allow"] = "hostsaccess",
+ ["/etc/hosts.deny"] = "hostsaccess",
+ ["/i3/config"] = "i3config",
+ ["/sway/config"] = "i3config",
+ ["/.sway/config"] = "i3config",
+ ["/.i3/config"] = "i3config",
+ ["/.icewm/menu"] = "icemenu",
+ [".indent.pro"] = "indent",
+ indentrc = "indent",
+ inittab = "inittab",
+ ["ipf.conf"] = "ipfilter",
+ ["ipf6.conf"] = "ipfilter",
+ ["ipf.rules"] = "ipfilter",
+ [".eslintrc"] = "json",
+ [".babelrc"] = "json",
+ ["Pipfile.lock"] = "json",
+ [".firebaserc"] = "json",
+ [".prettierrc"] = "json",
+ Kconfig = "kconfig",
+ ["Kconfig.debug"] = "kconfig",
+ ["lftp.conf"] = "lftp",
+ [".lftprc"] = "lftp",
+ ["/.libao"] = "libao",
+ ["/etc/libao.conf"] = "libao",
+ ["lilo.conf"] = "lilo",
+ ["/etc/limits"] = "limits",
+ [".emacs"] = "lisp",
+ sbclrc = "lisp",
+ [".sbclrc"] = "lisp",
+ [".sawfishrc"] = "lisp",
+ ["/etc/login.access"] = "loginaccess",
+ ["/etc/login.defs"] = "logindefs",
+ ["lynx.cfg"] = "lynx",
+ ["m3overrides"] = "m3build",
+ ["m3makefile"] = "m3build",
+ ["cm3.cfg"] = "m3quake",
+ [".followup"] = "mail",
+ [".article"] = "mail",
+ [".letter"] = "mail",
+ ["/etc/aliases"] = "mailaliases",
+ ["/etc/mail/aliases"] = "mailaliases",
+ mailcap = "mailcap",
+ [".mailcap"] = "mailcap",
+ ["/etc/man.conf"] = "manconf",
+ ["man.config"] = "manconf",
+ ["meson.build"] = "meson",
+ ["meson_options.txt"] = "meson",
+ ["/etc/conf.modules"] = "modconf",
+ ["/etc/modules"] = "modconf",
+ ["/etc/modules.conf"] = "modconf",
+ ["/.mplayer/config"] = "mplayerconf",
+ ["mplayer.conf"] = "mplayerconf",
+ mrxvtrc = "mrxvtrc",
+ [".mrxvtrc"] = "mrxvtrc",
+ ["/etc/nanorc"] = "nanorc",
+ Neomuttrc = "neomuttrc",
+ [".netrc"] = "netrc",
+ [".ocamlinit"] = "ocaml",
+ [".octaverc"] = "octave",
+ octaverc = "octave",
+ ["octave.conf"] = "octave",
+ opam = "opam",
+ ["/etc/pam.conf"] = "pamconf",
+ ["pam_env.conf"] = "pamenv",
+ [".pam_environment"] = "pamenv",
+ ["/var/backups/passwd.bak"] = "passwd",
+ ["/var/backups/shadow.bak"] = "passwd",
+ ["/etc/passwd"] = "passwd",
+ ["/etc/passwd-"] = "passwd",
+ ["/etc/shadow.edit"] = "passwd",
+ ["/etc/shadow-"] = "passwd",
+ ["/etc/shadow"] = "passwd",
+ ["/etc/passwd.edit"] = "passwd",
+ ["pf.conf"] = "pf",
+ ["main.cf"] = "pfmain",
+ pinerc = "pine",
+ [".pinercex"] = "pine",
+ [".pinerc"] = "pine",
+ pinercex = "pine",
+ ["/etc/pinforc"] = "pinfo",
+ ["/.pinforc"] = "pinfo",
+ [".povrayrc"] = "povini",
+ [".procmailrc"] = "procmail",
+ [".procmail"] = "procmail",
+ ["/etc/protocols"] = "protocols",
+ [".pythonstartup"] = "python",
+ [".pythonrc"] = "python",
+ SConstruct = "python",
+ ratpoisonrc = "ratpoison",
+ [".ratpoisonrc"] = "ratpoison",
+ v = "rcs",
+ inputrc = "readline",
+ [".inputrc"] = "readline",
+ [".reminders"] = "remind",
+ ["resolv.conf"] = "resolv",
+ ["robots.txt"] = "robots",
+ Gemfile = "ruby",
+ Puppetfile = "ruby",
+ [".irbrc"] = "ruby",
+ irbrc = "ruby",
+ ["smb.conf"] = "samba",
+ screenrc = "screen",
+ [".screenrc"] = "screen",
+ ["/etc/sensors3.conf"] = "sensors",
+ ["/etc/sensors.conf"] = "sensors",
+ ["/etc/services"] = "services",
+ ["/etc/serial.conf"] = "setserial",
+ ["/etc/udev/cdsymlinks.conf"] = "sh",
+ ["/etc/slp.conf"] = "slpconf",
+ ["/etc/slp.reg"] = "slpreg",
+ ["/etc/slp.spi"] = "slpspi",
+ [".slrnrc"] = "slrnrc",
+ ["sendmail.cf"] = "sm",
+ ["squid.conf"] = "squid",
+ ["/.ssh/config"] = "sshconfig",
+ ["ssh_config"] = "sshconfig",
+ ["sshd_config"] = "sshdconfig",
+ ["/etc/sudoers"] = "sudoers",
+ ["sudoers.tmp"] = "sudoers",
+ ["/etc/sysctl.conf"] = "sysctl",
+ tags = "tags",
+ [".tclshrc"] = "tcl",
+ [".wishrc"] = "tcl",
+ ["tclsh.rc"] = "tcl",
+ ["texmf.cnf"] = "texmf",
+ COPYING = "text",
+ README = "text",
+ LICENSE = "text",
+ AUTHORS = "text",
+ tfrc = "tf",
+ [".tfrc"] = "tf",
+ ["tidy.conf"] = "tidy",
+ tidyrc = "tidy",
+ [".tidyrc"] = "tidy",
+ [".tmux.conf"] = "tmux",
+ ["/.cargo/config"] = "toml",
+ Pipfile = "toml",
+ ["Gopkg.lock"] = "toml",
+ ["/.cargo/credentials"] = "toml",
+ ["Cargo.lock"] = "toml",
+ ["trustees.conf"] = "trustees",
+ ["/etc/udev/udev.conf"] = "udevconf",
+ ["/etc/updatedb.conf"] = "updatedb",
+ ["fdrupstream.log"] = "upstreamlog",
+ vgrindefs = "vgrindefs",
+ [".exrc"] = "vim",
+ ["_exrc"] = "vim",
+ ["_viminfo"] = "viminfo",
+ [".viminfo"] = "viminfo",
+ [".wgetrc"] = "wget",
+ wgetrc = "wget",
+ [".wvdialrc"] = "wvdial",
+ ["wvdial.conf"] = "wvdial",
+ [".Xresources"] = "xdefaults",
+ [".Xpdefaults"] = "xdefaults",
+ ["xdm-config"] = "xdefaults",
+ [".Xdefaults"] = "xdefaults",
+ ["/etc/xinetd.conf"] = "xinetd",
+ fglrxrc = "xml",
+ ["/etc/blkid.tab"] = "xml",
+ ["/etc/blkid.tab.old"] = "xml",
+ ["/etc/zprofile"] = "zsh",
+ [".zlogin"] = "zsh",
+ [".zlogout"] = "zsh",
+ [".zshrc"] = "zsh",
+ [".zprofile"] = "zsh",
+ [".zcompdump"] = "zsh",
+ [".zshenv"] = "zsh",
+ [".zfbfmarks"] = "zsh",
+ [".alias"] = function() vim.fn["dist#ft#CSH"]() end,
+ [".bashrc"] = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ [".cshrc"] = function() vim.fn["dist#ft#CSH"]() end,
+ [".env"] = function() vim.fn["dist#ft#SetFileTypeSH"](vim.fn.getline(1)) end,
+ [".kshrc"] = function() vim.fn["dist#ft#SetFileTypeSH"]("ksh") end,
+ [".login"] = function() vim.fn["dist#ft#CSH"]() end,
+ [".profile"] = function() vim.fn["dist#ft#SetFileTypeSH"](vim.fn.getline(1)) end,
+ [".tcshrc"] = function() vim.fn["dist#ft#SetFileTypeShell"]("tcsh") end,
+ ["/etc/profile"] = function() vim.fn["dist#ft#SetFileTypeSH"](vim.fn.getline(1)) end,
+ APKBUILD = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ PKGBUILD = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ ["bash.bashrc"] = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ bashrc = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ crontab = starsetf('crontab'),
+ ["csh.cshrc"] = function() vim.fn["dist#ft#CSH"]() end,
+ ["csh.login"] = function() vim.fn["dist#ft#CSH"]() end,
+ ["csh.logout"] = function() vim.fn["dist#ft#CSH"]() end,
+ ["indent.pro"] = function() vim.fn["dist#ft#ProtoCheck"]('indent') end,
+ ["tcsh.login"] = function() vim.fn["dist#ft#SetFileTypeShell"]("tcsh") end,
+ ["tcsh.tcshrc"] = function() vim.fn["dist#ft#SetFileTypeShell"]("tcsh") end,
+ -- END FILENAME
+}
+
+local pattern = {
+ -- BEGIN PATTERN
+ [".*/etc/a2ps/.*%.cfg"] = "a2ps",
+ [".*/etc/a2ps%.cfg"] = "a2ps",
+ [".*/usr/share/alsa/alsa%.conf"] = "alsaconf",
+ [".*/etc/asound%.conf"] = "alsaconf",
+ [".*/etc/apache2/sites%-.*/.*%.com"] = "apache",
+ [".*/etc/httpd/.*%.conf"] = "apache",
+ [".*/%.aptitude/config"] = "aptconf",
+ ["[mM]akefile%.am"] = "automake",
+ [".*bsd"] = "bsdl",
+ ["bzr_log%..*"] = "bzr",
+ [".*enlightenment/.*%.cfg"] = "c",
+ [".*/etc/defaults/cdrdao"] = "cdrdaoconf",
+ [".*/etc/cdrdao%.conf"] = "cdrdaoconf",
+ [".*/etc/default/cdrdao"] = "cdrdaoconf",
+ [".*hgrc"] = "cfg",
+ [".*%.%.ch"] = "chill",
+ [".*%.cmake%.in"] = "cmake",
+ [".*/debian/changelog"] = "debchangelog",
+ [".*/debian/control"] = "debcontrol",
+ [".*/debian/copyright"] = "debcopyright",
+ [".*/etc/apt/sources%.list%.d/.*%.list"] = "debsources",
+ [".*/etc/apt/sources%.list"] = "debsources",
+ ["dictd.*%.conf"] = "dictdconf",
+ [".*/etc/DIR_COLORS"] = "dircolors",
+ [".*/etc/dnsmasq%.conf"] = "dnsmasq",
+ ["php%.ini%-.*"] = "dosini",
+ [".*/etc/pacman%.conf"] = "dosini",
+ [".*/etc/yum%.conf"] = "dosini",
+ [".*lvs"] = "dracula",
+ [".*lpe"] = "dracula",
+ [".*esmtprc"] = "esmtprc",
+ [".*Eterm/.*%.cfg"] = "eterm",
+ [".*%.git/modules/.*/config"] = "gitconfig",
+ [".*%.git/config"] = "gitconfig",
+ [".*/etc/gitconfig"] = "gitconfig",
+ [".*/%.config/git/config"] = "gitconfig",
+ [".*%.git/config%.worktree"] = "gitconfig",
+ [".*%.git/worktrees/.*/config%.worktree"] = "gitconfig",
+ ["%.gitsendemail%.msg%......."] = "gitsendemail",
+ ["gkrellmrc_."] = "gkrellmrc",
+ [".*/usr/.*/gnupg/options%.skel"] = "gpg",
+ [".*/%.gnupg/options"] = "gpg",
+ [".*/%.gnupg/gpg%.conf"] = "gpg",
+ [".*/etc/group"] = "group",
+ [".*/etc/gshadow"] = "group",
+ [".*/etc/group%.edit"] = "group",
+ [".*/var/backups/gshadow%.bak"] = "group",
+ [".*/etc/group-"] = "group",
+ [".*/etc/gshadow-"] = "group",
+ [".*/var/backups/group%.bak"] = "group",
+ [".*/etc/gshadow%.edit"] = "group",
+ [".*/boot/grub/grub%.conf"] = "grub",
+ [".*/boot/grub/menu%.lst"] = "grub",
+ [".*/etc/grub%.conf"] = "grub",
+ ["hg%-editor%-.*%.txt"] = "hgcommit",
+ [".*/etc/host%.conf"] = "hostconf",
+ [".*/etc/hosts%.deny"] = "hostsaccess",
+ [".*/etc/hosts%.allow"] = "hostsaccess",
+ [".*%.html%.m4"] = "htmlm4",
+ [".*/%.i3/config"] = "i3config",
+ [".*/sway/config"] = "i3config",
+ [".*/i3/config"] = "i3config",
+ [".*/%.sway/config"] = "i3config",
+ [".*/%.icewm/menu"] = "icemenu",
+ [".*/etc/initng/.*/.*%.i"] = "initng",
+ [".*%.properties_.."] = "jproperties",
+ [".*%.properties_.._.."] = "jproperties",
+ [".*lftp/rc"] = "lftp",
+ [".*/%.libao"] = "libao",
+ [".*/etc/libao%.conf"] = "libao",
+ [".*/etc/.*limits%.conf"] = "limits",
+ [".*/etc/limits"] = "limits",
+ [".*/etc/.*limits%.d/.*%.conf"] = "limits",
+ [".*/LiteStep/.*/.*%.rc"] = "litestep",
+ [".*/etc/login%.access"] = "loginaccess",
+ [".*/etc/login%.defs"] = "logindefs",
+ [".*/etc/mail/aliases"] = "mailaliases",
+ [".*/etc/aliases"] = "mailaliases",
+ [".*[mM]akefile"] = "make",
+ [".*/etc/man%.conf"] = "manconf",
+ [".*/etc/modules%.conf"] = "modconf",
+ [".*/etc/conf%.modules"] = "modconf",
+ [".*/etc/modules"] = "modconf",
+ [".*%.[mi][3g]"] = "modula3",
+ [".*/%.mplayer/config"] = "mplayerconf",
+ ["rndc.*%.conf"] = "named",
+ ["rndc.*%.key"] = "named",
+ ["named.*%.conf"] = "named",
+ [".*/etc/nanorc"] = "nanorc",
+ [".*%.NS[ACGLMNPS]"] = "natural",
+ ["nginx.*%.conf"] = "nginx",
+ [".*/etc/nginx/.*"] = "nginx",
+ [".*nginx%.conf"] = "nginx",
+ [".*/nginx/.*%.conf"] = "nginx",
+ [".*/usr/local/nginx/conf/.*"] = "nginx",
+ [".*%.ml%.cppo"] = "ocaml",
+ [".*%.mli%.cppo"] = "ocaml",
+ [".*%.opam%.template"] = "opam",
+ [".*%.[Oo][Pp][Ll]"] = "opl",
+ [".*/etc/pam%.conf"] = "pamconf",
+ [".*/etc/passwd-"] = "passwd",
+ [".*/etc/shadow"] = "passwd",
+ [".*/etc/shadow%.edit"] = "passwd",
+ [".*/var/backups/shadow%.bak"] = "passwd",
+ [".*/var/backups/passwd%.bak"] = "passwd",
+ [".*/etc/passwd"] = "passwd",
+ [".*/etc/passwd%.edit"] = "passwd",
+ [".*/etc/shadow-"] = "passwd",
+ [".*/%.pinforc"] = "pinfo",
+ [".*/etc/pinforc"] = "pinfo",
+ [".*/etc/protocols"] = "protocols",
+ [".*baseq[2-3]/.*%.cfg"] = "quake",
+ [".*quake[1-3]/.*%.cfg"] = "quake",
+ [".*id1/.*%.cfg"] = "quake",
+ ["[rR]antfile"] = "ruby",
+ ["[rR]akefile"] = "ruby",
+ [".*/etc/sensors%.conf"] = "sensors",
+ [".*/etc/sensors3%.conf"] = "sensors",
+ [".*/etc/services"] = "services",
+ [".*/etc/serial%.conf"] = "setserial",
+ [".*/etc/udev/cdsymlinks%.conf"] = "sh",
+ [".*%._sst%.meta"] = "sisu",
+ [".*%.%-sst%.meta"] = "sisu",
+ [".*%.sst%.meta"] = "sisu",
+ [".*/etc/slp%.conf"] = "slpconf",
+ [".*/etc/slp%.reg"] = "slpreg",
+ [".*/etc/slp%.spi"] = "slpspi",
+ [".*/etc/ssh/ssh_config%.d/.*%.conf"] = "sshconfig",
+ [".*/%.ssh/config"] = "sshconfig",
+ [".*/etc/ssh/sshd_config%.d/.*%.conf"] = "sshdconfig",
+ [".*/etc/sudoers"] = "sudoers",
+ ["svn%-commit.*%.tmp"] = "svn",
+ [".*%.swift%.gyb"] = "swiftgyb",
+ [".*/etc/sysctl%.conf"] = "sysctl",
+ [".*/etc/sysctl%.d/.*%.conf"] = "sysctl",
+ [".*/etc/systemd/.*%.conf%.d/.*%.conf"] = "systemd",
+ [".*/%.config/systemd/user/.*%.d/.*%.conf"] = "systemd",
+ [".*/etc/systemd/system/.*%.d/.*%.conf"] = "systemd",
+ [".*%.t%.html"] = "tilde",
+ ["%.?tmux.*%.conf"] = "tmux",
+ ["%.?tmux.*%.conf.*"] = { "tmux", { priority = -1 } },
+ [".*/%.cargo/config"] = "toml",
+ [".*/%.cargo/credentials"] = "toml",
+ [".*/etc/udev/udev%.conf"] = "udevconf",
+ [".*/etc/udev/permissions%.d/.*%.permissions"] = "udevperm",
+ [".*/etc/updatedb%.conf"] = "updatedb",
+ [".*/%.init/.*%.override"] = "upstart",
+ [".*/usr/share/upstart/.*%.conf"] = "upstart",
+ [".*/%.config/upstart/.*%.override"] = "upstart",
+ [".*/etc/init/.*%.conf"] = "upstart",
+ [".*/etc/init/.*%.override"] = "upstart",
+ [".*/%.config/upstart/.*%.conf"] = "upstart",
+ [".*/%.init/.*%.conf"] = "upstart",
+ [".*/usr/share/upstart/.*%.override"] = "upstart",
+ [".*%.ws[fc]"] = "wsh",
+ [".*/etc/xinetd%.conf"] = "xinetd",
+ [".*/etc/blkid%.tab"] = "xml",
+ [".*/etc/blkid%.tab%.old"] = "xml",
+ [".*%.vbproj%.user"] = "xml",
+ [".*%.fsproj%.user"] = "xml",
+ [".*%.csproj%.user"] = "xml",
+ [".*/etc/xdg/menus/.*%.menu"] = "xml",
+ [".*Xmodmap"] = "xmodmap",
+ [".*/etc/zprofile"] = "zsh",
+ ["%.bash[_-]aliases"] = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ ["%.bash[_-]logout"] = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ ["%.bash[_-]profile"] = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ ["%.cshrc.*"] = function() vim.fn["dist#ft#CSH"]() end,
+ ["%.gtkrc.*"] = starsetf('gtkrc'),
+ ["%.kshrc.*"] = function() vim.fn["dist#ft#SetFileTypeSH"]("ksh") end,
+ ["%.login.*"] = function() vim.fn["dist#ft#CSH"]() end,
+ ["%.neomuttrc.*"] = starsetf('neomuttrc'),
+ ["%.profile.*"] = function() vim.fn["dist#ft#SetFileTypeSH"](vim.fn.getline(1)) end,
+ ["%.reminders.*"] = starsetf('remind'),
+ ["%.tcshrc.*"] = function() vim.fn["dist#ft#SetFileTypeShell"]("tcsh") end,
+ ["%.zcompdump.*"] = starsetf('zsh'),
+ ["%.zlog.*"] = starsetf('zsh'),
+ ["%.zsh.*"] = starsetf('zsh'),
+ [".*%.[1-9]"] = function() vim.fn["dist#ft#FTnroff"]() end,
+ [".*%.[aA]"] = function() vim.fn["dist#ft#FTasm"]() end,
+ [".*%.[sS]"] = function() vim.fn["dist#ft#FTasm"]() end,
+ [".*%.properties_.._.._.*"] = starsetf('jproperties'),
+ [".*%.vhdl_[0-9].*"] = starsetf('vhdl'),
+ [".*/%.fvwm/.*"] = starsetf('fvwm'),
+ [".*/%.gitconfig%.d/.*"] = starsetf('gitconfig'),
+ [".*/%.neomutt/neomuttrc.*"] = starsetf('neomuttrc'),
+ [".*/Xresources/.*"] = starsetf('xdefaults'),
+ [".*/app%-defaults/.*"] = starsetf('xdefaults'),
+ [".*/bind/db%..*"] = starsetf('bindzone'),
+ [".*/debian/patches/.*"] = function() vim.fn["dist#ft#Dep3patch"]() end,
+ [".*/etc/Muttrc%.d/.*"] = starsetf('muttrc'),
+ [".*/etc/apache2/.*%.conf.*"] = starsetf('apache'),
+ [".*/etc/apache2/conf%..*/.*"] = starsetf('apache'),
+ [".*/etc/apache2/mods%-.*/.*"] = starsetf('apache'),
+ [".*/etc/apache2/sites%-.*/.*"] = starsetf('apache'),
+ [".*/etc/cron%.d/.*"] = starsetf('crontab'),
+ [".*/etc/dnsmasq%.d/.*"] = starsetf('dnsmasq'),
+ [".*/etc/httpd/conf%..*/.*"] = starsetf('apache'),
+ [".*/etc/httpd/conf%.d/.*%.conf.*"] = starsetf('apache'),
+ [".*/etc/httpd/mods%-.*/.*"] = starsetf('apache'),
+ [".*/etc/httpd/sites%-.*/.*"] = starsetf('apache'),
+ [".*/etc/logcheck/.*%.d.*/.*"] = starsetf('logcheck'),
+ [".*/etc/modprobe%..*"] = starsetf('modconf'),
+ [".*/etc/pam%.d/.*"] = starsetf('pamconf'),
+ [".*/etc/profile"] = function() vim.fn["dist#ft#SetFileTypeSH"](vim.fn.getline(1)) end,
+ [".*/etc/proftpd/.*%.conf.*"] = starsetf('apachestyle'),
+ [".*/etc/proftpd/conf%..*/.*"] = starsetf('apachestyle'),
+ [".*/etc/sudoers%.d/.*"] = starsetf('sudoers'),
+ [".*/etc/xinetd%.d/.*"] = starsetf('xinetd'),
+ [".*/etc/yum%.repos%.d/.*"] = starsetf('dosini'),
+ [".*/gitolite%-admin/conf/.*"] = starsetf('gitolite'),
+ [".*/named/db%..*"] = starsetf('bindzone'),
+ [".*/tmp/lltmp.*"] = starsetf('gedcom'),
+ [".*asterisk.*/.*voicemail%.conf.*"] = starsetf('asteriskvm'),
+ [".*asterisk/.*%.conf.*"] = starsetf('asterisk'),
+ [".*vimrc.*"] = starsetf('vim'),
+ [".*xmodmap.*"] = starsetf('xmodmap'),
+ ["/etc/gitconfig%.d/.*"] = starsetf('gitconfig'),
+ ["/etc/hostname%..*"] = starsetf('config'),
+ ["Containerfile%..*"] = starsetf('dockerfile'),
+ ["Dockerfile%..*"] = starsetf('dockerfile'),
+ ["JAM.*%..*"] = starsetf('jam'),
+ ["Kconfig%..*"] = starsetf('kconfig'),
+ ["Neomuttrc.*"] = starsetf('neomuttrc'),
+ ["Prl.*%..*"] = starsetf('jam'),
+ ["Xresources.*"] = starsetf('xdefaults'),
+ ["[mM]akefile.*"] = starsetf('make'),
+ ["[rR]akefile.*"] = starsetf('ruby'),
+ ["access%.conf.*"] = starsetf('apache'),
+ ["apache%.conf.*"] = starsetf('apache'),
+ ["apache2%.conf.*"] = starsetf('apache'),
+ ["bash%-fc[-%.]"] = function() vim.fn["dist#ft#SetFileTypeSH"]("bash") end,
+ ["cabal%.project%..*"] = starsetf('cabalproject'),
+ ["crontab%..*"] = starsetf('crontab'),
+ ["drac%..*"] = starsetf('dracula'),
+ ["gtkrc.*"] = starsetf('gtkrc'),
+ ["httpd%.conf.*"] = starsetf('apache'),
+ ["lilo%.conf.*"] = starsetf('lilo'),
+ ["neomuttrc.*"] = starsetf('neomuttrc'),
+ ["proftpd%.conf.*"] = starsetf('apachestyle'),
+ ["reportbug%-.*"] = starsetf('mail'),
+ ["sgml%.catalog.*"] = starsetf('catalog'),
+ ["srm%.conf.*"] = starsetf('apache'),
+ ["tmac%..*"] = starsetf('nroff'),
+ ["zlog.*"] = starsetf('zsh'),
+ ["zsh.*"] = starsetf('zsh'),
+ ["ae%d+%.txt"] = 'mail',
+ ["[a-zA-Z0-9].*Dict"] = function() vim.fn["dist#ft#FTfoam"]() end,
+ ["[a-zA-Z0-9].*Dict%..*"] = function() vim.fn["dist#ft#FTfoam"]() end,
+ ["[a-zA-Z].*Properties"] = function() vim.fn["dist#ft#FTfoam"]() end,
+ ["[a-zA-Z].*Properties%..*"] = function() vim.fn["dist#ft#FTfoam"]() end,
+ [".*Transport%..*"] = function() vim.fn["dist#ft#FTfoam"]() end,
+ [".*/constant/g"] = function() vim.fn["dist#ft#FTfoam"]() end,
+ [".*/0/.*"] = function() vim.fn["dist#ft#FTfoam"]() end,
+ [".*/0%.orig/.*"] = function() vim.fn["dist#ft#FTfoam"]() end,
+ [".*/etc/sensors%.d/[^.].*"] = starsetf('sensors'),
+ [".*%.git/.*"] = function(path, bufnr)
+ local firstline = getline(bufnr, 1)
+ if firstline:find("^" .. string.rep("%x", 40) .. "+ ") or firstline:sub(1, 5) == "ref: " then
+ return "git"
+ end
+ end,
+ -- END PATTERN
+}
+-- luacheck: pop
+
+---@private
+local function sort_by_priority(t)
+ local sorted = {}
+ for k, v in pairs(t) do
+ local ft = type(v) == "table" and v[1] or v
+ assert(type(ft) == "string" or type(ft) == "function", "Expected string or function for filetype")
+
+ local opts = (type(v) == "table" and type(v[2]) == "table") and v[2] or {}
+ if not opts.priority then
+ opts.priority = 0
+ end
+ table.insert(sorted, { [k] = { ft, opts } })
+ end
+ table.sort(sorted, function(a, b)
+ return a[next(a)][2].priority > b[next(b)][2].priority
+ end)
+ return sorted
+end
+
+local pattern_sorted = sort_by_priority(pattern)
+
+---@private
+local function normalize_path(path)
+ return (path:gsub("\\", "/"):gsub("^~", vim.env.HOME))
+end
+
+--- Add new filetype mappings.
+---
+--- Filetype mappings can be added either by extension or by filename (either
+--- the "tail" or the full file path). The full file path is checked first,
+--- followed by the file name. If a match is not found using the filename, then
+--- the filename is matched against the list of patterns (sorted by priority)
+--- until a match is found. Lastly, if pattern matching does not find a
+--- filetype, then the file extension is used.
+---
+--- The filetype can be either a string (in which case it is used as the
+--- filetype directly) or a function. If a function, it takes the full path and
+--- buffer number of the file as arguments (along with captures from the matched
+--- pattern, if any) and should return a string that will be used as the
+--- buffer's filetype.
+---
+--- Filename patterns can specify an optional priority to resolve cases when a
+--- file path matches multiple patterns. Higher priorities are matched first.
+--- When omitted, the priority defaults to 0.
+---
+--- See $VIMRUNTIME/lua/vim/filetype.lua for more examples.
+---
+--- Note that Lua filetype detection is only enabled when |g:do_filetype_lua| is
+--- set to 1.
+---
+--- Example:
+--- <pre>
+--- vim.filetype.add({
+--- extension = {
+--- foo = "fooscript",
+--- bar = function(path, bufnr)
+--- if some_condition() then
+--- return "barscript"
+--- end
+--- return "bar"
+--- end,
+--- },
+--- filename = {
+--- [".foorc"] = "toml",
+--- ["/etc/foo/config"] = "toml",
+--- },
+--- pattern = {
+--- [".*/etc/foo/.*"] = "fooscript",
+--- -- Using an optional priority
+--- [".*/etc/foo/.*%.conf"] = { "dosini", { priority = 10 } },
+--- ["README.(%a+)$"] = function(path, bufnr, ext)
+--- if ext == "md" then
+--- return "markdown"
+--- elseif ext == "rst" then
+--- return "rst"
+--- end
+--- end,
+--- },
+--- })
+--- </pre>
+---
+---@param filetypes table A table containing new filetype maps (see example).
+function M.add(filetypes)
+ for k, v in pairs(filetypes.extension or {}) do
+ extension[k] = v
+ end
+
+ for k, v in pairs(filetypes.filename or {}) do
+ filename[normalize_path(k)] = v
+ end
+
+ for k, v in pairs(filetypes.pattern or {}) do
+ pattern[normalize_path(k)] = v
+ end
+
+ if filetypes.pattern then
+ pattern_sorted = sort_by_priority(pattern)
+ end
+end
+
+---@private
+local function dispatch(ft, path, bufnr, ...)
+ if type(ft) == "function" then
+ ft = ft(path, bufnr, ...)
+ end
+
+ if type(ft) == "string" then
+ api.nvim_buf_set_option(bufnr, "filetype", ft)
+ return true
+ end
+
+ -- Any non-falsey value (that is, anything other than 'nil' or 'false') will
+ -- end filetype matching. This is useful for e.g. the dist#ft functions that
+ -- return 0, but set the buffer's filetype themselves
+ return ft
+end
+
+---@private
+local function match_pattern(name, path, tail, pat)
+ -- If the pattern contains a / match against the full path, otherwise just the tail
+ local fullpat = "^" .. pat .. "$"
+ local matches
+ if pat:find("/") then
+ -- Similar to |autocmd-pattern|, if the pattern contains a '/' then check for a match against
+ -- both the short file name (as typed) and the full file name (after expanding to full path
+ -- and resolving symlinks)
+ matches = name:match(fullpat) or path:match(fullpat)
+ else
+ matches = tail:match(fullpat)
+ end
+ return matches
+end
+
+--- Set the filetype for the given buffer from a file name.
+---
+---@param name string File name (can be an absolute or relative path)
+---@param bufnr number|nil The buffer to set the filetype for. Defaults to the current buffer.
+function M.match(name, bufnr)
+ -- When fired from the main filetypedetect autocommand the {bufnr} argument is omitted, so we use
+ -- the current buffer. The {bufnr} argument is provided to allow extensibility in case callers
+ -- wish to perform filetype detection on buffers other than the current one.
+ bufnr = bufnr or api.nvim_get_current_buf()
+
+ name = normalize_path(name)
+
+ -- First check for the simple case where the full path exists as a key
+ local path = vim.fn.resolve(vim.fn.fnamemodify(name, ":p"))
+ if dispatch(filename[path], path, bufnr) then
+ return
+ end
+
+ -- Next check against just the file name
+ local tail = vim.fn.fnamemodify(name, ":t")
+ if dispatch(filename[tail], path, bufnr) then
+ return
+ end
+
+ -- Next, check the file path against available patterns with non-negative priority
+ local j = 1
+ for i, v in ipairs(pattern_sorted) do
+ local k = next(v)
+ local opts = v[k][2]
+ if opts.priority < 0 then
+ j = i
+ break
+ end
+
+ local ft = v[k][1]
+ local matches = match_pattern(name, path, tail, k)
+ if matches then
+ if dispatch(ft, path, bufnr, matches) then
+ return
+ end
+ end
+ end
+
+ -- Next, check file extension
+ local ext = vim.fn.fnamemodify(name, ":e")
+ if dispatch(extension[ext], path, bufnr) then
+ return
+ end
+
+ -- Finally, check patterns with negative priority
+ for i = j, #pattern_sorted do
+ local v = pattern_sorted[i]
+ local k = next(v)
+
+ local ft = v[k][1]
+ local matches = match_pattern(name, path, tail, k)
+ if matches then
+ if dispatch(ft, path, bufnr, matches) then
+ return
+ end
+ end
+ end
+end
+
+return M
diff --git a/runtime/lua/vim/highlight.lua b/runtime/lua/vim/highlight.lua
index 236f3165f2..12faa0a6e1 100644
--- a/runtime/lua/vim/highlight.lua
+++ b/runtime/lua/vim/highlight.lua
@@ -25,16 +25,29 @@ end
---@param higroup highlight group to use for highlighting
---@param rtype type of range (:help setreg, default charwise)
---@param inclusive boolean indicating whether the range is end-inclusive (default false)
-function highlight.range(bufnr, ns, higroup, start, finish, rtype, inclusive)
+---@param priority number indicating priority of highlight (default 50)
+function highlight.range(bufnr, ns, higroup, start, finish, rtype, inclusive, priority)
rtype = rtype or 'v'
inclusive = inclusive or false
+ priority = priority or 50
-- sanity check
if start[2] < 0 or finish[1] < start[1] then return end
local region = vim.region(bufnr, start, finish, rtype, inclusive)
for linenr, cols in pairs(region) do
- api.nvim_buf_add_highlight(bufnr, ns, higroup, linenr, cols[1], cols[2])
+ local end_row
+ if cols[2] == -1 then
+ end_row = linenr + 1
+ cols[2] = 0
+ end
+ api.nvim_buf_set_extmark(bufnr, ns, linenr, cols[1], {
+ hl_group = higroup,
+ end_row = end_row,
+ end_col = cols[2],
+ priority = priority,
+ strict = false
+ })
end
end
@@ -82,7 +95,7 @@ function highlight.on_yank(opts)
pos1 = {pos1[2] - 1, pos1[3] - 1 + pos1[4]}
pos2 = {pos2[2] - 1, pos2[3] - 1 + pos2[4]}
- highlight.range(bufnr, yank_ns, higroup, pos1, pos2, event.regtype, event.inclusive)
+ highlight.range(bufnr, yank_ns, higroup, pos1, pos2, event.regtype, event.inclusive, 200)
vim.defer_fn(
function()
diff --git a/runtime/lua/vim/keymap.lua b/runtime/lua/vim/keymap.lua
new file mode 100644
index 0000000000..d53b790746
--- /dev/null
+++ b/runtime/lua/vim/keymap.lua
@@ -0,0 +1,135 @@
+local keymap = {}
+
+--- Add a new |mapping|.
+--- Examples:
+--- <pre>
+--- -- Can add mapping to Lua functions
+--- vim.keymap.set('n', 'lhs', function() print("real lua function") end)
+---
+--- -- Can use it to map multiple modes
+--- vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, { buffer=true })
+---
+--- -- Can add mapping for specific buffer
+--- vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", { silent = true, buffer = 5 })
+---
+--- -- Expr mappings
+--- vim.keymap.set('i', '<Tab>', function()
+--- return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
+--- end, { expr = true })
+--- -- <Plug> mappings
+--- vim.keymap.set('n', '[%%', '<Plug>(MatchitNormalMultiBackward)')
+--- </pre>
+---
+--- Note that in a mapping like:
+--- <pre>
+--- vim.keymap.set('n', 'asdf', require('jkl').my_fun)
+--- </pre>
+---
+--- the require('jkl') gets evaluated during this call in order to access the function. If you want to
+--- avoid this cost at startup you can wrap it in a function, for example:
+--- <pre>
+--- vim.keymap.set('n', 'asdf', function() return require('jkl').my_fun() end)
+--- </pre>
+---
+---@param mode string|table Same mode short names as |nvim_set_keymap()|.
+--- Can also be list of modes to create mapping on multiple modes.
+---@param lhs string Left-hand side |{lhs}| of the mapping.
+---@param rhs string|function Right-hand side |{rhs}| of the mapping. Can also be a Lua function.
+--
+---@param opts table A table of |:map-arguments| such as "silent". In addition to the options
+--- listed in |nvim_set_keymap()|, this table also accepts the following keys:
+--- - replace_keycodes: (boolean, default true) When both this and expr is "true",
+--- |nvim_replace_termcodes()| is applied to the result of Lua expr maps.
+--- - remap: (boolean) Make the mapping recursive. This is the
+--- inverse of the "noremap" option from |nvim_set_keymap()|.
+--- Default `true` if `lhs` is a string starting with `<plug>` (case-insensitive), `false` otherwise.
+---@see |nvim_set_keymap()|
+function keymap.set(mode, lhs, rhs, opts)
+ vim.validate {
+ mode = {mode, {'s', 't'}},
+ lhs = {lhs, 's'},
+ rhs = {rhs, {'s', 'f'}},
+ opts = {opts, 't', true}
+ }
+
+ opts = vim.deepcopy(opts) or {}
+ local is_rhs_luaref = type(rhs) == "function"
+ mode = type(mode) == 'string' and {mode} or mode
+
+ if is_rhs_luaref and opts.expr and opts.replace_keycodes ~= false then
+ local user_rhs = rhs
+ rhs = function ()
+ return vim.api.nvim_replace_termcodes(user_rhs(), true, true, true)
+ end
+ end
+ -- clear replace_keycodes from opts table
+ opts.replace_keycodes = nil
+
+ if opts.remap == nil then
+ -- remap by default on <plug> mappings and don't otherwise.
+ opts.noremap = is_rhs_luaref or rhs:lower():match("^<plug>") == nil
+ else
+ -- remaps behavior is opposite of noremap option.
+ opts.noremap = not opts.remap
+ opts.remap = nil
+ end
+
+ if is_rhs_luaref then
+ opts.callback = rhs
+ rhs = ''
+ end
+
+ if opts.buffer then
+ local bufnr = opts.buffer == true and 0 or opts.buffer
+ opts.buffer = nil
+ for _, m in ipairs(mode) do
+ vim.api.nvim_buf_set_keymap(bufnr, m, lhs, rhs, opts)
+ end
+ else
+ opts.buffer = nil
+ for _, m in ipairs(mode) do
+ vim.api.nvim_set_keymap(m, lhs, rhs, opts)
+ end
+ end
+end
+
+--- Remove an existing mapping.
+--- Examples:
+--- <pre>
+--- vim.keymap.del('n', 'lhs')
+---
+--- vim.keymap.del({'n', 'i', 'v'}, '<leader>w', { buffer = 5 })
+--- </pre>
+---@param opts table A table of optional arguments:
+--- - buffer: (number or boolean) Remove a mapping from the given buffer.
+--- When "true" or 0, use the current buffer.
+---@see |vim.keymap.set()|
+---
+function keymap.del(modes, lhs, opts)
+ vim.validate {
+ mode = {modes, {'s', 't'}},
+ lhs = {lhs, 's'},
+ opts = {opts, 't', true}
+ }
+
+ opts = opts or {}
+ modes = type(modes) == 'string' and {modes} or modes
+
+ local buffer = false
+ if opts.buffer ~= nil then
+ buffer = opts.buffer == true and 0 or opts.buffer
+ opts.buffer = nil
+ end
+
+ if buffer == false then
+ for _, mode in ipairs(modes) do
+ vim.api.nvim_del_keymap(mode, lhs)
+ end
+ else
+ for _, mode in ipairs(modes) do
+ vim.api.nvim_buf_del_keymap(buffer, mode, lhs)
+ end
+ end
+end
+
+return keymap
diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua
index 72a84dcc53..37e222a5ce 100644
--- a/runtime/lua/vim/lsp.lua
+++ b/runtime/lua/vim/lsp.lua
@@ -256,7 +256,7 @@ local function validate_client_config(config)
(not config.flags
or not config.flags.debounce_text_changes
or type(config.flags.debounce_text_changes) == 'number'),
- "flags.debounce_text_changes must be nil or a number with the debounce time in milliseconds"
+ "flags.debounce_text_changes must be a number with the debounce time in milliseconds"
)
local cmd, cmd_args = lsp._cmd_parts(config.cmd)
@@ -290,7 +290,7 @@ end
--- Memoizes a function. On first run, the function return value is saved and
--- immediately returned on subsequent runs. If the function returns a multival,
--- only the first returned value will be memoized and returned. The function will only be run once,
---- even if it has side-effects.
+--- even if it has side effects.
---
---@param fn (function) Function to run
---@returns (function) Memoized function
@@ -306,70 +306,138 @@ local function once(fn)
end
end
-
local changetracking = {}
do
--@private
--- client_id → state
---
--- state
+ --- use_incremental_sync: bool
+ --- buffers: bufnr -> buffer_state
+ ---
+ --- buffer_state
--- pending_change?: function that the timer starts to trigger didChange
--- pending_changes: table (uri -> list of pending changeset tables));
- -- Only set if incremental_sync is used
- --- use_incremental_sync: bool
- --- buffers?: table (bufnr → lines); for incremental sync only
+ --- Only set if incremental_sync is used
+ ---
--- timer?: uv_timer
+ --- lines: table
local state_by_client = {}
---@private
function changetracking.init(client, bufnr)
+ local use_incremental_sync = (
+ if_nil(client.config.flags.allow_incremental_sync, true)
+ and client.resolved_capabilities.text_document_did_change == protocol.TextDocumentSyncKind.Incremental
+ )
local state = state_by_client[client.id]
if not state then
state = {
- pending_changes = {};
- use_incremental_sync = (
- if_nil(client.config.flags.allow_incremental_sync, true)
- and client.resolved_capabilities.text_document_did_change == protocol.TextDocumentSyncKind.Incremental
- );
+ buffers = {};
+ debounce = client.config.flags.debounce_text_changes or 150,
+ use_incremental_sync = use_incremental_sync;
}
state_by_client[client.id] = state
end
- if not state.use_incremental_sync then
- return
- end
- if not state.buffers then
- state.buffers = {}
+ if not state.buffers[bufnr] then
+ local buf_state = {}
+ state.buffers[bufnr] = buf_state
+ if use_incremental_sync then
+ buf_state.lines = nvim_buf_get_lines(bufnr, 0, -1, true)
+ buf_state.lines_tmp = {}
+ buf_state.pending_changes = {}
+ end
end
- state.buffers[bufnr] = nvim_buf_get_lines(bufnr, 0, -1, true)
end
---@private
function changetracking.reset_buf(client, bufnr)
- changetracking.flush(client)
+ changetracking.flush(client, bufnr)
local state = state_by_client[client.id]
if state and state.buffers then
+ local buf_state = state.buffers[bufnr]
state.buffers[bufnr] = nil
+ if buf_state and buf_state.timer then
+ buf_state.timer:stop()
+ buf_state.timer:close()
+ buf_state.timer = nil
+ end
end
end
---@private
function changetracking.reset(client_id)
local state = state_by_client[client_id]
- if state then
- state_by_client[client_id] = nil
- changetracking._reset_timer(state)
+ if not state then
+ return
end
+ for _, buf_state in pairs(state.buffers) do
+ if buf_state.timer then
+ buf_state.timer:stop()
+ buf_state.timer:close()
+ buf_state.timer = nil
+ end
+ end
+ state.buffers = {}
+ end
+
+ ---@private
+ --
+ -- Adjust debounce time by taking time of last didChange notification into
+ -- consideration. If the last didChange happened more than `debounce` time ago,
+ -- debounce can be skipped and otherwise maybe reduced.
+ --
+ -- This turns the debounce into a kind of client rate limiting
+ local function next_debounce(debounce, buf_state)
+ if debounce == 0 then
+ return 0
+ end
+ local ns_to_ms = 0.000001
+ if not buf_state.last_flush then
+ return debounce
+ end
+ local now = uv.hrtime()
+ local ms_since_last_flush = (now - buf_state.last_flush) * ns_to_ms
+ return math.max(debounce - ms_since_last_flush, 0)
end
---@private
function changetracking.prepare(bufnr, firstline, lastline, new_lastline)
- local incremental_changes = function(client)
- local cached_buffers = state_by_client[client.id].buffers
- local curr_lines = nvim_buf_get_lines(bufnr, 0, -1, true)
+ local incremental_changes = function(client, buf_state)
+
+ local prev_lines = buf_state.lines
+ local curr_lines = buf_state.lines_tmp
+
+ local changed_lines = nvim_buf_get_lines(bufnr, firstline, new_lastline, true)
+ for i = 1, firstline do
+ curr_lines[i] = prev_lines[i]
+ end
+ for i = firstline + 1, new_lastline do
+ curr_lines[i] = changed_lines[i - firstline]
+ end
+ for i = lastline + 1, #prev_lines do
+ curr_lines[i - lastline + new_lastline] = prev_lines[i]
+ end
+ if tbl_isempty(curr_lines) then
+ -- Can happen when deleting the entire contents of a buffer, see https://github.com/neovim/neovim/issues/16259.
+ curr_lines[1] = ''
+ end
+
local line_ending = buf_get_line_ending(bufnr)
local incremental_change = sync.compute_diff(
- cached_buffers[bufnr], curr_lines, firstline, lastline, new_lastline, client.offset_encoding or 'utf-16', line_ending)
- cached_buffers[bufnr] = curr_lines
+ buf_state.lines, curr_lines, firstline, lastline, new_lastline, client.offset_encoding or 'utf-16', line_ending)
+
+ -- Double-buffering of lines tables is used to reduce the load on the garbage collector.
+ -- At this point the prev_lines table is useless, but its internal storage has already been allocated,
+ -- so let's keep it around for the next didChange event, in which it will become the next
+ -- curr_lines table. Note that setting elements to nil doesn't actually deallocate slots in the
+ -- internal storage - it merely marks them as free, for the GC to deallocate them.
+ for i in ipairs(prev_lines) do
+ prev_lines[i] = nil
+ end
+ buf_state.lines = curr_lines
+ buf_state.lines_tmp = prev_lines
+
return incremental_change
end
local full_changes = once(function()
@@ -383,75 +451,68 @@ do
return
end
local state = state_by_client[client.id]
- local debounce = client.config.flags.debounce_text_changes
- if not debounce then
- local changes = state.use_incremental_sync and incremental_changes(client) or full_changes()
- client.notify("textDocument/didChange", {
- textDocument = {
- uri = uri;
- version = util.buf_versions[bufnr];
- };
- contentChanges = { changes, }
- })
- return
- end
- changetracking._reset_timer(state)
+ local buf_state = state.buffers[bufnr]
+ changetracking._reset_timer(buf_state)
+ local debounce = next_debounce(state.debounce, buf_state)
if state.use_incremental_sync then
-- This must be done immediately and cannot be delayed
-- The contents would further change and startline/endline may no longer fit
- if not state.pending_changes[uri] then
- state.pending_changes[uri] = {}
- end
- table.insert(state.pending_changes[uri], incremental_changes(client))
+ table.insert(buf_state.pending_changes, incremental_changes(client, buf_state))
end
- state.pending_change = function()
- state.pending_change = nil
+ buf_state.pending_change = function()
+ buf_state.pending_change = nil
+ buf_state.last_flush = uv.hrtime()
if client.is_stopped() or not vim.api.nvim_buf_is_valid(bufnr) then
return
end
- if state.use_incremental_sync then
- for change_uri, content_changes in pairs(state.pending_changes) do
- client.notify("textDocument/didChange", {
- textDocument = {
- uri = change_uri;
- version = util.buf_versions[vim.uri_to_bufnr(change_uri)];
- };
- contentChanges = content_changes,
- })
- end
- state.pending_changes = {}
- else
- client.notify("textDocument/didChange", {
- textDocument = {
- uri = uri;
- version = util.buf_versions[bufnr];
- };
- contentChanges = { full_changes() },
- })
- end
+ local changes = state.use_incremental_sync and buf_state.pending_changes or { full_changes() }
+ client.notify("textDocument/didChange", {
+ textDocument = {
+ uri = uri,
+ version = util.buf_versions[bufnr],
+ },
+ contentChanges = changes,
+ })
+ buf_state.pending_changes = {}
+ end
+ if debounce == 0 then
+ buf_state.pending_change()
+ else
+ local timer = vim.loop.new_timer()
+ buf_state.timer = timer
+ -- Must use schedule_wrap because `full_changes()` calls nvim_buf_get_lines
+ timer:start(debounce, 0, vim.schedule_wrap(buf_state.pending_change))
end
- state.timer = vim.loop.new_timer()
- -- Must use schedule_wrap because `full_changes()` calls nvim_buf_get_lines
- state.timer:start(debounce, 0, vim.schedule_wrap(state.pending_change))
end
end
- function changetracking._reset_timer(state)
- if state.timer then
- state.timer:stop()
- state.timer:close()
- state.timer = nil
+ function changetracking._reset_timer(buf_state)
+ if buf_state.timer then
+ buf_state.timer:stop()
+ buf_state.timer:close()
+ buf_state.timer = nil
end
end
--- Flushes any outstanding change notification.
---@private
- function changetracking.flush(client)
+ function changetracking.flush(client, bufnr)
local state = state_by_client[client.id]
- if state then
- changetracking._reset_timer(state)
- if state.pending_change then
- state.pending_change()
+ if not state then
+ return
+ end
+ if bufnr then
+ local buf_state = state.buffers[bufnr] or {}
+ changetracking._reset_timer(buf_state)
+ if buf_state.pending_change then
+ buf_state.pending_change()
+ end
+ else
+ for _, buf_state in pairs(state.buffers) do
+ changetracking._reset_timer(buf_state)
+ if buf_state.pending_change then
+ buf_state.pending_change()
+ end
end
end
end
@@ -645,8 +706,8 @@ end
---@param on_error Callback with parameters (code, ...), invoked
--- when the client operation throws an error. `code` is a number describing
--- the error. Other arguments may be passed depending on the error kind. See
---- |vim.lsp.client_errors| for possible errors.
---- Use `vim.lsp.client_errors[code]` to get human-friendly name.
+--- |vim.lsp.rpc.client_errors| for possible errors.
+--- Use `vim.lsp.rpc.client_errors[code]` to get human-friendly name.
---
---@param before_init Callback with parameters (initialize_params, config)
--- invoked before the LSP "initialize" phase, where `params` contains the
@@ -757,8 +818,8 @@ function lsp.start_client(config)
---
---@param code (number) Error code
---@param err (...) Other arguments may be passed depending on the error kind
- ---@see |vim.lsp.client_errors| for possible errors. Use
- ---`vim.lsp.client_errors[code]` to get a human-friendly name.
+ ---@see |vim.lsp.rpc.client_errors| for possible errors. Use
+ ---`vim.lsp.rpc.client_errors[code]` to get a human-friendly name.
function dispatch.on_error(code, err)
local _ = log.error() and log.error(log_prefix, "on_error", { code = lsp.client_errors[code], err = err })
err_message(log_prefix, ': Error ', lsp.client_errors[code], ': ', vim.inspect(err))
@@ -777,6 +838,10 @@ function lsp.start_client(config)
---@param code (number) exit code of the process
---@param signal (number) the signal used to terminate (if any)
function dispatch.on_exit(code, signal)
+ if config.on_exit then
+ pcall(config.on_exit, code, signal, client_id)
+ end
+
active_clients[client_id] = nil
uninitialized_clients[client_id] = nil
@@ -792,10 +857,6 @@ function lsp.start_client(config)
vim.notify(msg, vim.log.levels.WARN)
end)
end
-
- if config.on_exit then
- pcall(config.on_exit, code, signal, client_id)
- end
end
-- Start the RPC client.
@@ -897,7 +958,7 @@ function lsp.start_client(config)
client.initialized = true
uninitialized_clients[client_id] = nil
client.workspace_folders = workspace_folders
- -- TODO(mjlbach): Backwards compatbility, to be removed in 0.7
+ -- TODO(mjlbach): Backwards compatibility, to be removed in 0.7
client.workspaceFolders = client.workspace_folders
client.server_capabilities = assert(result.capabilities, "initialize result doesn't contain capabilities")
-- These are the cleaned up capabilities we use for dynamically deciding
@@ -957,7 +1018,7 @@ function lsp.start_client(config)
or error(string.format("not found: %q request handler for client %q.", method, client.name))
end
-- Ensure pending didChange notifications are sent so that the server doesn't operate on a stale state
- changetracking.flush(client)
+ changetracking.flush(client, bufnr)
bufnr = resolve_bufnr(bufnr)
local _ = log.debug() and log.debug(log_prefix, "client.request", client_id, method, params, handler, bufnr)
local success, request_id = rpc.request(method, params, function(err, result)
@@ -1014,14 +1075,16 @@ function lsp.start_client(config)
---@private
--- Sends a notification to an LSP server.
---
- ---@param method (string) LSP method name.
- ---@param params (optional, table) LSP request params.
- ---@param bufnr (number) Buffer handle, or 0 for current.
+ ---@param method string LSP method name.
+ ---@param params table|nil LSP request params.
---@returns {status} (bool) true if the notification was successful.
---If it is false, then it will always be false
---(the client has shutdown).
- function client.notify(...)
- return rpc.notify(...)
+ function client.notify(method, params)
+ if method ~= 'textDocument/didChange' then
+ changetracking.flush(client)
+ end
+ return rpc.notify(method, params)
end
---@private
@@ -1112,9 +1175,9 @@ local text_document_did_change_handler
do
text_document_did_change_handler = function(_, bufnr, changedtick, firstline, lastline, new_lastline)
- -- Don't do anything if there are no clients attached.
+ -- Detach (nvim_buf_attach) via returning True to on_lines if no clients are attached
if tbl_isempty(all_buffer_active_clients[bufnr] or {}) then
- return
+ return true
end
util.buf_versions[bufnr] = changedtick
local compute_change_and_notify = changetracking.prepare(bufnr, firstline, lastline, new_lastline)
@@ -1131,7 +1194,7 @@ function lsp._text_document_did_save_handler(bufnr)
if client.resolved_capabilities.text_document_save then
local included_text
if client.resolved_capabilities.text_document_save_include_text then
- included_text = text()
+ included_text = text(bufnr)
end
client.notify('textDocument/didSave', {
textDocument = {
@@ -1156,6 +1219,12 @@ function lsp.buf_attach_client(bufnr, client_id)
client_id = {client_id, 'n'};
}
bufnr = resolve_bufnr(bufnr)
+ if not vim.api.nvim_buf_is_loaded(bufnr) then
+ local _ = log.warn() and log.warn(
+ string.format("buf_attach_client called on unloaded buffer (id: %d): ", bufnr)
+ )
+ return false
+ end
local buffer_client_ids = all_buffer_active_clients[bufnr]
-- This is our first time attaching to this buffer.
if not buffer_client_ids then
@@ -1214,6 +1283,50 @@ function lsp.buf_attach_client(bufnr, client_id)
return true
end
+--- Detaches client from the specified buffer.
+--- Note: While the server is notified that the text document (buffer)
+--- was closed, it is still able to send notifications should it ignore this notification.
+---
+---@param bufnr number Buffer handle, or 0 for current
+---@param client_id number Client id
+function lsp.buf_detach_client(bufnr, client_id)
+ validate {
+ bufnr = {bufnr, 'n', true};
+ client_id = {client_id, 'n'};
+ }
+ bufnr = resolve_bufnr(bufnr)
+
+ local client = lsp.get_client_by_id(client_id)
+ if not client or not client.attached_buffers[bufnr] then
+ vim.notify(
+ string.format('Buffer (id: %d) is not attached to client (id: %d). Cannot detach.', client_id, bufnr)
+ )
+ return
+ end
+
+ changetracking.reset_buf(client, bufnr)
+
+ if client.resolved_capabilities.text_document_open_close then
+ local uri = vim.uri_from_bufnr(bufnr)
+ local params = { textDocument = { uri = uri; } }
+ client.notify('textDocument/didClose', params)
+ end
+
+ client.attached_buffers[bufnr] = nil
+ util.buf_versions[bufnr] = nil
+
+ all_buffer_active_clients[bufnr][client_id] = nil
+ if #vim.tbl_keys(all_buffer_active_clients[bufnr]) == 0 then
+ all_buffer_active_clients[bufnr] = nil
+ end
+
+ local namespace = vim.lsp.diagnostic.get_namespace(client_id)
+ vim.diagnostic.reset(namespace, bufnr)
+
+ vim.notify(string.format('Detached buffer (id: %d) from client (id: %d)', bufnr, client_id))
+
+end
+
--- Checks if a buffer is attached for a particular client.
---
---@param bufnr (number) Buffer handle, or 0 for current
@@ -1658,14 +1771,14 @@ end
--
-- Can be used to lookup the number from the name or the
-- name from the number.
--- Levels by name: "trace", "debug", "info", "warn", "error"
--- Level numbers begin with "trace" at 0
+-- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR"
+-- Level numbers begin with "TRACE" at 0
lsp.log_levels = log.levels
--- Sets the global log level for LSP logging.
---
---- Levels by name: "trace", "debug", "info", "warn", "error"
---- Level numbers begin with "trace" at 0
+--- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR"
+--- Level numbers begin with "TRACE" at 0
---
--- Use `lsp.log_levels` for reverse lookup.
---
diff --git a/runtime/lua/vim/lsp/buf.lua b/runtime/lua/vim/lsp/buf.lua
index 8e3ed9b002..eb7ec579f1 100644
--- a/runtime/lua/vim/lsp/buf.lua
+++ b/runtime/lua/vim/lsp/buf.lua
@@ -184,7 +184,7 @@ function M.formatting_sync(options, timeout_ms)
local result, err = client.request_sync('textDocument/formatting', params, timeout_ms, bufnr)
if result and result.result then
- util.apply_text_edits(result.result, bufnr)
+ util.apply_text_edits(result.result, bufnr, client.offset_encoding)
elseif err then
vim.notify('vim.lsp.buf.formatting_sync: ' .. err, vim.log.levels.WARN)
end
@@ -228,7 +228,7 @@ function M.formatting_seq_sync(options, timeout_ms, order)
local params = util.make_formatting_params(options)
local result, err = client.request_sync("textDocument/formatting", params, timeout_ms, vim.api.nvim_get_current_buf())
if result and result.result then
- util.apply_text_edits(result.result, bufnr)
+ util.apply_text_edits(result.result, bufnr, client.offset_encoding)
elseif err then
vim.notify(string.format("vim.lsp.buf.formatting_seq_sync: (%s) %s", client.name, err), vim.log.levels.WARN)
end
@@ -447,13 +447,16 @@ end
---@param query (string, optional)
function M.workspace_symbol(query)
query = query or npcall(vfn.input, "Query: ")
+ if query == nil then
+ return
+ end
local params = {query = query}
request('workspace/symbol', params)
end
--- Send request to the server to resolve document highlights for the current
--- text document position. This request can be triggered by a key mapping or
---- by events such as `CursorHold`, eg:
+--- by events such as `CursorHold`, e.g.:
---
--- <pre>
--- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
@@ -503,7 +506,7 @@ local function on_code_action_results(results, ctx)
---@private
local function apply_action(action, client)
if action.edit then
- util.apply_workspace_edit(action.edit)
+ util.apply_workspace_edit(action.edit, client.offset_encoding)
end
if action.command then
local command = type(action.command) == 'table' and action.command or action
@@ -627,14 +630,19 @@ end
--- Executes an LSP server command.
---
----@param command A valid `ExecuteCommandParams` object
+---@param command_params table A valid `ExecuteCommandParams` object
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_executeCommand
-function M.execute_command(command)
+function M.execute_command(command_params)
validate {
- command = { command.command, 's' },
- arguments = { command.arguments, 't', true }
+ command = { command_params.command, 's' },
+ arguments = { command_params.arguments, 't', true }
+ }
+ command_params = {
+ command=command_params.command,
+ arguments=command_params.arguments,
+ workDoneToken=command_params.workDoneToken,
}
- request('workspace/executeCommand', command)
+ request('workspace/executeCommand', command_params )
end
return M
diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua
index 8850d25233..68942ae11a 100644
--- a/runtime/lua/vim/lsp/diagnostic.lua
+++ b/runtime/lua/vim/lsp/diagnostic.lua
@@ -168,8 +168,8 @@ end
--- },
--- -- Use a function to dynamically turn signs off
--- -- and on, using buffer local variables
---- signs = function(bufnr, client_id)
---- return vim.bo[bufnr].show_signs == false
+--- signs = function(namespace, bufnr)
+--- return vim.b[bufnr].show_signs == true
--- end,
--- -- Disable a feature
--- update_in_insert = false,
@@ -243,7 +243,7 @@ end
---@param client_id number
---@private
function M.save(diagnostics, bufnr, client_id)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.save is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.save is deprecated. See :h deprecated', vim.log.levels.WARN)
local namespace = M.get_namespace(client_id)
vim.diagnostic.set(namespace, bufnr, diagnostic_lsp_to_vim(diagnostics, bufnr, client_id))
end
@@ -257,7 +257,7 @@ end
--- If nil, diagnostics of all clients are included.
---@return table with diagnostics grouped by bufnr (bufnr: Diagnostic[])
function M.get_all(client_id)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.get_all is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.get_all is deprecated. See :h deprecated', vim.log.levels.WARN)
local result = {}
local namespace
if client_id then
@@ -279,7 +279,7 @@ end
--- Else, return just the diagnostics associated with the client_id.
---@param predicate function|nil Optional function for filtering diagnostics
function M.get(bufnr, client_id, predicate)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.get is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.get is deprecated. See :h deprecated', vim.log.levels.WARN)
predicate = predicate or function() return true end
if client_id == nil then
local all_diagnostics = {}
@@ -341,7 +341,7 @@ end
---@param severity DiagnosticSeverity
---@param client_id number the client id
function M.get_count(bufnr, severity, client_id)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.get_count is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.get_count is deprecated. See :h deprecated', vim.log.levels.WARN)
severity = severity_lsp_to_vim(severity)
local opts = { severity = severity }
if client_id ~= nil then
@@ -358,7 +358,7 @@ end
---@param opts table See |vim.lsp.diagnostic.goto_next()|
---@return table Previous diagnostic
function M.get_prev(opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.get_prev is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.get_prev is deprecated. See :h deprecated', vim.log.levels.WARN)
if opts then
if opts.severity then
opts.severity = severity_lsp_to_vim(opts.severity)
@@ -376,7 +376,7 @@ end
---@param opts table See |vim.lsp.diagnostic.goto_next()|
---@return table Previous diagnostic position
function M.get_prev_pos(opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.get_prev_pos is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.get_prev_pos is deprecated. See :h deprecated', vim.log.levels.WARN)
if opts then
if opts.severity then
opts.severity = severity_lsp_to_vim(opts.severity)
@@ -393,7 +393,7 @@ end
---
---@param opts table See |vim.lsp.diagnostic.goto_next()|
function M.goto_prev(opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.goto_prev is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.goto_prev is deprecated. See :h deprecated', vim.log.levels.WARN)
if opts then
if opts.severity then
opts.severity = severity_lsp_to_vim(opts.severity)
@@ -411,7 +411,7 @@ end
---@param opts table See |vim.lsp.diagnostic.goto_next()|
---@return table Next diagnostic
function M.get_next(opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.get_next is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.get_next is deprecated. See :h deprecated', vim.log.levels.WARN)
if opts then
if opts.severity then
opts.severity = severity_lsp_to_vim(opts.severity)
@@ -429,7 +429,7 @@ end
---@param opts table See |vim.lsp.diagnostic.goto_next()|
---@return table Next diagnostic position
function M.get_next_pos(opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.get_next_pos is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.get_next_pos is deprecated. See :h deprecated', vim.log.levels.WARN)
if opts then
if opts.severity then
opts.severity = severity_lsp_to_vim(opts.severity)
@@ -444,7 +444,7 @@ end
---
---@deprecated Prefer |vim.diagnostic.goto_next()|
function M.goto_next(opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.goto_next is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.goto_next is deprecated. See :h deprecated', vim.log.levels.WARN)
if opts then
if opts.severity then
opts.severity = severity_lsp_to_vim(opts.severity)
@@ -468,7 +468,7 @@ end
--- - severity_limit (DiagnosticSeverity):
--- - Limit severity of diagnostics found. E.g. "Warning" means { "Error", "Warning" } will be valid.
function M.set_signs(diagnostics, bufnr, client_id, _, opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.set_signs is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.set_signs is deprecated. See :h deprecated', vim.log.levels.WARN)
local namespace = M.get_namespace(client_id)
if opts and not opts.severity and opts.severity_limit then
opts.severity = {min=severity_lsp_to_vim(opts.severity_limit)}
@@ -489,7 +489,7 @@ end
--- - severity_limit (DiagnosticSeverity):
--- - Limit severity of diagnostics found. E.g. "Warning" means { "Error", "Warning" } will be valid.
function M.set_underline(diagnostics, bufnr, client_id, _, opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.set_underline is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.set_underline is deprecated. See :h deprecated', vim.log.levels.WARN)
local namespace = M.get_namespace(client_id)
if opts and not opts.severity and opts.severity_limit then
opts.severity = {min=severity_lsp_to_vim(opts.severity_limit)}
@@ -511,7 +511,7 @@ end
--- - severity_limit (DiagnosticSeverity):
--- - Limit severity of diagnostics found. E.g. "Warning" means { "Error", "Warning" } will be valid.
function M.set_virtual_text(diagnostics, bufnr, client_id, _, opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.set_virtual_text is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.set_virtual_text is deprecated. See :h deprecated', vim.log.levels.WARN)
local namespace = M.get_namespace(client_id)
if opts and not opts.severity and opts.severity_limit then
opts.severity = {min=severity_lsp_to_vim(opts.severity_limit)}
@@ -530,7 +530,7 @@ end
---@return an array of [text, hl_group] arrays. This can be passed directly to
--- the {virt_text} option of |nvim_buf_set_extmark()|.
function M.get_virtual_text_chunks_for_line(bufnr, _, line_diags, opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.get_virtual_text_chunks_for_line is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.get_virtual_text_chunks_for_line is deprecated. See :h deprecated', vim.log.levels.WARN)
return vim.diagnostic._get_virt_text_chunks(diagnostic_lsp_to_vim(line_diags, bufnr), opts)
end
@@ -548,7 +548,7 @@ end
---@param position table|nil The (0,0)-indexed position
---@return table {popup_bufnr, win_id}
function M.show_position_diagnostics(opts, buf_nr, position)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.show_position_diagnostics is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.show_position_diagnostics is deprecated. See :h deprecated', vim.log.levels.WARN)
opts = opts or {}
opts.scope = "cursor"
opts.pos = position
@@ -572,7 +572,7 @@ end
---@param client_id number|nil the client id
---@return table {popup_bufnr, win_id}
function M.show_line_diagnostics(opts, buf_nr, line_nr, client_id)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.show_line_diagnostics is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.show_line_diagnostics is deprecated. See :h deprecated', vim.log.levels.WARN)
opts = opts or {}
opts.scope = "line"
opts.pos = line_nr
@@ -596,7 +596,7 @@ end
--- client. The default is to redraw diagnostics for all attached
--- clients.
function M.redraw(bufnr, client_id)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.redraw is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.redraw is deprecated. See :h deprecated', vim.log.levels.WARN)
bufnr = get_bufnr(bufnr)
if not client_id then
return vim.lsp.for_each_buffer_client(bufnr, function(client)
@@ -624,7 +624,7 @@ end
--- - {workspace}: (boolean, default true)
--- - Set the list with workspace diagnostics
function M.set_qflist(opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.set_qflist is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.set_qflist is deprecated. See :h deprecated', vim.log.levels.WARN)
opts = opts or {}
if opts.severity then
opts.severity = severity_lsp_to_vim(opts.severity)
@@ -656,7 +656,7 @@ end
--- - {workspace}: (boolean, default false)
--- - Set the list with workspace diagnostics
function M.set_loclist(opts)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.set_loclist is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.set_loclist is deprecated. See :h deprecated', vim.log.levels.WARN)
opts = opts or {}
if opts.severity then
opts.severity = severity_lsp_to_vim(opts.severity)
@@ -684,7 +684,7 @@ end
-- send diagnostic information and the client will still process it. The
-- diagnostics are simply not displayed to the user.
function M.disable(bufnr, client_id)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.disable is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.disable is deprecated. See :h deprecated', vim.log.levels.WARN)
if not client_id then
return vim.lsp.for_each_buffer_client(bufnr, function(client)
M.disable(bufnr, client.id)
@@ -705,7 +705,7 @@ end
--- client. The default is to enable diagnostics for all attached
--- clients.
function M.enable(bufnr, client_id)
- vim.api.nvim_echo({{'vim.lsp.diagnostic.enable is deprecated. See :h deprecated', 'WarningMsg'}}, true, {})
+ vim.notify_once('vim.lsp.diagnostic.enable is deprecated. See :h deprecated', vim.log.levels.WARN)
if not client_id then
return vim.lsp.for_each_buffer_client(bufnr, function(client)
M.enable(bufnr, client.id)
diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua
index c974d1a6b4..a997b887d9 100644
--- a/runtime/lua/vim/lsp/handlers.lua
+++ b/runtime/lua/vim/lsp/handlers.lua
@@ -111,13 +111,15 @@ M['client/registerCapability'] = function(_, _, ctx)
end
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit
-M['workspace/applyEdit'] = function(_, workspace_edit)
+M['workspace/applyEdit'] = function(_, workspace_edit, ctx)
if not workspace_edit then return end
-- TODO(ashkan) Do something more with label?
+ local client_id = ctx.client_id
+ local client = vim.lsp.get_client_by_id(client_id)
if workspace_edit.label then
print("Workspace edit", workspace_edit.label)
end
- local status, result = pcall(util.apply_workspace_edit, workspace_edit.edit)
+ local status, result = pcall(util.apply_workspace_edit, workspace_edit.edit, client.offset_encoding)
return {
applied = status;
failureReason = result;
@@ -150,6 +152,17 @@ M['workspace/configuration'] = function(_, result, ctx)
return response
end
+--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_workspaceFolders
+M['workspace/workspaceFolders'] = function(_, _, ctx)
+ local client_id = ctx.client_id
+ local client = vim.lsp.get_client_by_id(client_id)
+ if not client then
+ err_message("LSP[id=", client_id, "] client has shut down after sending the message")
+ return
+ end
+ return client.workspace_folders or vim.NIL
+end
+
M['textDocument/publishDiagnostics'] = function(...)
return require('vim.lsp.diagnostic').on_publish_diagnostics(...)
end
@@ -159,6 +172,31 @@ M['textDocument/codeLens'] = function(...)
end
+--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references
+M['textDocument/references'] = function(_, result, ctx, config)
+ if not result or vim.tbl_isempty(result) then
+ vim.notify('No references found')
+ else
+ local client = vim.lsp.get_client_by_id(ctx.client_id)
+ config = config or {}
+ if config.loclist then
+ vim.fn.setloclist(0, {}, ' ', {
+ title = 'References';
+ items = util.locations_to_items(result, client.offset_encoding);
+ context = ctx;
+ })
+ api.nvim_command("lopen")
+ else
+ vim.fn.setqflist({}, ' ', {
+ title = 'References';
+ items = util.locations_to_items(result, client.offset_encoding);
+ context = ctx;
+ })
+ api.nvim_command("botright copen")
+ end
+ end
+end
+
---@private
--- Return a function that converts LSP responses to list items and opens the list
@@ -169,23 +207,26 @@ end
--- loclist: (boolean) use the location list (default is to use the quickfix list)
---
---@param map_result function `((resp, bufnr) -> list)` to convert the response
----@param entity name of the resource used in a `not found` error message
-local function response_to_list(map_result, entity)
- return function(_,result, ctx, config)
+---@param entity string name of the resource used in a `not found` error message
+---@param title_fn function Function to call to generate list title
+local function response_to_list(map_result, entity, title_fn)
+ return function(_, result, ctx, config)
if not result or vim.tbl_isempty(result) then
vim.notify('No ' .. entity .. ' found')
else
config = config or {}
if config.loclist then
vim.fn.setloclist(0, {}, ' ', {
- title = 'Language Server';
+ title = title_fn(ctx);
items = map_result(result, ctx.bufnr);
+ context = ctx;
})
api.nvim_command("lopen")
else
vim.fn.setqflist({}, ' ', {
- title = 'Language Server';
+ title = title_fn(ctx);
items = map_result(result, ctx.bufnr);
+ context = ctx;
})
api.nvim_command("botright copen")
end
@@ -194,31 +235,36 @@ local function response_to_list(map_result, entity)
end
---see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_references
-M['textDocument/references'] = response_to_list(util.locations_to_items, 'references')
-
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_documentSymbol
-M['textDocument/documentSymbol'] = response_to_list(util.symbols_to_items, 'document symbols')
+M['textDocument/documentSymbol'] = response_to_list(util.symbols_to_items, 'document symbols', function(ctx)
+ local fname = vim.fn.fnamemodify(vim.uri_to_fname(ctx.params.textDocument.uri), ":.")
+ return string.format('Symbols in %s', fname)
+end)
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_symbol
-M['workspace/symbol'] = response_to_list(util.symbols_to_items, 'symbols')
+M['workspace/symbol'] = response_to_list(util.symbols_to_items, 'symbols', function(ctx)
+ return string.format("Symbols matching '%s'", ctx.params.query)
+end)
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rename
-M['textDocument/rename'] = function(_, result, _)
+M['textDocument/rename'] = function(_, result, ctx, _)
if not result then return end
- util.apply_workspace_edit(result)
+ local client = vim.lsp.get_client_by_id(ctx.client_id)
+ util.apply_workspace_edit(result, client.offset_encoding)
end
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_rangeFormatting
M['textDocument/rangeFormatting'] = function(_, result, ctx, _)
if not result then return end
- util.apply_text_edits(result, ctx.bufnr)
+ local client = vim.lsp.get_client_by_id(ctx.client_id)
+ util.apply_text_edits(result, ctx.bufnr, client.offset_encoding)
end
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_formatting
M['textDocument/formatting'] = function(_, result, ctx, _)
if not result then return end
- util.apply_text_edits(result, ctx.bufnr)
+ local client = vim.lsp.get_client_by_id(ctx.client_id)
+ util.apply_text_edits(result, ctx.bufnr, client.offset_encoding)
end
--see: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
@@ -246,7 +292,7 @@ end
---@param config table Configuration table.
--- - border: (default=nil)
--- - Add borders to the floating window
---- - See |vim.api.nvim_open_win()|
+--- - See |nvim_open_win()|
function M.hover(_, result, ctx, config)
config = config or {}
config.focus_id = ctx.method
@@ -277,19 +323,23 @@ local function location_handler(_, result, ctx, _)
local _ = log.info() and log.info(ctx.method, 'No location found')
return nil
end
+ local client = vim.lsp.get_client_by_id(ctx.client_id)
-- textDocument/definition can return Location or Location[]
-- https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_definition
if vim.tbl_islist(result) then
- util.jump_to_location(result[1])
+ util.jump_to_location(result[1], client.offset_encoding)
if #result > 1 then
- vim.fn.setqflist({}, ' ', {title = 'LSP locations', items = util.locations_to_items(result)})
+ vim.fn.setqflist({}, ' ', {
+ title = 'LSP locations',
+ items = util.locations_to_items(result, client.offset_encoding)
+ })
api.nvim_command("copen")
end
else
- util.jump_to_location(result)
+ util.jump_to_location(result, client.offset_encoding)
end
end
@@ -439,14 +489,20 @@ for k, fn in pairs(M) do
})
if err then
- local client = vim.lsp.get_client_by_id(ctx.client_id)
- local client_name = client and client.name or string.format("client_id=%d", ctx.client_id)
-- LSP spec:
-- interface ResponseError:
-- code: integer;
-- message: string;
-- data?: string | number | boolean | array | object | null;
- return err_message(client_name .. ': ' .. tostring(err.code) .. ': ' .. err.message)
+
+ -- Per LSP, don't show ContentModified error to the user.
+ if err.code ~= protocol.ErrorCodes.ContentModified then
+ local client = vim.lsp.get_client_by_id(ctx.client_id)
+ local client_name = client and client.name or string.format("client_id=%d", ctx.client_id)
+
+ err_message(client_name .. ': ' .. tostring(err.code) .. ': ' .. err.message)
+ end
+ return
end
return fn(err, result, ctx, config)
diff --git a/runtime/lua/vim/lsp/log.lua b/runtime/lua/vim/lsp/log.lua
index dbc473b52c..e0b5653587 100644
--- a/runtime/lua/vim/lsp/log.lua
+++ b/runtime/lua/vim/lsp/log.lua
@@ -8,8 +8,8 @@ local log = {}
-- Log level dictionary with reverse lookup as well.
--
-- Can be used to lookup the number from the name or the name from the number.
--- Levels by name: 'trace', 'debug', 'info', 'warn', 'error'
--- Level numbers begin with 'trace' at 0
+-- Levels by name: "TRACE", "DEBUG", "INFO", "WARN", "ERROR"
+-- Level numbers begin with "TRACE" at 0
log.levels = vim.deepcopy(vim.log.levels)
-- Default log level is warn.
diff --git a/runtime/lua/vim/lsp/rpc.lua b/runtime/lua/vim/lsp/rpc.lua
index 1fb75ddeb7..1ecac50df4 100644
--- a/runtime/lua/vim/lsp/rpc.lua
+++ b/runtime/lua/vim/lsp/rpc.lua
@@ -133,7 +133,8 @@ local function request_parser_loop()
end
end
-local client_errors = vim.tbl_add_reverse_lookup {
+--- Mapping of error codes used by the client
+local client_errors = {
INVALID_SERVER_MESSAGE = 1;
INVALID_SERVER_JSON = 2;
NO_RESULT_CALLBACK_FOUND = 3;
@@ -143,6 +144,8 @@ local client_errors = vim.tbl_add_reverse_lookup {
SERVER_RESULT_CALLBACK_ERROR = 7;
}
+client_errors = vim.tbl_add_reverse_lookup(client_errors)
+
--- Constructs an error message from an LSP error object.
---
---@param err (table) The error object
diff --git a/runtime/lua/vim/lsp/sync.lua b/runtime/lua/vim/lsp/sync.lua
index 5df2a4d144..0f4e5b572b 100644
--- a/runtime/lua/vim/lsp/sync.lua
+++ b/runtime/lua/vim/lsp/sync.lua
@@ -105,15 +105,16 @@ local function align_end_position(line, byte, offset_encoding)
char = compute_line_length(line, offset_encoding) + 1
else
-- Modifying line, find the nearest utf codepoint
- local offset = str_utf_end(line, byte)
+ local offset = str_utf_start(line, byte)
-- If the byte does not fall on the start of the character, then
-- align to the start of the next character.
- if offset > 0 then
- char = byte_to_utf(line, byte, offset_encoding) + 1
- byte = byte + offset
- else
+ if offset < 0 then
+ byte = byte + str_utf_end(line, byte) + 1
+ end
+ if byte <= #line then
char = byte_to_utf(line, byte, offset_encoding)
- byte = byte + offset
+ else
+ char = compute_line_length(line, offset_encoding) + 1
end
-- Extending line, find the nearest utf codepoint for the last valid character
end
@@ -167,7 +168,7 @@ local function compute_start_range(prev_lines, curr_lines, firstline, lastline,
char_idx = compute_line_length(prev_line, offset_encoding) + 1
else
byte_idx = start_byte_idx + str_utf_start(prev_line, start_byte_idx)
- char_idx = byte_to_utf(prev_line, start_byte_idx, offset_encoding)
+ char_idx = byte_to_utf(prev_line, byte_idx, offset_encoding)
end
-- Return the start difference (shared for new and prev lines)
@@ -297,7 +298,7 @@ end
---@private
-- rangelength depends on the offset encoding
--- bytes for utf-8 (clangd with extenion)
+-- bytes for utf-8 (clangd with extension)
-- codepoints for utf-16
-- codeunits for utf-32
-- Line endings count here as 2 chars for \r\n (dos), 1 char for \n (unix), and 1 char for \r (mac)
diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua
index 68a030d50b..d22c00ae76 100644
--- a/runtime/lua/vim/lsp/util.lua
+++ b/runtime/lua/vim/lsp/util.lua
@@ -10,14 +10,6 @@ local uv = vim.loop
local npcall = vim.F.npcall
local split = vim.split
-local _warned = {}
-local warn_once = function(message)
- if not _warned[message] then
- vim.api.nvim_err_writeln(message)
- _warned[message] = true
- end
-end
-
local M = {}
local default_border = {
@@ -97,15 +89,17 @@ end
---@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16
---@return number `encoding` index of `index` in `line`
function M._str_utfindex_enc(line, index, encoding)
- if encoding ~= 'utf-8' then
- local col32, col16 = vim.str_utfindex(line, index)
- if encoding == 'utf-32' then
- return col32
- else
- return col16
- end
+ if not encoding then encoding = 'utf-16' end
+ if encoding == 'utf-8' then
+ if index then return index else return #line end
+ elseif encoding == 'utf-16' then
+ local _, col16 = vim.str_utfindex(line, index)
+ return col16
+ elseif encoding == 'utf-32' then
+ local col32, _ = vim.str_utfindex(line, index)
+ return col32
else
- return index
+ error("Invalid encoding: " .. vim.inspect(encoding))
end
end
@@ -117,10 +111,15 @@ end
---@param encoding string utf-8|utf-16|utf-32|nil defaults to utf-16
---@return number byte (utf-8) index of `encoding` index `index` in `line`
function M._str_byteindex_enc(line, index, encoding)
- if encoding ~= 'utf-8' then
- return vim.str_byteindex(line, index, not encoding or encoding ~= 'utf-32')
+ if not encoding then encoding = 'utf-16' end
+ if encoding == 'utf-8' then
+ if index then return index else return #line end
+ elseif encoding == 'utf-16' then
+ return vim.str_byteindex(line, index, true)
+ elseif encoding == 'utf-32' then
+ return vim.str_byteindex(line, index)
else
- return index
+ error("Invalid encoding: " .. vim.inspect(encoding))
end
end
@@ -194,6 +193,11 @@ end
local function get_lines(bufnr, rows)
rows = type(rows) == "table" and rows or { rows }
+ -- This is needed for bufload and bufloaded
+ if bufnr == 0 then
+ bufnr = vim.api.nvim_get_current_buf()
+ end
+
---@private
local function buf_lines()
local lines = {}
@@ -273,7 +277,7 @@ end
---@private
--- Position is a https://microsoft.github.io/language-server-protocol/specifications/specification-current/#position
--- Returns a zero-indexed column, since set_lines() does the conversion to
----@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to utf-16
+---@param offset_encoding string utf-8|utf-16|utf-32
--- 1-indexed
local function get_line_byte_from_position(bufnr, position, offset_encoding)
-- LSP's line and characters are 0-indexed
@@ -282,7 +286,7 @@ local function get_line_byte_from_position(bufnr, position, offset_encoding)
-- When on the first character, we can ignore the difference between byte and
-- character
if col > 0 then
- local line = get_line(bufnr, position.line)
+ local line = get_line(bufnr, position.line) or ''
local ok, result
ok, result = pcall(_str_byteindex_enc, line, col, offset_encoding)
if ok then
@@ -356,15 +360,14 @@ end
--- Applies a list of text edits to a buffer.
---@param text_edits table list of `TextEdit` objects
---@param bufnr number Buffer id
----@param offset_encoding string utf-8|utf-16|utf-32|nil defaults to encoding of first client of `bufnr`
+---@param offset_encoding string utf-8|utf-16|utf-32 defaults to encoding of first client of `bufnr`
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textEdit
function M.apply_text_edits(text_edits, bufnr, offset_encoding)
validate {
text_edits = { text_edits, 't', false };
bufnr = { bufnr, 'number', false };
- offset_encoding = { offset_encoding, 'string', true };
+ offset_encoding = { offset_encoding, 'string', false };
}
- offset_encoding = offset_encoding or M._get_offset_encoding(bufnr)
if not next(text_edits) then return end
if not api.nvim_buf_is_loaded(bufnr) then
vim.fn.bufload(bufnr)
@@ -398,25 +401,6 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
end
end)
- -- Some LSP servers may return +1 range of the buffer content but nvim_buf_set_text can't accept it so we should fix it here.
- local has_eol_text_edit = false
- local max = vim.api.nvim_buf_line_count(bufnr)
- local len = _str_utfindex_enc(vim.api.nvim_buf_get_lines(bufnr, -2, -1, false)[1] or '', nil, offset_encoding)
- text_edits = vim.tbl_map(function(text_edit)
- if max <= text_edit.range.start.line then
- text_edit.range.start.line = max - 1
- text_edit.range.start.character = len
- text_edit.newText = '\n' .. text_edit.newText
- has_eol_text_edit = true
- end
- if max <= text_edit.range['end'].line then
- text_edit.range['end'].line = max - 1
- text_edit.range['end'].character = len
- has_eol_text_edit = true
- end
- return text_edit
- end, text_edits)
-
-- Some LSP servers are depending on the VSCode behavior.
-- The VSCode will re-locate the cursor position after applying TextEdit so we also do it.
local is_current_buf = vim.api.nvim_get_current_buf() == bufnr
@@ -436,16 +420,38 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
-- Apply text edits.
local is_cursor_fixed = false
+ local has_eol_text_edit = false
for _, text_edit in ipairs(text_edits) do
+ -- Normalize line ending
+ text_edit.newText, _ = string.gsub(text_edit.newText, '\r\n?', '\n')
+
+ -- Convert from LSP style ranges to Neovim style ranges.
local e = {
start_row = text_edit.range.start.line,
- start_col = get_line_byte_from_position(bufnr, text_edit.range.start),
+ start_col = get_line_byte_from_position(bufnr, text_edit.range.start, offset_encoding),
end_row = text_edit.range['end'].line,
- end_col = get_line_byte_from_position(bufnr, text_edit.range['end']),
+ end_col = get_line_byte_from_position(bufnr, text_edit.range['end'], offset_encoding),
text = vim.split(text_edit.newText, '\n', true),
}
+
+ -- Some LSP servers may return +1 range of the buffer content but nvim_buf_set_text can't accept it so we should fix it here.
+ local max = vim.api.nvim_buf_line_count(bufnr)
+ if max <= e.start_row or max <= e.end_row then
+ local len = #(get_line(bufnr, max - 1) or '')
+ if max <= e.start_row then
+ e.start_row = max - 1
+ e.start_col = len
+ table.insert(e.text, 1, '')
+ end
+ if max <= e.end_row then
+ e.end_row = max - 1
+ e.end_col = len
+ end
+ has_eol_text_edit = true
+ end
vim.api.nvim_buf_set_text(bufnr, e.start_row, e.start_col, e.end_row, e.end_col, e.text)
+ -- Fix cursor position.
local row_count = (e.end_row - e.start_row) + 1
if e.end_row < cursor.row then
cursor.row = cursor.row + (#e.text - row_count)
@@ -460,10 +466,13 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
end
end
+ local max = vim.api.nvim_buf_line_count(bufnr)
+
+ -- Apply fixed cursor position.
if is_cursor_fixed then
local is_valid_cursor = true
- is_valid_cursor = is_valid_cursor and cursor.row < vim.api.nvim_buf_line_count(bufnr)
- is_valid_cursor = is_valid_cursor and cursor.col <= #(vim.api.nvim_buf_get_lines(bufnr, cursor.row, cursor.row + 1, false)[1] or '')
+ is_valid_cursor = is_valid_cursor and cursor.row < max
+ is_valid_cursor = is_valid_cursor and cursor.col <= #(get_line(bufnr, max - 1) or '')
if is_valid_cursor then
vim.api.nvim_win_set_cursor(0, { cursor.row + 1, cursor.col })
end
@@ -472,7 +481,7 @@ function M.apply_text_edits(text_edits, bufnr, offset_encoding)
-- Remove final line if needed
local fix_eol = has_eol_text_edit
fix_eol = fix_eol and api.nvim_buf_get_option(bufnr, 'fixeol')
- fix_eol = fix_eol and (vim.api.nvim_buf_get_lines(bufnr, -2, -1, false)[1] or '') == ''
+ fix_eol = fix_eol and get_line(bufnr, max - 1) == ''
if fix_eol then
vim.api.nvim_buf_set_lines(bufnr, -2, -1, false, {})
end
@@ -510,9 +519,12 @@ end
---@param text_document_edit table: a `TextDocumentEdit` object
---@param index number: Optional index of the edit, if from a list of edits (or nil, if not from a list)
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocumentEdit
-function M.apply_text_document_edit(text_document_edit, index)
+function M.apply_text_document_edit(text_document_edit, index, offset_encoding)
local text_document = text_document_edit.textDocument
local bufnr = vim.uri_to_bufnr(text_document.uri)
+ if offset_encoding == nil then
+ vim.notify_once("apply_text_document_edit must be called with valid offset encoding", vim.log.levels.WARN)
+ end
-- For lists of text document edits,
-- do not check the version after the first edit.
@@ -531,7 +543,7 @@ function M.apply_text_document_edit(text_document_edit, index)
return
end
- M.apply_text_edits(text_document_edit.edits, bufnr)
+ M.apply_text_edits(text_document_edit.edits, bufnr, offset_encoding)
end
--- Parses snippets in a completion entry.
@@ -728,9 +740,13 @@ end
--- Applies a `WorkspaceEdit`.
---
----@param workspace_edit (table) `WorkspaceEdit`
+---@param workspace_edit table `WorkspaceEdit`
+---@param offset_encoding string utf-8|utf-16|utf-32 (required)
--see https://microsoft.github.io/language-server-protocol/specifications/specification-current/#workspace_applyEdit
-function M.apply_workspace_edit(workspace_edit)
+function M.apply_workspace_edit(workspace_edit, offset_encoding)
+ if offset_encoding == nil then
+ vim.notify_once("apply_workspace_edit must be called with valid offset encoding", vim.log.levels.WARN)
+ end
if workspace_edit.documentChanges then
for idx, change in ipairs(workspace_edit.documentChanges) do
if change.kind == "rename" then
@@ -746,7 +762,7 @@ function M.apply_workspace_edit(workspace_edit)
elseif change.kind then
error(string.format("Unsupported change: %q", vim.inspect(change)))
else
- M.apply_text_document_edit(change, idx)
+ M.apply_text_document_edit(change, idx, offset_encoding)
end
end
return
@@ -759,7 +775,7 @@ function M.apply_workspace_edit(workspace_edit)
for uri, changes in pairs(all_changes) do
local bufnr = vim.uri_to_bufnr(uri)
- M.apply_text_edits(changes, bufnr)
+ M.apply_text_edits(changes, bufnr, offset_encoding)
end
end
@@ -835,7 +851,8 @@ function M.convert_signature_help_to_markdown_lines(signature_help, ft, triggers
local active_hl
local active_signature = signature_help.activeSignature or 0
-- If the activeSignature is not inside the valid range, then clip it.
- if active_signature >= #signature_help.signatures then
+ -- In 3.15 of the protocol, activeSignature was allowed to be negative
+ if active_signature >= #signature_help.signatures or active_signature < 0 then
active_signature = 0
end
local signature = signature_help.signatures[active_signature + 1]
@@ -976,12 +993,16 @@ end
--- Jumps to a location.
---
----@param location (`Location`|`LocationLink`)
+---@param location table (`Location`|`LocationLink`)
+---@param offset_encoding string utf-8|utf-16|utf-32 (required)
---@returns `true` if the jump succeeded
-function M.jump_to_location(location)
+function M.jump_to_location(location, offset_encoding)
-- location may be Location or LocationLink
local uri = location.uri or location.targetUri
if uri == nil then return end
+ if offset_encoding == nil then
+ vim.notify_once("jump_to_location must be called with valid offset encoding", vim.log.levels.WARN)
+ end
local bufnr = vim.uri_to_bufnr(uri)
-- Save position in jumplist
vim.cmd "normal! m'"
@@ -993,10 +1014,10 @@ function M.jump_to_location(location)
--- Jump to new location (adjusting for UTF-16 encoding of characters)
api.nvim_set_current_buf(bufnr)
- api.nvim_buf_set_option(0, 'buflisted', true)
+ api.nvim_buf_set_option(bufnr, 'buflisted', true)
local range = location.range or location.targetSelectionRange
local row = range.start.line
- local col = get_line_byte_from_position(0, range.start)
+ local col = get_line_byte_from_position(bufnr, range.start, offset_encoding)
api.nvim_win_set_cursor(0, {row + 1, col})
-- Open folds under the cursor
vim.cmd("normal! zv")
@@ -1498,18 +1519,20 @@ do --[[ References ]]
---@param bufnr number Buffer id
function M.buf_clear_references(bufnr)
validate { bufnr = {bufnr, 'n', true} }
- api.nvim_buf_clear_namespace(bufnr, reference_ns, 0, -1)
+ api.nvim_buf_clear_namespace(bufnr or 0, reference_ns, 0, -1)
end
--- Shows a list of document highlights for a certain buffer.
---
---@param bufnr number Buffer id
---@param references table List of `DocumentHighlight` objects to highlight
- ---@param offset_encoding string One of "utf-8", "utf-16", "utf-32", or nil. Defaults to `offset_encoding` of first client of `bufnr`
+ ---@param offset_encoding string One of "utf-8", "utf-16", "utf-32".
---@see https://microsoft.github.io/language-server-protocol/specifications/specification-3-17/#documentHighlight
function M.buf_highlight_references(bufnr, references, offset_encoding)
- validate { bufnr = {bufnr, 'n', true} }
- offset_encoding = offset_encoding or M._get_offset_encoding(bufnr)
+ validate {
+ bufnr = {bufnr, 'n', true},
+ offset_encoding = { offset_encoding, 'string', false };
+ }
for _, reference in ipairs(references) do
local start_line, start_char = reference["range"]["start"]["line"], reference["range"]["start"]["character"]
local end_line, end_char = reference["range"]["end"]["line"], reference["range"]["end"]["character"]
@@ -1527,7 +1550,10 @@ do --[[ References ]]
reference_ns,
document_highlight_kind[kind],
{ start_line, start_idx },
- { end_line, end_idx })
+ { end_line, end_idx },
+ nil,
+ false,
+ 40)
end
end
end
@@ -1542,9 +1568,14 @@ end)
--- The result can be passed to the {list} argument of |setqflist()| or
--- |setloclist()|.
---
----@param locations (table) list of `Location`s or `LocationLink`s
+---@param locations table list of `Location`s or `LocationLink`s
+---@param offset_encoding string offset_encoding for locations utf-8|utf-16|utf-32
---@returns (table) list of items
-function M.locations_to_items(locations)
+function M.locations_to_items(locations, offset_encoding)
+ if offset_encoding == nil then
+ vim.notify_once("locations_to_items must be called with valid offset encoding", vim.log.levels.WARN)
+ end
+
local items = {}
local grouped = setmetatable({}, {
__index = function(t, k)
@@ -1584,7 +1615,7 @@ function M.locations_to_items(locations)
local pos = temp.start
local row = pos.line
local line = lines[row] or ""
- local col = pos.character
+ local col = M._str_byteindex_enc(line, pos.character, offset_encoding)
table.insert(items, {
filename = filename,
lnum = row + 1,
@@ -1670,7 +1701,7 @@ function M.symbols_to_items(symbols, bufnr)
end
return _items
end
- return _symbols_to_items(symbols, {}, bufnr)
+ return _symbols_to_items(symbols, {}, bufnr or 0)
end
--- Removes empty lines from the beginning and end.
@@ -1768,7 +1799,13 @@ function M._get_offset_encoding(bufnr)
local offset_encoding
for _, client in pairs(vim.lsp.buf_get_clients(bufnr)) do
- local this_offset_encoding = client.offset_encoding or "utf-16"
+ if client.offset_encoding == nil then
+ vim.notify_once(
+ string.format("Client (id: %s) offset_encoding is nil. Do not unset offset_encoding.", client.id),
+ vim.log.levels.ERROR
+ )
+ end
+ local this_offset_encoding = client.offset_encoding
if not offset_encoding then
offset_encoding = this_offset_encoding
elseif offset_encoding ~= this_offset_encoding then
@@ -1789,7 +1826,7 @@ end
---@returns { textDocument = { uri = `current_file_uri` }, range = { start =
---`current_position`, end = `current_position` } }
function M.make_range_params(window, offset_encoding)
- local buf = vim.api.nvim_win_get_buf(window)
+ local buf = vim.api.nvim_win_get_buf(window or 0)
offset_encoding = offset_encoding or M._get_offset_encoding(buf)
local position = make_position_param(window, offset_encoding)
return {
@@ -1815,7 +1852,7 @@ function M.make_given_range_params(start_pos, end_pos, bufnr, offset_encoding)
end_pos = {end_pos, 't', true};
offset_encoding = {offset_encoding, 's', true};
}
- bufnr = bufnr or 0
+ bufnr = bufnr or vim.api.nvim_get_current_buf()
offset_encoding = offset_encoding or M._get_offset_encoding(bufnr)
local A = list_extend({}, start_pos or api.nvim_buf_get_mark(bufnr, '<'))
local B = list_extend({}, end_pos or api.nvim_buf_get_mark(bufnr, '>'))
@@ -1897,7 +1934,9 @@ end
---@returns (number, number) `offset_encoding` index of the character in line {row} column {col} in buffer {buf}
function M.character_offset(buf, row, col, offset_encoding)
local line = get_line(buf, row)
- offset_encoding = offset_encoding or M._get_offset_encoding(buf)
+ if offset_encoding == nil then
+ vim.notify_once("character_offset must be called with valid offset encoding", vim.log.levels.WARN)
+ end
-- If the col is past the EOL, use the line length.
if col > #line then
return _str_utfindex_enc(line, nil, offset_encoding)
@@ -1921,7 +1960,6 @@ function M.lookup_section(settings, section)
end
M._get_line_byte_from_position = get_line_byte_from_position
-M._warn_once = warn_once
M.buf_versions = {}
diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua
index 1cf618725d..e170befa4c 100644
--- a/runtime/lua/vim/shared.lua
+++ b/runtime/lua/vim/shared.lua
@@ -526,13 +526,23 @@ end
--- => error('arg1: expected even number, got 3')
--- </pre>
---
----@param opt Map of parameter names to validations. Each key is a parameter
+--- If multiple types are valid they can be given as a list.
+--- <pre>
+--- vim.validate{arg1={{'foo'}, {'table', 'string'}}, arg2={'foo', {'table', 'string'}}}
+--- => NOP (success)
+---
+--- vim.validate{arg1={1, {'string', table'}}}
+--- => error('arg1: expected string|table, got number')
+---
+--- </pre>
+---
+---@param opt table of parameter names to validations. Each key is a parameter
--- name; each value is a tuple in one of these forms:
--- 1. (arg_value, type_name, optional)
--- - arg_value: argument value
---- - type_name: string type name, one of: ("table", "t", "string",
+--- - type_name: string|table type name, one of: ("table", "t", "string",
--- "s", "number", "n", "boolean", "b", "function", "f", "nil",
---- "thread", "userdata")
+--- "thread", "userdata") or list of them.
--- - optional: (optional) boolean, if true, `nil` is valid
--- 2. (arg_value, fn, msg)
--- - arg_value: argument value
@@ -571,31 +581,43 @@ do
end
local val = spec[1] -- Argument value.
- local t = spec[2] -- Type name, or callable.
+ local types = spec[2] -- Type name, or callable.
local optional = (true == spec[3])
- if type(t) == 'string' then
- local t_name = type_names[t]
- if not t_name then
- return false, string.format('invalid type name: %s', t)
- end
+ if type(types) == 'string' then
+ types = {types}
+ end
- if (not optional or val ~= nil) and not _is_type(val, t_name) then
- return false, string.format("%s: expected %s, got %s", param_name, t_name, type(val))
- end
- elseif vim.is_callable(t) then
+ if vim.is_callable(types) then
-- Check user-provided validation function.
- local valid, optional_message = t(val)
+ local valid, optional_message = types(val)
if not valid then
- local error_message = string.format("%s: expected %s, got %s", param_name, (spec[3] or '?'), val)
+ local error_message = string.format("%s: expected %s, got %s", param_name, (spec[3] or '?'), tostring(val))
if optional_message ~= nil then
error_message = error_message .. string.format(". Info: %s", optional_message)
end
return false, error_message
end
+ elseif type(types) == 'table' then
+ local success = false
+ for i, t in ipairs(types) do
+ local t_name = type_names[t]
+ if not t_name then
+ return false, string.format('invalid type name: %s', t)
+ end
+ types[i] = t_name
+
+ if (optional and val == nil) or _is_type(val, t_name) then
+ success = true
+ break
+ end
+ end
+ if not success then
+ return false, string.format("%s: expected %s, got %s", param_name, table.concat(types, '|'), type(val))
+ end
else
- return false, string.format("invalid type name: %s", tostring(t))
+ return false, string.format("invalid type name: %s", tostring(types))
end
end
diff --git a/runtime/lua/vim/treesitter/languagetree.lua b/runtime/lua/vim/treesitter/languagetree.lua
index 594765761d..85fd5cd8e0 100644
--- a/runtime/lua/vim/treesitter/languagetree.lua
+++ b/runtime/lua/vim/treesitter/languagetree.lua
@@ -77,7 +77,7 @@ end
--- Determines whether this tree is valid.
--- If the tree is invalid, `parse()` must be called
---- to get the an updated tree.
+--- to get the updated tree.
function LanguageTree:is_valid()
return self._valid
end
diff --git a/runtime/lua/vim/treesitter/query.lua b/runtime/lua/vim/treesitter/query.lua
index ebed502c92..b3036ea679 100644
--- a/runtime/lua/vim/treesitter/query.lua
+++ b/runtime/lua/vim/treesitter/query.lua
@@ -138,6 +138,13 @@ function M.get_query(lang, query_name)
end
end
+local query_cache = setmetatable({}, {
+ __index = function(tbl, key)
+ rawset(tbl, key, {})
+ return rawget(tbl, key)
+ end
+})
+
--- Parse {query} as a string. (If the query is in a file, the caller
--- should read the contents into a string before calling).
---
@@ -151,17 +158,23 @@ end
--- -` info.captures` also points to `captures`.
--- - `info.patterns` contains information about predicates.
---
----@param lang The language
----@param query A string containing the query (s-expr syntax)
+---@param lang string The language
+---@param query string A string containing the query (s-expr syntax)
---
---@returns The query
function M.parse_query(lang, query)
language.require_language(lang)
- local self = setmetatable({}, Query)
- self.query = vim._ts_parse_query(lang, query)
- self.info = self.query:inspect()
- self.captures = self.info.captures
- return self
+ local cached = query_cache[lang][query]
+ if cached then
+ return cached
+ else
+ local self = setmetatable({}, Query)
+ self.query = vim._ts_parse_query(lang, query)
+ self.info = self.query:inspect()
+ self.captures = self.info.captures
+ query_cache[lang][query] = self
+ return self
+ end
end
--- Gets the text corresponding to a given node
diff --git a/runtime/lua/vim/uri.lua b/runtime/lua/vim/uri.lua
index d08d2a3ee3..11b661cd1a 100644
--- a/runtime/lua/vim/uri.lua
+++ b/runtime/lua/vim/uri.lua
@@ -74,8 +74,8 @@ local function uri_from_fname(path)
return table.concat(uri_parts)
end
-local URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9+-.]*):.*'
-local WINDOWS_URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9+-.]*):[a-zA-Z]:.*'
+local URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9.+-]*):.*'
+local WINDOWS_URI_SCHEME_PATTERN = '^([a-zA-Z]+[a-zA-Z0-9.+-]*):[a-zA-Z]:.*'
--- Get a URI from a bufnr
---@param bufnr number
diff --git a/runtime/nvim.appdata.xml b/runtime/nvim.appdata.xml
index 225dd79878..4ad656f1a3 100644
--- a/runtime/nvim.appdata.xml
+++ b/runtime/nvim.appdata.xml
@@ -26,7 +26,9 @@
</screenshots>
<releases>
+ <release date="2021-12-31" version="0.6.1"/>
<release date="2021-11-30" version="0.6.0"/>
+ <release date="2021-09-26" version="0.5.1"/>
<release date="2021-07-02" version="0.5.0"/>
<release date="2020-08-04" version="0.4.4"/>
<release date="2019-11-06" version="0.4.3"/>
diff --git a/runtime/optwin.vim b/runtime/optwin.vim
index d4c10f7afa..c873252909 100644
--- a/runtime/optwin.vim
+++ b/runtime/optwin.vim
@@ -1,7 +1,7 @@
" These commands create the option window.
"
" Maintainer: Bram Moolenaar <Bram@vim.org>
-" Last Change: 2020 Oct 27
+" Last Change: 2021 Dec 12
" If there already is an option window, jump to that one.
let buf = bufnr('option-window')
@@ -261,6 +261,8 @@ call <SID>OptionG("sect", &sect)
call append("$", "path\tlist of directory names used for file searching")
call append("$", "\t(global or local to buffer)")
call <SID>OptionG("pa", &pa)
+call <SID>AddOption("cdhome", ":cd without argument goes to the home directory")
+call <SID>BinOptionG("cdh", &cdh)
call append("$", "cdpath\tlist of directory names used for :cd")
call <SID>OptionG("cd", &cd)
if exists("+autochdir")
diff --git a/runtime/pack/dist/opt/matchit/autoload/matchit.vim b/runtime/pack/dist/opt/matchit/autoload/matchit.vim
index 4f3dd8ff9e..e8689980ae 100644
--- a/runtime/pack/dist/opt/matchit/autoload/matchit.vim
+++ b/runtime/pack/dist/opt/matchit/autoload/matchit.vim
@@ -1,6 +1,11 @@
" matchit.vim: (global plugin) Extended "%" matching
" autload script of matchit plugin, see ../plugin/matchit.vim
-" Last Change: Mar 01, 2020
+" Last Change: Jun 10, 2021
+
+" Neovim does not support scriptversion
+if has("vimscript-4")
+ scriptversion 4
+endif
let s:last_mps = ""
let s:last_words = ":"
@@ -30,11 +35,11 @@ function s:RestoreOptions()
" In s:CleanUp(), :execute "set" restore_options .
let restore_options = ""
if get(b:, 'match_ignorecase', &ic) != &ic
- let restore_options .= (&ic ? " " : " no") . "ignorecase"
+ let restore_options ..= (&ic ? " " : " no") .. "ignorecase"
let &ignorecase = b:match_ignorecase
endif
if &ve != ''
- let restore_options = " ve=" . &ve . restore_options
+ let restore_options = " ve=" .. &ve .. restore_options
set ve=
endif
return restore_options
@@ -42,22 +47,23 @@ endfunction
function matchit#Match_wrapper(word, forward, mode) range
let restore_options = s:RestoreOptions()
- " If this function was called from Visual mode, make sure that the cursor
- " is at the correct end of the Visual range:
- if a:mode == "v"
- execute "normal! gv\<Esc>"
- elseif a:mode == "o" && mode(1) !~# '[vV]'
- exe "norm! v"
- elseif a:mode == "n" && mode(1) =~# 'ni'
- exe "norm! v"
- endif
" In s:CleanUp(), we may need to check whether the cursor moved forward.
let startpos = [line("."), col(".")]
- " Use default behavior if called with a count.
+ " if a count has been applied, use the default [count]% mode (see :h N%)
if v:count
- exe "normal! " . v:count . "%"
+ exe "normal! " .. v:count .. "%"
return s:CleanUp(restore_options, a:mode, startpos)
end
+ if a:mode =~# "v" && mode(1) =~# 'ni'
+ exe "norm! gv"
+ elseif a:mode == "o" && mode(1) !~# '[vV]'
+ exe "norm! v"
+ " If this function was called from Visual mode, make sure that the cursor
+ " is at the correct end of the Visual range:
+ elseif a:mode == "v"
+ execute "normal! gv\<Esc>"
+ let startpos = [line("."), col(".")]
+ endif
" First step: if not already done, set the script variables
" s:do_BR flag for whether there are backrefs
@@ -78,30 +84,30 @@ function matchit#Match_wrapper(word, forward, mode) range
" quote the special chars in 'matchpairs', replace [,:] with \| and then
" append the builtin pairs (/*, */, #if, #ifdef, #ifndef, #else, #elif,
" #endif)
- let default = escape(&mps, '[$^.*~\\/?]') . (strlen(&mps) ? "," : "") .
+ let default = escape(&mps, '[$^.*~\\/?]') .. (strlen(&mps) ? "," : "") ..
\ '\/\*:\*\/,#\s*if\%(n\=def\)\=:#\s*else\>:#\s*elif\>:#\s*endif\>'
" s:all = pattern with all the keywords
- let match_words = match_words . (strlen(match_words) ? "," : "") . default
+ let match_words = match_words .. (strlen(match_words) ? "," : "") .. default
let s:last_words = match_words
- if match_words !~ s:notslash . '\\\d'
+ if match_words !~ s:notslash .. '\\\d'
let s:do_BR = 0
let s:pat = match_words
else
let s:do_BR = 1
let s:pat = s:ParseWords(match_words)
endif
- let s:all = substitute(s:pat, s:notslash . '\zs[,:]\+', '\\|', 'g')
+ let s:all = substitute(s:pat, s:notslash .. '\zs[,:]\+', '\\|', 'g')
" Just in case there are too many '\(...)' groups inside the pattern, make
" sure to use \%(...) groups, so that error E872 can be avoided
let s:all = substitute(s:all, '\\(', '\\%(', 'g')
- let s:all = '\%(' . s:all . '\)'
+ let s:all = '\%(' .. s:all .. '\)'
if exists("b:match_debug")
let b:match_pat = s:pat
endif
" Reconstruct the version with unresolved backrefs.
- let s:patBR = substitute(match_words.',',
- \ s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
- let s:patBR = substitute(s:patBR, s:notslash.'\zs:\{2,}', ':', 'g')
+ let s:patBR = substitute(match_words .. ',',
+ \ s:notslash .. '\zs[,:]*,[,:]*', ',', 'g')
+ let s:patBR = substitute(s:patBR, s:notslash .. '\zs:\{2,}', ':', 'g')
endif
" Second step: set the following local variables:
@@ -128,12 +134,15 @@ function matchit#Match_wrapper(word, forward, mode) range
let curcol = match(matchline, regexp)
" If there is no match, give up.
if curcol == -1
+ " Make sure macros abort properly
+ "exe "norm! \<esc>"
+ call feedkeys("\e", 'tni')
return s:CleanUp(restore_options, a:mode, startpos)
endif
let endcol = matchend(matchline, regexp)
let suf = strlen(matchline) - endcol
- let prefix = (curcol ? '^.*\%' . (curcol + 1) . 'c\%(' : '^\%(')
- let suffix = (suf ? '\)\%' . (endcol + 1) . 'c.*$' : '\)$')
+ let prefix = (curcol ? '^.*\%' .. (curcol + 1) .. 'c\%(' : '^\%(')
+ let suffix = (suf ? '\)\%' .. (endcol + 1) .. 'c.*$' : '\)$')
endif
if exists("b:match_debug")
let b:match_match = matchstr(matchline, regexp)
@@ -150,7 +159,7 @@ function matchit#Match_wrapper(word, forward, mode) range
" 'while:endwhile' or whatever. A bit of a kluge: s:Choose() returns
" group . "," . groupBR, and we pick it apart.
let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, s:patBR)
- let i = matchend(group, s:notslash . ",")
+ let i = matchend(group, s:notslash .. ",")
let groupBR = strpart(group, i)
let group = strpart(group, 0, i-1)
" Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
@@ -159,32 +168,32 @@ function matchit#Match_wrapper(word, forward, mode) range
endif
if exists("b:match_debug")
let b:match_wholeBR = groupBR
- let i = matchend(groupBR, s:notslash . ":")
+ let i = matchend(groupBR, s:notslash .. ":")
let b:match_iniBR = strpart(groupBR, 0, i-1)
endif
" Fourth step: Set the arguments for searchpair().
- let i = matchend(group, s:notslash . ":")
- let j = matchend(group, '.*' . s:notslash . ":")
+ let i = matchend(group, s:notslash .. ":")
+ let j = matchend(group, '.*' .. s:notslash .. ":")
let ini = strpart(group, 0, i-1)
- let mid = substitute(strpart(group, i,j-i-1), s:notslash.'\zs:', '\\|', 'g')
+ let mid = substitute(strpart(group, i,j-i-1), s:notslash .. '\zs:', '\\|', 'g')
let fin = strpart(group, j)
"Un-escape the remaining , and : characters.
- let ini = substitute(ini, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
- let mid = substitute(mid, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
- let fin = substitute(fin, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
+ let ini = substitute(ini, s:notslash .. '\zs\\\(:\|,\)', '\1', 'g')
+ let mid = substitute(mid, s:notslash .. '\zs\\\(:\|,\)', '\1', 'g')
+ let fin = substitute(fin, s:notslash .. '\zs\\\(:\|,\)', '\1', 'g')
" searchpair() requires that these patterns avoid \(\) groups.
- let ini = substitute(ini, s:notslash . '\zs\\(', '\\%(', 'g')
- let mid = substitute(mid, s:notslash . '\zs\\(', '\\%(', 'g')
- let fin = substitute(fin, s:notslash . '\zs\\(', '\\%(', 'g')
+ let ini = substitute(ini, s:notslash .. '\zs\\(', '\\%(', 'g')
+ let mid = substitute(mid, s:notslash .. '\zs\\(', '\\%(', 'g')
+ let fin = substitute(fin, s:notslash .. '\zs\\(', '\\%(', 'g')
" Set mid. This is optimized for readability, not micro-efficiency!
- if a:forward && matchline =~ prefix . fin . suffix
- \ || !a:forward && matchline =~ prefix . ini . suffix
+ if a:forward && matchline =~ prefix .. fin .. suffix
+ \ || !a:forward && matchline =~ prefix .. ini .. suffix
let mid = ""
endif
" Set flag. This is optimized for readability, not micro-efficiency!
- if a:forward && matchline =~ prefix . fin . suffix
- \ || !a:forward && matchline !~ prefix . ini . suffix
+ if a:forward && matchline =~ prefix .. fin .. suffix
+ \ || !a:forward && matchline !~ prefix .. ini .. suffix
let flag = "bW"
else
let flag = "W"
@@ -193,14 +202,14 @@ function matchit#Match_wrapper(word, forward, mode) range
if exists("b:match_skip")
let skip = b:match_skip
elseif exists("b:match_comment") " backwards compatibility and testing!
- let skip = "r:" . b:match_comment
+ let skip = "r:" .. b:match_comment
else
let skip = 's:comment\|string'
endif
let skip = s:ParseSkip(skip)
if exists("b:match_debug")
let b:match_ini = ini
- let b:match_tail = (strlen(mid) ? mid.'\|' : '') . fin
+ let b:match_tail = (strlen(mid) ? mid .. '\|' : '') .. fin
endif
" Fifth step: actually start moving the cursor and call searchpair().
@@ -210,25 +219,29 @@ function matchit#Match_wrapper(word, forward, mode) range
if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
let skip = "0"
else
- execute "if " . skip . "| let skip = '0' | endif"
+ execute "if " .. skip .. "| let skip = '0' | endif"
endif
let sp_return = searchpair(ini, mid, fin, flag, skip)
if &selection isnot# 'inclusive' && a:mode == 'v'
" move cursor one pos to the right, because selection is not inclusive
- " add virtualedit=onemore, to make it work even when the match ends the " line
+ " add virtualedit=onemore, to make it work even when the match ends the
+ " line
if !(col('.') < col('$')-1)
- set ve=onemore
+ let eolmark=1 " flag to set a mark on eol (since we cannot move there)
endif
norm! l
endif
- let final_position = "call cursor(" . line(".") . "," . col(".") . ")"
+ let final_position = "call cursor(" .. line(".") .. "," .. col(".") .. ")"
" Restore cursor position and original screen.
call winrestview(view)
normal! m'
if sp_return > 0
execute final_position
endif
- return s:CleanUp(restore_options, a:mode, startpos, mid.'\|'.fin)
+ if exists('eolmark') && eolmark
+ call setpos("''", [0, line('.'), col('$'), 0]) " set mark on the eol
+ endif
+ return s:CleanUp(restore_options, a:mode, startpos, mid .. '\|' .. fin)
endfun
" Restore options and do some special handling for Operator-pending mode.
@@ -270,16 +283,16 @@ endfun
" a:matchline = "123<tag>12" or "123</tag>12"
" then extract "tag" from a:matchline and return "<tag>:</tag>" .
fun! s:InsertRefs(groupBR, prefix, group, suffix, matchline)
- if a:matchline !~ a:prefix .
- \ substitute(a:group, s:notslash . '\zs:', '\\|', 'g') . a:suffix
+ if a:matchline !~ a:prefix ..
+ \ substitute(a:group, s:notslash .. '\zs:', '\\|', 'g') .. a:suffix
return a:group
endif
- let i = matchend(a:groupBR, s:notslash . ':')
+ let i = matchend(a:groupBR, s:notslash .. ':')
let ini = strpart(a:groupBR, 0, i-1)
let tailBR = strpart(a:groupBR, i)
let word = s:Choose(a:group, a:matchline, ":", "", a:prefix, a:suffix,
\ a:groupBR)
- let i = matchend(word, s:notslash . ":")
+ let i = matchend(word, s:notslash .. ":")
let wordBR = strpart(word, i)
let word = strpart(word, 0, i-1)
" Now, a:matchline =~ a:prefix . word . a:suffix
@@ -289,10 +302,10 @@ fun! s:InsertRefs(groupBR, prefix, group, suffix, matchline)
let table = ""
let d = 0
while d < 10
- if tailBR =~ s:notslash . '\\' . d
- let table = table . d
+ if tailBR =~ s:notslash .. '\\' .. d
+ let table = table .. d
else
- let table = table . "-"
+ let table = table .. "-"
endif
let d = d + 1
endwhile
@@ -300,13 +313,13 @@ fun! s:InsertRefs(groupBR, prefix, group, suffix, matchline)
let d = 9
while d
if table[d] != "-"
- let backref = substitute(a:matchline, a:prefix.word.a:suffix,
- \ '\'.table[d], "")
+ let backref = substitute(a:matchline, a:prefix .. word .. a:suffix,
+ \ '\' .. table[d], "")
" Are there any other characters that should be escaped?
let backref = escape(backref, '*,:')
execute s:Ref(ini, d, "start", "len")
- let ini = strpart(ini, 0, start) . backref . strpart(ini, start+len)
- let tailBR = substitute(tailBR, s:notslash . '\zs\\' . d,
+ let ini = strpart(ini, 0, start) .. backref .. strpart(ini, start+len)
+ let tailBR = substitute(tailBR, s:notslash .. '\zs\\' .. d,
\ escape(backref, '\\&'), 'g')
endif
let d = d-1
@@ -320,7 +333,7 @@ fun! s:InsertRefs(groupBR, prefix, group, suffix, matchline)
let b:match_word = ""
endif
endif
- return ini . ":" . tailBR
+ return ini .. ":" .. tailBR
endfun
" Input a comma-separated list of groups with backrefs, such as
@@ -328,25 +341,25 @@ endfun
" and return a comma-separated list of groups with backrefs replaced:
" return '\(foo\):end\(foo\),\(bar\):end\(bar\)'
fun! s:ParseWords(groups)
- let groups = substitute(a:groups.",", s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
- let groups = substitute(groups, s:notslash . '\zs:\{2,}', ':', 'g')
+ let groups = substitute(a:groups .. ",", s:notslash .. '\zs[,:]*,[,:]*', ',', 'g')
+ let groups = substitute(groups, s:notslash .. '\zs:\{2,}', ':', 'g')
let parsed = ""
while groups =~ '[^,:]'
- let i = matchend(groups, s:notslash . ':')
- let j = matchend(groups, s:notslash . ',')
+ let i = matchend(groups, s:notslash .. ':')
+ let j = matchend(groups, s:notslash .. ',')
let ini = strpart(groups, 0, i-1)
- let tail = strpart(groups, i, j-i-1) . ":"
+ let tail = strpart(groups, i, j-i-1) .. ":"
let groups = strpart(groups, j)
- let parsed = parsed . ini
- let i = matchend(tail, s:notslash . ':')
+ let parsed = parsed .. ini
+ let i = matchend(tail, s:notslash .. ':')
while i != -1
" In 'if:else:endif', ini='if' and word='else' and then word='endif'.
let word = strpart(tail, 0, i-1)
let tail = strpart(tail, i)
- let i = matchend(tail, s:notslash . ':')
- let parsed = parsed . ":" . s:Resolve(ini, word, "word")
+ let i = matchend(tail, s:notslash .. ':')
+ let parsed = parsed .. ":" .. s:Resolve(ini, word, "word")
endwhile " Now, tail has been used up.
- let parsed = parsed . ","
+ let parsed = parsed .. ","
endwhile " groups =~ '[^,:]'
let parsed = substitute(parsed, ',$', '', '')
return parsed
@@ -364,14 +377,14 @@ endfun
" let j = matchend(getline("."), regexp)
" let match = matchstr(getline("."), regexp)
fun! s:Wholematch(string, pat, start)
- let group = '\%(' . a:pat . '\)'
- let prefix = (a:start ? '\(^.*\%<' . (a:start + 2) . 'c\)\zs' : '^')
+ let group = '\%(' .. a:pat .. '\)'
+ let prefix = (a:start ? '\(^.*\%<' .. (a:start + 2) .. 'c\)\zs' : '^')
let len = strlen(a:string)
- let suffix = (a:start+1 < len ? '\(\%>'.(a:start+1).'c.*$\)\@=' : '$')
- if a:string !~ prefix . group . suffix
+ let suffix = (a:start+1 < len ? '\(\%>' .. (a:start+1) .. 'c.*$\)\@=' : '$')
+ if a:string !~ prefix .. group .. suffix
let prefix = ''
endif
- return prefix . group . suffix
+ return prefix .. group .. suffix
endfun
" No extra arguments: s:Ref(string, d) will
@@ -392,7 +405,7 @@ fun! s:Ref(string, d, ...)
let match = a:string
while cnt
let cnt = cnt - 1
- let index = matchend(match, s:notslash . '\\(')
+ let index = matchend(match, s:notslash .. '\\(')
if index == -1
return ""
endif
@@ -404,7 +417,7 @@ fun! s:Ref(string, d, ...)
endif
let cnt = 1
while cnt
- let index = matchend(match, s:notslash . '\\(\|\\)') - 1
+ let index = matchend(match, s:notslash .. '\\(\|\\)') - 1
if index == -2
return ""
endif
@@ -418,7 +431,7 @@ fun! s:Ref(string, d, ...)
if a:0 == 1
return len
elseif a:0 == 2
- return "let " . a:1 . "=" . start . "| let " . a:2 . "=" . len
+ return "let " .. a:1 .. "=" .. start .. "| let " .. a:2 .. "=" .. len
else
return strpart(a:string, start, len)
endif
@@ -431,9 +444,9 @@ endfun
fun! s:Count(string, pattern, ...)
let pat = escape(a:pattern, '\\')
if a:0 > 1
- let foo = substitute(a:string, '[^'.a:pattern.']', "a:1", "g")
+ let foo = substitute(a:string, '[^' .. a:pattern .. ']', "a:1", "g")
let foo = substitute(a:string, pat, a:2, "g")
- let foo = substitute(foo, '[^' . a:2 . ']', "", "g")
+ let foo = substitute(foo, '[^' .. a:2 .. ']', "", "g")
return strlen(foo)
endif
let result = 0
@@ -456,7 +469,7 @@ endfun
" unless it is preceded by "\".
fun! s:Resolve(source, target, output)
let word = a:target
- let i = matchend(word, s:notslash . '\\\d') - 1
+ let i = matchend(word, s:notslash .. '\\\d') - 1
let table = "----------"
while i != -2 " There are back references to be replaced.
let d = word[i]
@@ -477,28 +490,28 @@ fun! s:Resolve(source, target, output)
if table[s] == "-"
if w + b < 10
" let table[s] = w + b
- let table = strpart(table, 0, s) . (w+b) . strpart(table, s+1)
+ let table = strpart(table, 0, s) .. (w+b) .. strpart(table, s+1)
endif
let b = b + 1
let s = s + 1
else
execute s:Ref(backref, b, "start", "len")
let ref = strpart(backref, start, len)
- let backref = strpart(backref, 0, start) . ":". table[s]
- \ . strpart(backref, start+len)
+ let backref = strpart(backref, 0, start) .. ":" .. table[s]
+ \ .. strpart(backref, start+len)
let s = s + s:Count(substitute(ref, '\\\\', '', 'g'), '\(', '1')
endif
endwhile
- let word = strpart(word, 0, i-1) . backref . strpart(word, i+1)
- let i = matchend(word, s:notslash . '\\\d') - 1
+ let word = strpart(word, 0, i-1) .. backref .. strpart(word, i+1)
+ let i = matchend(word, s:notslash .. '\\\d') - 1
endwhile
- let word = substitute(word, s:notslash . '\zs:', '\\', 'g')
+ let word = substitute(word, s:notslash .. '\zs:', '\\', 'g')
if a:output == "table"
return table
elseif a:output == "word"
return word
else
- return table . word
+ return table .. word
endif
endfun
@@ -508,21 +521,21 @@ endfun
" If <patn> is the first pattern that matches a:string then return <patn>
" if no optional arguments are given; return <patn>,<altn> if a:1 is given.
fun! s:Choose(patterns, string, comma, branch, prefix, suffix, ...)
- let tail = (a:patterns =~ a:comma."$" ? a:patterns : a:patterns . a:comma)
- let i = matchend(tail, s:notslash . a:comma)
+ let tail = (a:patterns =~ a:comma .. "$" ? a:patterns : a:patterns .. a:comma)
+ let i = matchend(tail, s:notslash .. a:comma)
if a:0
- let alttail = (a:1 =~ a:comma."$" ? a:1 : a:1 . a:comma)
- let j = matchend(alttail, s:notslash . a:comma)
+ let alttail = (a:1 =~ a:comma .. "$" ? a:1 : a:1 .. a:comma)
+ let j = matchend(alttail, s:notslash .. a:comma)
endif
let current = strpart(tail, 0, i-1)
if a:branch == ""
let currpat = current
else
- let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g')
+ let currpat = substitute(current, s:notslash .. a:branch, '\\|', 'g')
endif
- while a:string !~ a:prefix . currpat . a:suffix
+ while a:string !~ a:prefix .. currpat .. a:suffix
let tail = strpart(tail, i)
- let i = matchend(tail, s:notslash . a:comma)
+ let i = matchend(tail, s:notslash .. a:comma)
if i == -1
return -1
endif
@@ -530,15 +543,15 @@ fun! s:Choose(patterns, string, comma, branch, prefix, suffix, ...)
if a:branch == ""
let currpat = current
else
- let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g')
+ let currpat = substitute(current, s:notslash .. a:branch, '\\|', 'g')
endif
if a:0
let alttail = strpart(alttail, j)
- let j = matchend(alttail, s:notslash . a:comma)
+ let j = matchend(alttail, s:notslash .. a:comma)
endif
endwhile
if a:0
- let current = current . a:comma . strpart(alttail, 0, j-1)
+ let current = current .. a:comma .. strpart(alttail, 0, j-1)
endif
return current
endfun
@@ -562,7 +575,7 @@ fun! matchit#Match_debug()
" fin = 'endif' piece, with all backrefs resolved from match
amenu &Matchit.&word :echo b:match_word<CR>
" '\'.d in ini refers to the same thing as '\'.table[d] in word.
- amenu &Matchit.t&able :echo '0:' . b:match_table . ':9'<CR>
+ amenu &Matchit.t&able :echo '0:' .. b:match_table .. ':9'<CR>
endfun
" Jump to the nearest unmatched "(" or "if" or "<tag>" if a:spflag == "bW"
@@ -598,26 +611,26 @@ fun! matchit#MultiMatch(spflag, mode)
endif
if (match_words != s:last_words) || (&mps != s:last_mps) ||
\ exists("b:match_debug")
- let default = escape(&mps, '[$^.*~\\/?]') . (strlen(&mps) ? "," : "") .
+ let default = escape(&mps, '[$^.*~\\/?]') .. (strlen(&mps) ? "," : "") ..
\ '\/\*:\*\/,#\s*if\%(n\=def\)\=:#\s*else\>:#\s*elif\>:#\s*endif\>'
let s:last_mps = &mps
- let match_words = match_words . (strlen(match_words) ? "," : "") . default
+ let match_words = match_words .. (strlen(match_words) ? "," : "") .. default
let s:last_words = match_words
- if match_words !~ s:notslash . '\\\d'
+ if match_words !~ s:notslash .. '\\\d'
let s:do_BR = 0
let s:pat = match_words
else
let s:do_BR = 1
let s:pat = s:ParseWords(match_words)
endif
- let s:all = '\%(' . substitute(s:pat, '[,:]\+', '\\|', 'g') . '\)'
+ let s:all = '\%(' .. substitute(s:pat, '[,:]\+', '\\|', 'g') .. '\)'
if exists("b:match_debug")
let b:match_pat = s:pat
endif
" Reconstruct the version with unresolved backrefs.
- let s:patBR = substitute(match_words.',',
- \ s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
- let s:patBR = substitute(s:patBR, s:notslash.'\zs:\{2,}', ':', 'g')
+ let s:patBR = substitute(match_words .. ',',
+ \ s:notslash .. '\zs[,:]*,[,:]*', ',', 'g')
+ let s:patBR = substitute(s:patBR, s:notslash .. '\zs:\{2,}', ':', 'g')
endif
" Second step: figure out the patterns for searchpair()
@@ -625,23 +638,23 @@ fun! matchit#MultiMatch(spflag, mode)
" - TODO: A lot of this is copied from matchit#Match_wrapper().
" - maybe even more functionality should be split off
" - into separate functions!
- let openlist = split(s:pat . ',', s:notslash . '\zs:.\{-}' . s:notslash . ',')
- let midclolist = split(',' . s:pat, s:notslash . '\zs,.\{-}' . s:notslash . ':')
- call map(midclolist, {-> split(v:val, s:notslash . ':')})
+ let openlist = split(s:pat .. ',', s:notslash .. '\zs:.\{-}' .. s:notslash .. ',')
+ let midclolist = split(',' .. s:pat, s:notslash .. '\zs,.\{-}' .. s:notslash .. ':')
+ call map(midclolist, {-> split(v:val, s:notslash .. ':')})
let closelist = []
let middlelist = []
call map(midclolist, {i,v -> [extend(closelist, v[-1 : -1]),
\ extend(middlelist, v[0 : -2])]})
- call map(openlist, {i,v -> v =~# s:notslash . '\\|' ? '\%(' . v . '\)' : v})
- call map(middlelist, {i,v -> v =~# s:notslash . '\\|' ? '\%(' . v . '\)' : v})
- call map(closelist, {i,v -> v =~# s:notslash . '\\|' ? '\%(' . v . '\)' : v})
+ call map(openlist, {i,v -> v =~# s:notslash .. '\\|' ? '\%(' .. v .. '\)' : v})
+ call map(middlelist, {i,v -> v =~# s:notslash .. '\\|' ? '\%(' .. v .. '\)' : v})
+ call map(closelist, {i,v -> v =~# s:notslash .. '\\|' ? '\%(' .. v .. '\)' : v})
let open = join(openlist, ',')
let middle = join(middlelist, ',')
let close = join(closelist, ',')
if exists("b:match_skip")
let skip = b:match_skip
elseif exists("b:match_comment") " backwards compatibility and testing!
- let skip = "r:" . b:match_comment
+ let skip = "r:" .. b:match_comment
else
let skip = 's:comment\|string'
endif
@@ -650,18 +663,18 @@ fun! matchit#MultiMatch(spflag, mode)
" Third step: call searchpair().
" Replace '\('--but not '\\('--with '\%(' and ',' with '\|'.
- let openpat = substitute(open, '\%(' . s:notslash . '\)\@<=\\(', '\\%(', 'g')
+ let openpat = substitute(open, '\%(' .. s:notslash .. '\)\@<=\\(', '\\%(', 'g')
let openpat = substitute(openpat, ',', '\\|', 'g')
- let closepat = substitute(close, '\%(' . s:notslash . '\)\@<=\\(', '\\%(', 'g')
+ let closepat = substitute(close, '\%(' .. s:notslash .. '\)\@<=\\(', '\\%(', 'g')
let closepat = substitute(closepat, ',', '\\|', 'g')
- let middlepat = substitute(middle, '\%(' . s:notslash . '\)\@<=\\(', '\\%(', 'g')
+ let middlepat = substitute(middle, '\%(' .. s:notslash .. '\)\@<=\\(', '\\%(', 'g')
let middlepat = substitute(middlepat, ',', '\\|', 'g')
if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
let skip = '0'
else
try
- execute "if " . skip . "| let skip = '0' | endif"
+ execute "if " .. skip .. "| let skip = '0' | endif"
catch /^Vim\%((\a\+)\)\=:E363/
" We won't find anything, so skip searching, should keep Vim responsive.
return {}
@@ -744,11 +757,11 @@ fun! s:ParseSkip(str)
let skip = a:str
if skip[1] == ":"
if skip[0] == "s"
- let skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" .
- \ strpart(skip,2) . "'"
+ let skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" ..
+ \ strpart(skip,2) .. "'"
elseif skip[0] == "S"
- let skip = "synIDattr(synID(line('.'),col('.'),1),'name') !~? '" .
- \ strpart(skip,2) . "'"
+ let skip = "synIDattr(synID(line('.'),col('.'),1),'name') !~? '" ..
+ \ strpart(skip,2) .. "'"
elseif skip[0] == "r"
let skip = "strpart(getline('.'),0,col('.'))=~'" . strpart(skip,2). "'"
elseif skip[0] == "R"
diff --git a/runtime/pack/dist/opt/matchit/doc/matchit.txt b/runtime/pack/dist/opt/matchit/doc/matchit.txt
index b719fae730..553359ffaf 100644
--- a/runtime/pack/dist/opt/matchit/doc/matchit.txt
+++ b/runtime/pack/dist/opt/matchit/doc/matchit.txt
@@ -4,7 +4,7 @@ For instructions on installing this file, type
`:help matchit-install`
inside Vim.
-For Vim version 8.1. Last change: 2021 Nov 13
+For Vim version 8.2. Last change: 2021 Dec 24
VIM REFERENCE MANUAL by Benji Fisher et al
@@ -150,6 +150,10 @@ To use the matchit plugin add this line to your |vimrc|: >
The script should start working the next time you start Vim.
+To use the matchit plugin after startup, you can use this command (note the
+omitted '!'): >
+ packadd matchit
+
(Earlier versions of the script did nothing unless a |buffer-variable| named
|b:match_words| was defined. Even earlier versions contained autocommands
that set this variable for various file types. Now, |b:match_words| is
@@ -378,8 +382,8 @@ The back reference '\'.d refers to the same thing as '\'.b:match_table[d] in
5. Known Bugs and Limitations *matchit-bugs*
Repository: https://github.com/chrisbra/matchit/
-Bugs can be reported at the repository (alternatively you can send me a mail).
-The latest development snapshot can also be downloaded there.
+Bugs can be reported at the repository and the latest development snapshot can
+also be downloaded there.
Just because I know about a bug does not mean that it is on my todo list. I
try to respond to reports of bugs that cause real problems. If it does not
diff --git a/runtime/pack/dist/opt/matchit/plugin/matchit.vim b/runtime/pack/dist/opt/matchit/plugin/matchit.vim
index b62cc3913a..51ba3a7f51 100644
--- a/runtime/pack/dist/opt/matchit/plugin/matchit.vim
+++ b/runtime/pack/dist/opt/matchit/plugin/matchit.vim
@@ -1,7 +1,7 @@
" matchit.vim: (global plugin) Extended "%" matching
" Maintainer: Christian Brabandt
-" Version: 1.17
-" Last Change: 2019 Oct 24
+" Version: 1.18
+" Last Change: 2020 Dec 23
" Repository: https://github.com/chrisbra/matchit
" Previous URL:http://www.vim.org/script.php?script_id=39
" Previous Maintainer: Benji Fisher PhD <benji@member.AMS.org>
@@ -48,18 +48,12 @@ set cpo&vim
nnoremap <silent> <Plug>(MatchitNormalForward) :<C-U>call matchit#Match_wrapper('',1,'n')<CR>
nnoremap <silent> <Plug>(MatchitNormalBackward) :<C-U>call matchit#Match_wrapper('',0,'n')<CR>
-xnoremap <silent> <Plug>(MatchitVisualForward) :<C-U>call matchit#Match_wrapper('',1,'v')<CR>m'gv``
+xnoremap <silent> <Plug>(MatchitVisualForward) :<C-U>call matchit#Match_wrapper('',1,'v')<CR>
+ \:if col("''") != col("$") \| exe ":normal! m'" \| endif<cr>gv``
xnoremap <silent> <Plug>(MatchitVisualBackward) :<C-U>call matchit#Match_wrapper('',0,'v')<CR>m'gv``
onoremap <silent> <Plug>(MatchitOperationForward) :<C-U>call matchit#Match_wrapper('',1,'o')<CR>
onoremap <silent> <Plug>(MatchitOperationBackward) :<C-U>call matchit#Match_wrapper('',0,'o')<CR>
-nmap <silent> % <Plug>(MatchitNormalForward)
-nmap <silent> g% <Plug>(MatchitNormalBackward)
-xmap <silent> % <Plug>(MatchitVisualForward)
-xmap <silent> g% <Plug>(MatchitVisualBackward)
-omap <silent> % <Plug>(MatchitOperationForward)
-omap <silent> g% <Plug>(MatchitOperationBackward)
-
" Analogues of [{ and ]} using matching patterns:
nnoremap <silent> <Plug>(MatchitNormalMultiBackward) :<C-U>call matchit#MultiMatch("bW", "n")<CR>
nnoremap <silent> <Plug>(MatchitNormalMultiForward) :<C-U>call matchit#MultiMatch("W", "n")<CR>
@@ -68,16 +62,28 @@ xnoremap <silent> <Plug>(MatchitVisualMultiForward) :<C-U>call matchit#Multi
onoremap <silent> <Plug>(MatchitOperationMultiBackward) :<C-U>call matchit#MultiMatch("bW", "o")<CR>
onoremap <silent> <Plug>(MatchitOperationMultiForward) :<C-U>call matchit#MultiMatch("W", "o")<CR>
-nmap <silent> [% <Plug>(MatchitNormalMultiBackward)
-nmap <silent> ]% <Plug>(MatchitNormalMultiForward)
-xmap <silent> [% <Plug>(MatchitVisualMultiBackward)
-xmap <silent> ]% <Plug>(MatchitVisualMultiForward)
-omap <silent> [% <Plug>(MatchitOperationMultiBackward)
-omap <silent> ]% <Plug>(MatchitOperationMultiForward)
-
" text object:
xmap <silent> <Plug>(MatchitVisualTextObject) <Plug>(MatchitVisualMultiBackward)o<Plug>(MatchitVisualMultiForward)
-xmap a% <Plug>(MatchitVisualTextObject)
+
+if !exists("g:no_plugin_maps")
+ nmap <silent> % <Plug>(MatchitNormalForward)
+ nmap <silent> g% <Plug>(MatchitNormalBackward)
+ xmap <silent> % <Plug>(MatchitVisualForward)
+ xmap <silent> g% <Plug>(MatchitVisualBackward)
+ omap <silent> % <Plug>(MatchitOperationForward)
+ omap <silent> g% <Plug>(MatchitOperationBackward)
+
+ " Analogues of [{ and ]} using matching patterns:
+ nmap <silent> [% <Plug>(MatchitNormalMultiBackward)
+ nmap <silent> ]% <Plug>(MatchitNormalMultiForward)
+ xmap <silent> [% <Plug>(MatchitVisualMultiBackward)
+ xmap <silent> ]% <Plug>(MatchitVisualMultiForward)
+ omap <silent> [% <Plug>(MatchitOperationMultiBackward)
+ omap <silent> ]% <Plug>(MatchitOperationMultiForward)
+
+ " Text object
+ xmap a% <Plug>(MatchitVisualTextObject)
+endif
" Call this function to turn on debugging information. Every time the main
" script is run, buffer variables will be saved. These can be used directly
diff --git a/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim b/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim
index 67d91360d8..49d9389773 100644
--- a/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim
+++ b/runtime/pack/dist/opt/termdebug/plugin/termdebug.vim
@@ -2,7 +2,7 @@
"
" Author: Bram Moolenaar
" Copyright: Vim license applies, see ":help license"
-" Last Change: 2021 Nov 29
+" Last Change: 2022 Jan 17
"
" WORK IN PROGRESS - Only the basics work
" Note: On MS-Windows you need a recent version of gdb. The one included with
@@ -104,6 +104,10 @@ call s:Highlight(1, '', &background)
hi default debugBreakpoint term=reverse ctermbg=red guibg=red
hi default debugBreakpointDisabled term=reverse ctermbg=gray guibg=gray
+func s:GetCommand()
+ return type(g:termdebugger) == v:t_list ? copy(g:termdebugger) : [g:termdebugger]
+endfunc
+
func s:StartDebug(bang, ...)
" First argument is the command to debug, second core file or process ID.
call s:StartDebug_internal({'gdb_args': a:000, 'bang': a:bang})
@@ -119,8 +123,9 @@ func s:StartDebug_internal(dict)
echoerr 'Terminal debugger already running, cannot run two'
return
endif
- if !executable(g:termdebugger)
- echoerr 'Cannot execute debugger program "' .. g:termdebugger .. '"'
+ let gdbcmd = s:GetCommand()
+ if !executable(gdbcmd[0])
+ echoerr 'Cannot execute debugger program "' .. gdbcmd[0] .. '"'
return
endif
@@ -148,7 +153,7 @@ func s:StartDebug_internal(dict)
if &columns < g:termdebug_wide
let s:save_columns = &columns
let &columns = g:termdebug_wide
- " If we make the Vim window wider, use the whole left halve for the debug
+ " If we make the Vim window wider, use the whole left half for the debug
" windows.
let s:allleft = 1
endif
@@ -192,7 +197,7 @@ endfunc
func s:CheckGdbRunning()
if nvim_get_chan_info(s:gdb_job_id) == {}
- echoerr string(g:termdebugger) . ' exited unexpectedly'
+ echoerr string(s:GetCommand()[0]) . ' exited unexpectedly'
call s:CloseBuffers()
return ''
endif
@@ -245,7 +250,7 @@ func s:StartDebug_term(dict)
let gdb_args = get(a:dict, 'gdb_args', [])
let proc_args = get(a:dict, 'proc_args', [])
- let gdb_cmd = [g:termdebugger]
+ let gdb_cmd = s:GetCommand()
" Add -quiet to avoid the intro message causing a hit-enter prompt.
let gdb_cmd += ['-quiet']
" Disable pagination, it causes everything to stop at the gdb
@@ -379,7 +384,7 @@ func s:StartDebug_prompt(dict)
let gdb_args = get(a:dict, 'gdb_args', [])
let proc_args = get(a:dict, 'proc_args', [])
- let gdb_cmd = [g:termdebugger]
+ let gdb_cmd = s:GetCommand()
" Add -quiet to avoid the intro message causing a hit-enter prompt.
let gdb_cmd += ['-quiet']
" Disable pagination, it causes everything to stop at the gdb, needs to be run early
@@ -609,7 +614,7 @@ endfunc
" to the next ", unescaping characters:
" - remove line breaks
" - change \\t to \t
-" - change \0xhh to \xhh
+" - change \0xhh to \xhh (disabled for now)
" - change \ooo to octal
" - change \\ to \
func s:DecodeMessage(quotedText)
@@ -618,12 +623,21 @@ func s:DecodeMessage(quotedText)
return
endif
return a:quotedText
- \->substitute('^"\|".*\|\\n', '', 'g')
- \->substitute('\\t', "\t", 'g')
- \->substitute('\\0x\(\x\x\)', {-> eval('"\x' .. submatch(1) .. '"')}, 'g')
- \->substitute('\\\o\o\o', {-> eval('"' .. submatch(0) .. '"')}, 'g')
- \->substitute('\\\\', '\', 'g')
+ \ ->substitute('^"\|".*\|\\n', '', 'g')
+ \ ->substitute('\\t', "\t", 'g')
+ " multi-byte characters arrive in octal form
+ " NULL-values must be kept encoded as those break the string otherwise
+ \ ->substitute('\\000', s:NullRepl, 'g')
+ \ ->substitute('\\\o\o\o', {-> eval('"' .. submatch(0) .. '"')}, 'g')
+ " Note: GDB docs also mention hex encodings - the translations below work
+ " but we keep them out for performance-reasons until we actually see
+ " those in mi-returns
+ " \ ->substitute('\\0x\(\x\x\)', {-> eval('"\x' .. submatch(1) .. '"')}, 'g')
+ " \ ->substitute('\\0x00', s:NullRepl, 'g')
+ \ ->substitute('\\\\', '\', 'g')
+ \ ->substitute(s:NullRepl, '\\000', 'g')
endfunc
+const s:NullRepl = 'XXXNULLXXX'
" Extract the "name" value from a gdb message with fullname="name".
func s:GetFullname(msg)
@@ -1037,10 +1051,10 @@ func s:GetEvaluationExpression(range, arg)
return expr
endfunc
-" clean up expression that may got in because of range
+" clean up expression that may get in because of range
" (newlines and surrounding whitespace)
" As it can also be specified via ex-command for assignments this function
-" may not change the "content" parts (like replacing contained spaces
+" may not change the "content" parts (like replacing contained spaces)
func s:CleanupExpr(expr)
" replace all embedded newlines/tabs/...
let expr = substitute(a:expr, '\_s', ' ', 'g')
@@ -1066,11 +1080,20 @@ let s:evalFromBalloonExprResult = ''
" Handle the result of data-evaluate-expression
func s:HandleEvaluate(msg)
- let value = substitute(a:msg, '.*value="\(.*\)"', '\1', '')
- let value = substitute(value, '\\"', '"', 'g')
- " multi-byte characters arrive in octal form
- let value = substitute(value, '\\\o\o\o', {-> eval('"' .. submatch(0) .. '"')}, 'g')
- let value = substitute(value, ' ', '\1', '')
+ let value = a:msg
+ \ ->substitute('.*value="\(.*\)"', '\1', '')
+ \ ->substitute('\\"', '"', 'g')
+ \ ->substitute('\\\\', '\\', 'g')
+ "\ multi-byte characters arrive in octal form, replace everything but NULL values
+ \ ->substitute('\\000', s:NullRepl, 'g')
+ \ ->substitute('\\\o\o\o', {-> eval('"' .. submatch(0) .. '"')}, 'g')
+ "\ Note: GDB docs also mention hex encodings - the translations below work
+ "\ but we keep them out for performance-reasons until we actually see
+ "\ those in mi-returns
+ "\ ->substitute('\\0x00', s:NullRep, 'g')
+ "\ ->substitute('\\0x\(\x\x\)', {-> eval('"\x' .. submatch(1) .. '"')}, 'g')
+ \ ->substitute(s:NullRepl, '\\000', 'g')
+ \ ->substitute(' ', '\1', '')
if s:evalFromBalloonExpr
if s:evalFromBalloonExprResult == ''
let s:evalFromBalloonExprResult = s:evalexpr . ': ' . value
@@ -1321,6 +1344,16 @@ func s:HandleCursor(msg)
if lnum =~ '^[0-9]*$'
call s:GotoSourcewinOrCreateIt()
if expand('%:p') != fnamemodify(fname, ':p')
+ echomsg 'different fname: "' .. expand('%:p') .. '" vs "' .. fnamemodify(fname, ':p') .. '"'
+ augroup Termdebug
+ " Always open a file read-only instead of showing the ATTENTION
+ " prompt, since we are unlikely to want to edit the file.
+ " The file may be changed but not saved, warn for that.
+ au SwapExists * echohl WarningMsg
+ \ | echo 'Warning: file is being edited elsewhere'
+ \ | echohl None
+ \ | let v:swapchoice = 'o'
+ augroup END
if &modified
" TODO: find existing window
exe 'split ' . fnameescape(fname)
@@ -1329,6 +1362,9 @@ func s:HandleCursor(msg)
else
exe 'edit ' . fnameescape(fname)
endif
+ augroup Termdebug
+ au! SwapExists
+ augroup END
endif
exe lnum
normal! zv
diff --git a/runtime/scripts.vim b/runtime/scripts.vim
index 3790b1c10f..dd47f65ba0 100644
--- a/runtime/scripts.vim
+++ b/runtime/scripts.vim
@@ -384,7 +384,7 @@ else
set ft=scheme
" Git output
- elseif s:line1 =~# '^\(commit\|tree\|object\) \x\{40\}\>\|^tag \S\+$'
+ elseif s:line1 =~# '^\(commit\|tree\|object\) \x\{40,\}\>\|^tag \S\+$'
set ft=git
" Gprof (gnu profiler)
@@ -406,6 +406,12 @@ else
elseif s:line1 =~# '^#.*by RouterOS.*$'
set ft=routeros
+ " Sed scripts
+ " #ncomment is allowed but most likely a false positive so require a space
+ " before any trailing comment text
+ elseif s:line1 =~# '^#n\%($\|\s\)'
+ set ft=sed
+
" CVS diff
else
let s:lnum = 1
diff --git a/runtime/syntax/c.vim b/runtime/syntax/c.vim
index 20f8632006..e86e1b8669 100644
--- a/runtime/syntax/c.vim
+++ b/runtime/syntax/c.vim
@@ -1,7 +1,7 @@
" Vim syntax file
" Language: C
" Maintainer: Bram Moolenaar <Bram@vim.org>
-" Last Change: 2021 May 24
+" Last Change: 2021 Dec 07
" Quit when a (custom) syntax file was already loaded
if exists("b:current_syntax")
@@ -196,7 +196,6 @@ syn match cNumber display contained "0x\x\+\(u\=l\{0,2}\|ll\=u\)\>"
" Flag the first zero of an octal number as something special
syn match cOctal display contained "0\o\+\(u\=l\{0,2}\|ll\=u\)\>" contains=cOctalZero
syn match cOctalZero display contained "\<0"
-syn match cFloat display contained "\d\+f"
"floating point number, with dot, optional exponent
syn match cFloat display contained "\d\+\.\d*\(e[-+]\=\d\+\)\=[fl]\="
"floating point number, starting with a dot, optional exponent
diff --git a/runtime/syntax/checkhealth.vim b/runtime/syntax/checkhealth.vim
new file mode 100644
index 0000000000..37f1822740
--- /dev/null
+++ b/runtime/syntax/checkhealth.vim
@@ -0,0 +1,30 @@
+" Vim syntax file
+" Language: Neovim checkhealth buffer
+" Last Change: 2021 Dec 15
+
+if exists("b:current_syntax")
+ finish
+endif
+
+runtime! syntax/markdown.vim
+unlet! b:current_syntax
+
+syn case match
+
+" We do not care about markdown syntax errors
+if hlexists('markdownError')
+ syn clear markdownError
+endif
+
+syn keyword healthError ERROR[:] containedin=markdownCodeBlock,mkdListItemLine
+syn keyword healthWarning WARNING[:] containedin=markdownCodeBlock,mkdListItemLine
+syn keyword healthSuccess OK[:] containedin=markdownCodeBlock,mkdListItemLine
+syn match healthHelp "|.\{-}|" containedin=markdownCodeBlock,mkdListItemLine contains=healthBar
+syn match healthBar "|" contained conceal
+
+hi def link healthError Error
+hi def link healthWarning WarningMsg
+hi def healthSuccess guibg=#5fff00 guifg=#080808 ctermbg=82 ctermfg=232
+hi def link healthHelp Identifier
+
+let b:current_syntax = "checkhealth"
diff --git a/runtime/syntax/css.vim b/runtime/syntax/css.vim
index 67ad1ea335..564dc151bc 100644
--- a/runtime/syntax/css.vim
+++ b/runtime/syntax/css.vim
@@ -7,7 +7,7 @@
" Nikolai Weibull (Add CSS2 support)
" URL: https://github.com/vim-language-dept/css-syntax.vim
" Maintainer: Jay Sitter <jay@jaysitter.com>
-" Last Change: 2021 Oct 15
+" Last Change: 2021 Oct 20
" quit when a syntax file was already loaded
if !exists("main_syntax")
@@ -116,7 +116,7 @@ syn keyword cssColor contained ActiveBorder ActiveCaption AppWorkspace ButtonFac
syn case ignore
syn match cssImportant contained "!\s*important\>"
-syn match cssCustomProp contained "--[a-zA-Z0-9-_]*"
+syn match cssCustomProp contained "\<--[a-zA-Z0-9-_]*\>"
syn match cssColor contained "\<transparent\>"
syn match cssColor contained "\<currentColor\>"
@@ -126,6 +126,7 @@ syn match cssColor contained "#\x\{6\}\>" contains=cssUnitDecorators
syn match cssColor contained "#\x\{8\}\>" contains=cssUnitDecorators
syn region cssURL contained matchgroup=cssFunctionName start="\<\(uri\|url\|local\|format\)\s*(" end=")" contains=cssStringQ,cssStringQQ oneline
+syn region cssMathGroup contained matchgroup=cssMathParens start="(" end=")" containedin=cssFunction,cssMathGroup contains=cssCustomProp,cssValue.*,cssFunction,cssColor,cssStringQ,cssStringQQ oneline
syn region cssFunction contained matchgroup=cssFunctionName start="\<\(var\|calc\)\s*(" end=")" contains=cssCustomProp,cssValue.*,cssFunction,cssColor,cssStringQ,cssStringQQ oneline
syn region cssFunction contained matchgroup=cssFunctionName start="\<\(rgb\|clip\|attr\|counter\|rect\|cubic-bezier\|steps\)\s*(" end=")" oneline contains=cssValueInteger,cssValueNumber,cssValueLength,cssFunctionComma
syn region cssFunction contained matchgroup=cssFunctionName start="\<\(rgba\|hsl\|hsla\|color-stop\|from\|to\)\s*(" end=")" oneline contains=cssColor,cssValueInteger,cssValueNumber,cssValueLength,cssFunctionComma,cssFunction
@@ -395,9 +396,9 @@ syn match cssUIAttr contained '\<preserve-3d\>'
syn match cssIEUIAttr contained '\<bicubic\>'
" Webkit/iOS specific properties
-syn match cssUIProp contained '\<tap-highlight-color\|user-select\|touch-callout\>'
+syn match cssUIProp contained '\<\(tap-highlight-color\|user-select\|touch-callout\)\>'
" IE specific properties
-syn match cssIEUIProp contained '\<interpolation-mode\|zoom\|filter\>'
+syn match cssIEUIProp contained '\<\(interpolation-mode\|zoom\|filter\)\>'
" Webkit/Firebox specific properties/attributes
syn keyword cssUIProp contained appearance
@@ -423,11 +424,15 @@ syn keyword cssAuralAttr contained male female child code digits continuous
syn match cssMobileTextProp contained "\<text-size-adjust\>"
syn keyword cssMediaProp contained width height orientation scan
-syn match cssMediaProp contained /\(\(max\|min\)-\)\=\(\(device\)-\)\=aspect-ratio/
-syn match cssMediaProp contained /\(\(max\|min\)-\)\=device-pixel-ratio/
-syn match cssMediaProp contained /\(\(max\|min\)-\)\=device-\(height\|width\)/
-syn match cssMediaProp contained /\(\(max\|min\)-\)\=\(height\|width\|resolution\|monochrome\|color\(-index\)\=\)/
+syn keyword cssMediaProp contained any-hover any-pointer color-gamut grid hover
+syn keyword cssMediaProp contained overflow-block overflow-inline pointer update
+syn match cssMediaProp contained /\<\(\(max\|min\)-\)\=\(\(device\)-\)\=aspect-ratio\>/
+syn match cssMediaProp contained /\<\(\(max\|min\)-\)\=device-pixel-ratio\>/
+syn match cssMediaProp contained /\<\(\(max\|min\)-\)\=device-\(height\|width\)\>/
+syn match cssMediaProp contained /\<\(\(max\|min\)-\)\=\(height\|width\|resolution\|monochrome\|color\(-index\)\=\)\>/
syn keyword cssMediaAttr contained portrait landscape progressive interlace
+syn keyword cssMediaAttr contained coarse fast fine hover infinite p3 paged
+syn keyword cssMediaAttr contained rec2020 scroll slow srgb
syn match cssKeyFrameProp contained /\(\d\+\(\.\d\+\)\?%\|\(\<from\|to\>\)\)/ nextgroup=cssDefinition
syn match cssPageMarginProp /@\(\(top\|left\|right\|bottom\)-\(left\|center\|right\|middle\|bottom\)\)\(-corner\)\=/ contained nextgroup=cssDefinition
syn keyword cssPageProp contained content size
@@ -445,17 +450,17 @@ syn match cssBraceError "}"
syn match cssAttrComma ","
" Pseudo class
-" http://www.w3.org/TR/css3-selectors/
+" https://www.w3.org/TR/selectors-4/
syn match cssPseudoClass ":[A-Za-z0-9_-]*" contains=cssNoise,cssPseudoClassId,cssUnicodeEscape,cssVendor,cssPseudoClassFn
syn keyword cssPseudoClassId contained link visited active hover before after left right
-syn keyword cssPseudoClassId contained root empty target enable disabled checked invalid
+syn keyword cssPseudoClassId contained root empty target enabled disabled checked invalid
syn match cssPseudoClassId contained "\<first-\(line\|letter\)\>"
syn match cssPseudoClassId contained "\<\(first\|last\|only\)-\(of-type\|child\)\>"
-syn region cssPseudoClassFn contained matchgroup=cssFunctionName start="\<\(not\|lang\|\(nth\|nth-last\)-\(of-type\|child\)\)(" end=")" contains=cssStringQ,cssStringQQ
+syn match cssPseudoClassId contained "\<focus\(-within\|-visible\)\=\>"
+syn region cssPseudoClassFn contained matchgroup=cssFunctionName start="\<\(not\|is\|lang\|\(nth\|nth-last\)-\(of-type\|child\)\)(" end=")" contains=cssStringQ,cssStringQQ,cssTagName,cssAttributeSelector,cssClassName,cssIdentifier
" ------------------------------------
" Vendor specific properties
syn match cssPseudoClassId contained "\<selection\>"
-syn match cssPseudoClassId contained "\<focus\(-inner\)\=\>"
syn match cssPseudoClassId contained "\<\(input-\)\=placeholder\>"
" Misc highlight groups
diff --git a/runtime/syntax/debcontrol.vim b/runtime/syntax/debcontrol.vim
index 25fc252de6..8b65ece4ca 100644
--- a/runtime/syntax/debcontrol.vim
+++ b/runtime/syntax/debcontrol.vim
@@ -3,7 +3,7 @@
" Maintainer: Debian Vim Maintainers
" Former Maintainers: Gerfried Fuchs <alfie@ist.org>
" Wichert Akkerman <wakkerma@debian.org>
-" Last Change: 2020 Oct 26
+" Last Change: 2021 Nov 26
" URL: https://salsa.debian.org/vim-team/vim-debian/blob/master/syntax/debcontrol.vim
" Standard syntax initialization
@@ -91,6 +91,11 @@ syn case ignore
" Handle all fields from deb-src-control(5)
+" Catch-all for the legal fields
+syn region debcontrolField matchgroup=debcontrolKey start="^\%(\%(XSBC-Original-\)\=Maintainer\|Standards-Version\|Bugs\|Origin\|X[SB]-Python-Version\|\%(XS-\)\=Vcs-Mtn\|\%(XS-\)\=Testsuite\%(-Triggers\)\=\|Build-Profiles\|Tag\|Subarchitecture\|Kernel-Version\|Installer-Menu-Item\): " end="$" contains=debcontrolVariable,debcontrolEmail oneline
+syn region debcontrolMultiField matchgroup=debcontrolKey start="^\%(Build-\%(Conflicts\|Depends\)\%(-Arch\|-Indep\)\=\|\%(Pre-\)\=Depends\|Recommends\|Suggests\|Breaks\|Enhances\|Replaces\|Conflicts\|Provides\|Built-Using\|Uploaders\|X[SBC]\{0,3\}\%(Private-\)\=-[-a-zA-Z0-9]\+\): *" skip="^[ \t]" end="^$"me=s-1 end="^[^ \t#]"me=s-1 contains=debcontrolEmail,debcontrolVariable,debcontrolComment
+syn region debcontrolMultiFieldSpell matchgroup=debcontrolKey start="^Description: *" skip="^[ \t]" end="^$"me=s-1 end="^[^ \t#]"me=s-1 contains=debcontrolEmail,debcontrolVariable,debcontrolComment,@Spell
+
" Fields for which we do strict syntax checking
syn region debcontrolStrictField matchgroup=debcontrolKey start="^Architecture: *" end="$" contains=debcontrolArchitecture,debcontrolSpace oneline
syn region debcontrolStrictField matchgroup=debcontrolKey start="^Multi-Arch: *" end="$" contains=debcontrolMultiArch oneline
@@ -99,20 +104,15 @@ syn region debcontrolStrictField matchgroup=debcontrolKey start="^Priority: *" e
syn region debcontrolStrictField matchgroup=debcontrolKey start="^Section: *" end="$" contains=debcontrolSection oneline
syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(XC-\)\=Package-Type: *" end="$" contains=debcontrolPackageType oneline
syn region debcontrolStrictField matchgroup=debcontrolKey start="^Homepage: *" end="$" contains=debcontrolHTTPUrl oneline keepend
-syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(XS-\)\=Vcs-\%(Browser\|Arch\|Bzr\|Darcs\|Hg\): *" end="$" contains=debcontrolHTTPUrl oneline keepend
-syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(XS-\)\=Vcs-Svn: *" end="$" contains=debcontrolVcsSvn,debcontrolHTTPUrl oneline keepend
-syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(XS-\)\=Vcs-Cvs: *" end="$" contains=debcontrolVcsCvs oneline keepend
-syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(XS-\)\=Vcs-Git: *" end="$" contains=debcontrolVcsGit oneline keepend
+syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(XS-[-a-zA-Z0-9]\+-\)\=Vcs-\%(Browser\|Arch\|Bzr\|Darcs\|Hg\): *" end="$" contains=debcontrolHTTPUrl oneline keepend
+syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(XS-[-a-zA-Z0-9]\+-\)\=Vcs-Svn: *" end="$" contains=debcontrolVcsSvn,debcontrolHTTPUrl oneline keepend
+syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(XS-[-a-zA-Z0-9]\+-\)\=Vcs-Cvs: *" end="$" contains=debcontrolVcsCvs oneline keepend
+syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(XS-[-a-zA-Z0-9]\+-\)\=Vcs-Git: *" end="$" contains=debcontrolVcsGit oneline keepend
syn region debcontrolStrictField matchgroup=debcontrolKey start="^Rules-Requires-Root: *" end="$" contains=debcontrolR3 oneline
syn region debcontrolStrictField matchgroup=debcontrolKey start="^\%(Build-\)\=Essential: *" end="$" contains=debcontrolYesNo oneline
syn region debcontrolStrictField matchgroup=debcontrolDeprecatedKey start="^\%(XS-\)\=DM-Upload-Allowed: *" end="$" contains=debcontrolDmUpload oneline
-" Catch-all for the other legal fields
-syn region debcontrolField matchgroup=debcontrolKey start="^\%(\%(XSBC-Original-\)\=Maintainer\|Standards-Version\|Bugs\|Origin\|X[SB]-Python-Version\|\%(XS-\)\=Vcs-Mtn\|\%(XS-\)\=Testsuite\%(-Triggers\)\=\|Build-Profiles\|Tag\|Subarchitecture\|Kernel-Version\|Installer-Menu-Item\): " end="$" contains=debcontrolVariable,debcontrolEmail oneline
-syn region debcontrolMultiField matchgroup=debcontrolKey start="^\%(Build-\%(Conflicts\|Depends\)\%(-Arch\|-Indep\)\=\|\%(Pre-\)\=Depends\|Recommends\|Suggests\|Breaks\|Enhances\|Replaces\|Conflicts\|Provides\|Built-Using\|Uploaders\|X[SBC]\{0,3\}\%(Private-\)\=-[-a-zA-Z0-9]\+\): *" skip="^[ \t]" end="^$"me=s-1 end="^[^ \t#]"me=s-1 contains=debcontrolEmail,debcontrolVariable,debcontrolComment
-syn region debcontrolMultiFieldSpell matchgroup=debcontrolKey start="^Description: *" skip="^[ \t]" end="^$"me=s-1 end="^[^ \t#]"me=s-1 contains=debcontrolEmail,debcontrolVariable,debcontrolComment,@Spell
-
" Associate our matches and regions with pretty colours
hi def link debcontrolKey Keyword
hi def link debcontrolField Normal
diff --git a/runtime/syntax/dep3patch.vim b/runtime/syntax/dep3patch.vim
new file mode 100644
index 0000000000..8b2cee629c
--- /dev/null
+++ b/runtime/syntax/dep3patch.vim
@@ -0,0 +1,57 @@
+" Vim syntax file
+" Language: Debian DEP3 Patch headers
+" Maintainer: Gabriel Filion <gabster@lelutin.ca>
+" Last Change: 2021-01-09
+" URL: https://salsa.debian.org/vim-team/vim-debian/blob/master/syntax/dep3patch.vim
+"
+" Specification of the DEP3 patch header format is available at:
+" https://dep-team.pages.debian.net/deps/dep3/
+
+" Standard syntax initialization
+if exists('b:current_syntax')
+ finish
+endif
+
+runtime! syntax/diff.vim
+unlet! b:current_syntax
+
+let s:cpo_save = &cpo
+set cpo&vim
+
+syn region dep3patchHeaders start="\%^" end="^\%(---\)\@=" contains=dep3patchKey,dep3patchMultiField
+
+syn case ignore
+
+syn region dep3patchMultiField matchgroup=dep3patchKey start="^\%(Description\|Subject\)\ze: *" skip="^[ \t]" end="^$"me=s-1 end="^[^ \t#]"me=s-1 contained contains=@Spell
+syn region dep3patchMultiField matchgroup=dep3patchKey start="^Origin\ze: *" end="$" contained contains=dep3patchHTTPUrl,dep3patchCommitID,dep3patchOriginCategory oneline keepend
+syn region dep3patchMultiField matchgroup=dep3patchKey start="^Bug\%(-[[:graph:]]\+\)\?\ze: *" end="$" contained contains=dep3patchHTTPUrl oneline keepend
+syn region dep3patchMultiField matchgroup=dep3patchKey start="^Forwarded\ze: *" end="$" contained contains=dep3patchHTTPUrl,dep3patchForwardedShort oneline keepend
+syn region dep3patchMultiField matchgroup=dep3patchKey start="^\%(Author\|From\)\ze: *" end="$" contained contains=dep3patchEmail oneline keepend
+syn region dep3patchMultiField matchgroup=dep3patchKey start="^\%(Reviewed-by\|Acked-by\)\ze: *" end="$" contained contains=dep3patchEmail oneline keepend
+syn region dep3patchMultiField matchgroup=dep3patchKey start="^Last-Updated\ze: *" end="$" contained contains=dep3patchISODate oneline keepend
+syn region dep3patchMultiField matchgroup=dep3patchKey start="^Applied-Upstream\ze: *" end="$" contained contains=dep3patchHTTPUrl,dep3patchCommitID oneline keepend
+
+syn match dep3patchHTTPUrl contained "\vhttps?://[[:alnum:]][-[:alnum:]]*[[:alnum:]]?(\.[[:alnum:]][-[:alnum:]]*[[:alnum:]]?)*\.[[:alpha:]][-[:alnum:]]*[[:alpha:]]?(:\d+)?(/[^[:space:]]*)?$"
+syn match dep3patchCommitID contained "commit:[[:alnum:]]\+"
+syn match dep3patchOriginCategory contained "\%(upstream\|backport\|vendor\|other\), "
+syn match dep3patchForwardedShort contained "\%(yes\|no\|not-needed\), "
+syn match dep3patchEmail "[_=[:alnum:]\.+-]\+@[[:alnum:]\./\-]\+"
+syn match dep3patchEmail "<.\{-}>"
+syn match dep3patchISODate "[[:digit:]]\{4}-[[:digit:]]\{2}-[[:digit:]]\{2}"
+
+" Associate our matches and regions with pretty colours
+hi def link dep3patchKey Keyword
+hi def link dep3patchOriginCategory Keyword
+hi def link dep3patchForwardedShort Keyword
+hi def link dep3patchMultiField Normal
+hi def link dep3patchHTTPUrl Identifier
+hi def link dep3patchCommitID Identifier
+hi def link dep3patchEmail Identifier
+hi def link dep3patchISODate Identifier
+
+let b:current_syntax = 'dep3patch'
+
+let &cpo = s:cpo_save
+unlet s:cpo_save
+
+" vim: ts=8 sw=2
diff --git a/runtime/syntax/dtd.vim b/runtime/syntax/dtd.vim
index ef0592e1d1..58f07c98dd 100644
--- a/runtime/syntax/dtd.vim
+++ b/runtime/syntax/dtd.vim
@@ -45,7 +45,7 @@ if !exists("dtd_no_tag_errors")
syn region dtdError contained start=+<!+lc=2 end=+>+
endif
-" if this is a html like comment hightlight also
+" if this is a html like comment highlight also
" the opening <! and the closing > as Comment.
syn region dtdComment start=+<![ \t]*--+ end=+-->+ contains=dtdTodo,@Spell
@@ -99,8 +99,8 @@ syn match dtdEntity "&[^; \t]*;" contains=dtdEntityPunct
syn match dtdEntityPunct contained "[&.;]"
" Strings are between quotes
-syn region dtdString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=dtdAttrDef,dtdAttrType,dtdEnum,dtdParamEntityInst,dtdEntity,dtdCard
-syn region dtdString start=+'+ skip=+\\\\\|\\'+ end=+'+ contains=dtdAttrDef,dtdAttrType,dtdEnum,dtdParamEntityInst,dtdEntity,dtdCard
+syn region dtdString start=+"+ skip=+\\\\\|\\"+ end=+"+ contains=dtdAttrDef,dtdAttrType,dtdParamEntityInst,dtdEntity,dtdCard
+syn region dtdString start=+'+ skip=+\\\\\|\\'+ end=+'+ contains=dtdAttrDef,dtdAttrType,dtdParamEntityInst,dtdEntity,dtdCard
" Enumeration of elements or data between parenthesis
"
diff --git a/runtime/syntax/git.vim b/runtime/syntax/git.vim
index a8467edd43..bf013ce195 100644
--- a/runtime/syntax/git.vim
+++ b/runtime/syntax/git.vim
@@ -1,7 +1,7 @@
" Vim syntax file
" Language: generic git output
" Maintainer: Tim Pope <vimNOSPAM@tpope.org>
-" Last Change: 2019 Dec 05
+" Last Change: 2022 Jan 05
if exists("b:current_syntax")
finish
@@ -12,12 +12,28 @@ syn sync minlines=50
syn include @gitDiff syntax/diff.vim
-syn region gitHead start=/\%^/ end=/^$/
-syn region gitHead start=/\%(^commit\%( \x\{40\}\)\{1,\}\%(\s*(.*)\)\=$\)\@=/ end=/^$/
-
-" For git reflog and git show ...^{tree}, avoid sync issues
-syn match gitHead /^\d\{6\} \%(\w\{4} \)\=\x\{40\}\%( [0-3]\)\=\t.*/
-syn match gitHead /^\x\{40\} \x\{40}\t.*/
+syn region gitHead start=/\%^\%(tag \|tree \|object \)\@=/ end=/^$/ contains=@NoSpell
+syn region gitHead start=/\%(^commit\%( \x\{4,\}\)\{1,\}\%(\s*(.*)\)\=$\)\@=/ end=/^$/ contains=@NoSpell
+" git log --oneline
+" minimize false positives by verifying contents of buffer
+if getline(1) =~# '^\x\{7,\} ' && getline('$') =~# '^\x\{7,\} '
+ syn match gitHashAbbrev /^\x\{7,\} \@=/ contains=@NoSpell
+elseif getline(1) =~# '^[|\/\\_ ]\{-\}\*[|\/\\_ ]\{-\} \x\{7,\} '
+ syn match gitHashAbbrev /^[|\/\\_ ]\{-\}\*[|\/\\_ ]\{-\} \zs\x\{7,\} \@=/ contains=@NoSpell
+endif
+" git log --graph
+syn region gitGraph start=/\%(^[|\/\\_ ]*\*[|\/\\_ ]\{-\} commit\%( \x\{4,\}\)\{1,\}\%(\s*(.*)\)\=$\)\@=/ end=/^\%([|\/\\_ ]*$\)\@=/ contains=@NoSpell
+" git blame --porcelain
+syn region gitHead start=/\%(^\x\{40,\} \d\+ \d\+\%( \d\+\)\=$\)\@=/ end=/^\t\@=/ contains=@NoSpell
+" git ls-tree
+syn match gitMode /^\d\{6\}\%( \%(blob\|tree\) \x\{4,\}\t\)\@=/ nextgroup=gitType skipwhite contains=@NoSpell
+" git ls-files --stage
+syn match gitMode /^\d\{6\}\%( \x\{4,\} [0-3]\t\)\@=/ nextgroup=gitHashStage skipwhite contains=@NoSpell
+" .git/HEAD, .git/refs/
+syn match gitKeyword /\%^ref: \@=/ nextgroup=gitReference skipwhite contains=@NoSpell
+syn match gitHash /\%^\x\{40,}\%$/ skipwhite contains=@NoSpell
+" .git/logs/
+syn match gitReflog /^\x\{40,\} \x\{40,\} .\{-\}\d\+\s-\d\{4\}\t.*/ skipwhite contains=@NoSpell,gitReflogOld
syn region gitDiff start=/^\%(diff --git \)\@=/ end=/^\%(diff --\|$\)\@=/ contains=@gitDiff fold
syn region gitDiff start=/^\%(@@ -\)\@=/ end=/^\%(diff --\%(git\|cc\|combined\) \|$\)\@=/ contains=@gitDiff
@@ -25,35 +41,47 @@ syn region gitDiff start=/^\%(@@ -\)\@=/ end=/^\%(diff --\%(git\|cc\|combined\)
syn region gitDiffMerge start=/^\%(diff --\%(cc\|combined\) \)\@=/ end=/^\%(diff --\|$\)\@=/ contains=@gitDiff
syn region gitDiffMerge start=/^\%(@@@@* -\)\@=/ end=/^\%(diff --\|$\)\@=/ contains=@gitDiff
syn match gitDiffAdded "^ \++.*" contained containedin=gitDiffMerge
-syn match gitDiffAdded "{+.*+}" contained containedin=gitDiff
+syn match gitDiffAdded "{+[^}]*+}" contained containedin=gitDiff
syn match gitDiffRemoved "^ \+-.*" contained containedin=gitDiffMerge
-syn match gitDiffRemoved "\[-.*-\]" contained containedin=gitDiff
+syn match gitDiffRemoved "\[-[^]]*-\]" contained containedin=gitDiff
+
+syn match gitKeyword /^commit \@=/ contained containedin=gitHead nextgroup=gitHashAbbrev skipwhite contains=@NoSpell
+syn match gitKeyword /^\%(object\|tree\|parent\|encoding\|gpgsig\%(-\w\+\)\=\|previous\) \@=/ contained containedin=gitHead nextgroup=gitHash skipwhite contains=@NoSpell
+syn match gitKeyword /^Merge:/ contained containedin=gitHead nextgroup=gitHashAbbrev skipwhite contains=@NoSpell
+syn match gitIdentityKeyword /^\%(author\|committer\|tagger\) \@=/ contained containedin=gitHead nextgroup=gitIdentity skipwhite contains=@NoSpell
+syn match gitIdentityHeader /^\%(Author\|Commit\|Tagger\):/ contained containedin=gitHead nextgroup=gitIdentity skipwhite contains=@NoSpell
+syn match gitDateHeader /^\%(AuthorDate\|CommitDate\|Date\):/ contained containedin=gitHead nextgroup=gitDate skipwhite contains=@NoSpell
-syn match gitKeyword /^\%(object\|type\|tag\|commit\|tree\|parent\|encoding\)\>/ contained containedin=gitHead nextgroup=gitHash,gitType skipwhite
-syn match gitKeyword /^\%(tag\>\|ref:\)/ contained containedin=gitHead nextgroup=gitReference skipwhite
-syn match gitKeyword /^Merge:/ contained containedin=gitHead nextgroup=gitHashAbbrev skipwhite
-syn match gitMode /^\d\{6\}\>/ contained containedin=gitHead nextgroup=gitType,gitHash skipwhite
-syn match gitIdentityKeyword /^\%(author\|committer\|tagger\)\>/ contained containedin=gitHead nextgroup=gitIdentity skipwhite
-syn match gitIdentityHeader /^\%(Author\|Commit\|Tagger\):/ contained containedin=gitHead nextgroup=gitIdentity skipwhite
-syn match gitDateHeader /^\%(AuthorDate\|CommitDate\|Date\):/ contained containedin=gitHead nextgroup=gitDate skipwhite
+syn match gitKeyword /^[*|\/\\_ ]\+\zscommit \@=/ contained containedin=gitGraph nextgroup=gitHashAbbrev skipwhite contains=@NoSpell
+syn match gitKeyword /^[|\/\\_ ]\+\zs\%(object\|tree\|parent\|encoding\|gpgsig\%(-\w\+\)\=\|previous\) \@=/ contained containedin=gitGraph nextgroup=gitHash skipwhite contains=@NoSpell
+syn match gitKeyword /^[|\/\\_ ]\+\zsMerge:/ contained containedin=gitGraph nextgroup=gitHashAbbrev skipwhite contains=@NoSpell
+syn match gitIdentityKeyword /^[|\/\\_ ]\+\zs\%(author\|committer\|tagger\) \@=/ contained containedin=gitGraph nextgroup=gitIdentity skipwhite contains=@NoSpell
+syn match gitIdentityHeader /^[|\/\\_ ]\+\zs\%(Author\|Commit\|Tagger\):/ contained containedin=gitGraph nextgroup=gitIdentity skipwhite contains=@NoSpell
+syn match gitDateHeader /^[|\/\\_ ]\+\zs\%(AuthorDate\|CommitDate\|Date\):/ contained containedin=gitGraph nextgroup=gitDate skipwhite contains=@NoSpell
-syn match gitReflogHeader /^Reflog:/ contained containedin=gitHead nextgroup=gitReflogMiddle skipwhite
-syn match gitReflogHeader /^Reflog message:/ contained containedin=gitHead skipwhite
-syn match gitReflogMiddle /\S\+@{\d\+} (/he=e-2 nextgroup=gitIdentity
+syn match gitKeyword /^type \@=/ contained containedin=gitHead nextgroup=gitType skipwhite contains=@NoSpell
+syn match gitKeyword /^\%(summary\|boundary\|filename\|\%(author\|committer\)-\%(time\|tz\)\) \@=/ contained containedin=gitHead skipwhite contains=@NoSpell
+syn match gitKeyword /^tag \@=/ contained containedin=gitHead nextgroup=gitReference skipwhite contains=@NoSpell
+syn match gitIdentityKeyword /^\%(author\|committer\)-mail \@=/ contained containedin=gitHead nextgroup=gitEmail skipwhite contains=@NoSpell
+syn match gitReflogHeader /^Reflog:/ contained containedin=gitHead nextgroup=gitReflogMiddle skipwhite contains=@NoSpell
+syn match gitReflogHeader /^Reflog message:/ contained containedin=gitHead skipwhite contains=@NoSpell
+syn match gitReflogMiddle /\S\+@{\d\+} (/he=e-2 nextgroup=gitIdentity contains=@NoSpell
-syn match gitDate /\<\u\l\l \u\l\l \d\=\d \d\d:\d\d:\d\d \d\d\d\d [+-]\d\d\d\d/ contained
-syn match gitDate /-\=\d\+ [+-]\d\d\d\d\>/ contained
-syn match gitDate /\<\d\+ \l\+ ago\>/ contained
-syn match gitType /\<\%(tag\|commit\|tree\|blob\)\>/ contained nextgroup=gitHash skipwhite
-syn match gitStage /\<\d\t\@=/ contained
-syn match gitReference /\S\+\S\@!/ contained
-syn match gitHash /\<\x\{40\}\>/ contained nextgroup=gitIdentity,gitStage,gitHash skipwhite
-syn match gitHash /^\<\x\{40\}\>/ containedin=gitHead contained nextgroup=gitHash skipwhite
-syn match gitHashAbbrev /\<\x\{4,40\}\>/ contained nextgroup=gitHashAbbrev skipwhite
-syn match gitHashAbbrev /\<\x\{4,39\}\.\.\./he=e-3 contained nextgroup=gitHashAbbrev skipwhite
+syn match gitIdentity /\S.\{-\} <[^>]*>/ contained nextgroup=gitDate skipwhite contains=@NoSpell
+syn region gitEmail matchgroup=gitEmailDelimiter start=/</ end=/>/ keepend oneline contained containedin=gitIdentity contains=@NoSpell
+syn match gitDate /\<\u\l\l \u\l\l \d\=\d \d\d:\d\d:\d\d \d\d\d\d [+-]\d\d\d\d/ contained contains=@NoSpell
+syn match gitDate /-\=\d\+ [+-]\d\d\d\d\>/ contained contains=@NoSpell
+syn match gitDate /\<\d\+ \l\+ ago\>/ contained contains=@NoSpell
+syn match gitType /\<\%(tag\|commit\|tree\|blob\)\>/ contained nextgroup=gitHashAbbrev skipwhite contains=@NoSpell
+syn match gitReference /\S\+\S\@!/ contained contains=@NoSpell
+syn match gitHash /\<\x\{40,\}\>/ contained nextgroup=gitIdentity,gitHash skipwhite contains=@NoSpell
+syn match gitReflogOld /^\x\{40,\} \@=/ contained nextgroup=gitReflogNew skipwhite contains=@NoSpell
+syn match gitReflogNew /\<\x\{40,\} \@=/ contained nextgroup=gitIdentity skipwhite contains=@NoSpell
+syn match gitHashAbbrev /\<\x\{4,\}\>/ contained nextgroup=gitHashAbbrev skipwhite contains=@NoSpell
+syn match gitHashAbbrev /\<\x\{4,39\}\.\.\./he=e-3 contained nextgroup=gitHashAbbrev skipwhite contains=@NoSpell
+syn match gitHashStage /\<\x\{4,\}\>/ contained nextgroup=gitStage skipwhite contains=@NoSpell
+syn match gitStage /\<\d\t\@=/ contained contains=@NoSpell
-syn match gitIdentity /\S.\{-\} <[^>]*>/ contained nextgroup=gitDate skipwhite
-syn region gitEmail matchgroup=gitEmailDelimiter start=/</ end=/>/ keepend oneline contained containedin=gitIdentity
syn match gitNotesHeader /^Notes:\ze\n /
@@ -68,7 +96,10 @@ hi def link gitEmailDelimiter Delimiter
hi def link gitEmail Special
hi def link gitDate Number
hi def link gitMode Number
+hi def link gitHashStage gitHash
hi def link gitHashAbbrev gitHash
+hi def link gitReflogOld gitHash
+hi def link gitReflogNew gitHash
hi def link gitHash Identifier
hi def link gitReflogMiddle gitReference
hi def link gitReference Function
diff --git a/runtime/syntax/gitcommit.vim b/runtime/syntax/gitcommit.vim
index 63b1ce920f..42c8d4414f 100644
--- a/runtime/syntax/gitcommit.vim
+++ b/runtime/syntax/gitcommit.vim
@@ -2,71 +2,87 @@
" Language: git commit file
" Maintainer: Tim Pope <vimNOSPAM@tpope.org>
" Filenames: *.git/COMMIT_EDITMSG
-" Last Change: 2019 Dec 05
+" Last Change: 2022 Jan 05
if exists("b:current_syntax")
finish
endif
+scriptencoding utf-8
+
syn case match
syn sync minlines=50
+syn sync linebreaks=1
if has("spell")
syn spell toplevel
endif
syn include @gitcommitDiff syntax/diff.vim
-syn region gitcommitDiff start=/\%(^diff --\%(git\|cc\|combined\) \)\@=/ end=/^\%(diff --\|$\|#\)\@=/ fold contains=@gitcommitDiff
+syn region gitcommitDiff start=/\%(^diff --\%(git\|cc\|combined\) \)\@=/ end=/^\%(diff --\|$\|@@\@!\|[^[:alnum:]\ +-]\S\@!\)\@=/ fold contains=@gitcommitDiff
syn match gitcommitSummary "^.*\%<51v." contained containedin=gitcommitFirstLine nextgroup=gitcommitOverflow contains=@Spell
syn match gitcommitOverflow ".*" contained contains=@Spell
-syn match gitcommitBlank "^[^#].*" contained contains=@Spell
+syn match gitcommitBlank "^.\+" contained contains=@Spell
+syn match gitcommitFirstLine "\%^.*" nextgroup=gitcommitBlank,gitcommitComment skipnl
+
+let s:scissors = 0
+let s:l = search('^[#;@!$%^&|:] -\{24,\} >8 -\{24,\}$', 'cnW', '', 100)
+if s:l == 0
+ let s:l = line('$')
+elseif getline(s:l)[0] !=# getline(s:l - 1)[0]
+ let s:scissors = 1
+endif
+let s:comment = escape((matchstr(getline(s:l), '^[#;@!$%^&|:]\S\@!') . '#')[0], '^$.*[]~\"/')
-if get(g:, "gitcommit_cleanup") is# "scissors"
- syn match gitcommitFirstLine "\%^.*" nextgroup=gitcommitBlank skipnl
- syn region gitcommitComment start=/^# -\+ >8 -\+$/ end=/\%$/ contains=gitcommitDiff
+if s:scissors
+ let s:comment .= ' -\{24,\} >8 -\{24,\}$'
+ exe 'syn region gitcommitComment start="^' . s:comment . '" end="\%$" contains=gitcommitDiff'
else
- syn match gitcommitFirstLine "\%^[^#].*" nextgroup=gitcommitBlank skipnl
- syn match gitcommitComment "^#.*"
+ exe 'syn match gitcommitComment "^' . s:comment . '.*"'
endif
+exe 'syn match gitcommitTrailers "\n\@<=\n\%([[:alnum:]-]\+\s*:.*\|(cherry picked from commit .*\)\%(\n\s.*\|\n[[:alnum:]-]\+\s*:.*\|\n(cherry picked from commit .*\)*\%(\n\n*\%(' . s:comment . '\)\|\n*\%$\)\@="'
-syn match gitcommitHead "^\%(# .*\n\)\+#$" contained transparent
-syn match gitcommitOnBranch "\%(^# \)\@<=On branch" contained containedin=gitcommitComment nextgroup=gitcommitBranch skipwhite
-syn match gitcommitOnBranch "\%(^# \)\@<=Your branch .\{-\} '" contained containedin=gitcommitComment nextgroup=gitcommitBranch skipwhite
+unlet s:l s:comment s:scissors
+
+syn match gitcommitTrailerToken "^[[:alnum:]-]\+\s*:" contained containedin=gitcommitTrailers
+
+syn match gitcommitHash "\<\x\{40,}\>" contains=@NoSpell display
+syn match gitcommitOnBranch "\%(^. \)\@<=On branch" contained containedin=gitcommitComment nextgroup=gitcommitBranch skipwhite
+syn match gitcommitOnBranch "\%(^. \)\@<=Your branch .\{-\} '" contained containedin=gitcommitComment nextgroup=gitcommitBranch skipwhite
syn match gitcommitBranch "[^ ']\+" contained
-syn match gitcommitNoBranch "\%(^# \)\@<=Not currently on any branch." contained containedin=gitcommitComment
-syn match gitcommitHeader "\%(^# \)\@<=.*:$" contained containedin=gitcommitComment
-syn region gitcommitAuthor matchgroup=gitCommitHeader start=/\%(^# \)\@<=\%(Author\|Committer\):/ end=/$/ keepend oneline contained containedin=gitcommitComment transparent
-syn match gitcommitNoChanges "\%(^# \)\@<=No changes$" contained containedin=gitcommitComment
+syn match gitcommitNoBranch "\%(^. \)\@<=Not currently on any branch." contained containedin=gitcommitComment
+syn match gitcommitHeader "\%(^. \)\@<=\S.*[::]\%(\n^$\)\@!$" contained containedin=gitcommitComment
+syn region gitcommitAuthor matchgroup=gitCommitHeader start=/\%(^. \)\@<=\%(Author\|Committer\|Date\):/ end=/$/ keepend oneline contained containedin=gitcommitComment transparent
+syn match gitcommitHeader "\%(^. \)\@<=commit\%( \x\{40,\}$\)\@=" contained containedin=gitcommitComment nextgroup=gitcommitHash skipwhite
+syn match gitcommitNoChanges "\%(^. \)\@<=No changes$" contained containedin=gitcommitComment
-syn region gitcommitUntracked start=/^# Untracked files:/ end=/^#$\|^#\@!/ contains=gitcommitHeader,gitcommitHead,gitcommitUntrackedFile fold
-syn match gitcommitUntrackedFile "\t\@<=.*" contained
+syn match gitcommitType "\%(^.\t\)\@<=[^[:punct:][:space:]][^/::]*[^[:punct:][:space:]][::]\ze "he=e-1 contained containedin=gitcommitComment nextgroup=gitcommitFile skipwhite
+syn match gitcommitFile ".\{-\}\%($\| -> \)\@=" contained nextgroup=gitcommitArrow
+syn match gitcommitArrow " -> " contained nextgroup=gitcommitFile
+syn match gitcommitUntrackedFile "\%(^.\t\)\@<=[^::/]*\%(/.*\)\=$" contained containedin=gitcommitComment
-syn region gitcommitDiscarded start=/^# Change\%(s not staged for commit\|d but not updated\):/ end=/^#$\|^#\@!/ contains=gitcommitHeader,gitcommitHead,gitcommitDiscardedType fold
-syn region gitcommitSelected start=/^# Changes to be committed:/ end=/^#$\|^#\@!/ contains=gitcommitHeader,gitcommitHead,gitcommitSelectedType fold
-syn region gitcommitUnmerged start=/^# Unmerged paths:/ end=/^#$\|^#\@!/ contains=gitcommitHeader,gitcommitHead,gitcommitUnmergedType fold
+syn region gitcommitUntracked start=/^\z(.\) Untracked files:$/ end=/^\z1\=$\|^\z1\@!/ contains=gitcommitHeader containedin=gitcommitComment containedin=gitcommitComment contained transparent fold
+syn region gitcommitDiscarded start=/^\z(.\) Change\%(s not staged for commit\|d but not updated\):$/ end=/^\z1\=$\|^\z1\@!/ contains=gitcommitHeader,gitcommitDiscardedType containedin=gitcommitComment containedin=gitcommitComment contained transparent fold
+syn region gitcommitSelected start=/^\z(.\) Changes to be committed:$/ end=/^\z1$\|^\z1\@!/ contains=gitcommitHeader,gitcommitSelectedType containedin=gitcommitComment containedin=gitcommitComment contained transparent fold
+syn region gitcommitUnmerged start=/^\z(.\) Unmerged paths:$/ end=/^\z1\=$\|^\z1\@!/ contains=gitcommitHeader,gitcommitUnmergedType containedin=gitcommitComment containedin=gitcommitComment contained transparent fold
+syn match gitcommitUntrackedFile "\%(^.\t\)\@<=.*" contained containedin=gitcommitUntracked
-syn match gitcommitDiscardedType "\t\@<=[[:lower:]][^:]*[[:lower:]]: "he=e-2 contained containedin=gitcommitComment nextgroup=gitcommitDiscardedFile skipwhite
-syn match gitcommitSelectedType "\t\@<=[[:lower:]][^:]*[[:lower:]]: "he=e-2 contained containedin=gitcommitComment nextgroup=gitcommitSelectedFile skipwhite
-syn match gitcommitUnmergedType "\t\@<=[[:lower:]][^:]*[[:lower:]]: "he=e-2 contained containedin=gitcommitComment nextgroup=gitcommitUnmergedFile skipwhite
-syn match gitcommitDiscardedFile ".\{-\}\%($\| -> \)\@=" contained nextgroup=gitcommitDiscardedArrow
-syn match gitcommitSelectedFile ".\{-\}\%($\| -> \)\@=" contained nextgroup=gitcommitSelectedArrow
-syn match gitcommitUnmergedFile ".\{-\}\%($\| -> \)\@=" contained nextgroup=gitcommitSelectedArrow
+syn match gitcommitDiscardedType "\%(^.\t\)\@<=[^[:punct:][:space:]][^/::]*[^[:punct:][:space:]][::]\ze "he=e-1 contained nextgroup=gitcommitDiscardedFile skipwhite
+syn match gitcommitSelectedType "\%(^.\t\)\@<=[^[:punct:][:space:]][^/::]*[^[:punct:][:space:]][::]\ze "he=e-1 contained nextgroup=gitcommitSelectedFile skipwhite
+syn match gitcommitUnmergedType "\%(^.\t\)\@<=[^[:punct:][:space:]][^/::]*[^[:punct:][:space:]][::]\ze "he=e-1 contained nextgroup=gitcommitUnmergedFile skipwhite
+syn match gitcommitDiscardedFile "\S.\{-\}\%($\| -> \)\@=" contained nextgroup=gitcommitDiscardedArrow
+syn match gitcommitSelectedFile "\S.\{-\}\%($\| -> \)\@=" contained nextgroup=gitcommitSelectedArrow
+syn match gitcommitUnmergedFile "\S.\{-\}\%($\| -> \)\@=" contained nextgroup=gitcommitUnmergedArrow
syn match gitcommitDiscardedArrow " -> " contained nextgroup=gitcommitDiscardedFile
syn match gitcommitSelectedArrow " -> " contained nextgroup=gitcommitSelectedFile
-syn match gitcommitUnmergedArrow " -> " contained nextgroup=gitcommitSelectedFile
-
-syn match gitcommitWarning "\%^[^#].*: needs merge$" nextgroup=gitcommitWarning skipnl
-syn match gitcommitWarning "^[^#].*: needs merge$" nextgroup=gitcommitWarning skipnl contained
-syn match gitcommitWarning "^\%(no changes added to commit\|nothing \%(added \)\=to commit\)\>.*\%$"
+syn match gitcommitUnmergedArrow " -> " contained nextgroup=gitcommitUnmergedFile
hi def link gitcommitSummary Keyword
+hi def link gitcommitTrailerToken Label
hi def link gitcommitComment Comment
-hi def link gitcommitUntracked gitcommitComment
-hi def link gitcommitDiscarded gitcommitComment
-hi def link gitcommitSelected gitcommitComment
-hi def link gitcommitUnmerged gitcommitComment
+hi def link gitcommitHash Identifier
hi def link gitcommitOnBranch Comment
hi def link gitcommitBranch Special
hi def link gitcommitNoBranch gitCommitBranch
diff --git a/runtime/syntax/gitrebase.vim b/runtime/syntax/gitrebase.vim
index bc6f34d1a7..13f157b005 100644
--- a/runtime/syntax/gitrebase.vim
+++ b/runtime/syntax/gitrebase.vim
@@ -2,7 +2,7 @@
" Language: git rebase --interactive
" Maintainer: Tim Pope <vimNOSPAM@tpope.org>
" Filenames: git-rebase-todo
-" Last Change: 2019 Dec 06
+" Last Change: 2022 Jan 05
if exists("b:current_syntax")
finish
@@ -10,8 +10,10 @@ endif
syn case match
-syn match gitrebaseHash "\v<\x{7,}>" contained
-syn match gitrebaseCommit "\v<\x{7,}>" nextgroup=gitrebaseSummary skipwhite
+let s:c = escape((matchstr(getline('$'), '^[#;@!$%^&|:]\S\@!') . '#')[0], '^$.*[]~\"/')
+
+syn match gitrebaseHash "\v<\x{7,}>" contained contains=@NoSpell
+syn match gitrebaseCommit "\v<\x{7,}>" nextgroup=gitrebaseSummary skipwhite contains=@NoSpell
syn match gitrebasePick "\v^p%(ick)=>" nextgroup=gitrebaseCommit skipwhite
syn match gitrebaseReword "\v^r%(eword)=>" nextgroup=gitrebaseCommit skipwhite
syn match gitrebaseEdit "\v^e%(dit)=>" nextgroup=gitrebaseCommit skipwhite
@@ -26,12 +28,15 @@ syn match gitrebaseLabel "\v^l(abel)=>" nextgroup=gitrebaseName skipwhite
syn match gitrebaseReset "\v^(t|reset)=>" nextgroup=gitrebaseName skipwhite
syn match gitrebaseSummary ".*" contains=gitrebaseHash contained
syn match gitrebaseCommand ".*" contained
-syn match gitrebaseComment "^\s*#.*" contains=gitrebaseHash
+exe 'syn match gitrebaseComment " \@<=' . s:c . ' empty$" containedin=gitrebaseSummary contained'
+exe 'syn match gitrebaseComment "^\s*' . s:c . '.*" contains=gitrebaseHash'
syn match gitrebaseSquashError "\v%^%(s%(quash)=>|f%(ixup)=>)" nextgroup=gitrebaseCommit skipwhite
syn match gitrebaseMergeOption "\v-[Cc]>" nextgroup=gitrebaseMergeCommit skipwhite contained
syn match gitrebaseMergeCommit "\v<\x{7,}>" nextgroup=gitrebaseName skipwhite contained
syn match gitrebaseName "\v[^[:space:].*?i:^~/-]\S+" nextgroup=gitrebaseMergeComment skipwhite contained
-syn match gitrebaseMergeComment "#" nextgroup=gitrebaseSummary skipwhite contained
+exe 'syn match gitrebaseMergeComment "' . s:c . '" nextgroup=gitrebaseSummary skipwhite contained'
+
+unlet s:c
hi def link gitrebaseCommit gitrebaseHash
hi def link gitrebaseHash Identifier
diff --git a/runtime/syntax/i3config.vim b/runtime/syntax/i3config.vim
new file mode 100644
index 0000000000..a2f50e50b8
--- /dev/null
+++ b/runtime/syntax/i3config.vim
@@ -0,0 +1,257 @@
+" Vim syntax file
+" Language: i3 config file
+" Original Author: Mohamed Boughaba <mohamed dot bgb at gmail dot com>
+" Maintainer: Quentin Hibon (github user hiqua)
+" Version: 0.4
+" Last Change: 2022 Jan 15
+
+" References:
+" http://i3wm.org/docs/userguide.html#configuring
+" http://vimdoc.sourceforge.net/htmldoc/syntax.html
+"
+"
+" Quit when a syntax file was already loaded
+if exists("b:current_syntax")
+ finish
+endif
+
+scriptencoding utf-8
+
+" Error
+syn match i3ConfigError /.*/
+
+" Todo
+syn keyword i3ConfigTodo TODO FIXME XXX contained
+
+" Comment
+" Comments are started with a # and can only be used at the beginning of a line
+syn match i3ConfigComment /^\s*#.*$/ contains=i3ConfigTodo
+
+" Font
+" A FreeType font description is composed by:
+" a font family, a style, a weight, a variant, a stretch and a size.
+syn match i3ConfigFontSeparator /,/ contained
+syn match i3ConfigFontSeparator /:/ contained
+syn keyword i3ConfigFontKeyword font contained
+syn match i3ConfigFontNamespace /\w\+:/ contained contains=i3ConfigFontSeparator
+syn match i3ConfigFontContent /-\?\w\+\(-\+\|\s\+\|,\)/ contained contains=i3ConfigFontNamespace,i3ConfigFontSeparator,i3ConfigFontKeyword
+syn match i3ConfigFontSize /\s\=\d\+\(px\)\?\s\?$/ contained
+syn match i3ConfigFont /^\s*font\s\+.*$/ contains=i3ConfigFontContent,i3ConfigFontSeparator,i3ConfigFontSize,i3ConfigFontNamespace
+syn match i3ConfigFont /^\s*font\s\+.*\(\\\_.*\)\?$/ contains=i3ConfigFontContent,i3ConfigFontSeparator,i3ConfigFontSize,i3ConfigFontNamespace
+syn match i3ConfigFont /^\s*font\s\+.*\(\\\_.*\)\?[^\\]\+$/ contains=i3ConfigFontContent,i3ConfigFontSeparator,i3ConfigFontSize,i3ConfigFontNamespace
+syn match i3ConfigFont /^\s*font\s\+\(\(.*\\\_.*\)\|\(.*[^\\]\+$\)\)/ contains=i3ConfigFontContent,i3ConfigFontSeparator,i3ConfigFontSize,i3ConfigFontNamespace
+
+" variables
+syn match i3ConfigString /\(['"]\)\(.\{-}\)\1/ contained
+syn match i3ConfigColor /#\w\{6}/ contained
+syn match i3ConfigVariableModifier /+/ contained
+syn match i3ConfigVariableAndModifier /+\w\+/ contained contains=i3ConfigVariableModifier
+syn match i3ConfigVariable /\$\w\+\(\(-\w\+\)\+\)\?\(\s\|+\)\?/ contains=i3ConfigVariableModifier,i3ConfigVariableAndModifier
+syn keyword i3ConfigInitializeKeyword set contained
+syn match i3ConfigInitialize /^\s*set\s\+.*$/ contains=i3ConfigVariable,i3ConfigInitializeKeyword,i3ConfigColor,i3ConfigString
+
+" Gaps
+syn keyword i3ConfigGapStyleKeyword inner outer horizontal vertical top right bottom left current all set plus minus toggle up down contained
+syn match i3ConfigGapStyle /^\s*\(gaps\)\s\+\(inner\|outer\|horizontal\|vertical\|left\|top\|right\|bottom\)\(\s\+\(current\|all\)\)\?\(\s\+\(set\|plus\|minus\|toggle\)\)\?\(\s\+\(-\?\d\+\|\$.*\)\)$/ contains=i3ConfigGapStyleKeyword,i3ConfigNumber,i3ConfigVariable
+syn keyword i3ConfigSmartGapKeyword on inverse_outer contained
+syn match i3ConfigSmartGap /^\s*smart_gaps\s\+\(on\|inverse_outer\)\s\?$/ contains=i3ConfigSmartGapKeyword
+syn keyword i3ConfigSmartBorderKeyword on no_gaps contained
+syn match i3ConfigSmartBorder /^\s*smart_borders\s\+\(on\|no_gaps\)\s\?$/ contains=i3ConfigSmartBorderKeyword
+
+" Keyboard bindings
+syn keyword i3ConfigAction toggle fullscreen restart key import kill shrink grow contained
+syn keyword i3ConfigAction focus move grow height width split layout resize restore reload mute unmute exit mode workspace container to contained
+syn match i3ConfigModifier /\w\++\w\+\(\(+\w\+\)\+\)\?/ contained contains=i3ConfigVariableModifier
+syn match i3ConfigNumber /\s\d\+/ contained
+syn match i3ConfigUnit /\sp\(pt\|x\)/ contained
+syn match i3ConfigUnitOr /\sor/ contained
+syn keyword i3ConfigBindKeyword bindsym bindcode exec gaps border contained
+syn match i3ConfigBindArgument /--\w\+\(\(-\w\+\)\+\)\?\s/ contained
+syn match i3ConfigBind /^\s*\(bindsym\|bindcode\)\s\+.*$/ contains=i3ConfigVariable,i3ConfigBindKeyword,i3ConfigVariableAndModifier,i3ConfigNumber,i3ConfigUnit,i3ConfigUnitOr,i3ConfigBindArgument,i3ConfigModifier,i3ConfigAction,i3ConfigString,i3ConfigGapStyleKeyword,i3ConfigBorderStyleKeyword
+
+" Floating
+syn keyword i3ConfigSizeSpecial x contained
+syn match i3ConfigNegativeSize /-/ contained
+syn match i3ConfigSize /-\?\d\+\s\?x\s\?-\?\d\+/ contained contains=i3ConfigSizeSpecial,i3ConfigNumber,i3ConfigNegativeSize
+syn match i3ConfigFloating /^\s*floating_modifier\s\+\$\w\+\d\?/ contains=i3ConfigVariable
+syn match i3ConfigFloating /^\s*floating_\(maximum\|minimum\)_size\s\+-\?\d\+\s\?x\s\?-\?\d\+/ contains=i3ConfigSize
+
+" Orientation
+syn keyword i3ConfigOrientationKeyword vertical horizontal auto contained
+syn match i3ConfigOrientation /^\s*default_orientation\s\+\(vertical\|horizontal\|auto\)\s\?$/ contains=i3ConfigOrientationKeyword
+
+" Layout
+syn keyword i3ConfigLayoutKeyword default stacking tabbed contained
+syn match i3ConfigLayout /^\s*workspace_layout\s\+\(default\|stacking\|tabbed\)\s\?$/ contains=i3ConfigLayoutKeyword
+
+" Border style
+syn keyword i3ConfigBorderStyleKeyword none normal pixel contained
+syn match i3ConfigBorderStyle /^\s*\(new_window\|new_float\|default_border\|default_floating_border\)\s\+\(none\|\(normal\|pixel\)\(\s\+\d\+\)\?\(\s\+\$\w\+\(\(-\w\+\)\+\)\?\(\s\|+\)\?\)\?\)\s\?$/ contains=i3ConfigBorderStyleKeyword,i3ConfigNumber,i3ConfigVariable
+
+" Hide borders and edges
+syn keyword i3ConfigEdgeKeyword none vertical horizontal both smart smart_no_gaps contained
+syn match i3ConfigEdge /^\s*hide_edge_borders\s\+\(none\|vertical\|horizontal\|both\|smart\|smart_no_gaps\)\s\?$/ contains=i3ConfigEdgeKeyword
+
+" Arbitrary commands for specific windows (for_window)
+syn keyword i3ConfigCommandKeyword for_window contained
+syn region i3ConfigWindowStringSpecial start=+"+ skip=+\\"+ end=+"+ contained contains=i3ConfigString
+syn region i3ConfigWindowCommandSpecial start="\[" end="\]" contained contains=i3ConfigWindowStringSpacial,i3ConfigString
+syn match i3ConfigArbitraryCommand /^\s*for_window\s\+.*$/ contains=i3ConfigWindowCommandSpecial,i3ConfigCommandKeyword,i3ConfigBorderStyleKeyword,i3ConfigLayoutKeyword,i3ConfigOrientationKeyword,Size,i3ConfigNumber
+
+" Disable focus open opening
+syn keyword i3ConfigNoFocusKeyword no_focus contained
+syn match i3ConfigDisableFocus /^\s*no_focus\s\+.*$/ contains=i3ConfigWindowCommandSpecial,i3ConfigNoFocusKeyword
+
+" Move client to specific workspace automatically
+syn keyword i3ConfigAssignKeyword assign contained
+syn match i3ConfigAssignSpecial /→/ contained
+syn match i3ConfigAssign /^\s*assign\s\+.*$/ contains=i3ConfigAssignKeyword,i3ConfigWindowCommandSpecial,i3ConfigAssignSpecial
+
+" X resources
+syn keyword i3ConfigResourceKeyword set_from_resource contained
+syn match i3ConfigResource /^\s*set_from_resource\s\+.*$/ contains=i3ConfigResourceKeyword,i3ConfigWindowCommandSpecial,i3ConfigColor,i3ConfigVariable
+
+" Auto start applications
+syn keyword i3ConfigExecKeyword exec exec_always contained
+syn match i3ConfigNoStartupId /--no-startup-id/ contained " We are not using i3ConfigBindArgument as only no-startup-id is supported here
+syn match i3ConfigExec /^\s*exec\(_always\)\?\s\+.*$/ contains=i3ConfigExecKeyword,i3ConfigNoStartupId,i3ConfigString
+
+" Automatically putting workspaces on specific screens
+syn keyword i3ConfigWorkspaceKeyword workspace contained
+syn keyword i3ConfigOutput output contained
+syn match i3ConfigWorkspace /^\s*workspace\s\+.*$/ contains=i3ConfigWorkspaceKeyword,i3ConfigNumber,i3ConfigString,i3ConfigOutput
+
+" Changing colors
+syn keyword i3ConfigClientColorKeyword client focused focused_inactive unfocused urgent placeholder background contained
+syn match i3ConfigClientColor /^\s*client.\w\+\s\+.*$/ contains=i3ConfigClientColorKeyword,i3ConfigColor,i3ConfigVariable
+
+syn keyword i3ConfigTitleAlignKeyword left center right contained
+syn match i3ConfigTitleAlign /^\s*title_align\s\+.*$/ contains=i3ConfigTitleAlignKeyword
+
+" Interprocess communication
+syn match i3ConfigInterprocessKeyword /ipc-socket/ contained
+syn match i3ConfigInterprocess /^\s*ipc-socket\s\+.*$/ contains=i3ConfigInterprocessKeyword
+
+" Mouse warping
+syn keyword i3ConfigMouseWarpingKeyword mouse_warping contained
+syn keyword i3ConfigMouseWarpingType output none contained
+syn match i3ConfigMouseWarping /^\s*mouse_warping\s\+\(output\|none\)\s\?$/ contains=i3ConfigMouseWarpingKeyword,i3ConfigMouseWarpingType
+
+" Focus follows mouse
+syn keyword i3ConfigFocusFollowsMouseKeyword focus_follows_mouse contained
+syn keyword i3ConfigFocusFollowsMouseType yes no contained
+syn match i3ConfigFocusFollowsMouse /^\s*focus_follows_mouse\s\+\(yes\|no\)\s\?$/ contains=i3ConfigFocusFollowsMouseKeyword,i3ConfigFocusFollowsMouseType
+
+" Popups during fullscreen mode
+syn keyword i3ConfigPopupOnFullscreenKeyword popup_during_fullscreen contained
+syn keyword i3ConfigPopuponFullscreenType smart ignore leave_fullscreen contained
+syn match i3ConfigPopupOnFullscreen /^\s*popup_during_fullscreen\s\+\w\+\s\?$/ contains=i3ConfigPopupOnFullscreenKeyword,i3ConfigPopupOnFullscreenType
+
+" Focus wrapping
+syn keyword i3ConfigFocusWrappingKeyword force_focus_wrapping focus_wrapping contained
+syn keyword i3ConfigFocusWrappingType yes no contained
+syn match i3ConfigFocusWrapping /^\s*\(force_\)\?focus_wrapping\s\+\(yes\|no\)\s\?$/ contains=i3ConfigFocusWrappingType,i3ConfigFocusWrappingKeyword
+
+" Forcing Xinerama
+syn keyword i3ConfigForceXineramaKeyword force_xinerama contained
+syn match i3ConfigForceXinerama /^\s*force_xinerama\s\+\(yes\|no\)\s\?$/ contains=i3ConfigFocusWrappingType,i3ConfigForceXineramaKeyword
+
+" Automatic back-and-forth when switching to the current workspace
+syn keyword i3ConfigAutomaticSwitchKeyword workspace_auto_back_and_forth contained
+syn match i3ConfigAutomaticSwitch /^\s*workspace_auto_back_and_forth\s\+\(yes\|no\)\s\?$/ contains=i3ConfigFocusWrappingType,i3ConfigAutomaticSwitchKeyword
+
+" Delay urgency hint
+syn keyword i3ConfigTimeUnit ms contained
+syn keyword i3ConfigDelayUrgencyKeyword force_display_urgency_hint contained
+syn match i3ConfigDelayUrgency /^\s*force_display_urgency_hint\s\+\d\+\s\+ms\s\?$/ contains=i3ConfigFocusWrappingType,i3ConfigDelayUrgencyKeyword,i3ConfigNumber,i3ConfigTimeUnit
+
+" Focus on window activation
+syn keyword i3ConfigFocusOnActivationKeyword focus_on_window_activation contained
+syn keyword i3ConfigFocusOnActivationType smart urgent focus none contained
+syn match i3ConfigFocusOnActivation /^\s*focus_on_window_activation\s\+\(smart\|urgent\|focus\|none\)\s\?$/ contains=i3ConfigFocusOnActivationKeyword,i3ConfigFocusOnActivationType
+
+" Automatic back-and-forth when switching to the current workspace
+syn keyword i3ConfigDrawingMarksKeyword show_marks contained
+syn match i3ConfigDrawingMarks /^\s*show_marks\s\+\(yes\|no\)\s\?$/ contains=i3ConfigFocusWrappingType,i3ConfigDrawingMarksKeyword
+
+" Group mode/bar
+syn keyword i3ConfigBlockKeyword mode bar colors i3bar_command status_command position exec mode hidden_state modifier id position output background statusline tray_output tray_padding separator separator_symbol workspace_min_width workspace_buttons strip_workspace_numbers binding_mode_indicator focused_workspace active_workspace inactive_workspace urgent_workspace binding_mode contained
+syn region i3ConfigBlock start=+.*s\?{$+ end=+^}$+ contains=i3ConfigBlockKeyword,i3ConfigString,i3ConfigBind,i3ConfigComment,i3ConfigFont,i3ConfigFocusWrappingType,i3ConfigColor,i3ConfigVariable transparent keepend extend
+
+" Line continuation
+syn region i3ConfigLineCont start=/^.*\\$/ end=/^.*$/ contains=i3ConfigBlockKeyword,i3ConfigString,i3ConfigBind,i3ConfigComment,i3ConfigFont,i3ConfigFocusWrappingType,i3ConfigColor,i3ConfigVariable transparent keepend extend
+
+" Define the highlighting.
+hi def link i3ConfigError Error
+hi def link i3ConfigTodo Todo
+hi def link i3ConfigComment Comment
+hi def link i3ConfigFontContent Type
+hi def link i3ConfigFocusOnActivationType Type
+hi def link i3ConfigPopupOnFullscreenType Type
+hi def link i3ConfigOrientationKeyword Type
+hi def link i3ConfigMouseWarpingType Type
+hi def link i3ConfigFocusFollowsMouseType Type
+hi def link i3ConfigGapStyleKeyword Type
+hi def link i3ConfigTitleAlignKeyword Type
+hi def link i3ConfigSmartGapKeyword Type
+hi def link i3ConfigSmartBorderKeyword Type
+hi def link i3ConfigLayoutKeyword Type
+hi def link i3ConfigBorderStyleKeyword Type
+hi def link i3ConfigEdgeKeyword Type
+hi def link i3ConfigAction Type
+hi def link i3ConfigCommand Type
+hi def link i3ConfigOutput Type
+hi def link i3ConfigWindowCommandSpecial Type
+hi def link i3ConfigFocusWrappingType Type
+hi def link i3ConfigUnitOr Type
+hi def link i3ConfigFontSize Constant
+hi def link i3ConfigColor Constant
+hi def link i3ConfigNumber Constant
+hi def link i3ConfigUnit Constant
+hi def link i3ConfigVariableAndModifier Constant
+hi def link i3ConfigTimeUnit Constant
+hi def link i3ConfigModifier Constant
+hi def link i3ConfigString Constant
+hi def link i3ConfigNegativeSize Constant
+hi def link i3ConfigFontSeparator Special
+hi def link i3ConfigVariableModifier Special
+hi def link i3ConfigSizeSpecial Special
+hi def link i3ConfigWindowSpecial Special
+hi def link i3ConfigAssignSpecial Special
+hi def link i3ConfigFontNamespace PreProc
+hi def link i3ConfigBindArgument PreProc
+hi def link i3ConfigNoStartupId PreProc
+hi def link i3ConfigFontKeyword Identifier
+hi def link i3ConfigBindKeyword Identifier
+hi def link i3ConfigOrientation Identifier
+hi def link i3ConfigGapStyle Identifier
+hi def link i3ConfigTitleAlign Identifier
+hi def link i3ConfigSmartGap Identifier
+hi def link i3ConfigSmartBorder Identifier
+hi def link i3ConfigLayout Identifier
+hi def link i3ConfigBorderStyle Identifier
+hi def link i3ConfigEdge Identifier
+hi def link i3ConfigFloating Identifier
+hi def link i3ConfigCommandKeyword Identifier
+hi def link i3ConfigNoFocusKeyword Identifier
+hi def link i3ConfigInitializeKeyword Identifier
+hi def link i3ConfigAssignKeyword Identifier
+hi def link i3ConfigResourceKeyword Identifier
+hi def link i3ConfigExecKeyword Identifier
+hi def link i3ConfigWorkspaceKeyword Identifier
+hi def link i3ConfigClientColorKeyword Identifier
+hi def link i3ConfigInterprocessKeyword Identifier
+hi def link i3ConfigMouseWarpingKeyword Identifier
+hi def link i3ConfigFocusFollowsMouseKeyword Identifier
+hi def link i3ConfigPopupOnFullscreenKeyword Identifier
+hi def link i3ConfigFocusWrappingKeyword Identifier
+hi def link i3ConfigForceXineramaKeyword Identifier
+hi def link i3ConfigAutomaticSwitchKeyword Identifier
+hi def link i3ConfigDelayUrgencyKeyword Identifier
+hi def link i3ConfigFocusOnActivationKeyword Identifier
+hi def link i3ConfigDrawingMarksKeyword Identifier
+hi def link i3ConfigBlockKeyword Identifier
+hi def link i3ConfigVariable Statement
+hi def link i3ConfigArbitraryCommand Type
+
+let b:current_syntax = "i3config"
diff --git a/runtime/syntax/python.vim b/runtime/syntax/python.vim
index 3427aa06c8..2293163a5b 100644
--- a/runtime/syntax/python.vim
+++ b/runtime/syntax/python.vim
@@ -1,7 +1,7 @@
" Vim syntax file
" Language: Python
" Maintainer: Zvezdan Petkovic <zpetkovic@acm.org>
-" Last Change: 2021 Feb 15
+" Last Change: 2021 Dec 10
" Credits: Neil Schemenauer <nas@python.ca>
" Dmitry Vasiliev
"
@@ -77,13 +77,14 @@ endif
"
" The list can be checked using:
"
-" python3 -c 'import keyword, pprint; pprint.pprint(keyword.kwlist, compact=True)'
+" python3 -c 'import keyword, pprint; pprint.pprint(keyword.kwlist + keyword.softkwlist, compact=True)'
"
syn keyword pythonStatement False None True
syn keyword pythonStatement as assert break continue del global
syn keyword pythonStatement lambda nonlocal pass return with yield
syn keyword pythonStatement class def nextgroup=pythonFunction skipwhite
syn keyword pythonConditional elif else if
+syn keyword pythonConditional case match
syn keyword pythonRepeat for while
syn keyword pythonOperator and in is not or
syn keyword pythonException except finally raise try
diff --git a/runtime/syntax/rc.vim b/runtime/syntax/rc.vim
index 4c6856bc83..d69edd00fd 100644
--- a/runtime/syntax/rc.vim
+++ b/runtime/syntax/rc.vim
@@ -1,7 +1,7 @@
" Vim syntax file
" Language: M$ Resource files (*.rc)
" Maintainer: Christian Brabandt
-" Last Change: 2015-05-29
+" Last Change: 20220116
" Repository: https://github.com/chrisbra/vim-rc-syntax
" License: Vim (see :h license)
" Previous Maintainer: Heiko Erhardt <Heiko.Erhardt@munich.netsurf.de>
@@ -173,16 +173,17 @@ hi def link rcAttribute rcCommonAttribute
hi def link rcStdId rcStatement
hi def link rcStatement Statement
-" Default color overrides
-hi def rcLanguage term=reverse ctermbg=Red ctermfg=Yellow guibg=Red guifg=Yellow
-hi def rcMainObject term=underline ctermfg=Blue guifg=Blue
-hi def rcSubObject ctermfg=Green guifg=Green
-hi def rcCaptionParam term=underline ctermfg=DarkGreen guifg=Green
-hi def rcParam ctermfg=DarkGreen guifg=DarkGreen
-hi def rcStatement ctermfg=DarkGreen guifg=DarkGreen
-hi def rcCommonAttribute ctermfg=Brown guifg=Brown
+hi def link rcLanguage Constant
+hi def link rcCaptionParam Constant
+hi def link rcCommonAttribute Constant
+
+hi def link rcMainObject Identifier
+hi def link rcSubObject Define
+hi def link rcParam Constant
+hi def link rcStatement Statement
+"
+"hi def link rcIdentifier Identifier
-"hi def link rcIdentifier Identifier
let b:current_syntax = "rc"
diff --git a/runtime/syntax/scala.vim b/runtime/syntax/scala.vim
index 16e114778d..c08e60e55a 100644
--- a/runtime/syntax/scala.vim
+++ b/runtime/syntax/scala.vim
@@ -3,7 +3,7 @@
" Maintainer: Derek Wyatt
" URL: https://github.com/derekwyatt/vim-scala
" License: Same as Vim
-" Last Change: 23 August 2021
+" Last Change: 23 January 2022
" ----------------------------------------------------------------------------
if !exists('main_syntax')
@@ -43,55 +43,55 @@ syn keyword scalaKeyword class trait object extends with nextgroup=scalaInstance
syn keyword scalaKeyword case nextgroup=scalaKeyword,scalaCaseFollowing skipwhite
syn keyword scalaKeyword val nextgroup=scalaNameDefinition,scalaQuasiQuotes skipwhite
syn keyword scalaKeyword def var nextgroup=scalaNameDefinition skipwhite
-hi link scalaKeyword Keyword
+hi def link scalaKeyword Keyword
exe 'syn region scalaBlock start=/{/ end=/}/ contains=' . s:ContainedGroup() . ' fold'
syn keyword scalaAkkaSpecialWord when goto using startWith initialize onTransition stay become unbecome
-hi link scalaAkkaSpecialWord PreProc
+hi def link scalaAkkaSpecialWord PreProc
syn keyword scalatestSpecialWord shouldBe
syn match scalatestShouldDSLA /^\s\+\zsit should/
syn match scalatestShouldDSLB /\<should\>/
-hi link scalatestSpecialWord PreProc
-hi link scalatestShouldDSLA PreProc
-hi link scalatestShouldDSLB PreProc
+hi def link scalatestSpecialWord PreProc
+hi def link scalatestShouldDSLA PreProc
+hi def link scalatestShouldDSLB PreProc
syn match scalaSymbol /'[_A-Za-z0-9$]\+/
-hi link scalaSymbol Number
+hi def link scalaSymbol Number
syn match scalaChar /'.'/
syn match scalaChar /'\\[\\"'ntbrf]'/ contains=scalaEscapedChar
syn match scalaChar /'\\u[A-Fa-f0-9]\{4}'/ contains=scalaUnicodeChar
syn match scalaEscapedChar /\\[\\"'ntbrf]/
syn match scalaUnicodeChar /\\u[A-Fa-f0-9]\{4}/
-hi link scalaChar Character
-hi link scalaEscapedChar Special
-hi link scalaUnicodeChar Special
+hi def link scalaChar Character
+hi def link scalaEscapedChar Special
+hi def link scalaUnicodeChar Special
syn match scalaOperator "||"
syn match scalaOperator "&&"
syn match scalaOperator "|"
syn match scalaOperator "&"
-hi link scalaOperator Special
+hi def link scalaOperator Special
syn match scalaNameDefinition /\<[_A-Za-z0-9$]\+\>/ contained nextgroup=scalaPostNameDefinition,scalaVariableDeclarationList
syn match scalaNameDefinition /`[^`]\+`/ contained nextgroup=scalaPostNameDefinition
syn match scalaVariableDeclarationList /\s*,\s*/ contained nextgroup=scalaNameDefinition
syn match scalaPostNameDefinition /\_s*:\_s*/ contained nextgroup=scalaTypeDeclaration
-hi link scalaNameDefinition Function
+hi def link scalaNameDefinition Function
syn match scalaInstanceDeclaration /\<[_\.A-Za-z0-9$]\+\>/ contained nextgroup=scalaInstanceHash
syn match scalaInstanceDeclaration /`[^`]\+`/ contained
syn match scalaInstanceHash /#/ contained nextgroup=scalaInstanceDeclaration
-hi link scalaInstanceDeclaration Special
-hi link scalaInstanceHash Type
+hi def link scalaInstanceDeclaration Special
+hi def link scalaInstanceHash Type
syn match scalaUnimplemented /???/
-hi link scalaUnimplemented ERROR
+hi def link scalaUnimplemented ERROR
syn match scalaCapitalWord /\<[A-Z][A-Za-z0-9$]*\>/
-hi link scalaCapitalWord Special
+hi def link scalaCapitalWord Special
" Handle type declarations specially
syn region scalaTypeStatement matchgroup=Keyword start=/\<type\_s\+\ze/ end=/$/ contains=scalaTypeTypeDeclaration,scalaSquareBrackets,scalaTypeTypeEquals,scalaTypeStatement
@@ -105,18 +105,18 @@ syn match scalaTypeTypeEquals /=\ze[^>]/ contained nextgroup=scalaTypeTypePostDe
syn match scalaTypeTypeExtension /)\?\_s*\zs\%(⇒\|=>\|<:\|:>\|=:=\|::\|#\)/ contained contains=scalaTypeOperator nextgroup=scalaTypeTypeDeclaration skipwhite
syn match scalaTypeTypePostDeclaration /\<[_\.A-Za-z0-9$]\+\>/ contained nextgroup=scalaTypeTypePostExtension skipwhite
syn match scalaTypeTypePostExtension /\%(⇒\|=>\|<:\|:>\|=:=\|::\)/ contained contains=scalaTypeOperator nextgroup=scalaTypeTypePostDeclaration skipwhite
-hi link scalaTypeTypeDeclaration Type
-hi link scalaTypeTypeExtension Keyword
-hi link scalaTypeTypePostDeclaration Special
-hi link scalaTypeTypePostExtension Keyword
+hi def link scalaTypeTypeDeclaration Type
+hi def link scalaTypeTypeExtension Keyword
+hi def link scalaTypeTypePostDeclaration Special
+hi def link scalaTypeTypePostExtension Keyword
syn match scalaTypeDeclaration /(/ contained nextgroup=scalaTypeExtension contains=scalaRoundBrackets skipwhite
syn match scalaTypeDeclaration /\%(⇒\|=>\)\ze/ contained nextgroup=scalaTypeDeclaration contains=scalaTypeExtension skipwhite
syn match scalaTypeDeclaration /\<[_\.A-Za-z0-9$]\+\>/ contained nextgroup=scalaTypeExtension skipwhite
syn match scalaTypeExtension /)\?\_s*\zs\%(⇒\|=>\|<:\|:>\|=:=\|::\|#\)/ contained contains=scalaTypeOperator nextgroup=scalaTypeDeclaration skipwhite
-hi link scalaTypeDeclaration Type
-hi link scalaTypeExtension Keyword
-hi link scalaTypePostExtension Keyword
+hi def link scalaTypeDeclaration Type
+hi def link scalaTypeExtension Keyword
+hi def link scalaTypePostExtension Keyword
syn match scalaTypeAnnotation /\%([_a-zA-Z0-9$\s]:\_s*\)\ze[_=(\.A-Za-z0-9$]\+/ skipwhite nextgroup=scalaTypeDeclaration contains=scalaRoundBrackets
syn match scalaTypeAnnotation /)\_s*:\_s*\ze[_=(\.A-Za-z0-9$]\+/ skipwhite nextgroup=scalaTypeDeclaration
@@ -124,51 +124,51 @@ hi clear scalaTypeAnnotation
syn match scalaCaseFollowing /\<[_\.A-Za-z0-9$]\+\>/ contained contains=scalaCapitalWord
syn match scalaCaseFollowing /`[^`]\+`/ contained contains=scalaCapitalWord
-hi link scalaCaseFollowing Special
+hi def link scalaCaseFollowing Special
syn keyword scalaKeywordModifier abstract override final lazy implicit private protected sealed null super
syn keyword scalaSpecialFunction implicitly require
-hi link scalaKeywordModifier Function
-hi link scalaSpecialFunction Function
+hi def link scalaKeywordModifier Function
+hi def link scalaSpecialFunction Function
syn keyword scalaSpecial this true false ne eq
syn keyword scalaSpecial new nextgroup=scalaInstanceDeclaration skipwhite
syn match scalaSpecial "\%(=>\|⇒\|<-\|←\|->\|→\)"
syn match scalaSpecial /`[^`]\+`/ " Backtick literals
-hi link scalaSpecial PreProc
+hi def link scalaSpecial PreProc
syn keyword scalaExternal package import
-hi link scalaExternal Include
+hi def link scalaExternal Include
syn match scalaStringEmbeddedQuote /\\"/ contained
syn region scalaString start=/"/ end=/"/ contains=scalaStringEmbeddedQuote,scalaEscapedChar,scalaUnicodeChar
-hi link scalaString String
-hi link scalaStringEmbeddedQuote String
+hi def link scalaString String
+hi def link scalaStringEmbeddedQuote String
syn region scalaIString matchgroup=scalaInterpolationBrackets start=/\<[a-zA-Z][a-zA-Z0-9_]*"/ skip=/\\"/ end=/"/ contains=scalaInterpolation,scalaInterpolationB,scalaEscapedChar,scalaUnicodeChar
syn region scalaTripleIString matchgroup=scalaInterpolationBrackets start=/\<[a-zA-Z][a-zA-Z0-9_]*"""/ end=/"""\ze\%([^"]\|$\)/ contains=scalaInterpolation,scalaInterpolationB,scalaEscapedChar,scalaUnicodeChar
-hi link scalaIString String
-hi link scalaTripleIString String
+hi def link scalaIString String
+hi def link scalaTripleIString String
syn match scalaInterpolation /\$[a-zA-Z0-9_$]\+/ contained
exe 'syn region scalaInterpolationB matchgroup=scalaInterpolationBoundary start=/\${/ end=/}/ contained contains=' . s:ContainedGroup()
-hi link scalaInterpolation Function
+hi def link scalaInterpolation Function
hi clear scalaInterpolationB
syn region scalaFString matchgroup=scalaInterpolationBrackets start=/f"/ skip=/\\"/ end=/"/ contains=scalaFInterpolation,scalaFInterpolationB,scalaEscapedChar,scalaUnicodeChar
syn match scalaFInterpolation /\$[a-zA-Z0-9_$]\+\(%[-A-Za-z0-9\.]\+\)\?/ contained
exe 'syn region scalaFInterpolationB matchgroup=scalaInterpolationBoundary start=/${/ end=/}\(%[-A-Za-z0-9\.]\+\)\?/ contained contains=' . s:ContainedGroup()
-hi link scalaFString String
-hi link scalaFInterpolation Function
+hi def link scalaFString String
+hi def link scalaFInterpolation Function
hi clear scalaFInterpolationB
syn region scalaTripleString start=/"""/ end=/"""\%([^"]\|$\)/ contains=scalaEscapedChar,scalaUnicodeChar
syn region scalaTripleFString matchgroup=scalaInterpolationBrackets start=/f"""/ end=/"""\%([^"]\|$\)/ contains=scalaFInterpolation,scalaFInterpolationB,scalaEscapedChar,scalaUnicodeChar
-hi link scalaTripleString String
-hi link scalaTripleFString String
+hi def link scalaTripleString String
+hi def link scalaTripleFString String
-hi link scalaInterpolationBrackets Special
-hi link scalaInterpolationBoundary Function
+hi def link scalaInterpolationBrackets Special
+hi def link scalaInterpolationBoundary Function
syn match scalaNumber /\<0[dDfFlL]\?\>/ " Just a bare 0
syn match scalaNumber /\<[1-9]\d*[dDfFlL]\?\>/ " A multi-digit number - octal numbers with leading 0's are deprecated in Scala
@@ -176,16 +176,16 @@ syn match scalaNumber /\<0[xX][0-9a-fA-F]\+[dDfFlL]\?\>/ " Hex number
syn match scalaNumber /\%(\<\d\+\.\d*\|\.\d\+\)\%([eE][-+]\=\d\+\)\=[fFdD]\=/ " exponential notation 1
syn match scalaNumber /\<\d\+[eE][-+]\=\d\+[fFdD]\=\>/ " exponential notation 2
syn match scalaNumber /\<\d\+\%([eE][-+]\=\d\+\)\=[fFdD]\>/ " exponential notation 3
-hi link scalaNumber Number
+hi def link scalaNumber Number
syn region scalaRoundBrackets start="(" end=")" skipwhite contained contains=scalaTypeDeclaration,scalaSquareBrackets,scalaRoundBrackets
syn region scalaSquareBrackets matchgroup=scalaSquareBracketsBrackets start="\[" end="\]" skipwhite nextgroup=scalaTypeExtension contains=scalaTypeDeclaration,scalaSquareBrackets,scalaTypeOperator,scalaTypeAnnotationParameter
syn match scalaTypeOperator /[-+=:<>]\+/ contained
syn match scalaTypeAnnotationParameter /@\<[`_A-Za-z0-9$]\+\>/ contained
-hi link scalaSquareBracketsBrackets Type
-hi link scalaTypeOperator Keyword
-hi link scalaTypeAnnotationParameter Function
+hi def link scalaSquareBracketsBrackets Type
+hi def link scalaTypeOperator Keyword
+hi def link scalaTypeAnnotationParameter Function
syn match scalaShebang "\%^#!.*" display
syn region scalaMultilineComment start="/\*" end="\*/" contains=scalaMultilineComment,scalaDocLinks,scalaParameterAnnotation,scalaCommentAnnotation,scalaTodo,scalaCommentCodeBlock,@Spell keepend fold
@@ -195,20 +195,20 @@ syn match scalaParamAnnotationValue /[.`_A-Za-z0-9$]\+/ contained
syn region scalaDocLinks start="\[\[" end="\]\]" contained
syn region scalaCommentCodeBlock matchgroup=Keyword start="{{{" end="}}}" contained
syn match scalaTodo "\vTODO|FIXME|XXX" contained
-hi link scalaShebang Comment
-hi link scalaMultilineComment Comment
-hi link scalaDocLinks Function
-hi link scalaParameterAnnotation Function
-hi link scalaParamAnnotationValue Keyword
-hi link scalaCommentAnnotation Function
-hi link scalaCommentCodeBlock String
-hi link scalaTodo Todo
+hi def link scalaShebang Comment
+hi def link scalaMultilineComment Comment
+hi def link scalaDocLinks Function
+hi def link scalaParameterAnnotation Function
+hi def link scalaParamAnnotationValue Keyword
+hi def link scalaCommentAnnotation Function
+hi def link scalaCommentCodeBlock String
+hi def link scalaTodo Todo
syn match scalaAnnotation /@\<[`_A-Za-z0-9$]\+\>/
-hi link scalaAnnotation PreProc
+hi def link scalaAnnotation PreProc
syn match scalaTrailingComment "//.*$" contains=scalaTodo,@Spell
-hi link scalaTrailingComment Comment
+hi def link scalaTrailingComment Comment
syn match scalaAkkaFSM /goto([^)]*)\_s\+\<using\>/ contains=scalaAkkaFSMGotoUsing
syn match scalaAkkaFSM /stay\_s\+using/
@@ -221,8 +221,8 @@ syn match scalaAkkaFSM /onTermination/
syn match scalaAkkaFSM /whenUnhandled/
syn match scalaAkkaFSMGotoUsing /\<using\>/
syn match scalaAkkaFSMGotoUsing /\<goto\>/
-hi link scalaAkkaFSM PreProc
-hi link scalaAkkaFSMGotoUsing PreProc
+hi def link scalaAkkaFSM PreProc
+hi def link scalaAkkaFSMGotoUsing PreProc
let b:current_syntax = 'scala'
diff --git a/runtime/syntax/texinfo.vim b/runtime/syntax/texinfo.vim
index a4b7689707..79a4dfe821 100644
--- a/runtime/syntax/texinfo.vim
+++ b/runtime/syntax/texinfo.vim
@@ -1,396 +1,46 @@
" Vim syntax file
-" Language: Texinfo (macro package for TeX)
-" Maintainer: Sandor Kopanyi <sandor.kopanyi@mailbox.hu>
-" URL: <->
-" Last Change: 2004 Jun 23
-"
-" the file follows the Texinfo manual structure; this file is based
-" on manual for Texinfo version 4.0, 28 September 1999
-" since @ can have special meanings, everything is 'match'-ed and 'region'-ed
-" (including @ in 'iskeyword' option has unexpected effects)
+" Language: Texinfo (documentation format)
+" Maintainer: Robert Dodier <robert.dodier@gmail.com>
+" Latest Revision: 2021-12-15
-" quit when a syntax file was already loaded
if exists("b:current_syntax")
finish
endif
-if !exists("main_syntax")
- let main_syntax = 'texinfo'
-endif
-
-"in Texinfo can be real big things, like tables; sync for that
-syn sync lines=200
-
-"some general stuff
-"syn match texinfoError "\S" contained TODO
-syn match texinfoIdent "\k\+" contained "IDENTifier
-syn match texinfoAssignment "\k\+\s*=\s*\k\+\s*$" contained "assigment statement ( var = val )
-syn match texinfoSinglePar "\k\+\s*$" contained "single parameter (used for several @-commands)
-syn match texinfoIndexPar "\k\k\s*$" contained "param. used for different *index commands (+ @documentlanguage command)
-
-
-"marking words and phrases (chap. 9 in Texinfo manual)
-"(almost) everything appears as 'contained' too; is for tables (@table)
-
-"this chapter is at the beginning of this file to avoid overwritings
-
-syn match texinfoSpecialChar "@acronym" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@acronym{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@b" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@b{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@cite" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@cite{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@code" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@code{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@command" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@command{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@dfn" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@dfn{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@email" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@email{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@emph" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@emph{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@env" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@env{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@file" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@file{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@i" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@i{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@kbd" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@kbd{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@key" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@key{" end="}" contains=texinfoSpecialChar
-syn match texinfoSpecialChar "@option" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@option{" end="}" contains=texinfoSpecialChar
-syn match texinfoSpecialChar "@r" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@r{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@samp" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@samp{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@sc" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@sc{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@strong" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@strong{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@t" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@t{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@url" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@url{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoSpecialChar "@var" contained
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@var{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn match texinfoAtCmd "^@kbdinputstyle" nextgroup=texinfoSinglePar skipwhite
-
-
-"overview of Texinfo (chap. 1 in Texinfo manual)
-syn match texinfoComment "@c .*"
-syn match texinfoComment "@c$"
-syn match texinfoComment "@comment .*"
-syn region texinfoMltlnAtCmd matchgroup=texinfoComment start="^@ignore\s*$" end="^@end ignore\s*$" contains=ALL
-
-
-"beginning a Texinfo file (chap. 3 in Texinfo manual)
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="@center " skip="\\$" end="$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd oneline
-syn region texinfoMltlnDMAtCmd matchgroup=texinfoAtCmd start="^@detailmenu\s*$" end="^@end detailmenu\s*$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@setfilename " skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@settitle " skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@shorttitlepage " skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@title " skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@titlefont{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@titlepage\s*$" end="^@end titlepage\s*$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd,texinfoMltlnDMAtCmd,texinfoAtCmd,texinfoPrmAtCmd,texinfoMltlnAtCmd
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@vskip " skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn match texinfoAtCmd "^@exampleindent" nextgroup=texinfoSinglePar skipwhite
-syn match texinfoAtCmd "^@headings" nextgroup=texinfoSinglePar skipwhite
-syn match texinfoAtCmd "^\\input" nextgroup=texinfoSinglePar skipwhite
-syn match texinfoAtCmd "^@paragraphindent" nextgroup=texinfoSinglePar skipwhite
-syn match texinfoAtCmd "^@setchapternewpage" nextgroup=texinfoSinglePar skipwhite
-
-
-"ending a Texinfo file (chap. 4 in Texinfo manual)
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="@author " skip="\\$" end="$" contains=texinfoSpecialChar oneline
-"all below @bye should be comment TODO
-syn match texinfoAtCmd "^@bye\s*$"
-syn match texinfoAtCmd "^@contents\s*$"
-syn match texinfoAtCmd "^@printindex" nextgroup=texinfoIndexPar skipwhite
-syn match texinfoAtCmd "^@setcontentsaftertitlepage\s*$"
-syn match texinfoAtCmd "^@setshortcontentsaftertitlepage\s*$"
-syn match texinfoAtCmd "^@shortcontents\s*$"
-syn match texinfoAtCmd "^@summarycontents\s*$"
-
-
-"chapter structuring (chap. 5 in Texinfo manual)
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@appendix" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@appendixsec" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@appendixsection" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@appendixsubsec" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@appendixsubsubsec" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@centerchap" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@chapheading" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@chapter" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@heading" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@majorheading" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@section" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@subheading " skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@subsection" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@subsubheading" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@subsubsection" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@subtitle" skip="\\$" end="$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@unnumbered" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@unnumberedsec" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@unnumberedsubsec" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@unnumberedsubsubsec" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn match texinfoAtCmd "^@lowersections\s*$"
-syn match texinfoAtCmd "^@raisesections\s*$"
-
-
-"nodes (chap. 6 in Texinfo manual)
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@anchor{" end="}"
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@top" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@node" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-
-
-"menus (chap. 7 in Texinfo manual)
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@menu\s*$" end="^@end menu\s*$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd,texinfoMltlnDMAtCmd
-
-
-"cross references (chap. 8 in Texinfo manual)
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@inforef{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@pxref{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@ref{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@uref{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@xref{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-
-
-"marking words and phrases (chap. 9 in Texinfo manual)
-"(almost) everything appears as 'contained' too; is for tables (@table)
-
-"this chapter is at the beginning of this file to avoid overwritings
-
-
-"quotations and examples (chap. 10 in Texinfo manual)
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@cartouche\s*$" end="^@end cartouche\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@display\s*$" end="^@end display\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@example\s*$" end="^@end example\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@flushleft\s*$" end="^@end flushleft\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@flushright\s*$" end="^@end flushright\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@format\s*$" end="^@end format\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@lisp\s*$" end="^@end lisp\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@quotation\s*$" end="^@end quotation\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@smalldisplay\s*$" end="^@end smalldisplay\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@smallexample\s*$" end="^@end smallexample\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@smallformat\s*$" end="^@end smallformat\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@smalllisp\s*$" end="^@end smalllisp\s*$" contains=ALL
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@exdent" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn match texinfoAtCmd "^@noindent\s*$"
-syn match texinfoAtCmd "^@smallbook\s*$"
-
-
-"lists and tables (chap. 11 in Texinfo manual)
-syn match texinfoAtCmd "@asis" contained
-syn match texinfoAtCmd "@columnfractions" contained
-syn match texinfoAtCmd "@item" contained
-syn match texinfoAtCmd "@itemx" contained
-syn match texinfoAtCmd "@tab" contained
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@enumerate" end="^@end enumerate\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@ftable" end="^@end ftable\s*$" contains=ALL
-syn region texinfoMltlnNAtCmd matchgroup=texinfoAtCmd start="^@itemize" end="^@end itemize\s*$" contains=ALL
-syn region texinfoMltlnNAtCmd matchgroup=texinfoAtCmd start="^@multitable" end="^@end multitable\s*$" contains=ALL
-syn region texinfoMltlnNAtCmd matchgroup=texinfoAtCmd start="^@table" end="^@end table\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@vtable" end="^@end vtable\s*$" contains=ALL
+let s:cpo_save = &cpo
+set cpo&vim
+syn match texinfoControlSequence display '\(@end [a-zA-Z@]\+\|@[a-zA-Z@]\+\)'
-"indices (chap. 12 in Texinfo manual)
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@\(c\|f\|k\|p\|t\|v\)index" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@..index" skip="\\$" end="$" contains=texinfoSpecialChar oneline
-"@defcodeindex and @defindex is defined after chap. 15's @def* commands (otherwise those ones will overwrite these ones)
-syn match texinfoSIPar "\k\k\s*\k\k\s*$" contained
-syn match texinfoAtCmd "^@syncodeindex" nextgroup=texinfoSIPar skipwhite
-syn match texinfoAtCmd "^@synindex" nextgroup=texinfoSIPar skipwhite
+syn match texinfoComment display '^\s*\(@comment\|@c\)\>.*$'
-"special insertions (chap. 13 in Texinfo manual)
-syn match texinfoSpecialChar "@\(!\|?\|@\|\s\)"
-syn match texinfoSpecialChar "@{"
-syn match texinfoSpecialChar "@}"
-"accents
-syn match texinfoSpecialChar "@=."
-syn match texinfoSpecialChar "@\('\|\"\|\^\|`\)[aeiouyAEIOUY]"
-syn match texinfoSpecialChar "@\~[aeinouyAEINOUY]"
-syn match texinfoSpecialChar "@dotaccent{.}"
-syn match texinfoSpecialChar "@H{.}"
-syn match texinfoSpecialChar "@,{[cC]}"
-syn match texinfoSpecialChar "@AA{}"
-syn match texinfoSpecialChar "@aa{}"
-syn match texinfoSpecialChar "@L{}"
-syn match texinfoSpecialChar "@l{}"
-syn match texinfoSpecialChar "@O{}"
-syn match texinfoSpecialChar "@o{}"
-syn match texinfoSpecialChar "@ringaccent{.}"
-syn match texinfoSpecialChar "@tieaccent{..}"
-syn match texinfoSpecialChar "@u{.}"
-syn match texinfoSpecialChar "@ubaraccent{.}"
-syn match texinfoSpecialChar "@udotaccent{.}"
-syn match texinfoSpecialChar "@v{.}"
-"ligatures
-syn match texinfoSpecialChar "@AE{}"
-syn match texinfoSpecialChar "@ae{}"
-syn match texinfoSpecialChar "@copyright{}"
-syn match texinfoSpecialChar "@bullet" contained "for tables and lists
-syn match texinfoSpecialChar "@bullet{}"
-syn match texinfoSpecialChar "@dotless{i}"
-syn match texinfoSpecialChar "@dotless{j}"
-syn match texinfoSpecialChar "@dots{}"
-syn match texinfoSpecialChar "@enddots{}"
-syn match texinfoSpecialChar "@equiv" contained "for tables and lists
-syn match texinfoSpecialChar "@equiv{}"
-syn match texinfoSpecialChar "@error{}"
-syn match texinfoSpecialChar "@exclamdown{}"
-syn match texinfoSpecialChar "@expansion{}"
-syn match texinfoSpecialChar "@minus" contained "for tables and lists
-syn match texinfoSpecialChar "@minus{}"
-syn match texinfoSpecialChar "@OE{}"
-syn match texinfoSpecialChar "@oe{}"
-syn match texinfoSpecialChar "@point" contained "for tables and lists
-syn match texinfoSpecialChar "@point{}"
-syn match texinfoSpecialChar "@pounds{}"
-syn match texinfoSpecialChar "@print{}"
-syn match texinfoSpecialChar "@questiondown{}"
-syn match texinfoSpecialChar "@result" contained "for tables and lists
-syn match texinfoSpecialChar "@result{}"
-syn match texinfoSpecialChar "@ss{}"
-syn match texinfoSpecialChar "@TeX{}"
-"other
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@dmn{" end="}"
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@footnote{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@image{" end="}"
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@math{" end="}"
-syn match texinfoAtCmd "@footnotestyle" nextgroup=texinfoSinglePar skipwhite
+syn region texinfoCode matchgroup=texinfoControlSequence start="@code{" end="}" contains=ALL
+syn region texinfoVerb matchgroup=texinfoControlSequence start="@verb{" end="}" contains=ALL
+syn region texinfoArgument matchgroup=texinfoBrace start="{" end="}" contains=ALLBUT
-"making and preventing breaks (chap. 14 in Texinfo manual)
-syn match texinfoSpecialChar "@\(\*\|-\|\.\)"
-syn match texinfoAtCmd "^@need" nextgroup=texinfoSinglePar skipwhite
-syn match texinfoAtCmd "^@page\s*$"
-syn match texinfoAtCmd "^@sp" nextgroup=texinfoSinglePar skipwhite
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@group\s*$" end="^@end group\s*$" contains=ALL
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@hyphenation{" end="}"
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@w{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
+syn region texinfoExample matchgroup=texinfoControlSequence start="^@example\s*$" end="^@end example\s*$" contains=ALL
+syn region texinfoVerbatim matchgroup=texinfoControlSequence start="^@verbatim\s*$" end="^@end verbatim\s*$"
-"definition commands (chap. 15 in Texinfo manual)
-syn match texinfoMltlnAtCmdFLine "^@def\k\+" contained
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@def\k\+" end="^@end def\k\+$" contains=ALL
-
-"next 2 commands are from chap. 12; must be defined after @def* commands above to overwrite them
-syn match texinfoAtCmd "@defcodeindex" nextgroup=texinfoIndexPar skipwhite
-syn match texinfoAtCmd "@defindex" nextgroup=texinfoIndexPar skipwhite
-
-
-"conditionally visible text (chap. 16 in Texinfo manual)
-syn match texinfoAtCmd "^@clear" nextgroup=texinfoSinglePar skipwhite
-syn region texinfoMltln2AtCmd matchgroup=texinfoAtCmd start="^@html\s*$" end="^@end html\s*$"
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@ifclear" end="^@end ifclear\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@ifhtml" end="^@end ifhtml\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@ifinfo" end="^@end ifinfo\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@ifnothtml" end="^@end ifnothtml\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@ifnotinfo" end="^@end ifnotinfo\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@ifnottex" end="^@end ifnottex\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@ifset" end="^@end ifset\s*$" contains=ALL
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@iftex" end="^@end iftex\s*$" contains=ALL
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@set " skip="\\$" end="$" contains=texinfoSpecialChar oneline
-syn region texinfoTexCmd start="\$\$" end="\$\$" contained
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@tex" end="^@end tex\s*$" contains=texinfoTexCmd
-syn region texinfoBrcPrmAtCmd matchgroup=texinfoAtCmd start="@value{" end="}" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-
-
-"internationalization (chap. 17 in Texinfo manual)
-syn match texinfoAtCmd "@documentencoding" nextgroup=texinfoSinglePar skipwhite
-syn match texinfoAtCmd "@documentlanguage" nextgroup=texinfoIndexPar skipwhite
-
-
-"defining new texinfo commands (chap. 18 in Texinfo manual)
-syn match texinfoAtCmd "@alias" nextgroup=texinfoAssignment skipwhite
-syn match texinfoDIEPar "\S*\s*,\s*\S*\s*,\s*\S*\s*$" contained
-syn match texinfoAtCmd "@definfoenclose" nextgroup=texinfoDIEPar skipwhite
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@macro" end="^@end macro\s*$" contains=ALL
-
-
-"formatting hardcopy (chap. 19 in Texinfo manual)
-syn match texinfoAtCmd "^@afourlatex\s*$"
-syn match texinfoAtCmd "^@afourpaper\s*$"
-syn match texinfoAtCmd "^@afourwide\s*$"
-syn match texinfoAtCmd "^@finalout\s*$"
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@pagesizes" end="$" oneline
-
-
-"creating and installing Info Files (chap. 20 in Texinfo manual)
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@dircategory" skip="\\$" end="$" oneline
-syn region texinfoMltlnAtCmd matchgroup=texinfoAtCmd start="^@direntry\s*$" end="^@end direntry\s*$" contains=texinfoSpecialChar
-syn match texinfoAtCmd "^@novalidate\s*$"
-
-
-"include files (appendix E in Texinfo manual)
-syn match texinfoAtCmd "^@include" nextgroup=texinfoSinglePar skipwhite
-
-
-"page headings (appendix F in Texinfo manual)
-syn match texinfoHFSpecialChar "@|" contained
-syn match texinfoThisAtCmd "@thischapter" contained
-syn match texinfoThisAtCmd "@thischaptername" contained
-syn match texinfoThisAtCmd "@thisfile" contained
-syn match texinfoThisAtCmd "@thispage" contained
-syn match texinfoThisAtCmd "@thistitle" contained
-syn match texinfoThisAtCmd "@today{}" contained
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@evenfooting" skip="\\$" end="$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd,texinfoThisAtCmd,texinfoHFSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@evenheading" skip="\\$" end="$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd,texinfoThisAtCmd,texinfoHFSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@everyfooting" skip="\\$" end="$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd,texinfoThisAtCmd,texinfoHFSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@everyheading" skip="\\$" end="$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd,texinfoThisAtCmd,texinfoHFSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@oddfooting" skip="\\$" end="$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd,texinfoThisAtCmd,texinfoHFSpecialChar oneline
-syn region texinfoPrmAtCmd matchgroup=texinfoAtCmd start="^@oddheading" skip="\\$" end="$" contains=texinfoSpecialChar,texinfoBrcPrmAtCmd,texinfoThisAtCmd,texinfoHFSpecialChar oneline
-
-
-"refilling paragraphs (appendix H in Texinfo manual)
-syn match texinfoAtCmd "@refill"
-
-
-syn cluster texinfoAll contains=ALLBUT,texinfoThisAtCmd,texinfoHFSpecialChar
-syn cluster texinfoReducedAll contains=texinfoSpecialChar,texinfoBrcPrmAtCmd
-"==============================================================================
-" highlighting
-
-" Only when an item doesn't have highlighting yet
-
-hi def link texinfoSpecialChar Special
-hi def link texinfoHFSpecialChar Special
-
-hi def link texinfoError Error
-hi def link texinfoIdent Identifier
-hi def link texinfoAssignment Identifier
-hi def link texinfoSinglePar Identifier
-hi def link texinfoIndexPar Identifier
-hi def link texinfoSIPar Identifier
-hi def link texinfoDIEPar Identifier
-hi def link texinfoTexCmd PreProc
-
-
-hi def link texinfoAtCmd Statement "@-command
-hi def link texinfoPrmAtCmd String "@-command in one line with unknown nr. of parameters
- "is String because is found as a region and is 'matchgroup'-ed
- "to texinfoAtCmd
-hi def link texinfoBrcPrmAtCmd String "@-command with parameter(s) in braces ({})
- "is String because is found as a region and is 'matchgroup'-ed to texinfoAtCmd
-hi def link texinfoMltlnAtCmdFLine texinfoAtCmd "repeated embedded First lines in @-commands
-hi def link texinfoMltlnAtCmd String "@-command in multiple lines
- "is String because is found as a region and is 'matchgroup'-ed to texinfoAtCmd
-hi def link texinfoMltln2AtCmd PreProc "@-command in multiple lines (same as texinfoMltlnAtCmd, just with other colors)
-hi def link texinfoMltlnDMAtCmd PreProc "@-command in multiple lines (same as texinfoMltlnAtCmd, just with other colors; used for @detailmenu, which can be included in @menu)
-hi def link texinfoMltlnNAtCmd Normal "@-command in multiple lines (same as texinfoMltlnAtCmd, just with other colors)
-hi def link texinfoThisAtCmd Statement "@-command used in headers and footers (@this... series)
-
-hi def link texinfoComment Comment
+syn region texinfoMenu matchgroup=texinfoControlSequence start="^@menu\s*$" end="^@end menu\s*$"
+if exists("g:texinfo_delimiters")
+ syn match texinfoDelimiter display '[][{}]'
+endif
+hi def link texinfoDelimiter Delimiter
+hi def link texinfoComment Comment
+hi def link texinfoControlSequence Identifier
+hi def link texinfoBrace Operator
+hi def link texinfoArgument Special
+hi def link texinfoExample String
+hi def link texinfoVerbatim String
+hi def link texinfoVerb String
+hi def link texinfoCode String
+hi def link texinfoMenu String
let b:current_syntax = "texinfo"
-if main_syntax == 'texinfo'
- unlet main_syntax
-endif
-
-" vim: ts=8
+let &cpo = s:cpo_save
+unlet s:cpo_save
diff --git a/runtime/syntax/xml.vim b/runtime/syntax/xml.vim
index 7c9791a7cc..d99f8b467a 100644
--- a/runtime/syntax/xml.vim
+++ b/runtime/syntax/xml.vim
@@ -10,6 +10,7 @@
" 20190923 - Fix xmlEndTag to match xmlTag (vim/vim#884)
" 20190924 - Fix xmlAttribute property (amadeus/vim-xml@d8ce1c946)
" 20191103 - Enable spell checking globally
+" 20210428 - Improve syntax synchronizing
" CONFIGURATION:
" syntax folding can be turned on by
@@ -302,9 +303,12 @@ unlet b:current_syntax
" synchronizing
-" TODO !!! to be improved !!!
-syn sync match xmlSyncDT grouphere xmlDocType +\_.\(<!DOCTYPE\)\@=+
+syn sync match xmlSyncComment grouphere xmlComment +<!--+
+syn sync match xmlSyncComment groupthere NONE +-->+
+
+" The following is slow on large documents (and the doctype is optional
+" syn sync match xmlSyncDT grouphere xmlDocType +\_.\(<!DOCTYPE\)\@=+
" syn sync match xmlSyncDT groupthere NONE +]>+
if exists('g:xml_syntax_folding')
@@ -313,7 +317,7 @@ if exists('g:xml_syntax_folding')
syn sync match xmlSync groupthere xmlRegion +</[^ /!?<>"']\+>+
endif
-syn sync minlines=100
+syn sync minlines=100 maxlines=200
" The default highlighting.
@@ -354,4 +358,4 @@ let b:current_syntax = "xml"
let &cpo = s:xml_cpo_save
unlet s:xml_cpo_save
-" vim: ts=8
+" vim: ts=4
diff --git a/runtime/syntax/zsh.vim b/runtime/syntax/zsh.vim
index 819c419228..bab89b916e 100644
--- a/runtime/syntax/zsh.vim
+++ b/runtime/syntax/zsh.vim
@@ -41,11 +41,12 @@ if get(g:, 'zsh_fold_enable', 0)
setlocal foldmethod=syntax
endif
+syn match zshQuoted '\\.'
syn match zshPOSIXQuoted '\\[xX][0-9a-fA-F]\{1,2}'
syn match zshPOSIXQuoted '\\[0-7]\{1,3}'
syn match zshPOSIXQuoted '\\u[0-9a-fA-F]\{1,4}'
syn match zshPOSIXQuoted '\\U[1-9a-fA-F]\{1,8}'
-syn match zshQuoted '\\.'
+
syn region zshString matchgroup=zshStringDelimiter start=+"+ end=+"+
\ contains=zshQuoted,@zshDerefs,@zshSubst fold
syn region zshString matchgroup=zshStringDelimiter start=+'+ end=+'+ fold
@@ -133,217 +134,15 @@ syn keyword zshCommands alias autoload bg bindkey break bye cap cd
\ zmodload zparseopts zprof zpty zrecompile
\ zregexparse zsocket zstyle ztcp
-" Options, generated by: echo ${(j:\n:)options[(I)*]} | sort
-" Create a list of option names from zsh source dir:
-" #!/bin/zsh
-" topdir=/path/to/zsh-xxx
-" grep '^pindex([A-Za-z_]*)$' $topdir/Doc/Zsh/options.yo |
-" while read opt
-" do
-" echo ${${(L)opt#pindex\(}%\)}
-" done
-
+" Options, generated by from the zsh source with the make-options.zsh script.
syn case ignore
-
-syn match zshOptStart /^\s*\%(\%(\%(un\)\?setopt\)\|set\s+[-+]o\)/ nextgroup=zshOption skipwhite
-syn match zshOption /
- \ \%(\%(\<no_\?\)\?aliases\>\)\|
- \ \%(\%(\<no_\?\)\?aliasfuncdef\>\)\|\%(\%(no_\?\)\?alias_func_def\>\)\|
- \ \%(\%(\<no_\?\)\?allexport\>\)\|\%(\%(no_\?\)\?all_export\>\)\|
- \ \%(\%(\<no_\?\)\?alwayslastprompt\>\)\|\%(\%(no_\?\)\?always_last_prompt\>\)\|\%(\%(no_\?\)\?always_lastprompt\>\)\|
- \ \%(\%(\<no_\?\)\?alwaystoend\>\)\|\%(\%(no_\?\)\?always_to_end\>\)\|
- \ \%(\%(\<no_\?\)\?appendcreate\>\)\|\%(\%(no_\?\)\?append_create\>\)\|
- \ \%(\%(\<no_\?\)\?appendhistory\>\)\|\%(\%(no_\?\)\?append_history\>\)\|
- \ \%(\%(\<no_\?\)\?autocd\>\)\|\%(\%(no_\?\)\?auto_cd\>\)\|
- \ \%(\%(\<no_\?\)\?autocontinue\>\)\|\%(\%(no_\?\)\?auto_continue\>\)\|
- \ \%(\%(\<no_\?\)\?autolist\>\)\|\%(\%(no_\?\)\?auto_list\>\)\|
- \ \%(\%(\<no_\?\)\?automenu\>\)\|\%(\%(no_\?\)\?auto_menu\>\)\|
- \ \%(\%(\<no_\?\)\?autonamedirs\>\)\|\%(\%(no_\?\)\?auto_name_dirs\>\)\|
- \ \%(\%(\<no_\?\)\?autoparamkeys\>\)\|\%(\%(no_\?\)\?auto_param_keys\>\)\|
- \ \%(\%(\<no_\?\)\?autoparamslash\>\)\|\%(\%(no_\?\)\?auto_param_slash\>\)\|
- \ \%(\%(\<no_\?\)\?autopushd\>\)\|\%(\%(no_\?\)\?auto_pushd\>\)\|
- \ \%(\%(\<no_\?\)\?autoremoveslash\>\)\|\%(\%(no_\?\)\?auto_remove_slash\>\)\|
- \ \%(\%(\<no_\?\)\?autoresume\>\)\|\%(\%(no_\?\)\?auto_resume\>\)\|
- \ \%(\%(\<no_\?\)\?badpattern\>\)\|\%(\%(no_\?\)\?bad_pattern\>\)\|
- \ \%(\%(\<no_\?\)\?banghist\>\)\|\%(\%(no_\?\)\?bang_hist\>\)\|
- \ \%(\%(\<no_\?\)\?bareglobqual\>\)\|\%(\%(no_\?\)\?bare_glob_qual\>\)\|
- \ \%(\%(\<no_\?\)\?bashautolist\>\)\|\%(\%(no_\?\)\?bash_auto_list\>\)\|
- \ \%(\%(\<no_\?\)\?bashrematch\>\)\|\%(\%(no_\?\)\?bash_rematch\>\)\|
- \ \%(\%(\<no_\?\)\?beep\>\)\|
- \ \%(\%(\<no_\?\)\?bgnice\>\)\|\%(\%(no_\?\)\?bg_nice\>\)\|
- \ \%(\%(\<no_\?\)\?braceccl\>\)\|\%(\%(no_\?\)\?brace_ccl\>\)\|
- \ \%(\%(\<no_\?\)\?braceexpand\>\)\|\%(\%(no_\?\)\?brace_expand\>\)\|
- \ \%(\%(\<no_\?\)\?bsdecho\>\)\|\%(\%(no_\?\)\?bsd_echo\>\)\|
- \ \%(\%(\<no_\?\)\?caseglob\>\)\|\%(\%(no_\?\)\?case_glob\>\)\|
- \ \%(\%(\<no_\?\)\?casematch\>\)\|\%(\%(no_\?\)\?case_match\>\)\|
- \ \%(\%(\<no_\?\)\?cbases\>\)\|\%(\%(no_\?\)\?c_bases\>\)\|
- \ \%(\%(\<no_\?\)\?cdablevars\>\)\|\%(\%(no_\?\)\?cdable_vars\>\)\|\%(\%(no_\?\)\?cd_able_vars\>\)\|
- \ \%(\%(\<no_\?\)\?cdsilent\>\)\|\%(\%(no_\?\)\?cd_silent\>\)\|\%(\%(no_\?\)\?cd_silent\>\)\|
- \ \%(\%(\<no_\?\)\?chasedots\>\)\|\%(\%(no_\?\)\?chase_dots\>\)\|
- \ \%(\%(\<no_\?\)\?chaselinks\>\)\|\%(\%(no_\?\)\?chase_links\>\)\|
- \ \%(\%(\<no_\?\)\?checkjobs\>\)\|\%(\%(no_\?\)\?check_jobs\>\)\|
- \ \%(\%(\<no_\?\)\?checkrunningjobs\>\)\|\%(\%(no_\?\)\?check_running_jobs\>\)\|
- \ \%(\%(\<no_\?\)\?clobber\>\)\|
- \ \%(\%(\<no_\?\)\?clobberempty\>\)\|\%(\%(no_\?\)\?clobber_empty\>\)\|
- \ \%(\%(\<no_\?\)\?combiningchars\>\)\|\%(\%(no_\?\)\?combining_chars\>\)\|
- \ \%(\%(\<no_\?\)\?completealiases\>\)\|\%(\%(no_\?\)\?complete_aliases\>\)\|
- \ \%(\%(\<no_\?\)\?completeinword\>\)\|\%(\%(no_\?\)\?complete_in_word\>\)\|
- \ \%(\%(\<no_\?\)\?continueonerror\>\)\|\%(\%(no_\?\)\?continue_on_error\>\)\|
- \ \%(\%(\<no_\?\)\?correct\>\)\|
- \ \%(\%(\<no_\?\)\?correctall\>\)\|\%(\%(no_\?\)\?correct_all\>\)\|
- \ \%(\%(\<no_\?\)\?cprecedences\>\)\|\%(\%(no_\?\)\?c_precedences\>\)\|
- \ \%(\%(\<no_\?\)\?cshjunkiehistory\>\)\|\%(\%(no_\?\)\?csh_junkie_history\>\)\|
- \ \%(\%(\<no_\?\)\?cshjunkieloops\>\)\|\%(\%(no_\?\)\?csh_junkie_loops\>\)\|
- \ \%(\%(\<no_\?\)\?cshjunkiequotes\>\)\|\%(\%(no_\?\)\?csh_junkie_quotes\>\)\|
- \ \%(\%(\<no_\?\)\?csh_nullcmd\>\)\|\%(\%(no_\?\)\?csh_null_cmd\>\)\|\%(\%(no_\?\)\?cshnullcmd\>\)\|\%(\%(no_\?\)\?csh_null_cmd\>\)\|
- \ \%(\%(\<no_\?\)\?cshnullglob\>\)\|\%(\%(no_\?\)\?csh_null_glob\>\)\|
- \ \%(\%(\<no_\?\)\?debugbeforecmd\>\)\|\%(\%(no_\?\)\?debug_before_cmd\>\)\|
- \ \%(\%(\<no_\?\)\?dotglob\>\)\|\%(\%(no_\?\)\?dot_glob\>\)\|
- \ \%(\%(\<no_\?\)\?dvorak\>\)\|
- \ \%(\%(\<no_\?\)\?emacs\>\)\|
- \ \%(\%(\<no_\?\)\?equals\>\)\|
- \ \%(\%(\<no_\?\)\?errexit\>\)\|\%(\%(no_\?\)\?err_exit\>\)\|
- \ \%(\%(\<no_\?\)\?errreturn\>\)\|\%(\%(no_\?\)\?err_return\>\)\|
- \ \%(\%(\<no_\?\)\?evallineno\>\)\|\%(\%(no_\?\)\?eval_lineno\>\)\|
- \ \%(\%(\<no_\?\)\?exec\>\)\|
- \ \%(\%(\<no_\?\)\?extendedglob\>\)\|\%(\%(no_\?\)\?extended_glob\>\)\|
- \ \%(\%(\<no_\?\)\?extendedhistory\>\)\|\%(\%(no_\?\)\?extended_history\>\)\|
- \ \%(\%(\<no_\?\)\?flowcontrol\>\)\|\%(\%(no_\?\)\?flow_control\>\)\|
- \ \%(\%(\<no_\?\)\?forcefloat\>\)\|\%(\%(no_\?\)\?force_float\>\)\|
- \ \%(\%(\<no_\?\)\?functionargzero\>\)\|\%(\%(no_\?\)\?function_argzero\>\)\|\%(\%(no_\?\)\?function_arg_zero\>\)\|
- \ \%(\%(\<no_\?\)\?glob\>\)\|
- \ \%(\%(\<no_\?\)\?globalexport\>\)\|\%(\%(no_\?\)\?global_export\>\)\|
- \ \%(\%(\<no_\?\)\?globalrcs\>\)\|\%(\%(no_\?\)\?global_rcs\>\)\|
- \ \%(\%(\<no_\?\)\?globassign\>\)\|\%(\%(no_\?\)\?glob_assign\>\)\|
- \ \%(\%(\<no_\?\)\?globcomplete\>\)\|\%(\%(no_\?\)\?glob_complete\>\)\|
- \ \%(\%(\<no_\?\)\?globdots\>\)\|\%(\%(no_\?\)\?glob_dots\>\)\|
- \ \%(\%(\<no_\?\)\?glob_subst\>\)\|\%(\%(no_\?\)\?globsubst\>\)\|
- \ \%(\%(\<no_\?\)\?globstarshort\>\)\|\%(\%(no_\?\)\?glob_star_short\>\)\|
- \ \%(\%(\<no_\?\)\?hashall\>\)\|\%(\%(no_\?\)\?hash_all\>\)\|
- \ \%(\%(\<no_\?\)\?hashcmds\>\)\|\%(\%(no_\?\)\?hash_cmds\>\)\|
- \ \%(\%(\<no_\?\)\?hashdirs\>\)\|\%(\%(no_\?\)\?hash_dirs\>\)\|
- \ \%(\%(\<no_\?\)\?hashexecutablesonly\>\)\|\%(\%(no_\?\)\?hash_executables_only\>\)\|
- \ \%(\%(\<no_\?\)\?hashlistall\>\)\|\%(\%(no_\?\)\?hash_list_all\>\)\|
- \ \%(\%(\<no_\?\)\?histallowclobber\>\)\|\%(\%(no_\?\)\?hist_allow_clobber\>\)\|
- \ \%(\%(\<no_\?\)\?histappend\>\)\|\%(\%(no_\?\)\?hist_append\>\)\|
- \ \%(\%(\<no_\?\)\?histbeep\>\)\|\%(\%(no_\?\)\?hist_beep\>\)\|
- \ \%(\%(\<no_\?\)\?hist_expand\>\)\|\%(\%(no_\?\)\?histexpand\>\)\|
- \ \%(\%(\<no_\?\)\?hist_expire_dups_first\>\)\|\%(\%(no_\?\)\?histexpiredupsfirst\>\)\|
- \ \%(\%(\<no_\?\)\?histfcntllock\>\)\|\%(\%(no_\?\)\?hist_fcntl_lock\>\)\|
- \ \%(\%(\<no_\?\)\?histfindnodups\>\)\|\%(\%(no_\?\)\?hist_find_no_dups\>\)\|
- \ \%(\%(\<no_\?\)\?histignorealldups\>\)\|\%(\%(no_\?\)\?hist_ignore_all_dups\>\)\|
- \ \%(\%(\<no_\?\)\?histignoredups\>\)\|\%(\%(no_\?\)\?hist_ignore_dups\>\)\|
- \ \%(\%(\<no_\?\)\?histignorespace\>\)\|\%(\%(no_\?\)\?hist_ignore_space\>\)\|
- \ \%(\%(\<no_\?\)\?histlexwords\>\)\|\%(\%(no_\?\)\?hist_lex_words\>\)\|
- \ \%(\%(\<no_\?\)\?histnofunctions\>\)\|\%(\%(no_\?\)\?hist_no_functions\>\)\|
- \ \%(\%(\<no_\?\)\?histnostore\>\)\|\%(\%(no_\?\)\?hist_no_store\>\)\|
- \ \%(\%(\<no_\?\)\?histreduceblanks\>\)\|\%(\%(no_\?\)\?hist_reduce_blanks\>\)\|
- \ \%(\%(\<no_\?\)\?histsavebycopy\>\)\|\%(\%(no_\?\)\?hist_save_by_copy\>\)\|
- \ \%(\%(\<no_\?\)\?histsavenodups\>\)\|\%(\%(no_\?\)\?hist_save_no_dups\>\)\|
- \ \%(\%(\<no_\?\)\?histsubstpattern\>\)\|\%(\%(no_\?\)\?hist_subst_pattern\>\)\|
- \ \%(\%(\<no_\?\)\?histverify\>\)\|\%(\%(no_\?\)\?hist_verify\>\)\|
- \ \%(\%(\<no_\?\)\?hup\>\)\|
- \ \%(\%(\<no_\?\)\?ignorebraces\>\)\|\%(\%(no_\?\)\?ignore_braces\>\)\|
- \ \%(\%(\<no_\?\)\?ignoreclosebraces\>\)\|\%(\%(no_\?\)\?ignore_close_braces\>\)\|
- \ \%(\%(\<no_\?\)\?ignoreeof\>\)\|\%(\%(no_\?\)\?ignore_eof\>\)\|
- \ \%(\%(\<no_\?\)\?incappendhistory\>\)\|\%(\%(no_\?\)\?inc_append_history\>\)\|
- \ \%(\%(\<no_\?\)\?incappendhistorytime\>\)\|\%(\%(no_\?\)\?inc_append_history_time\>\)\|
- \ \%(\%(\<no_\?\)\?interactive\>\)\|
- \ \%(\%(\<no_\?\)\?interactivecomments\>\)\|\%(\%(no_\?\)\?interactive_comments\>\)\|
- \ \%(\%(\<no_\?\)\?ksharrays\>\)\|\%(\%(no_\?\)\?ksh_arrays\>\)\|
- \ \%(\%(\<no_\?\)\?kshautoload\>\)\|\%(\%(no_\?\)\?ksh_autoload\>\)\|
- \ \%(\%(\<no_\?\)\?kshglob\>\)\|\%(\%(no_\?\)\?ksh_glob\>\)\|
- \ \%(\%(\<no_\?\)\?kshoptionprint\>\)\|\%(\%(no_\?\)\?ksh_option_print\>\)\|
- \ \%(\%(\<no_\?\)\?kshtypeset\>\)\|\%(\%(no_\?\)\?ksh_typeset\>\)\|
- \ \%(\%(\<no_\?\)\?kshzerosubscript\>\)\|\%(\%(no_\?\)\?ksh_zero_subscript\>\)\|
- \ \%(\%(\<no_\?\)\?listambiguous\>\)\|\%(\%(no_\?\)\?list_ambiguous\>\)\|
- \ \%(\%(\<no_\?\)\?listbeep\>\)\|\%(\%(no_\?\)\?list_beep\>\)\|
- \ \%(\%(\<no_\?\)\?listpacked\>\)\|\%(\%(no_\?\)\?list_packed\>\)\|
- \ \%(\%(\<no_\?\)\?listrowsfirst\>\)\|\%(\%(no_\?\)\?list_rows_first\>\)\|
- \ \%(\%(\<no_\?\)\?listtypes\>\)\|\%(\%(no_\?\)\?list_types\>\)\|
- \ \%(\%(\<no_\?\)\?localloops\>\)\|\%(\%(no_\?\)\?local_loops\>\)\|
- \ \%(\%(\<no_\?\)\?localoptions\>\)\|\%(\%(no_\?\)\?local_options\>\)\|
- \ \%(\%(\<no_\?\)\?localpatterns\>\)\|\%(\%(no_\?\)\?local_patterns\>\)\|
- \ \%(\%(\<no_\?\)\?localtraps\>\)\|\%(\%(no_\?\)\?local_traps\>\)\|
- \ \%(\%(\<no_\?\)\?log\>\)\|
- \ \%(\%(\<no_\?\)\?login\>\)\|
- \ \%(\%(\<no_\?\)\?longlistjobs\>\)\|\%(\%(no_\?\)\?long_list_jobs\>\)\|
- \ \%(\%(\<no_\?\)\?magicequalsubst\>\)\|\%(\%(no_\?\)\?magic_equal_subst\>\)\|
- \ \%(\%(\<no_\?\)\?mark_dirs\>\)\|
- \ \%(\%(\<no_\?\)\?mailwarn\>\)\|\%(\%(no_\?\)\?mail_warn\>\)\|
- \ \%(\%(\<no_\?\)\?mailwarning\>\)\|\%(\%(no_\?\)\?mail_warning\>\)\|
- \ \%(\%(\<no_\?\)\?markdirs\>\)\|
- \ \%(\%(\<no_\?\)\?menucomplete\>\)\|\%(\%(no_\?\)\?menu_complete\>\)\|
- \ \%(\%(\<no_\?\)\?monitor\>\)\|
- \ \%(\%(\<no_\?\)\?multibyte\>\)\|\%(\%(no_\?\)\?multi_byte\>\)\|
- \ \%(\%(\<no_\?\)\?multifuncdef\>\)\|\%(\%(no_\?\)\?multi_func_def\>\)\|
- \ \%(\%(\<no_\?\)\?multios\>\)\|\%(\%(no_\?\)\?multi_os\>\)\|
- \ \%(\%(\<no_\?\)\?nomatch\>\)\|\%(\%(no_\?\)\?no_match\>\)\|
- \ \%(\%(\<no_\?\)\?notify\>\)\|
- \ \%(\%(\<no_\?\)\?nullglob\>\)\|\%(\%(no_\?\)\?null_glob\>\)\|
- \ \%(\%(\<no_\?\)\?numericglobsort\>\)\|\%(\%(no_\?\)\?numeric_glob_sort\>\)\|
- \ \%(\%(\<no_\?\)\?octalzeroes\>\)\|\%(\%(no_\?\)\?octal_zeroes\>\)\|
- \ \%(\%(\<no_\?\)\?onecmd\>\)\|\%(\%(no_\?\)\?one_cmd\>\)\|
- \ \%(\%(\<no_\?\)\?overstrike\>\)\|\%(\%(no_\?\)\?over_strike\>\)\|
- \ \%(\%(\<no_\?\)\?pathdirs\>\)\|\%(\%(no_\?\)\?path_dirs\>\)\|
- \ \%(\%(\<no_\?\)\?pathscript\>\)\|\%(\%(no_\?\)\?path_script\>\)\|
- \ \%(\%(\<no_\?\)\?physical\>\)\|
- \ \%(\%(\<no_\?\)\?pipefail\>\)\|\%(\%(no_\?\)\?pipe_fail\>\)\|
- \ \%(\%(\<no_\?\)\?posixaliases\>\)\|\%(\%(no_\?\)\?posix_aliases\>\)\|
- \ \%(\%(\<no_\?\)\?posixargzero\>\)\|\%(\%(no_\?\)\?posix_arg_zero\>\)\|\%(\%(no_\?\)\?posix_argzero\>\)\|
- \ \%(\%(\<no_\?\)\?posixbuiltins\>\)\|\%(\%(no_\?\)\?posix_builtins\>\)\|
- \ \%(\%(\<no_\?\)\?posixcd\>\)\|\%(\%(no_\?\)\?posix_cd\>\)\|
- \ \%(\%(\<no_\?\)\?posixidentifiers\>\)\|\%(\%(no_\?\)\?posix_identifiers\>\)\|
- \ \%(\%(\<no_\?\)\?posixjobs\>\)\|\%(\%(no_\?\)\?posix_jobs\>\)\|
- \ \%(\%(\<no_\?\)\?posixstrings\>\)\|\%(\%(no_\?\)\?posix_strings\>\)\|
- \ \%(\%(\<no_\?\)\?posixtraps\>\)\|\%(\%(no_\?\)\?posix_traps\>\)\|
- \ \%(\%(\<no_\?\)\?printeightbit\>\)\|\%(\%(no_\?\)\?print_eight_bit\>\)\|
- \ \%(\%(\<no_\?\)\?printexitvalue\>\)\|\%(\%(no_\?\)\?print_exit_value\>\)\|
- \ \%(\%(\<no_\?\)\?privileged\>\)\|
- \ \%(\%(\<no_\?\)\?promptbang\>\)\|\%(\%(no_\?\)\?prompt_bang\>\)\|
- \ \%(\%(\<no_\?\)\?promptcr\>\)\|\%(\%(no_\?\)\?prompt_cr\>\)\|
- \ \%(\%(\<no_\?\)\?promptpercent\>\)\|\%(\%(no_\?\)\?prompt_percent\>\)\|
- \ \%(\%(\<no_\?\)\?promptsp\>\)\|\%(\%(no_\?\)\?prompt_sp\>\)\|
- \ \%(\%(\<no_\?\)\?promptsubst\>\)\|\%(\%(no_\?\)\?prompt_subst\>\)\|
- \ \%(\%(\<no_\?\)\?promptvars\>\)\|\%(\%(no_\?\)\?prompt_vars\>\)\|
- \ \%(\%(\<no_\?\)\?pushdignoredups\>\)\|\%(\%(no_\?\)\?pushd_ignore_dups\>\)\|
- \ \%(\%(\<no_\?\)\?pushdminus\>\)\|\%(\%(no_\?\)\?pushd_minus\>\)\|
- \ \%(\%(\<no_\?\)\?pushdsilent\>\)\|\%(\%(no_\?\)\?pushd_silent\>\)\|
- \ \%(\%(\<no_\?\)\?pushdtohome\>\)\|\%(\%(no_\?\)\?pushd_to_home\>\)\|
- \ \%(\%(\<no_\?\)\?rcexpandparam\>\)\|\%(\%(no_\?\)\?rc_expandparam\>\)\|\%(\%(no_\?\)\?rc_expand_param\>\)\|
- \ \%(\%(\<no_\?\)\?rcquotes\>\)\|\%(\%(no_\?\)\?rc_quotes\>\)\|
- \ \%(\%(\<no_\?\)\?rcs\>\)\|
- \ \%(\%(\<no_\?\)\?recexact\>\)\|\%(\%(no_\?\)\?rec_exact\>\)\|
- \ \%(\%(\<no_\?\)\?rematchpcre\>\)\|\%(\%(no_\?\)\?re_match_pcre\>\)\|\%(\%(no_\?\)\?rematch_pcre\>\)\|
- \ \%(\%(\<no_\?\)\?restricted\>\)\|
- \ \%(\%(\<no_\?\)\?rmstarsilent\>\)\|\%(\%(no_\?\)\?rm_star_silent\>\)\|
- \ \%(\%(\<no_\?\)\?rmstarwait\>\)\|\%(\%(no_\?\)\?rm_star_wait\>\)\|
- \ \%(\%(\<no_\?\)\?sharehistory\>\)\|\%(\%(no_\?\)\?share_history\>\)\|
- \ \%(\%(\<no_\?\)\?shfileexpansion\>\)\|\%(\%(no_\?\)\?sh_file_expansion\>\)\|
- \ \%(\%(\<no_\?\)\?shglob\>\)\|\%(\%(no_\?\)\?sh_glob\>\)\|
- \ \%(\%(\<no_\?\)\?shinstdin\>\)\|\%(\%(no_\?\)\?shin_stdin\>\)\|
- \ \%(\%(\<no_\?\)\?shnullcmd\>\)\|\%(\%(no_\?\)\?sh_nullcmd\>\)\|
- \ \%(\%(\<no_\?\)\?shoptionletters\>\)\|\%(\%(no_\?\)\?sh_option_letters\>\)\|
- \ \%(\%(\<no_\?\)\?shortloops\>\)\|\%(\%(no_\?\)\?short_loops\>\)\|
- \ \%(\%(\<no_\?\)\?shortrepeat\>\)\|\%(\%(no_\?\)\?short_repeat\>\)\|
- \ \%(\%(\<no_\?\)\?shwordsplit\>\)\|\%(\%(no_\?\)\?sh_word_split\>\)\|
- \ \%(\%(\<no_\?\)\?singlecommand\>\)\|\%(\%(no_\?\)\?single_command\>\)\|
- \ \%(\%(\<no_\?\)\?singlelinezle\>\)\|\%(\%(no_\?\)\?single_line_zle\>\)\|
- \ \%(\%(\<no_\?\)\?sourcetrace\>\)\|\%(\%(no_\?\)\?source_trace\>\)\|
- \ \%(\%(\<no_\?\)\?stdin\>\)\|
- \ \%(\%(\<no_\?\)\?sunkeyboardhack\>\)\|\%(\%(no_\?\)\?sun_keyboard_hack\>\)\|
- \ \%(\%(\<no_\?\)\?trackall\>\)\|\%(\%(no_\?\)\?track_all\>\)\|
- \ \%(\%(\<no_\?\)\?transientrprompt\>\)\|\%(\%(no_\?\)\?transient_rprompt\>\)\|
- \ \%(\%(\<no_\?\)\?trapsasync\>\)\|\%(\%(no_\?\)\?traps_async\>\)\|
- \ \%(\%(\<no_\?\)\?typesetsilent\>\)\|\%(\%(no_\?\)\?type_set_silent\>\)\|\%(\%(no_\?\)\?typeset_silent\>\)\|
- \ \%(\%(\<no_\?\)\?unset\>\)\|
- \ \%(\%(\<no_\?\)\?verbose\>\)\|
- \ \%(\%(\<no_\?\)\?vi\>\)\|
- \ \%(\%(\<no_\?\)\?warnnestedvar\>\)\|\%(\%(no_\?\)\?warn_nested_var\>\)\|
- \ \%(\%(\<no_\?\)\?warncreateglobal\>\)\|\%(\%(no_\?\)\?warn_create_global\>\)\|
- \ \%(\%(\<no_\?\)\?xtrace\>\)\|
- \ \%(\%(\<no_\?\)\?zle\>\)/ nextgroup=zshOption,zshComment skipwhite contained
-
+syn match zshOptStart
+ \ /\v^\s*%(%(un)?setopt|set\s+[-+]o)/
+ \ nextgroup=zshOption skipwhite
+syn match zshOption nextgroup=zshOption,zshComment skipwhite contained /\v
+ \ <%(no_?)?%(
+ \ auto_?cd|auto_?pushd|cdable_?vars|cd_?silent|chase_?dots|chase_?links|posix_?cd|pushd_?ignore_?dups|pushd_?minus|pushd_?silent|pushd_?to_?home|always_?last_?prompt|always_?to_?end|auto_?list|auto_?menu|auto_?name_?dirs|auto_?param_?keys|auto_?param_?slash|auto_?remove_?slash|bash_?auto_?list|complete_?aliases|complete_?in_?word|glob_?complete|hash_?list_?all|list_?ambiguous|list_?beep|list_?packed|list_?rows_?first|list_?types|menu_?complete|rec_?exact|bad_?pattern|bare_?glob_?qual|brace_?ccl|case_?glob|case_?match|case_?paths|csh_?null_?glob|equals|extended_?glob|force_?float|glob|glob_?assign|glob_?dots|glob_?star_?short|glob_?subst|hist_?subst_?pattern|ignore_?braces|ignore_?close_?braces|ksh_?glob|magic_?equal_?subst|mark_?dirs|multibyte|nomatch|null_?glob|numeric_?glob_?sort|rc_?expand_?param|rematch_?pcre|sh_?glob|unset|warn_?create_?global|warn_?nested_?var|warnnestedvar|append_?history|bang_?hist|extended_?history|hist_?allow_?clobber|hist_?beep|hist_?expire_?dups_?first|hist_?fcntl_?lock|hist_?find_?no_?dups|hist_?ignore_?all_?dups|hist_?ignore_?dups|hist_?ignore_?space|hist_?lex_?words|hist_?no_?functions|hist_?no_?store|hist_?reduce_?blanks|hist_?save_?by_?copy|hist_?save_?no_?dups|hist_?verify|inc_?append_?history|inc_?append_?history_?time|share_?history|all_?export|global_?export|global_?rcs|rcs|aliases|clobber|clobber_?empty|correct|correct_?all|dvorak|flow_?control|ignore_?eof|interactive_?comments|hash_?cmds|hash_?dirs|hash_?executables_?only|mail_?warning|path_?dirs|path_?script|print_?eight_?bit|print_?exit_?value|rc_?quotes|rm_?star_?silent|rm_?star_?wait|short_?loops|short_?repeat|sun_?keyboard_?hack|auto_?continue|auto_?resume|bg_?nice|check_?jobs|check_?running_?jobs|hup|long_?list_?jobs|monitor|notify|posix_?jobs|prompt_?bang|prompt_?cr|prompt_?sp|prompt_?percent|prompt_?subst|transient_?rprompt|alias_?func_?def|c_?bases|c_?precedences|debug_?before_?cmd|err_?exit|err_?return|eval_?lineno|exec|function_?argzero|local_?loops|local_?options|local_?patterns|local_?traps|multi_?func_?def|multios|octal_?zeroes|pipe_?fail|source_?trace|typeset_?silent|typeset_?to_?unset|verbose|xtrace|append_?create|bash_?rematch|bsd_?echo|continue_?on_?error|csh_?junkie_?history|csh_?junkie_?loops|csh_?junkie_?quotes|csh_?nullcmd|ksh_?arrays|ksh_?autoload|ksh_?option_?print|ksh_?typeset|ksh_?zero_?subscript|posix_?aliases|posix_?argzero|posix_?builtins|posix_?identifiers|posix_?strings|posix_?traps|sh_?file_?expansion|sh_?nullcmd|sh_?option_?letters|sh_?word_?split|traps_?async|interactive|login|privileged|restricted|shin_?stdin|single_?command|beep|combining_?chars|emacs|overstrike|single_?line_?zle|vi|zle|brace_?expand|dot_?glob|hash_?all|hist_?append|hist_?expand|log|mail_?warn|one_?cmd|physical|prompt_?vars|stdin|track_?all|no_?match
+ \)>/
syn case match
syn keyword zshTypes float integer local typeset declare private readonly
@@ -365,7 +164,7 @@ syn region zshGlob start='(#' end=')'
syn region zshMathSubst matchgroup=zshSubstDelim transparent
\ start='\%(\$\?\)[<=>]\@<!((' skip='\\)' end='))'
\ contains=zshParentheses,@zshSubst,zshNumber,
- \ @zshDerefs,zshString keepend fold
+ \ @zshDerefs,zshString fold
" The ms=s+1 prevents matching zshBrackets several times on opening brackets
" (see https://github.com/chrisbra/vim-zsh/issues/21#issuecomment-576330348)
syn region zshBrackets contained transparent start='{'ms=s+1 skip='\\}'
diff --git a/scripts/gen_filetype.lua b/scripts/gen_filetype.lua
new file mode 100644
index 0000000000..42478a1082
--- /dev/null
+++ b/scripts/gen_filetype.lua
@@ -0,0 +1,201 @@
+local do_not_run = true
+if do_not_run then
+ print([[
+ This script was used to bootstrap the filetype patterns in runtime/lua/vim/filetype.lua. It
+ should no longer be used except for testing purposes. New filetypes, or changes to existing
+ filetypes, should be ported manually as part of the vim-patch process.
+ ]])
+ return
+end
+
+local filetype_vim = "runtime/filetype.vim"
+local filetype_lua = "runtime/lua/vim/filetype.lua"
+
+local keywords = {
+ ["for"] = true,
+ ["or"] = true,
+ ["and"] = true,
+ ["end"] = true,
+ ["do"] = true,
+ ["if"] = true,
+ ["while"] = true,
+ ["repeat"] = true,
+}
+
+local sections = {
+ extension = { str = {}, func = {} },
+ filename = { str = {}, func = {} },
+ pattern = { str = {}, func = {} },
+}
+
+local specialchars = "%*%?\\%$%[%]%{%}"
+
+local function add_pattern(pat, ft)
+ local ok = true
+
+ -- Patterns that start or end with { or } confuse splitting on commas and make parsing harder, so just skip those
+ if not string.find(pat, "^%{") and not string.find(pat, "%}$") then
+ for part in string.gmatch(pat, "[^,]+") do
+ if not string.find(part, "[" .. specialchars .. "]") then
+ if type(ft) == "string" then
+ sections.filename.str[part] = ft
+ else
+ sections.filename.func[part] = ft
+ end
+ elseif string.match(part, "^%*%.[^%./" .. specialchars .. "]+$") then
+ if type(ft) == "string" then
+ sections.extension.str[part:sub(3)] = ft
+ else
+ sections.extension.func[part:sub(3)] = ft
+ end
+ else
+ if string.match(part, "^%*/[^" .. specialchars .. "]+$") then
+ -- For patterns matching */some/pattern we want to easily match files
+ -- with path /some/pattern, so include those in filename detection
+ if type(ft) == "string" then
+ sections.filename.str[part:sub(2)] = ft
+ else
+ sections.filename.func[part:sub(2)] = ft
+ end
+ end
+
+ if string.find(part, "^[%w-_.*?%[%]/]+$") then
+ local p = part:gsub("%.", "%%."):gsub("%*", ".*"):gsub("%?", ".")
+ -- Insert into array to maintain order rather than setting
+ -- key-value directly
+ if type(ft) == "string" then
+ sections.pattern.str[p] = ft
+ else
+ sections.pattern.func[p] = ft
+ end
+ else
+ ok = false
+ end
+ end
+ end
+ end
+
+ return ok
+end
+
+local function parse_line(line)
+ local pat, ft
+ pat, ft = line:match("^%s*au%a* Buf[%a,]+%s+(%S+)%s+setf%s+(%S+)")
+ if pat then
+ return add_pattern(pat, ft)
+ else
+ local func
+ pat, func = line:match("^%s*au%a* Buf[%a,]+%s+(%S+)%s+call%s+(%S+)")
+ if pat then
+ return add_pattern(pat, function() return func end)
+ end
+ end
+end
+
+local unparsed = {}
+local full_line
+for line in io.lines(filetype_vim) do
+ local cont = string.match(line, "^%s*\\%s*(.*)$")
+ if cont then
+ full_line = full_line .. " " .. cont
+ else
+ if full_line then
+ if not parse_line(full_line) and string.find(full_line, "^%s*au%a* Buf") then
+ table.insert(unparsed, full_line)
+ end
+ end
+ full_line = line
+ end
+end
+
+if #unparsed > 0 then
+ print("Failed to parse the following patterns:")
+ for _, v in ipairs(unparsed) do
+ print(v)
+ end
+end
+
+local function add_item(indent, key, ft)
+ if type(ft) == "string" then
+ if string.find(key, "%A") or keywords[key] then
+ key = string.format("[\"%s\"]", key)
+ end
+ return string.format([[%s%s = "%s",]], indent, key, ft)
+ elseif type(ft) == "function" then
+ local func = ft()
+ if string.find(key, "%A") or keywords[key] then
+ key = string.format("[\"%s\"]", key)
+ end
+ -- Right now only a single argument is supported, which covers
+ -- everything in filetype.vim as of this writing
+ local arg = string.match(func, "%((.*)%)$")
+ func = string.gsub(func, "%(.*$", "")
+ if arg == "" then
+ -- Function with no arguments, call the function directly
+ return string.format([[%s%s = function() vim.fn["%s"]() end,]], indent, key, func)
+ elseif string.match(arg, [[^(["']).*%1$]]) then
+ -- String argument
+ if func == "s:StarSetf" then
+ return string.format([[%s%s = starsetf(%s),]], indent, key, arg)
+ else
+ return string.format([[%s%s = function() vim.fn["%s"](%s) end,]], indent, key, func, arg)
+ end
+ elseif string.find(arg, "%(") then
+ -- Function argument
+ return string.format([[%s%s = function() vim.fn["%s"](vim.fn.%s) end,]], indent, key, func, arg)
+ else
+ assert(false, arg)
+ end
+ end
+end
+
+do
+ local lines = {}
+ local start = false
+ for line in io.lines(filetype_lua) do
+ if line:match("^%s+-- END [A-Z]+$") then
+ start = false
+ end
+
+ if not start then
+ table.insert(lines, line)
+ end
+
+ local indent, section = line:match("^(%s+)-- BEGIN ([A-Z]+)$")
+ if section then
+ start = true
+ local t = sections[string.lower(section)]
+
+ local sorted = {}
+ for k, v in pairs(t.str) do
+ table.insert(sorted, {[k] = v})
+ end
+
+ table.sort(sorted, function(a, b)
+ return a[next(a)] < b[next(b)]
+ end)
+
+ for _, v in ipairs(sorted) do
+ local k = next(v)
+ table.insert(lines, add_item(indent, k, v[k]))
+ end
+
+ sorted = {}
+ for k, v in pairs(t.func) do
+ table.insert(sorted, {[k] = v})
+ end
+
+ table.sort(sorted, function(a, b)
+ return next(a) < next(b)
+ end)
+
+ for _, v in ipairs(sorted) do
+ local k = next(v)
+ table.insert(lines, add_item(indent, k, v[k]))
+ end
+ end
+ end
+ local f = io.open(filetype_lua, "w")
+ f:write(table.concat(lines, "\n") .. "\n")
+ f:close()
+end
diff --git a/scripts/gen_vimdoc.py b/scripts/gen_vimdoc.py
index 89fc14121e..3e9fb21039 100755
--- a/scripts/gen_vimdoc.py
+++ b/scripts/gen_vimdoc.py
@@ -128,12 +128,16 @@ CONFIG = {
'shared.lua',
'uri.lua',
'ui.lua',
+ 'filetype.lua',
+ 'keymap.lua',
],
'files': ' '.join([
os.path.join(base_dir, 'src/nvim/lua/vim.lua'),
os.path.join(base_dir, 'runtime/lua/vim/shared.lua'),
os.path.join(base_dir, 'runtime/lua/vim/uri.lua'),
os.path.join(base_dir, 'runtime/lua/vim/ui.lua'),
+ os.path.join(base_dir, 'runtime/lua/vim/filetype.lua'),
+ os.path.join(base_dir, 'runtime/lua/vim/keymap.lua'),
]),
'file_patterns': '*.lua',
'fn_name_prefix': '',
@@ -148,6 +152,8 @@ CONFIG = {
'shared': 'vim',
'uri': 'vim',
'ui': 'vim.ui',
+ 'filetype': 'vim.filetype',
+ 'keymap': 'vim.keymap',
},
'append_only': [
'shared.lua',
diff --git a/scripts/squash_typos.py b/scripts/squash_typos.py
deleted file mode 100644
index b403a9b7c8..0000000000
--- a/scripts/squash_typos.py
+++ /dev/null
@@ -1,263 +0,0 @@
-#!/usr/bin/env python
-"""
-
-This script squashes a PR tagged with the "typo" label into a single, dedicated
-"squash PR".
-
-"""
-
-import subprocess
-import sys
-import os
-
-
-def get_authors_and_emails_from_pr():
- """
-
- Return all contributing authors and their emails for the PR on current branch.
- This includes co-authors, meaning that if two authors are credited for a
- single commit, which is possible with GitHub, then both will get credited.
-
- """
-
- # Get a list of all authors involved in the pull request (including co-authors).
- authors = subprocess.check_output(
- [
- "gh",
- "pr",
- "view",
- os.environ["PR_NUMBER"],
- "--json",
- "commits",
- "--jq",
- ".[][].authors.[].name",
- ],
- text=True,
- ).splitlines()
-
- # Get a list of emails of the aforementioned authors.
- emails = subprocess.check_output(
- [
- "gh",
- "pr",
- "view",
- os.environ["PR_NUMBER"],
- "--json",
- "commits",
- "--jq",
- ".[][].authors.[].email",
- ],
- text=True,
- ).splitlines()
-
- authors_and_emails = [(author, mail) for author, mail in zip(authors, emails)]
-
- return authors_and_emails
-
-
-def rebase_onto_pr():
- """
-
- Rebase current branch onto the PR.
-
- """
-
- # Check out the pull request.
- subprocess.call(["gh", "pr", "checkout", os.environ["PR_NUMBER"]])
-
- rebase_onto_master()
-
- # Change back to the original branch.
- subprocess.call(["git", "switch", "-"])
-
- # Rebase onto the pull request, aka include the commits in the pull request
- # in the current branch. Abort with error message if rebase fails.
-
- try:
- subprocess.check_call(["git", "rebase", "-"])
- except subprocess.CalledProcessError:
- subprocess.call(["git", "rebase", "--abort"])
- squash_url = subprocess.check_output(
- ["gh", "pr", "view", "--json", "url", "--jq", ".url"], text=True
- ).strip()
-
- subprocess.call(
- [
- "gh",
- "pr",
- "comment",
- os.environ["PR_NUMBER"],
- "--body",
- f"Your edit conflicts with an already scheduled fix \
- ({squash_url}). Please check that batch PR whether your fix is \
- already included; if not, then please wait until the batch PR \
- is merged and then rebase your PR on top of master.",
- ]
- )
-
- sys.exit(
- f"\n\nERROR: Your edit conflicts with an already scheduled fix \
-{squash_url} \n\n"
- )
-
-
-def rebase_onto_master():
- """
-
- Rebase current branch onto the master i.e. make sure current branch is up
- to date. Abort on error.
-
- """
-
- default_branch = f"{os.environ['GITHUB_BASE_REF']}"
- subprocess.check_call(["git", "rebase", default_branch])
-
-
-def squash_all_commits(message_body_before):
- """
-
- Squash all commits on the PR into a single commit. Credit all authors by
- name and email.
-
- """
-
- default_branch = f"{os.environ['GITHUB_BASE_REF']}"
- subprocess.call(["git", "reset", "--soft", default_branch])
-
- authors_and_emails = get_authors_and_emails_from_pr()
- commit_message_coauthors = (
- "\n"
- + "\n".join([f"Co-authored-by: {i[0]} <{i[1]}>" for i in authors_and_emails])
- + "\n"
- + message_body_before
- )
- subprocess.call(
- ["git", "commit", "-m", "chore: typo fixes", "-m", commit_message_coauthors]
- )
-
-
-def force_push(branch):
- """
-
- Like the name implies, force push <branch>.
-
- """
-
- gh_actor = os.environ["GITHUB_ACTOR"]
- gh_token = os.environ["GITHUB_TOKEN"]
- gh_repo = os.environ["GITHUB_REPOSITORY"]
- subprocess.call(
- [
- "git",
- "push",
- "--force",
- f"https://{gh_actor}:{gh_token}@github.com/{gh_repo}",
- branch,
- ]
- )
-
-
-def checkout_branch(branch):
- """
-
- Create and checkout <branch>. Check if branch exists on remote, if so then
- sync local branch to remote.
-
- Return True if remote branch exists, else False.
-
- """
-
- # FIXME I'm not sure why the local branch isn't tracking the remote branch
- # automatically. This works but I'm pretty sure it can be done in a more
- # "elegant" fashion
-
- show_ref_output = subprocess.check_output(["git", "show-ref"], text=True).strip()
-
- if branch in show_ref_output:
- subprocess.call(["git", "checkout", "-b", branch, f"origin/{branch}"])
- return True
-
- subprocess.call(["git", "checkout", "-b", branch])
- return False
-
-
-def get_all_pr_urls(pr_branch_exists):
- """
-
- Return a list of URLs for the pull requests with the typo fixes. If a
- squash branch exists then extract the URLs from the body text.
-
- """
-
- all_pr_urls = ""
- if pr_branch_exists:
- all_pr_urls += subprocess.check_output(
- ["gh", "pr", "view", "--json", "body", "--jq", ".body"], text=True
- )
-
- all_pr_urls += subprocess.check_output(
- ["gh", "pr", "view", os.environ["PR_NUMBER"], "--json", "url", "--jq", ".url"],
- text=True,
- ).strip()
-
- return all_pr_urls
-
-
-def main():
- pr_branch = "marvim/squash-typos"
-
- pr_branch_exists = checkout_branch(pr_branch)
-
- rebase_onto_master()
- force_push(pr_branch)
-
- message_body_before = "\n".join(
- subprocess.check_output(
- ["git", "log", "--format=%B", "-n1", pr_branch], text=True
- ).splitlines()[2:]
- )
-
- rebase_onto_pr()
- force_push(pr_branch)
-
- subprocess.call(
- [
- "gh",
- "pr",
- "create",
- "--fill",
- "--head",
- pr_branch,
- "--title",
- "chore: typo fixes (automated)",
- ],
- text=True,
- )
-
- squash_all_commits(message_body_before)
- force_push(pr_branch)
-
- all_pr_urls = get_all_pr_urls(pr_branch_exists)
- subprocess.call(["gh", "pr", "edit", "--add-label", "typo", "--body", all_pr_urls])
-
- subprocess.call(["gh", "pr", "close", os.environ["PR_NUMBER"]])
-
- squash_url = subprocess.check_output(
- ["gh", "pr", "view", "--json", "url", "--jq", ".url"], text=True
- ).strip()
- subprocess.call(
- [
- "gh",
- "pr",
- "comment",
- os.environ["PR_NUMBER"],
- "--body",
- f"Thank you for your contribution! We collect all typo fixes \
- into a single pull request and merge it once it gets big enough: \
- {squash_url}",
- ]
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/vim-patch.sh b/scripts/vim-patch.sh
index ac47f6aafd..1c265f0f40 100755
--- a/scripts/vim-patch.sh
+++ b/scripts/vim-patch.sh
@@ -266,8 +266,6 @@ get_vimpatch() {
msg_ok "Saved patch to '${NVIM_SOURCE_DIR}/${patch_file}'."
}
-# shellcheck disable=SC2015
-# ^ "Note that A && B || C is not if-then-else."
stage_patch() {
get_vimpatch "$1"
local try_apply="${2:-}"
@@ -282,23 +280,32 @@ stage_patch() {
echo " branch; not creating a new branch."
else
printf '\nFetching "%s/master".\n' "${nvim_remote}"
- output="$(git fetch "${nvim_remote}" master 2>&1)" &&
- msg_ok "${output}" ||
- (msg_err "${output}"; false)
+ if output="$(git fetch "$nvim_remote" master 2>&1)"; then
+ msg_ok "$output"
+ else
+ msg_err "$output"
+ exit 1
+ fi
local nvim_branch="${BRANCH_PREFIX}${vim_version}"
echo
echo "Creating new branch '${nvim_branch}' based on '${nvim_remote}/master'."
cd "${NVIM_SOURCE_DIR}"
- output="$(git checkout -b "${nvim_branch}" "${nvim_remote}/master" 2>&1)" &&
- msg_ok "${output}" ||
- (msg_err "${output}"; false)
+ if output="$(git checkout -b "$nvim_branch" "$nvim_remote/master" 2>&1)"; then
+ msg_ok "$output"
+ else
+ msg_err "$output"
+ exit 1
+ fi
fi
printf "\nCreating empty commit with correct commit message.\n"
- output="$(commit_message | git commit --allow-empty --file 2>&1 -)" &&
- msg_ok "${output}" ||
- (msg_err "${output}"; false)
+ if output="$(commit_message | git commit --allow-empty --file 2>&1 -)"; then
+ msg_ok "$output"
+ else
+ msg_err "$output"
+ exit 1
+ fi
local ret=0
if test -n "$try_apply" ; then
@@ -340,8 +347,6 @@ git_hub_pr() {
git hub pull new -m "${pr_message}"
}
-# shellcheck disable=SC2015
-# ^ "Note that A && B || C is not if-then-else."
submit_pr() {
require_executable git
local push_first
@@ -392,17 +397,23 @@ submit_pr() {
fi
fi
echo "Pushing to '${push_remote}/${checked_out_branch}'."
- output="$(git push "${push_remote}" "${checked_out_branch}" 2>&1)" &&
- msg_ok "${output}" ||
- (msg_err "${output}"; false)
+ if output="$(git push "$push_remote" "$checked_out_branch" 2>&1)"; then
+ msg_ok "$output"
+ else
+ msg_err "$output"
+ exit 1
+ fi
echo
fi
echo "Creating pull request."
- output="$(${submit_fn} "${pr_title}" "${pr_body}" 2>&1)" &&
- msg_ok "${output}" ||
- (msg_err "${output}"; false)
+ if output="$($submit_fn "$pr_title" "$pr_body" 2>&1)"; then
+ msg_ok "$output"
+ else
+ msg_err "$output"
+ exit 1
+ fi
echo
echo "Cleaning up files."
@@ -565,13 +576,13 @@ show_vimpatches() {
runtime_commits[$commit]=1
done
- list_missing_vimpatches 1 "$@" | while read -r vim_commit; do
+ while read -r vim_commit; do
if [[ "${runtime_commits[$vim_commit]-}" ]]; then
printf ' • %s (+runtime)\n' "${vim_commit}"
else
printf ' • %s\n' "${vim_commit}"
fi
- done
+ done <<< "$(list_missing_vimpatches 1 "$@")"
cat << EOF
@@ -692,14 +703,14 @@ review_commit() {
message_length="$(wc -l <<< "${expected_commit_message}")"
local commit_message
commit_message="$(tail -n +4 "${NVIM_SOURCE_DIR}/n${patch_file}" | head -n "${message_length}")"
- if [[ "${commit_message#${git_patch_prefix}}" == "${expected_commit_message}" ]]; then
+ if [[ "${commit_message#"$git_patch_prefix"}" == "${expected_commit_message}" ]]; then
msg_ok "Found expected commit message."
else
msg_err "Wrong commit message."
echo " Expected:"
echo "${expected_commit_message}"
echo " Actual:"
- echo "${commit_message#${git_patch_prefix}}"
+ echo "${commit_message#"$git_patch_prefix"}"
fi
get_vimpatch "${vim_version}"
diff --git a/src/mpack/lmpack.c b/src/mpack/lmpack.c
index 87acf46592..126f2f3824 100644
--- a/src/mpack/lmpack.c
+++ b/src/mpack/lmpack.c
@@ -595,6 +595,7 @@ static void lmpack_unparse_enter(mpack_parser_t *parser, mpack_node_t *node)
/* push the pair */
result = lua_next(L, -2);
assert(result); /* should not be here if the map was fully processed */
+ (void)result; /* ignore unused warning */
if (parent->key_visited) {
/* release the current key */
lmpack_unref(L, packer->reg, (int)parent->data[1].i);
@@ -1010,6 +1011,7 @@ static int lmpack_session_reply(lua_State *L)
"invalid request id");
result = mpack_rpc_reply(session->session, &b, &bl, (mpack_uint32_t)id);
assert(result == MPACK_OK);
+ (void)result; /* ignore unused warning */
lua_pushlstring(L, buf, sizeof(buf) - bl);
return 1;
}
@@ -1027,6 +1029,7 @@ static int lmpack_session_notify(lua_State *L)
session = lmpack_check_session(L, 1);
result = mpack_rpc_notify(session->session, &b, &bl);
assert(result == MPACK_OK);
+ (void)result; /* ignore unused warning */
lua_pushlstring(L, buf, sizeof(buf) - bl);
return 1;
}
diff --git a/src/nvim/CMakeLists.txt b/src/nvim/CMakeLists.txt
index bb16459a7f..94572b57cd 100644
--- a/src/nvim/CMakeLists.txt
+++ b/src/nvim/CMakeLists.txt
@@ -62,6 +62,7 @@ set(LUA_SHARED_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/shared.lua)
set(LUA_INSPECT_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/inspect.lua)
set(LUA_F_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/F.lua)
set(LUA_META_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/_meta.lua)
+set(LUA_FILETYPE_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/filetype.lua)
set(CHAR_BLOB_GENERATOR ${GENERATOR_DIR}/gen_char_blob.lua)
set(LINT_SUPPRESS_FILE ${PROJECT_BINARY_DIR}/errors.json)
set(LINT_SUPPRESS_URL_BASE "https://raw.githubusercontent.com/neovim/doc/gh-pages/reports/clint")
@@ -326,12 +327,15 @@ add_custom_command(
add_custom_command(
OUTPUT ${VIM_MODULE_FILE}
- COMMAND ${LUA_PRG} ${CHAR_BLOB_GENERATOR} ${VIM_MODULE_FILE}
+ COMMAND ${CMAKE_COMMAND} -E env
+ "LUAC_PRG=${LUAC_PRG}"
+ ${LUA_PRG} ${CHAR_BLOB_GENERATOR} -c ${VIM_MODULE_FILE}
${LUA_VIM_MODULE_SOURCE} vim_module
${LUA_SHARED_MODULE_SOURCE} shared_module
${LUA_INSPECT_MODULE_SOURCE} inspect_module
${LUA_F_MODULE_SOURCE} lua_F_module
${LUA_META_MODULE_SOURCE} lua_meta_module
+ ${LUA_FILETYPE_MODULE_SOURCE} lua_filetype_module
DEPENDS
${CHAR_BLOB_GENERATOR}
${LUA_VIM_MODULE_SOURCE}
@@ -339,6 +343,8 @@ add_custom_command(
${LUA_INSPECT_MODULE_SOURCE}
${LUA_F_MODULE_SOURCE}
${LUA_META_MODULE_SOURCE}
+ ${LUA_FILETYPE_MODULE_SOURCE}
+ VERBATIM
)
list(APPEND NVIM_GENERATED_SOURCES
diff --git a/src/nvim/api/buffer.c b/src/nvim/api/buffer.c
index 7988bff25a..2d5403d4b8 100644
--- a/src/nvim/api/buffer.c
+++ b/src/nvim/api/buffer.c
@@ -12,20 +12,16 @@
#include "nvim/api/buffer.h"
#include "nvim/api/private/defs.h"
#include "nvim/api/private/helpers.h"
+#include "nvim/autocmd.h"
#include "nvim/buffer.h"
#include "nvim/buffer_updates.h"
#include "nvim/change.h"
-#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/decoration.h"
#include "nvim/ex_cmds.h"
#include "nvim/ex_docmd.h"
#include "nvim/extmark.h"
-#include "nvim/fileio.h"
-#include "nvim/getchar.h"
#include "nvim/lua/executor.h"
-#include "nvim/map.h"
-#include "nvim/map_defs.h"
#include "nvim/mark.h"
#include "nvim/memline.h"
#include "nvim/memory.h"
@@ -839,7 +835,7 @@ Integer nvim_buf_get_changedtick(Buffer buffer, Error *err)
/// @param[out] err Error details, if any
/// @returns Array of maparg()-like dictionaries describing mappings.
/// The "buffer" key holds the associated buffer handle.
-ArrayOf(Dictionary) nvim_buf_get_keymap(Buffer buffer, String mode, Error *err)
+ArrayOf(Dictionary) nvim_buf_get_keymap(uint64_t channel_id, Buffer buffer, String mode, Error *err)
FUNC_API_SINCE(3)
{
buf_T *buf = find_buffer_by_handle(buffer, err);
@@ -848,7 +844,7 @@ ArrayOf(Dictionary) nvim_buf_get_keymap(Buffer buffer, String mode, Error *err)
return (Array)ARRAY_DICT_INIT;
}
- return keymap_array(mode, buf);
+ return keymap_array(mode, buf, channel_id == LUA_INTERNAL_CALL);
}
/// Sets a buffer-local |mapping| for the given mode.
@@ -1277,6 +1273,63 @@ Object nvim_buf_call(Buffer buffer, LuaRef fun, Error *err)
return res;
}
+/// Create a new user command |user-commands| in the given buffer.
+///
+/// @param buffer Buffer handle, or 0 for current buffer.
+/// @param[out] err Error details, if any.
+/// @see nvim_add_user_command
+void nvim_buf_add_user_command(Buffer buffer, String name, Object command,
+ Dict(user_command) *opts, Error *err)
+ FUNC_API_SINCE(9)
+{
+ buf_T *target_buf = find_buffer_by_handle(buffer, err);
+ if (ERROR_SET(err)) {
+ return;
+ }
+
+ buf_T *save_curbuf = curbuf;
+ curbuf = target_buf;
+ add_user_command(name, command, opts, UC_BUFFER, err);
+ curbuf = save_curbuf;
+}
+
+/// Delete a buffer-local user-defined command.
+///
+/// Only commands created with |:command-buffer| or
+/// |nvim_buf_add_user_command()| can be deleted with this function.
+///
+/// @param buffer Buffer handle, or 0 for current buffer.
+/// @param name Name of the command to delete.
+/// @param[out] err Error details, if any.
+void nvim_buf_del_user_command(Buffer buffer, String name, Error *err)
+ FUNC_API_SINCE(9)
+{
+ garray_T *gap;
+ if (buffer == -1) {
+ gap = &ucmds;
+ } else {
+ buf_T *buf = find_buffer_by_handle(buffer, err);
+ gap = &buf->b_ucmds;
+ }
+
+ for (int i = 0; i < gap->ga_len; i++) {
+ ucmd_T *cmd = USER_CMD_GA(gap, i);
+ if (!STRCMP(name.data, cmd->uc_name)) {
+ free_ucmd(cmd);
+
+ gap->ga_len -= 1;
+
+ if (i < gap->ga_len) {
+ memmove(cmd, cmd + 1, (size_t)(gap->ga_len - i) * sizeof(ucmd_T));
+ }
+
+ return;
+ }
+ }
+
+ api_set_error(err, kErrorTypeException, "No such user-defined command: %s", name.data);
+}
+
Dictionary nvim__buf_stats(Buffer buffer, Error *err)
{
Dictionary rv = ARRAY_DICT_INIT;
diff --git a/src/nvim/api/deprecated.c b/src/nvim/api/deprecated.c
index 76b699800e..18243fec2b 100644
--- a/src/nvim/api/deprecated.c
+++ b/src/nvim/api/deprecated.c
@@ -130,7 +130,7 @@ Integer nvim_buf_set_virtual_text(Buffer buffer, Integer src_id, Integer line, A
return 0;
}
- uint64_t ns_id = src2ns(&src_id);
+ uint32_t ns_id = src2ns(&src_id);
int width;
VirtText virt_text = parse_virt_text(chunks, err, &width);
@@ -148,11 +148,12 @@ Integer nvim_buf_set_virtual_text(Buffer buffer, Integer src_id, Integer line, A
return src_id;
}
- Decoration *decor = xcalloc(1, sizeof(*decor));
- decor->virt_text = virt_text;
- decor->virt_text_width = width;
+ Decoration decor = DECORATION_INIT;
+ decor.virt_text = virt_text;
+ decor.virt_text_width = width;
+ decor.priority = 0;
- extmark_set(buf, ns_id, NULL, (int)line, 0, -1, -1, decor, true,
+ extmark_set(buf, ns_id, NULL, (int)line, 0, -1, -1, &decor, true,
false, kExtmarkNoUndo);
return src_id;
}
diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c
index 742b953c2a..80bd88c4ee 100644
--- a/src/nvim/api/extmark.c
+++ b/src/nvim/api/extmark.c
@@ -85,12 +85,12 @@ const char *describe_ns(NS ns_id)
}
// Is the Namespace in use?
-static bool ns_initialized(uint64_t ns)
+static bool ns_initialized(uint32_t ns)
{
if (ns < 1) {
return false;
}
- return ns < (uint64_t)next_namespace_id;
+ return ns < (uint32_t)next_namespace_id;
}
@@ -111,17 +111,47 @@ static Array extmark_to_array(ExtmarkInfo extmark, bool id, bool add_dict)
PUT(dict, "end_col", INTEGER_OBJ(extmark.end_col));
}
- if (extmark.decor) {
- Decoration *decor = extmark.decor;
- if (decor->hl_id) {
- String name = cstr_to_string((const char *)syn_id2name(decor->hl_id));
- PUT(dict, "hl_group", STRING_OBJ(name));
+ Decoration *decor = &extmark.decor;
+ if (decor->hl_id) {
+ String name = cstr_to_string((const char *)syn_id2name(decor->hl_id));
+ PUT(dict, "hl_group", STRING_OBJ(name));
+ PUT(dict, "hl_eol", BOOLEAN_OBJ(decor->hl_eol));
+ }
+ if (decor->hl_mode) {
+ PUT(dict, "hl_mode", STRING_OBJ(cstr_to_string(hl_mode_str[decor->hl_mode])));
+ }
+
+ if (kv_size(decor->virt_text)) {
+ Array chunks = ARRAY_DICT_INIT;
+ for (size_t i = 0; i < decor->virt_text.size; i++) {
+ Array chunk = ARRAY_DICT_INIT;
+ VirtTextChunk *vtc = &decor->virt_text.items[i];
+ ADD(chunk, STRING_OBJ(cstr_to_string(vtc->text)));
+ if (vtc->hl_id > 0) {
+ ADD(chunk,
+ STRING_OBJ(cstr_to_string((const char *)syn_id2name(vtc->hl_id))));
+ }
+ ADD(chunks, ARRAY_OBJ(chunk));
+ }
+ PUT(dict, "virt_text", ARRAY_OBJ(chunks));
+ PUT(dict, "virt_text_hide", BOOLEAN_OBJ(decor->virt_text_hide));
+ if (decor->virt_text_pos == kVTWinCol) {
+ PUT(dict, "virt_text_win_col", INTEGER_OBJ(decor->col));
}
- if (kv_size(decor->virt_text)) {
+ PUT(dict, "virt_text_pos",
+ STRING_OBJ(cstr_to_string(virt_text_pos_str[decor->virt_text_pos])));
+ }
+
+ if (kv_size(decor->virt_lines)) {
+ Array all_chunks = ARRAY_DICT_INIT;
+ bool virt_lines_leftcol = false;
+ for (size_t i = 0; i < decor->virt_lines.size; i++) {
Array chunks = ARRAY_DICT_INIT;
- for (size_t i = 0; i < decor->virt_text.size; i++) {
+ VirtText *vt = &decor->virt_lines.items[i].line;
+ virt_lines_leftcol = decor->virt_lines.items[i].left_col;
+ for (size_t j = 0; j < vt->size; j++) {
Array chunk = ARRAY_DICT_INIT;
- VirtTextChunk *vtc = &decor->virt_text.items[i];
+ VirtTextChunk *vtc = &vt->items[j];
ADD(chunk, STRING_OBJ(cstr_to_string(vtc->text)));
if (vtc->hl_id > 0) {
ADD(chunk,
@@ -129,9 +159,14 @@ static Array extmark_to_array(ExtmarkInfo extmark, bool id, bool add_dict)
}
ADD(chunks, ARRAY_OBJ(chunk));
}
- PUT(dict, "virt_text", ARRAY_OBJ(chunks));
+ ADD(all_chunks, ARRAY_OBJ(chunks));
}
+ PUT(dict, "virt_lines", ARRAY_OBJ(all_chunks));
+ PUT(dict, "virt_lines_above", BOOLEAN_OBJ(decor->virt_lines_above));
+ PUT(dict, "virt_lines_leftcol", BOOLEAN_OBJ(virt_lines_leftcol));
+ }
+ if (decor->hl_id || kv_size(decor->virt_text)) {
PUT(dict, "priority", INTEGER_OBJ(decor->priority));
}
@@ -166,7 +201,7 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id,
return rv;
}
- if (!ns_initialized((uint64_t)ns_id)) {
+ if (!ns_initialized((uint32_t)ns_id)) {
api_set_error(err, kErrorTypeValidation, "Invalid ns_id");
return rv;
}
@@ -191,7 +226,7 @@ ArrayOf(Integer) nvim_buf_get_extmark_by_id(Buffer buffer, Integer ns_id,
}
- ExtmarkInfo extmark = extmark_from_id(buf, (uint64_t)ns_id, (uint64_t)id);
+ ExtmarkInfo extmark = extmark_from_id(buf, (uint32_t)ns_id, (uint32_t)id);
if (extmark.row < 0) {
return rv;
}
@@ -252,7 +287,7 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e
return rv;
}
- if (!ns_initialized((uint64_t)ns_id)) {
+ if (!ns_initialized((uint32_t)ns_id)) {
api_set_error(err, kErrorTypeValidation, "Invalid ns_id");
return rv;
}
@@ -310,7 +345,7 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e
}
- ExtmarkInfoArray marks = extmark_get(buf, (uint64_t)ns_id, l_row, l_col,
+ ExtmarkInfoArray marks = extmark_get(buf, (uint32_t)ns_id, l_row, l_col,
u_row, u_col, (int64_t)limit, reverse);
for (size_t i = 0; i < kv_size(marks); i++) {
@@ -404,6 +439,10 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e
/// for left). Defaults to false.
/// - priority: a priority value for the highlight group. For
/// example treesitter highlighting uses a value of 100.
+/// - strict: boolean that indicates extmark should not be placed
+/// if the line or column value is past the end of the
+/// buffer or end of the line respectively. Defaults to true.
+///
/// @param[out] err Error details, if any
/// @return Id of the created/updated extmark
Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer col,
@@ -417,14 +456,14 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
goto error;
}
- if (!ns_initialized((uint64_t)ns_id)) {
+ if (!ns_initialized((uint32_t)ns_id)) {
api_set_error(err, kErrorTypeValidation, "Invalid ns_id");
goto error;
}
- uint64_t id = 0;
+ uint32_t id = 0;
if (opts->id.type == kObjectTypeInteger && opts->id.data.integer > 0) {
- id = (uint64_t)opts->id.data.integer;
+ id = (uint32_t)opts->id.data.integer;
} else if (HAS_KEY(opts->id)) {
api_set_error(err, kErrorTypeValidation, "id is not a positive integer");
goto error;
@@ -441,9 +480,18 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
opts->end_row = opts->end_line;
}
+#define OPTION_TO_BOOL(target, name, val) \
+ target = api_object_to_bool(opts->name, #name, val, err); \
+ if (ERROR_SET(err)) { \
+ goto error; \
+ }
+
+ bool strict = true;
+ OPTION_TO_BOOL(strict, strict, true);
+
if (opts->end_row.type == kObjectTypeInteger) {
Integer val = opts->end_row.data.integer;
- if (val < 0 || val > buf->b_ml.ml_line_count) {
+ if (val < 0 || (val > buf->b_ml.ml_line_count && strict)) {
api_set_error(err, kErrorTypeValidation, "end_row value outside range");
goto error;
} else {
@@ -512,12 +560,6 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
goto error;
}
-#define OPTION_TO_BOOL(target, name, val) \
- target = api_object_to_bool(opts->name, #name, val, err); \
- if (ERROR_SET(err)) { \
- goto error; \
- }
-
OPTION_TO_BOOL(decor.virt_text_hide, virt_text_hide, false);
OPTION_TO_BOOL(decor.hl_eol, hl_eol, false);
@@ -596,16 +638,30 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
bool ephemeral = false;
OPTION_TO_BOOL(ephemeral, ephemeral, false);
- if (line < 0 || line > buf->b_ml.ml_line_count) {
+ if (line < 0) {
api_set_error(err, kErrorTypeValidation, "line value outside range");
goto error;
+ } else if (line > buf->b_ml.ml_line_count) {
+ if (strict) {
+ api_set_error(err, kErrorTypeValidation, "line value outside range");
+ goto error;
+ } else {
+ line = buf->b_ml.ml_line_count;
+ }
} else if (line < buf->b_ml.ml_line_count) {
len = ephemeral ? MAXCOL : STRLEN(ml_get_buf(buf, (linenr_T)line+1, false));
}
if (col == -1) {
col = (Integer)len;
- } else if (col < -1 || col > (Integer)len) {
+ } else if (col > (Integer)len) {
+ if (strict) {
+ api_set_error(err, kErrorTypeValidation, "col value outside range");
+ goto error;
+ } else {
+ col = (Integer)len;
+ }
+ } else if (col < -1) {
api_set_error(err, kErrorTypeValidation, "col value outside range");
goto error;
}
@@ -621,27 +677,17 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
line2 = (int)line;
}
if (col2 > (Integer)len) {
- api_set_error(err, kErrorTypeValidation, "end_col value outside range");
- goto error;
+ if (strict) {
+ api_set_error(err, kErrorTypeValidation, "end_col value outside range");
+ goto error;
+ } else {
+ col2 = (int)len;
+ }
}
} else if (line2 >= 0) {
col2 = 0;
}
- Decoration *d = NULL;
-
- if (ephemeral) {
- d = &decor;
- } else if (kv_size(decor.virt_text) || kv_size(decor.virt_lines)
- || decor.priority != DECOR_PRIORITY_BASE
- || decor.hl_eol) {
- // TODO(bfredl): this is a bit sketchy. eventually we should
- // have predefined decorations for both marks/ephemerals
- d = xcalloc(1, sizeof(*d));
- *d = decor;
- } else if (decor.hl_id) {
- d = decor_hl(decor.hl_id);
- }
// TODO(bfredl): synergize these two branches even more
if (ephemeral && decor_state.buf == buf) {
@@ -652,12 +698,8 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
goto error;
}
- extmark_set(buf, (uint64_t)ns_id, &id, (int)line, (colnr_T)col, line2, col2,
- d, right_gravity, end_right_gravity, kExtmarkNoUndo);
-
- if (kv_size(decor.virt_lines)) {
- redraw_buf_line_later(buf, MIN(buf->b_ml.ml_line_count, line+1+(decor.virt_lines_above?0:1)));
- }
+ extmark_set(buf, (uint32_t)ns_id, &id, (int)line, (colnr_T)col, line2, col2,
+ &decor, right_gravity, end_right_gravity, kExtmarkNoUndo);
}
return (Integer)id;
@@ -682,23 +724,23 @@ Boolean nvim_buf_del_extmark(Buffer buffer, Integer ns_id, Integer id, Error *er
if (!buf) {
return false;
}
- if (!ns_initialized((uint64_t)ns_id)) {
+ if (!ns_initialized((uint32_t)ns_id)) {
api_set_error(err, kErrorTypeValidation, "Invalid ns_id");
return false;
}
- return extmark_del(buf, (uint64_t)ns_id, (uint64_t)id);
+ return extmark_del(buf, (uint32_t)ns_id, (uint32_t)id);
}
-uint64_t src2ns(Integer *src_id)
+uint32_t src2ns(Integer *src_id)
{
if (*src_id == 0) {
*src_id = nvim_create_namespace((String)STRING_INIT);
}
if (*src_id < 0) {
- return UINT64_MAX;
+ return (((uint32_t)1) << 31) - 1;
} else {
- return (uint64_t)(*src_id);
+ return (uint32_t)(*src_id);
}
}
@@ -753,7 +795,7 @@ Integer nvim_buf_add_highlight(Buffer buffer, Integer ns_id, String hl_group, In
col_end = MAXCOL;
}
- uint64_t ns = src2ns(&ns_id);
+ uint32_t ns = src2ns(&ns_id);
if (!(line < buf->b_ml.ml_line_count)) {
// safety check, we can't add marks outside the range
@@ -773,10 +815,13 @@ Integer nvim_buf_add_highlight(Buffer buffer, Integer ns_id, String hl_group, In
end_line++;
}
+ Decoration decor = DECORATION_INIT;
+ decor.hl_id = hl_id;
+
extmark_set(buf, ns, NULL,
(int)line, (colnr_T)col_start,
end_line, (colnr_T)col_end,
- decor_hl(hl_id), true, false, kExtmarkNoUndo);
+ &decor, true, false, kExtmarkNoUndo);
return ns_id;
}
@@ -808,7 +853,7 @@ void nvim_buf_clear_namespace(Buffer buffer, Integer ns_id, Integer line_start,
if (line_end < 0 || line_end > MAXLNUM) {
line_end = MAXLNUM;
}
- extmark_clear(buf, (ns_id < 0 ? 0 : (uint64_t)ns_id),
+ extmark_clear(buf, (ns_id < 0 ? 0 : (uint32_t)ns_id),
(int)line_start, 0,
(int)line_end-1, MAXCOL);
}
diff --git a/src/nvim/api/keysets.lua b/src/nvim/api/keysets.lua
index f3e7f2f1dc..7d521bbf25 100644
--- a/src/nvim/api/keysets.lua
+++ b/src/nvim/api/keysets.lua
@@ -21,6 +21,7 @@ return {
"virt_lines";
"virt_lines_above";
"virt_lines_leftcol";
+ "strict";
};
keymap = {
"noremap";
@@ -29,10 +30,25 @@ return {
"script";
"expr";
"unique";
+ "callback";
+ "desc";
};
get_commands = {
"builtin";
};
+ user_command = {
+ "addr";
+ "bang";
+ "bar";
+ "complete";
+ "count";
+ "desc";
+ "force";
+ "keepscript";
+ "nargs";
+ "range";
+ "register";
+ };
float_config = {
"row";
"col";
diff --git a/src/nvim/api/private/converter.c b/src/nvim/api/private/converter.c
index 36da6c13a9..3d4ff202fe 100644
--- a/src/nvim/api/private/converter.c
+++ b/src/nvim/api/private/converter.c
@@ -10,6 +10,9 @@
#include "nvim/api/private/helpers.h"
#include "nvim/assert.h"
#include "nvim/eval/typval.h"
+#include "nvim/eval/userfunc.h"
+#include "nvim/lua/converter.h"
+#include "nvim/lua/executor.h"
/// Helper structure for vim_to_object
typedef struct {
@@ -228,6 +231,14 @@ static inline void typval_encode_dict_end(EncodedData *const edata)
/// @return The converted value
Object vim_to_object(typval_T *obj)
{
+ if (obj->v_type == VAR_FUNC) {
+ ufunc_T *fp = find_func(obj->vval.v_string);
+ assert(fp != NULL);
+ if (fp->uf_cb == nlua_CFunction_func_call) {
+ LuaRef ref = api_new_luaref(((LuaCFunctionState *)fp->uf_cb_state)->lua_callable.func_ref);
+ return LUAREF_OBJ(ref);
+ }
+ }
EncodedData edata;
kvi_init(edata.stack);
const int evo_ret = encode_vim_to_object(&edata, obj,
@@ -340,6 +351,16 @@ bool object_to_vim(Object obj, typval_T *tv, Error *err)
tv->vval.v_dict = dict;
break;
}
+
+ case kObjectTypeLuaRef: {
+ LuaCFunctionState *state = xmalloc(sizeof(LuaCFunctionState));
+ state->lua_callable.func_ref = api_new_luaref(obj.data.luaref);
+ char_u *name = register_cfunc(&nlua_CFunction_func_call, &nlua_CFunction_func_free, state);
+ tv->v_type = VAR_FUNC;
+ tv->vval.v_string = vim_strsave(name);
+ break;
+ }
+
default:
abort();
}
diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c
index 9b407eab8b..f540f8f7ee 100644
--- a/src/nvim/api/private/helpers.c
+++ b/src/nvim/api/private/helpers.c
@@ -594,6 +594,7 @@ Array string_to_array(const String input, bool crlf)
void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String rhs,
Dict(keymap) *opts, Error *err)
{
+ LuaRef lua_funcref = LUA_NOREF;
bool global = (buffer == -1);
if (global) {
buffer = 0;
@@ -604,6 +605,10 @@ void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String
return;
}
+ if (opts != NULL && opts->callback.type == kObjectTypeLuaRef) {
+ lua_funcref = opts->callback.data.luaref;
+ opts->callback.data.luaref = LUA_NOREF;
+ }
MapArguments parsed_args = MAP_ARGUMENTS_INIT;
if (opts) {
#define KEY_TO_BOOL(name) \
@@ -623,9 +628,13 @@ void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String
parsed_args.buffer = !global;
set_maparg_lhs_rhs((char_u *)lhs.data, lhs.size,
- (char_u *)rhs.data, rhs.size,
+ (char_u *)rhs.data, rhs.size, lua_funcref,
CPO_TO_CPO_FLAGS, &parsed_args);
-
+ if (opts != NULL && opts->desc.type == kObjectTypeString) {
+ parsed_args.desc = xstrdup(opts->desc.data.string.data);
+ } else {
+ parsed_args.desc = NULL;
+ }
if (parsed_args.lhs_len > MAXMAPLEN) {
api_set_error(err, kErrorTypeValidation, "LHS exceeds maximum map length: %s", lhs.data);
goto fail_and_free;
@@ -658,7 +667,8 @@ void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String
bool is_noremap = parsed_args.noremap;
assert(!(is_unmap && is_noremap));
- if (!is_unmap && (parsed_args.rhs_len == 0 && !parsed_args.rhs_is_noop)) {
+ if (!is_unmap && lua_funcref == LUA_NOREF
+ && (parsed_args.rhs_len == 0 && !parsed_args.rhs_is_noop)) {
if (rhs.size == 0) { // assume that the user wants RHS to be a <Nop>
parsed_args.rhs_is_noop = true;
} else {
@@ -668,9 +678,13 @@ void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String
api_set_error(err, kErrorTypeValidation, "Parsing of nonempty RHS failed: %s", rhs.data);
goto fail_and_free;
}
- } else if (is_unmap && parsed_args.rhs_len) {
- api_set_error(err, kErrorTypeValidation,
- "Gave nonempty RHS in unmap command: %s", parsed_args.rhs);
+ } else if (is_unmap && (parsed_args.rhs_len || parsed_args.rhs_lua != LUA_NOREF)) {
+ if (parsed_args.rhs_len) {
+ api_set_error(err, kErrorTypeValidation,
+ "Gave nonempty RHS in unmap command: %s", parsed_args.rhs);
+ } else {
+ api_set_error(err, kErrorTypeValidation, "Gave nonempty RHS for unmap");
+ }
goto fail_and_free;
}
@@ -700,9 +714,12 @@ void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String
goto fail_and_free;
} // switch
+ parsed_args.rhs_lua = LUA_NOREF; // don't clear ref on success
fail_and_free:
+ NLUA_CLEAR_REF(parsed_args.rhs_lua);
xfree(parsed_args.rhs);
xfree(parsed_args.orig_rhs);
+ XFREE_CLEAR(parsed_args.desc);
return;
}
@@ -961,6 +978,10 @@ Object copy_object(Object obj)
case kObjectTypeDictionary:
return DICTIONARY_OBJ(copy_dictionary(obj.data.dictionary));
+
+ case kObjectTypeLuaRef:
+ return LUAREF_OBJ(api_new_luaref(obj.data.luaref));
+
default:
abort();
}
@@ -1048,8 +1069,9 @@ void api_set_error(Error *err, ErrorType errType, const char *format, ...)
///
/// @param mode The abbreviation for the mode
/// @param buf The buffer to get the mapping array. NULL for global
+/// @param from_lua Whether it is called from internal lua api.
/// @returns Array of maparg()-like dictionaries describing mappings
-ArrayOf(Dictionary) keymap_array(String mode, buf_T *buf)
+ArrayOf(Dictionary) keymap_array(String mode, buf_T *buf, bool from_lua)
{
Array mappings = ARRAY_DICT_INIT;
dict_T *const dict = tv_dict_alloc();
@@ -1069,8 +1091,19 @@ ArrayOf(Dictionary) keymap_array(String mode, buf_T *buf)
// Check for correct mode
if (int_mode & current_maphash->m_mode) {
mapblock_fill_dict(dict, current_maphash, buffer_value, false);
- ADD(mappings, vim_to_object((typval_T[]) { { .v_type = VAR_DICT, .vval.v_dict = dict } }));
-
+ Object api_dict = vim_to_object((typval_T[]) { { .v_type = VAR_DICT,
+ .vval.v_dict = dict } });
+ if (from_lua) {
+ Dictionary d = api_dict.data.dictionary;
+ for (size_t j = 0; j < d.size; j++) {
+ if (strequal("callback", d.items[j].key.data)) {
+ d.items[j].value.type = kObjectTypeLuaRef;
+ d.items[j].value.data.luaref = api_new_luaref((LuaRef)d.items[j].value.data.integer);
+ break;
+ }
+ }
+ }
+ ADD(mappings, api_dict);
tv_dict_clear(dict);
}
}
@@ -1108,7 +1141,7 @@ bool extmark_get_index_from_obj(buf_T *buf, Integer ns_id, Object obj, int
return false;
}
- ExtmarkInfo extmark = extmark_from_id(buf, (uint64_t)ns_id, (uint64_t)id);
+ ExtmarkInfo extmark = extmark_from_id(buf, (uint32_t)ns_id, (uint32_t)id);
if (extmark.row >= 0) {
*row = extmark.row;
*col = extmark.col;
@@ -1342,3 +1375,195 @@ const char *get_default_stl_hl(win_T *wp)
return "StatusLineNC";
}
}
+
+void add_user_command(String name, Object command, Dict(user_command) *opts, int flags, Error *err)
+{
+ uint32_t argt = 0;
+ long def = -1;
+ cmd_addr_T addr_type_arg = ADDR_NONE;
+ int compl = EXPAND_NOTHING;
+ char *compl_arg = NULL;
+ char *rep = NULL;
+ LuaRef luaref = LUA_NOREF;
+ LuaRef compl_luaref = LUA_NOREF;
+
+ if (mb_islower(name.data[0])) {
+ api_set_error(err, kErrorTypeValidation, "'name' must begin with an uppercase letter");
+ goto err;
+ }
+
+ if (HAS_KEY(opts->range) && HAS_KEY(opts->count)) {
+ api_set_error(err, kErrorTypeValidation, "'range' and 'count' are mutually exclusive");
+ goto err;
+ }
+
+ if (opts->nargs.type == kObjectTypeInteger) {
+ switch (opts->nargs.data.integer) {
+ case 0:
+ // Default value, nothing to do
+ break;
+ case 1:
+ argt |= EX_EXTRA | EX_NOSPC | EX_NEEDARG;
+ break;
+ default:
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'nargs'");
+ goto err;
+ }
+ } else if (opts->nargs.type == kObjectTypeString) {
+ if (opts->nargs.data.string.size > 1) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'nargs'");
+ goto err;
+ }
+
+ switch (opts->nargs.data.string.data[0]) {
+ case '*':
+ argt |= EX_EXTRA;
+ break;
+ case '?':
+ argt |= EX_EXTRA | EX_NOSPC;
+ break;
+ case '+':
+ argt |= EX_EXTRA | EX_NEEDARG;
+ break;
+ default:
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'nargs'");
+ goto err;
+ }
+ } else if (HAS_KEY(opts->nargs)) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'nargs'");
+ goto err;
+ }
+
+ if (HAS_KEY(opts->complete) && !argt) {
+ api_set_error(err, kErrorTypeValidation, "'complete' used without 'nargs'");
+ goto err;
+ }
+
+ if (opts->range.type == kObjectTypeBoolean) {
+ if (opts->range.data.boolean) {
+ argt |= EX_RANGE;
+ addr_type_arg = ADDR_LINES;
+ }
+ } else if (opts->range.type == kObjectTypeString) {
+ if (opts->range.data.string.data[0] == '%' && opts->range.data.string.size == 1) {
+ argt |= EX_RANGE | EX_DFLALL;
+ addr_type_arg = ADDR_LINES;
+ } else {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'range'");
+ goto err;
+ }
+ } else if (opts->range.type == kObjectTypeInteger) {
+ argt |= EX_RANGE | EX_ZEROR;
+ def = opts->range.data.integer;
+ addr_type_arg = ADDR_LINES;
+ } else if (HAS_KEY(opts->range)) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'range'");
+ goto err;
+ }
+
+ if (opts->count.type == kObjectTypeBoolean) {
+ if (opts->count.data.boolean) {
+ argt |= EX_COUNT | EX_ZEROR | EX_RANGE;
+ addr_type_arg = ADDR_OTHER;
+ def = 0;
+ }
+ } else if (opts->count.type == kObjectTypeInteger) {
+ argt |= EX_COUNT | EX_ZEROR | EX_RANGE;
+ addr_type_arg = ADDR_OTHER;
+ def = opts->count.data.integer;
+ } else if (HAS_KEY(opts->count)) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'count'");
+ goto err;
+ }
+
+ if (opts->addr.type == kObjectTypeString) {
+ if (parse_addr_type_arg((char_u *)opts->addr.data.string.data, (int)opts->addr.data.string.size,
+ &addr_type_arg) != OK) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'addr'");
+ goto err;
+ }
+
+ if (addr_type_arg != ADDR_LINES) {
+ argt |= EX_ZEROR;
+ }
+ } else if (HAS_KEY(opts->addr)) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'addr'");
+ goto err;
+ }
+
+ if (api_object_to_bool(opts->bang, "bang", false, err)) {
+ argt |= EX_BANG;
+ } else if (ERROR_SET(err)) {
+ goto err;
+ }
+
+ if (api_object_to_bool(opts->bar, "bar", false, err)) {
+ argt |= EX_TRLBAR;
+ } else if (ERROR_SET(err)) {
+ goto err;
+ }
+
+
+ if (api_object_to_bool(opts->register_, "register", false, err)) {
+ argt |= EX_REGSTR;
+ } else if (ERROR_SET(err)) {
+ goto err;
+ }
+
+ if (api_object_to_bool(opts->keepscript, "keepscript", false, err)) {
+ argt |= EX_KEEPSCRIPT;
+ } else if (ERROR_SET(err)) {
+ goto err;
+ }
+
+ bool force = api_object_to_bool(opts->force, "force", true, err);
+ if (ERROR_SET(err)) {
+ goto err;
+ }
+
+ if (opts->complete.type == kObjectTypeLuaRef) {
+ compl = EXPAND_USER_LUA;
+ compl_luaref = api_new_luaref(opts->complete.data.luaref);
+ } else if (opts->complete.type == kObjectTypeString) {
+ if (parse_compl_arg((char_u *)opts->complete.data.string.data,
+ (int)opts->complete.data.string.size, &compl, &argt,
+ (char_u **)&compl_arg) != OK) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'complete'");
+ goto err;
+ }
+ } else if (HAS_KEY(opts->complete)) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'complete'");
+ goto err;
+ }
+
+ switch (command.type) {
+ case kObjectTypeLuaRef:
+ luaref = api_new_luaref(command.data.luaref);
+ if (opts->desc.type == kObjectTypeString) {
+ rep = opts->desc.data.string.data;
+ } else {
+ snprintf((char *)IObuff, IOSIZE, "<Lua function %d>", luaref);
+ rep = (char *)IObuff;
+ }
+ break;
+ case kObjectTypeString:
+ rep = command.data.string.data;
+ break;
+ default:
+ api_set_error(err, kErrorTypeValidation, "'command' must be a string or Lua function");
+ goto err;
+ }
+
+ if (uc_add_command((char_u *)name.data, name.size, (char_u *)rep, argt, def, flags,
+ compl, (char_u *)compl_arg, compl_luaref, addr_type_arg, luaref,
+ force) != OK) {
+ api_set_error(err, kErrorTypeException, "Failed to create user command");
+ goto err;
+ }
+
+ return;
+
+err:
+ NLUA_CLEAR_REF(luaref);
+ NLUA_CLEAR_REF(compl_luaref);
+}
diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c
index 4f7c320129..7c194935ce 100644
--- a/src/nvim/api/vim.c
+++ b/src/nvim/api/vim.c
@@ -169,7 +169,7 @@ void nvim__set_hl_ns(Integer ns_id, Error *err)
// event path for redraws caused by "fast" events. This could tie in with
// better throttling of async events causing redraws, such as non-batched
// nvim_buf_set_extmark calls from async contexts.
- if (!provider_active && !ns_hl_changed) {
+ if (!provider_active && !ns_hl_changed && must_redraw < NOT_VALID) {
multiqueue_put(main_loop.events, on_redraw_event, 0);
}
ns_hl_changed = true;
@@ -187,21 +187,23 @@ static void on_redraw_event(void **argv)
/// On execution error: does not fail, but updates v:errmsg.
///
/// To input sequences like <C-o> use |nvim_replace_termcodes()| (typically
-/// with escape_csi=true) to replace |keycodes|, then pass the result to
+/// with escape_ks=false) to replace |keycodes|, then pass the result to
/// nvim_feedkeys().
///
/// Example:
/// <pre>
/// :let key = nvim_replace_termcodes("<C-o>", v:true, v:false, v:true)
-/// :call nvim_feedkeys(key, 'n', v:true)
+/// :call nvim_feedkeys(key, 'n', v:false)
/// </pre>
///
/// @param keys to be typed
/// @param mode behavior flags, see |feedkeys()|
-/// @param escape_csi If true, escape K_SPECIAL/CSI bytes in `keys`
+/// @param escape_ks If true, escape K_SPECIAL bytes in `keys`
+/// This should be false if you already used
+/// |nvim_replace_termcodes()|, and true otherwise.
/// @see feedkeys()
-/// @see vim_strsave_escape_csi
-void nvim_feedkeys(String keys, String mode, Boolean escape_csi)
+/// @see vim_strsave_escape_ks
+void nvim_feedkeys(String keys, String mode, Boolean escape_ks)
FUNC_API_SINCE(1)
{
bool remap = true;
@@ -232,10 +234,10 @@ void nvim_feedkeys(String keys, String mode, Boolean escape_csi)
}
char *keys_esc;
- if (escape_csi) {
- // Need to escape K_SPECIAL and CSI before putting the string in the
+ if (escape_ks) {
+ // Need to escape K_SPECIAL before putting the string in the
// typeahead buffer.
- keys_esc = (char *)vim_strsave_escape_csi((char_u *)keys.data);
+ keys_esc = (char *)vim_strsave_escape_ks((char_u *)keys.data);
} else {
keys_esc = keys.data;
}
@@ -245,7 +247,7 @@ void nvim_feedkeys(String keys, String mode, Boolean escape_csi)
typebuf_was_filled = true;
}
- if (escape_csi) {
+ if (escape_ks) {
xfree(keys_esc);
}
@@ -383,7 +385,7 @@ error:
/// @param str String to be converted.
/// @param from_part Legacy Vim parameter. Usually true.
/// @param do_lt Also translate <lt>. Ignored if `special` is false.
-/// @param special Replace |keycodes|, e.g. <CR> becomes a "\n" char.
+/// @param special Replace |keycodes|, e.g. <CR> becomes a "\r" char.
/// @see replace_termcodes
/// @see cpoptions
String nvim_replace_termcodes(String str, Boolean from_part, Boolean do_lt, Boolean special)
@@ -662,7 +664,7 @@ Object nvim_get_option(String name, Error *err)
///
/// @param name Option name
/// @param opts Optional parameters
-/// - scope: One of 'global' or 'local'. Analagous to
+/// - scope: One of 'global' or 'local'. Analogous to
/// |:setglobal| and |:setlocal|, respectively.
/// @param[out] err Error details, if any
/// @return Option value
@@ -696,7 +698,17 @@ Object nvim_get_option_value(String name, Dict(option) *opts, Error *err)
rv = INTEGER_OBJ(numval);
break;
case 2:
- rv = BOOLEAN_OBJ(!!numval);
+ switch (numval) {
+ case 0:
+ case 1:
+ rv = BOOLEAN_OBJ(numval);
+ break;
+ default:
+ // Boolean options that return something other than 0 or 1 should return nil. Currently this
+ // only applies to 'autoread' which uses -1 as a local value to indicate "unset"
+ rv = NIL;
+ break;
+ }
break;
default:
api_set_error(err, kErrorTypeValidation, "unknown option '%s'", name.data);
@@ -714,7 +726,7 @@ end:
/// @param name Option name
/// @param value New option value
/// @param opts Optional parameters
-/// - scope: One of 'global' or 'local'. Analagous to
+/// - scope: One of 'global' or 'local'. Analogous to
/// |:setglobal| and |:setlocal|, respectively.
/// @param[out] err Error details, if any
void nvim_set_option_value(String name, Object value, Dict(option) *opts, Error *err)
@@ -749,7 +761,7 @@ void nvim_set_option_value(String name, Object value, Dict(option) *opts, Error
stringval = value.data.string.data;
break;
case kObjectTypeNil:
- // Do nothing
+ scope |= OPT_CLEAR;
break;
default:
api_set_error(err, kErrorTypeValidation, "invalid value for option");
@@ -1153,7 +1165,7 @@ static void term_close(void *data)
/// Send data to channel `id`. For a job, it writes it to the
/// stdin of the process. For the stdio channel |channel-stdio|,
/// it writes to Nvim's stdout. For an internal terminal instance
-/// (|nvim_open_term()|) it writes directly to terimal output.
+/// (|nvim_open_term()|) it writes directly to terminal output.
/// See |channel-bytes| for more information.
///
/// This function writes raw data, not RPC messages. If the channel
@@ -1528,10 +1540,10 @@ Dictionary nvim_get_mode(void)
/// @param mode Mode short-name ("n", "i", "v", ...)
/// @returns Array of maparg()-like dictionaries describing mappings.
/// The "buffer" key is always zero.
-ArrayOf(Dictionary) nvim_get_keymap(String mode)
+ArrayOf(Dictionary) nvim_get_keymap(uint64_t channel_id, String mode)
FUNC_API_SINCE(3)
{
- return keymap_array(mode, NULL);
+ return keymap_array(mode, NULL, channel_id == LUA_INTERNAL_CALL);
}
/// Sets a global |mapping| for the given mode.
@@ -1556,7 +1568,10 @@ ArrayOf(Dictionary) nvim_get_keymap(String mode)
/// @param lhs Left-hand-side |{lhs}| of the mapping.
/// @param rhs Right-hand-side |{rhs}| of the mapping.
/// @param opts Optional parameters map. Accepts all |:map-arguments|
-/// as keys excluding |<buffer>| but including |noremap|.
+/// as keys excluding |<buffer>| but including |noremap| and "desc".
+/// |desc| can be used to give a description to keymap.
+/// When called from Lua, also accepts a "callback" key that takes
+/// a Lua function to call when the mapping is executed.
/// Values are Booleans. Unknown key is an error.
/// @param[out] err Error details, if any.
void nvim_set_keymap(String mode, String lhs, String rhs, Dict(keymap) *opts, Error *err)
@@ -1731,7 +1746,7 @@ Array nvim_list_chans(void)
/// 1. To perform several requests from an async context atomically, i.e.
/// without interleaving redraws, RPC requests from other clients, or user
/// interactions (however API methods may trigger autocommands or event
-/// processing which have such side-effects, e.g. |:sleep| may wake timers).
+/// processing which have such side effects, e.g. |:sleep| may wake timers).
/// 2. To minimize RPC overhead (roundtrips) of a sequence of many requests.
///
/// @param channel_id
@@ -2091,7 +2106,7 @@ void nvim__screenshot(String path)
}
-/// Deletes a uppercase/file named mark. See |mark-motions|.
+/// Deletes an uppercase/file named mark. See |mark-motions|.
///
/// @note fails with error if a lowercase or buffer local named mark is used.
/// @param name Mark name
@@ -2268,6 +2283,11 @@ Dictionary nvim_eval_statusline(String str, Dict(eval_statusline) *opts, Error *
fillchar = ' ';
} else {
wp = find_window_by_handle(window, err);
+
+ if (wp == NULL) {
+ api_set_error(err, kErrorTypeException, "unknown winid %d", window);
+ return result;
+ }
ewp = wp;
if (fillchar == 0) {
@@ -2353,3 +2373,53 @@ Dictionary nvim_eval_statusline(String str, Dict(eval_statusline) *opts, Error *
return result;
}
+
+/// Create a new user command |user-commands|
+///
+/// {name} is the name of the new command. The name must begin with an uppercase letter.
+///
+/// {command} is the replacement text or Lua function to execute.
+///
+/// Example:
+/// <pre>
+/// :call nvim_add_user_command('SayHello', 'echo "Hello world!"', {})
+/// :SayHello
+/// Hello world!
+/// </pre>
+///
+/// @param name Name of the new user command. Must begin with an uppercase letter.
+/// @param command Replacement command to execute when this user command is executed. When called
+/// from Lua, the command can also be a Lua function. The function is called with a
+/// single table argument that contains the following keys:
+/// - args: (string) The args passed to the command, if any |<args>|
+/// - bang: (boolean) "true" if the command was executed with a ! modifier |<bang>|
+/// - line1: (number) The starting line of the command range |<line1>|
+/// - line2: (number) The final line of the command range |<line2>|
+/// - range: (number) The number of items in the command range: 0, 1, or 2 |<range>|
+/// - count: (number) Any count supplied |<count>|
+/// - reg: (string) The optional register, if specified |<reg>|
+/// - mods: (string) Command modifiers, if any |<mods>|
+/// @param opts Optional command attributes. See |command-attributes| for more details. To use
+/// boolean attributes (such as |:command-bang| or |:command-bar|) set the value to
+/// "true". In addition to the string options listed in |:command-complete|, the
+/// "complete" key also accepts a Lua function which works like the "customlist"
+/// completion mode |:command-completion-customlist|. Additional parameters:
+/// - desc: (string) Used for listing the command when a Lua function is used for
+/// {command}.
+/// - force: (boolean, default true) Override any previous definition.
+/// @param[out] err Error details, if any.
+void nvim_add_user_command(String name, Object command, Dict(user_command) *opts, Error *err)
+ FUNC_API_SINCE(9)
+{
+ add_user_command(name, command, opts, 0, err);
+}
+
+/// Delete a user-defined command.
+///
+/// @param name Name of the command to delete.
+/// @param[out] err Error details, if any.
+void nvim_del_user_command(String name, Error *err)
+ FUNC_API_SINCE(9)
+{
+ nvim_buf_del_user_command(-1, name, err);
+}
diff --git a/src/nvim/api/window.c b/src/nvim/api/window.c
index 6e68c057dc..907306da7b 100644
--- a/src/nvim/api/window.c
+++ b/src/nvim/api/window.c
@@ -39,7 +39,7 @@ Buffer nvim_win_get_buf(Window window, Error *err)
return win->w_buffer->handle;
}
-/// Sets the current buffer in a window, without side-effects
+/// Sets the current buffer in a window, without side effects
///
/// @param window Window handle, or 0 for current window
/// @param buffer Buffer handle
diff --git a/src/nvim/auevents.lua b/src/nvim/auevents.lua
index 6227b08b26..8fe623fc96 100644
--- a/src/nvim/auevents.lua
+++ b/src/nvim/auevents.lua
@@ -75,6 +75,8 @@ return {
'QuickFixCmdPost', -- after :make, :grep etc.
'QuickFixCmdPre', -- before :make, :grep etc.
'QuitPre', -- before :quit
+ 'RecordingEnter', -- when starting to record a macro
+ 'RecordingLeave', -- just before a macro stops recording
'RemoteReply', -- upon string reception from a remote vim
'SearchWrapped', -- after the search wrapped around
'SessionLoadPost', -- after loading a session file
@@ -131,6 +133,8 @@ return {
BufModifiedSet=true,
DiagnosticChanged=true,
DirChanged=true,
+ RecordingEnter=true,
+ RecordingLeave=true,
Signal=true,
TabClosed=true,
TabNew=true,
diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c
index 3780cad1d6..463bd5e0e6 100644
--- a/src/nvim/autocmd.c
+++ b/src/nvim/autocmd.c
@@ -932,6 +932,12 @@ static int do_autocmd_event(event_T event, char_u *pat, bool once, int nested, c
last_mode = get_mode();
}
+ // If the event is CursorMoved, update the last cursor position
+ // position to avoid immediately triggering the autocommand
+ if (event == EVENT_CURSORMOVED && !has_event(EVENT_CURSORMOVED)) {
+ curwin->w_last_cursormoved = curwin->w_cursor;
+ }
+
ap->cmds = NULL;
*prev_ap = ap;
last_autopat[(int)event] = ap;
diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c
index 89baea83f8..0248d42f58 100644
--- a/src/nvim/buffer.c
+++ b/src/nvim/buffer.c
@@ -4351,7 +4351,7 @@ int build_stl_str_hl(win_T *wp, char_u *out, size_t outlen, char_u *fmt, int use
// Only free the string buffer if we allocated it.
// Note: This is not needed if `str` is pointing at `tmp`
if (opt == STL_VIM_EXPR) {
- xfree(str);
+ XFREE_CLEAR(str);
}
if (num >= 0 || (!itemisflag && str && *str)) {
@@ -4576,7 +4576,7 @@ int build_stl_str_hl(win_T *wp, char_u *out, size_t outlen, char_u *fmt, int use
cur_tab_rec->def.func = NULL;
}
- // When inside update_screen we do not want redrawing a stausline, ruler,
+ // When inside update_screen we do not want redrawing a statusline, ruler,
// title, etc. to trigger another redraw, it may cause an endless loop.
if (updating_screen) {
must_redraw = save_must_redraw;
diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h
index 49e527e98b..bba53b415a 100644
--- a/src/nvim/buffer_defs.h
+++ b/src/nvim/buffer_defs.h
@@ -352,6 +352,7 @@ struct mapblock {
char_u *m_keys; // mapped from, lhs
char_u *m_str; // mapped to, rhs
char_u *m_orig_str; // rhs as entered by the user
+ LuaRef m_luaref; // lua function reference as rhs
int m_keylen; // strlen(m_keys)
int m_mode; // valid mode
int m_noremap; // if non-zero no re-mapping for m_str
@@ -359,6 +360,7 @@ struct mapblock {
char m_nowait; // <nowait> used
char m_expr; // <expr> used, m_str is an expression
sctx_T m_script_ctx; // SCTX where map was defined
+ char *m_desc; // description of keymap
};
/// Used for highlighting in the status line.
@@ -864,8 +866,7 @@ struct file_buffer {
int b_mapped_ctrl_c; // modes where CTRL-C is mapped
MarkTree b_marktree[1];
- Map(uint64_t, ExtmarkItem) b_extmark_index[1];
- Map(uint64_t, ExtmarkNs) b_extmark_ns[1]; // extmark namespaces
+ Map(uint32_t, uint32_t) b_extmark_ns[1]; // extmark namespaces
size_t b_virt_line_blocks; // number of virt_line blocks
// array of channel_id:s which have asked to receive updates for this
diff --git a/src/nvim/decoration.c b/src/nvim/decoration.c
index c0f3c32f93..935b233752 100644
--- a/src/nvim/decoration.c
+++ b/src/nvim/decoration.c
@@ -13,8 +13,6 @@
# include "decoration.c.generated.h"
#endif
-static PMap(uint64_t) hl_decors;
-
/// Add highlighting to a buffer, bounded by two cursor positions,
/// with an offset.
///
@@ -33,9 +31,9 @@ void bufhl_add_hl_pos_offset(buf_T *buf, int src_id, int hl_id, lpos_T pos_start
{
colnr_T hl_start = 0;
colnr_T hl_end = 0;
- Decoration *decor = decor_hl(hl_id);
+ Decoration decor = DECORATION_INIT;
+ decor.hl_id = hl_id;
- decor->priority = DECOR_PRIORITY_BASE;
// TODO(bfredl): if decoration had blocky mode, we could avoid this loop
for (linenr_T lnum = pos_start.lnum; lnum <= pos_end.lnum; lnum++) {
int end_off = 0;
@@ -59,40 +57,23 @@ void bufhl_add_hl_pos_offset(buf_T *buf, int src_id, int hl_id, lpos_T pos_start
hl_start = pos_start.col + offset;
hl_end = pos_end.col + offset;
}
- (void)extmark_set(buf, (uint64_t)src_id, NULL,
- (int)lnum-1, hl_start, (int)lnum-1+end_off, hl_end,
- decor, true, false, kExtmarkNoUndo);
- }
-}
-
-Decoration *decor_hl(int hl_id)
-{
- assert(hl_id > 0);
- Decoration **dp = (Decoration **)pmap_ref(uint64_t)(&hl_decors,
- (uint64_t)hl_id, true);
- if (*dp) {
- return *dp;
+ extmark_set(buf, (uint32_t)src_id, NULL,
+ (int)lnum-1, hl_start, (int)lnum-1+end_off, hl_end,
+ &decor, true, false, kExtmarkNoUndo);
}
-
- Decoration *decor = xcalloc(1, sizeof(*decor));
- decor->hl_id = hl_id;
- decor->shared = true;
- decor->priority = DECOR_PRIORITY_BASE;
- *dp = decor;
- return decor;
}
void decor_redraw(buf_T *buf, int row1, int row2, Decoration *decor)
{
- if (decor->hl_id && row2 >= row1) {
+ if ((!decor || decor->hl_id) && row2 >= row1) {
redraw_buf_range_later(buf, row1+1, row2+1);
}
- if (kv_size(decor->virt_text)) {
+ if (decor && kv_size(decor->virt_text)) {
redraw_buf_line_later(buf, row1+1);
}
- if (kv_size(decor->virt_lines)) {
+ if (decor && kv_size(decor->virt_lines)) {
redraw_buf_line_later(buf, MIN(buf->b_ml.ml_line_count,
row1+1+(decor->virt_lines_above?0:1)));
}
@@ -100,17 +81,17 @@ void decor_redraw(buf_T *buf, int row1, int row2, Decoration *decor)
void decor_remove(buf_T *buf, int row, int row2, Decoration *decor)
{
- if (kv_size(decor->virt_lines)) {
+ decor_redraw(buf, row, row2, decor);
+ if (decor && kv_size(decor->virt_lines)) {
assert(buf->b_virt_line_blocks > 0);
buf->b_virt_line_blocks--;
}
- decor_redraw(buf, row, row2, decor);
decor_free(decor);
}
void decor_free(Decoration *decor)
{
- if (decor && !decor->shared) {
+ if (decor) {
clear_virttext(&decor->virt_text);
for (size_t i = 0; i < kv_size(decor->virt_lines); i++) {
clear_virttext(&kv_A(decor->virt_lines, i).line);
@@ -134,17 +115,16 @@ Decoration *decor_find_virttext(buf_T *buf, int row, uint64_t ns_id)
MarkTreeIter itr[1] = { 0 };
marktree_itr_get(buf->b_marktree, row, 0, itr);
while (true) {
- mtmark_t mark = marktree_itr_current(itr);
- if (mark.row < 0 || mark.row > row) {
+ mtkey_t mark = marktree_itr_current(itr);
+ if (mark.pos.row < 0 || mark.pos.row > row) {
break;
- } else if (marktree_decor_level(mark.id) < kDecorLevelVisible) {
+ } else if (marktree_decor_level(mark) < kDecorLevelVisible) {
goto next_mark;
}
- ExtmarkItem *item = map_ref(uint64_t, ExtmarkItem)(buf->b_extmark_index,
- mark.id, false);
- if (item && (ns_id == 0 || ns_id == item->ns_id)
- && item->decor && kv_size(item->decor->virt_text)) {
- return item->decor;
+ Decoration *decor = mark.decor_full;
+ if ((ns_id == 0 || ns_id == mark.ns)
+ && decor && kv_size(decor->virt_text)) {
+ return decor;
}
next_mark:
marktree_itr_next(buf->b_marktree, itr);
@@ -163,7 +143,20 @@ bool decor_redraw_reset(buf_T *buf, DecorState *state)
}
}
kv_size(state->active) = 0;
- return map_size(buf->b_extmark_index);
+ return buf->b_marktree->n_keys;
+}
+
+Decoration get_decor(mtkey_t mark)
+{
+ if (mark.decor_full) {
+ return *mark.decor_full;
+ } else {
+ Decoration fake = DECORATION_INIT;
+ fake.hl_id = mark.hl_id;
+ fake.priority = mark.priority;
+ fake.hl_eol = (mark.flags & MT_FLAG_HL_EOL);
+ return fake;
+ }
}
@@ -176,42 +169,35 @@ bool decor_redraw_start(buf_T *buf, int top_row, DecorState *state)
}
marktree_itr_rewind(buf->b_marktree, state->itr);
while (true) {
- mtmark_t mark = marktree_itr_current(state->itr);
- if (mark.row < 0) { // || mark.row > end_row
+ mtkey_t mark = marktree_itr_current(state->itr);
+ if (mark.pos.row < 0) { // || mark.row > end_row
break;
}
- if ((mark.row < top_row && mark.id&MARKTREE_END_FLAG)
- || marktree_decor_level(mark.id) < kDecorLevelVisible) {
+ if ((mark.pos.row < top_row && mt_end(mark))
+ || marktree_decor_level(mark) < kDecorLevelVisible) {
goto next_mark;
}
- uint64_t start_id = mark.id & ~MARKTREE_END_FLAG;
- ExtmarkItem *item = map_ref(uint64_t, ExtmarkItem)(buf->b_extmark_index,
- start_id, false);
- if (!item || !item->decor) {
- goto next_mark;
- }
- Decoration *decor = item->decor;
+ Decoration decor = get_decor(mark);
- mtpos_t altpos = marktree_lookup(buf->b_marktree,
- mark.id^MARKTREE_END_FLAG, NULL);
+ mtpos_t altpos = marktree_get_altpos(buf->b_marktree, mark, NULL);
- if ((!(mark.id&MARKTREE_END_FLAG) && altpos.row < top_row
- && !kv_size(decor->virt_text))
- || ((mark.id&MARKTREE_END_FLAG) && altpos.row >= top_row)) {
+ if ((!mt_end(mark) && altpos.row < top_row
+ && !kv_size(decor.virt_text))
+ || (mt_end(mark) && altpos.row >= top_row)) {
goto next_mark;
}
- if (mark.id&MARKTREE_END_FLAG) {
- decor_add(state, altpos.row, altpos.col, mark.row, mark.col,
- decor, false);
+ if (mt_end(mark)) {
+ decor_add(state, altpos.row, altpos.col, mark.pos.row, mark.pos.col,
+ &decor, false);
} else {
if (altpos.row == -1) {
- altpos.row = mark.row;
- altpos.col = mark.col;
+ altpos.row = mark.pos.row;
+ altpos.col = mark.pos.col;
}
- decor_add(state, mark.row, mark.col, altpos.row, altpos.col,
- decor, false);
+ decor_add(state, mark.pos.row, mark.pos.col, altpos.row, altpos.col,
+ &decor, false);
}
next_mark:
@@ -266,43 +252,36 @@ int decor_redraw_col(buf_T *buf, int col, int win_col, bool hidden, DecorState *
while (true) {
// TODO(bfredl): check duplicate entry in "intersection"
// branch
- mtmark_t mark = marktree_itr_current(state->itr);
- if (mark.row < 0 || mark.row > state->row) {
+ mtkey_t mark = marktree_itr_current(state->itr);
+ if (mark.pos.row < 0 || mark.pos.row > state->row) {
break;
- } else if (mark.row == state->row && mark.col > col) {
- state->col_until = mark.col-1;
+ } else if (mark.pos.row == state->row && mark.pos.col > col) {
+ state->col_until = mark.pos.col-1;
break;
}
- if ((mark.id&MARKTREE_END_FLAG)
- || marktree_decor_level(mark.id) < kDecorLevelVisible) {
+ if (mt_end(mark)
+ || marktree_decor_level(mark) < kDecorLevelVisible) {
goto next_mark;
}
- ExtmarkItem *item = map_ref(uint64_t, ExtmarkItem)(buf->b_extmark_index,
- mark.id, false);
- if (!item || !item->decor) {
- goto next_mark;
- }
- Decoration *decor = item->decor;
+ Decoration decor = get_decor(mark);
- mtpos_t endpos = marktree_lookup(buf->b_marktree,
- mark.id|MARKTREE_END_FLAG, NULL);
+ mtpos_t endpos = marktree_get_altpos(buf->b_marktree, mark, NULL);
if (endpos.row == -1) {
- endpos.row = mark.row;
- endpos.col = mark.col;
+ endpos = mark.pos;
}
- if (endpos.row < mark.row
- || (endpos.row == mark.row && endpos.col <= mark.col)) {
- if (!kv_size(decor->virt_text)) {
+ if (endpos.row < mark.pos.row
+ || (endpos.row == mark.pos.row && endpos.col <= mark.pos.col)) {
+ if (!kv_size(decor.virt_text)) {
goto next_mark;
}
}
- decor_add(state, mark.row, mark.col, endpos.row, endpos.col,
- decor, false);
+ decor_add(state, mark.pos.row, mark.pos.col, endpos.row, endpos.col,
+ &decor, false);
next_mark:
marktree_itr_next(buf->b_marktree, state->itr);
@@ -452,18 +431,18 @@ int decor_virt_lines(win_T *wp, linenr_T lnum, VirtLines *lines)
MarkTreeIter itr[1] = { 0 };
marktree_itr_get(buf->b_marktree, row, 0, itr);
while (true) {
- mtmark_t mark = marktree_itr_current(itr);
- if (mark.row < 0 || mark.row >= end_row) {
+ mtkey_t mark = marktree_itr_current(itr);
+ if (mark.pos.row < 0 || mark.pos.row >= end_row) {
break;
- } else if (marktree_decor_level(mark.id) < kDecorLevelVirtLine) {
+ } else if (marktree_decor_level(mark) < kDecorLevelVirtLine) {
goto next_mark;
}
- bool above = mark.row > (int)(lnum - 2);
- ExtmarkItem *item = map_ref(uint64_t, ExtmarkItem)(buf->b_extmark_index, mark.id, false);
- if (item && item->decor && item->decor->virt_lines_above == above) {
- virt_lines += (int)kv_size(item->decor->virt_lines);
+ bool above = mark.pos.row > (int)(lnum - 2);
+ Decoration *decor = mark.decor_full;
+ if (decor && decor->virt_lines_above == above) {
+ virt_lines += (int)kv_size(decor->virt_lines);
if (lines) {
- kv_splice(*lines, item->decor->virt_lines);
+ kv_splice(*lines, decor->virt_lines);
}
}
next_mark:
diff --git a/src/nvim/decoration.h b/src/nvim/decoration.h
index 611b4223da..02472d09e4 100644
--- a/src/nvim/decoration.h
+++ b/src/nvim/decoration.h
@@ -17,6 +17,8 @@ typedef enum {
kVTRightAlign,
} VirtTextPos;
+EXTERN const char *const virt_text_pos_str[] INIT(= { "eol", "overlay", "win_col", "right_align" });
+
typedef enum {
kHlModeUnknown,
kHlModeReplace,
@@ -24,6 +26,8 @@ typedef enum {
kHlModeBlend,
} HlMode;
+EXTERN const char *const hl_mode_str[] INIT(= { "", "replace", "combine", "blend" });
+
typedef kvec_t(VirtTextChunk) VirtText;
#define VIRTTEXT_EMPTY ((VirtText)KV_INITIAL_VALUE)
@@ -42,7 +46,6 @@ struct Decoration {
// TODO(bfredl): at some point turn this into FLAGS
bool virt_text_hide;
bool hl_eol;
- bool shared; // shared decoration, don't free
bool virt_lines_above;
// TODO(bfredl): style, signs, etc
DecorPriority priority;
@@ -50,7 +53,7 @@ struct Decoration {
int virt_text_width; // width of virt_text
};
#define DECORATION_INIT { KV_INITIAL_VALUE, KV_INITIAL_VALUE, 0, kVTEndOfLine, kHlModeUnknown, \
- false, false, false, false, DECOR_PRIORITY_BASE, 0, 0 }
+ false, false, false, DECOR_PRIORITY_BASE, 0, 0 }
typedef struct {
int start_row;
diff --git a/src/nvim/diff.c b/src/nvim/diff.c
index 0233b3a5ab..340fec230c 100644
--- a/src/nvim/diff.c
+++ b/src/nvim/diff.c
@@ -37,8 +37,8 @@
#include "nvim/path.h"
#include "nvim/screen.h"
#include "nvim/strings.h"
-#include "nvim/undo.h"
#include "nvim/ui.h"
+#include "nvim/undo.h"
#include "nvim/vim.h"
#include "nvim/window.h"
#include "xdiff/xdiff.h"
@@ -82,6 +82,14 @@ typedef struct {
garray_T dout_ga; // used for internal diff
} diffout_T;
+// used for recording hunks from xdiff
+typedef struct {
+ linenr_T lnum_orig;
+ long count_orig;
+ linenr_T lnum_new;
+ long count_new;
+} diffhunk_T;
+
// two diff inputs and one result
typedef struct {
diffin_T dio_orig; // original file input
@@ -674,11 +682,11 @@ void diff_redraw(bool dofold)
}
if (wp_other != NULL && curwin->w_p_scb) {
if (used_max_fill_curwin) {
- // The current window was set to used the maximum number of filler
+ // The current window was set to use the maximum number of filler
// lines, may need to reduce them.
diff_set_topline(wp_other, curwin);
} else if (used_max_fill_other) {
- // The other window was set to used the maximum number of filler
+ // The other window was set to use the maximum number of filler
// lines, may need to reduce them.
diff_set_topline(curwin, wp_other);
}
@@ -852,7 +860,7 @@ static void diff_try_update(diffio_T *dio, int idx_orig, exarg_T *eap)
}
// Read the diff output and add each entry to the diff list.
- diff_read(idx_orig, idx_new, &dio->dio_diff);
+ diff_read(idx_orig, idx_new, dio);
clear_diffin(&dio->dio_new);
clear_diffout(&dio->dio_diff);
@@ -1078,7 +1086,7 @@ static int diff_file_internal(diffio_T *diffio)
emit_cfg.ctxlen = 0; // don't need any diff_context here
emit_cb.priv = &diffio->dio_diff;
- emit_cb.out_line = xdiff_out;
+ emit_cfg.hunk_func = xdiff_out;
if (xdl_diff(&diffio->dio_orig.din_mmfile,
&diffio->dio_new.din_mmfile,
&param, &emit_cfg, &emit_cb) < 0) {
@@ -1508,7 +1516,7 @@ void ex_diffoff(exarg_T *eap)
diff_clear(curtab);
}
- // Remove "hor" from from 'scrollopt' if there are no diff windows left.
+ // Remove "hor" from 'scrollopt' if there are no diff windows left.
if (!diffwin && (vim_strchr(p_sbo, 'h') != NULL)) {
do_cmdline_cmd("set sbo-=hor");
}
@@ -1519,20 +1527,20 @@ void ex_diffoff(exarg_T *eap)
/// @param idx_orig idx of original file
/// @param idx_new idx of new file
/// @dout diff output
-static void diff_read(int idx_orig, int idx_new, diffout_T *dout)
+static void diff_read(int idx_orig, int idx_new, diffio_T *dio)
{
FILE *fd = NULL;
int line_idx = 0;
diff_T *dprev = NULL;
diff_T *dp = curtab->tp_first_diff;
diff_T *dn, *dpl;
+ diffout_T *dout = &dio->dio_diff;
char_u linebuf[LBUFLEN]; // only need to hold the diff line
char_u *line;
long off;
int i;
- linenr_T lnum_orig, lnum_new;
- long count_orig, count_new;
int notset = true; // block "*dp" not set yet
+ diffhunk_T *hunk;
enum {
DIFF_ED,
DIFF_UNIFIED,
@@ -1549,70 +1557,79 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout)
}
}
+ if (!dio->dio_internal) {
+ hunk = xmalloc(sizeof(*hunk));
+ }
+
for (;;) {
- if (fd == NULL) {
+ if (dio->dio_internal) {
if (line_idx >= dout->dout_ga.ga_len) {
break; // did last line
}
- line = ((char_u **)dout->dout_ga.ga_data)[line_idx++];
+ hunk = ((diffhunk_T **)dout->dout_ga.ga_data)[line_idx++];
} else {
- if (vim_fgets(linebuf, LBUFLEN, fd)) {
- break; // end of file
- }
- line = linebuf;
- }
-
- if (diffstyle == DIFF_NONE) {
- // Determine diff style.
- // ed like diff looks like this:
- // {first}[,{last}]c{first}[,{last}]
- // {first}a{first}[,{last}]
- // {first}[,{last}]d{first}
- //
- // unified diff looks like this:
- // --- file1 2018-03-20 13:23:35.783153140 +0100
- // +++ file2 2018-03-20 13:23:41.183156066 +0100
- // @@ -1,3 +1,5 @@
- if (isdigit(*line)) {
- diffstyle = DIFF_ED;
- } else if ((STRNCMP(line, "@@ ", 3) == 0)) {
- diffstyle = DIFF_UNIFIED;
- } else if ((STRNCMP(line, "--- ", 4) == 0) // -V501
- && (vim_fgets(linebuf, LBUFLEN, fd) == 0) // -V501
- && (STRNCMP(line, "+++ ", 4) == 0)
- && (vim_fgets(linebuf, LBUFLEN, fd) == 0) // -V501
- && (STRNCMP(line, "@@ ", 3) == 0)) {
- diffstyle = DIFF_UNIFIED;
+ if (fd == NULL) {
+ if (line_idx >= dout->dout_ga.ga_len) {
+ break; // did last line
+ }
+ line = ((char_u **)dout->dout_ga.ga_data)[line_idx++];
} else {
- // Format not recognized yet, skip over this line. Cygwin diff
- // may put a warning at the start of the file.
- continue;
+ if (vim_fgets(linebuf, LBUFLEN, fd)) {
+ break; // end of file
+ }
+ line = linebuf;
}
- }
- if (diffstyle == DIFF_ED) {
- if (!isdigit(*line)) {
- continue; // not the start of a diff block
- }
- if (parse_diff_ed(line, &lnum_orig, &count_orig,
- &lnum_new, &count_new) == FAIL) {
- continue;
- }
- } else {
- assert(diffstyle == DIFF_UNIFIED);
- if (STRNCMP(line, "@@ ", 3) != 0) {
- continue; // not the start of a diff block
+ if (diffstyle == DIFF_NONE) {
+ // Determine diff style.
+ // ed like diff looks like this:
+ // {first}[,{last}]c{first}[,{last}]
+ // {first}a{first}[,{last}]
+ // {first}[,{last}]d{first}
+ //
+ // unified diff looks like this:
+ // --- file1 2018-03-20 13:23:35.783153140 +0100
+ // +++ file2 2018-03-20 13:23:41.183156066 +0100
+ // @@ -1,3 +1,5 @@
+ if (isdigit(*line)) {
+ diffstyle = DIFF_ED;
+ } else if ((STRNCMP(line, "@@ ", 3) == 0)) {
+ diffstyle = DIFF_UNIFIED;
+ } else if ((STRNCMP(line, "--- ", 4) == 0) // -V501
+ && (vim_fgets(linebuf, LBUFLEN, fd) == 0) // -V501
+ && (STRNCMP(line, "+++ ", 4) == 0)
+ && (vim_fgets(linebuf, LBUFLEN, fd) == 0) // -V501
+ && (STRNCMP(line, "@@ ", 3) == 0)) {
+ diffstyle = DIFF_UNIFIED;
+ } else {
+ // Format not recognized yet, skip over this line. Cygwin diff
+ // may put a warning at the start of the file.
+ continue;
+ }
}
- if (parse_diff_unified(line, &lnum_orig, &count_orig,
- &lnum_new, &count_new) == FAIL) {
- continue;
+
+ if (diffstyle == DIFF_ED) {
+ if (!isdigit(*line)) {
+ continue; // not the start of a diff block
+ }
+ if (parse_diff_ed(line, hunk) == FAIL) {
+ continue;
+ }
+ } else {
+ assert(diffstyle == DIFF_UNIFIED);
+ if (STRNCMP(line, "@@ ", 3) != 0) {
+ continue; // not the start of a diff block
+ }
+ if (parse_diff_unified(line, hunk) == FAIL) {
+ continue;
+ }
}
}
// Go over blocks before the change, for which orig and new are equal.
// Copy blocks from orig to new.
while (dp != NULL
- && lnum_orig > dp->df_lnum[idx_orig] + dp->df_count[idx_orig]) {
+ && hunk->lnum_orig > dp->df_lnum[idx_orig] + dp->df_count[idx_orig]) {
if (notset) {
diff_copy_entry(dprev, dp, idx_orig, idx_new);
}
@@ -1622,19 +1639,19 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout)
}
if ((dp != NULL)
- && (lnum_orig <= dp->df_lnum[idx_orig] + dp->df_count[idx_orig])
- && (lnum_orig + count_orig >= dp->df_lnum[idx_orig])) {
+ && (hunk->lnum_orig <= dp->df_lnum[idx_orig] + dp->df_count[idx_orig])
+ && (hunk->lnum_orig + hunk->count_orig >= dp->df_lnum[idx_orig])) {
// New block overlaps with existing block(s).
// First find last block that overlaps.
for (dpl = dp; dpl->df_next != NULL; dpl = dpl->df_next) {
- if (lnum_orig + count_orig < dpl->df_next->df_lnum[idx_orig]) {
+ if (hunk->lnum_orig + hunk->count_orig < dpl->df_next->df_lnum[idx_orig]) {
break;
}
}
// If the newly found block starts before the old one, set the
// start back a number of lines.
- off = dp->df_lnum[idx_orig] - lnum_orig;
+ off = dp->df_lnum[idx_orig] - hunk->lnum_orig;
if (off > 0) {
for (i = idx_orig; i < idx_new; ++i) {
@@ -1642,15 +1659,15 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout)
dp->df_lnum[i] -= off;
}
}
- dp->df_lnum[idx_new] = lnum_new;
- dp->df_count[idx_new] = count_new;
+ dp->df_lnum[idx_new] = hunk->lnum_new;
+ dp->df_count[idx_new] = hunk->count_new;
} else if (notset) {
// new block inside existing one, adjust new block
- dp->df_lnum[idx_new] = lnum_new + off;
- dp->df_count[idx_new] = count_new - off;
+ dp->df_lnum[idx_new] = hunk->lnum_new + off;
+ dp->df_count[idx_new] = hunk->count_new - off;
} else {
// second overlap of new block with existing block
- dp->df_count[idx_new] += count_new - count_orig
+ dp->df_count[idx_new] += hunk->count_new - hunk->count_orig
+ dpl->df_lnum[idx_orig] +
dpl->df_count[idx_orig]
- (dp->df_lnum[idx_orig] +
@@ -1659,7 +1676,7 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout)
// Adjust the size of the block to include all the lines to the
// end of the existing block or the new diff, whatever ends last.
- off = (lnum_orig + count_orig)
+ off = (hunk->lnum_orig + hunk->count_orig)
- (dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]);
if (off < 0) {
@@ -1691,10 +1708,10 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout)
// Allocate a new diffblock.
dp = diff_alloc_new(curtab, dprev, dp);
- dp->df_lnum[idx_orig] = lnum_orig;
- dp->df_count[idx_orig] = count_orig;
- dp->df_lnum[idx_new] = lnum_new;
- dp->df_count[idx_new] = count_new;
+ dp->df_lnum[idx_orig] = hunk->lnum_orig;
+ dp->df_count[idx_orig] = hunk->count_orig;
+ dp->df_lnum[idx_new] = hunk->lnum_new;
+ dp->df_count[idx_new] = hunk->count_new;
// Set values for other buffers, these must be equal to the
// original buffer, otherwise there would have been a change
@@ -1718,6 +1735,10 @@ static void diff_read(int idx_orig, int idx_new, diffout_T *dout)
notset = true;
}
+ if (!dio->dio_internal) {
+ xfree(hunk);
+ }
+
if (fd != NULL) {
fclose(fd);
}
@@ -3026,8 +3047,7 @@ linenr_T diff_lnum_win(linenr_T lnum, win_T *wp)
/// Handle an ED style diff line.
/// Return FAIL if the line does not contain diff info.
///
-static int parse_diff_ed(char_u *line, linenr_T *lnum_orig, long *count_orig, linenr_T *lnum_new,
- long *count_new)
+static int parse_diff_ed(char_u *line, diffhunk_T *hunk)
{
char_u *p;
long f1, l1, f2, l2;
@@ -3061,18 +3081,18 @@ static int parse_diff_ed(char_u *line, linenr_T *lnum_orig, long *count_orig, li
}
if (difftype == 'a') {
- *lnum_orig = f1 + 1;
- *count_orig = 0;
+ hunk->lnum_orig = f1 + 1;
+ hunk->count_orig = 0;
} else {
- *lnum_orig = f1;
- *count_orig = l1 - f1 + 1;
+ hunk->lnum_orig = f1;
+ hunk->count_orig = l1 - f1 + 1;
}
if (difftype == 'd') {
- *lnum_new = f2 + 1;
- *count_new = 0;
+ hunk->lnum_new = f2 + 1;
+ hunk->count_new = 0;
} else {
- *lnum_new = f2;
- *count_new = l2 - f2 + 1;
+ hunk->lnum_new = f2;
+ hunk->count_new = l2 - f2 + 1;
}
return OK;
}
@@ -3081,8 +3101,7 @@ static int parse_diff_ed(char_u *line, linenr_T *lnum_orig, long *count_orig, li
/// Parses unified diff with zero(!) context lines.
/// Return FAIL if there is no diff information in "line".
///
-static int parse_diff_unified(char_u *line, linenr_T *lnum_orig, long *count_orig,
- linenr_T *lnum_new, long *count_new)
+static int parse_diff_unified(char_u *line, diffhunk_T *hunk)
{
char_u *p;
long oldline, oldcount, newline, newcount;
@@ -3120,10 +3139,10 @@ static int parse_diff_unified(char_u *line, linenr_T *lnum_orig, long *count_ori
newline = 1;
}
- *lnum_orig = oldline;
- *count_orig = oldcount;
- *lnum_new = newline;
- *count_new = newcount;
+ hunk->lnum_orig = oldline;
+ hunk->count_orig = oldcount;
+ hunk->lnum_new = newline;
+ hunk->count_new = newcount;
return OK;
}
@@ -3135,25 +3154,17 @@ static int parse_diff_unified(char_u *line, linenr_T *lnum_orig, long *count_ori
/// Callback function for the xdl_diff() function.
/// Stores the diff output in a grow array.
///
-static int xdiff_out(void *priv, mmbuffer_t *mb, int nbuf)
+static int xdiff_out(long start_a, long count_a, long start_b, long count_b,
+ void *priv)
{
diffout_T *dout = (diffout_T *)priv;
- char_u *p;
-
- // The header line always comes by itself, text lines in at least two
- // parts. We drop the text part.
- if (nbuf > 1) {
- return 0;
- }
-
- // sanity check
- if (STRNCMP(mb[0].ptr, "@@ ", 3) != 0) {
- return 0;
- }
+ diffhunk_T *p = xmalloc(sizeof(*p));
ga_grow(&dout->dout_ga, 1);
-
- p = vim_strnsave((char_u *)mb[0].ptr, mb[0].size);
- ((char_u **)dout->dout_ga.ga_data)[dout->dout_ga.ga_len++] = p;
+ p->lnum_orig = start_a + 1;
+ p->count_orig = count_a;
+ p->lnum_new = start_b + 1;
+ p->count_new = count_b;
+ ((diffhunk_T **)dout->dout_ga.ga_data)[dout->dout_ga.ga_len++] = p;
return 0;
}
diff --git a/src/nvim/edit.c b/src/nvim/edit.c
index 2135d0bcd2..a9c606ec13 100644
--- a/src/nvim/edit.c
+++ b/src/nvim/edit.c
@@ -260,7 +260,7 @@ static colnr_T Insstart_blank_vcol; // vcol for first inserted blank
static bool update_Insstart_orig = true; // set Insstart_orig to Insstart
static char_u *last_insert = NULL; // the text of the previous insert,
- // K_SPECIAL and CSI are escaped
+ // K_SPECIAL is escaped
static int last_insert_skip; // nr of chars in front of previous insert
static int new_insert_skip; // nr of chars in front of current insert
static int did_restart_edit; // "restart_edit" when calling edit()
@@ -643,7 +643,10 @@ static int insert_check(VimState *state)
update_curswant();
s->old_topline = curwin->w_topline;
s->old_topfill = curwin->w_topfill;
- s->lastc = s->c; // remember previous char for CTRL-D
+
+ if (s->c != K_EVENT) {
+ s->lastc = s->c; // remember previous char for CTRL-D
+ }
// After using CTRL-G U the next cursor key will not break undo.
if (dont_sync_undo == kNone) {
@@ -1073,8 +1076,14 @@ static int insert_handle_key(InsertState *s)
case K_COMMAND: // some command
do_cmdline(NULL, getcmdkeycmd, NULL, 0);
+ goto check_pum;
+
+ case K_LUA:
+ map_execute_lua();
check_pum:
+ // nvim_select_popupmenu_item() can be called from the handling of
+ // K_EVENT, K_COMMAND, or K_LUA.
// TODO(bfredl): Not entirely sure this indirection is necessary
// but doing like this ensures using nvim_select_popupmenu_item is
// equivalent to selecting the item with a typed key.
@@ -1597,8 +1606,8 @@ static void ins_ctrl_v(void)
*/
static int pc_status;
#define PC_STATUS_UNSET 0 // pc_bytes was not set
-#define PC_STATUS_RIGHT 1 // right halve of double-wide char
-#define PC_STATUS_LEFT 2 // left halve of double-wide char
+#define PC_STATUS_RIGHT 1 // right half of double-wide char
+#define PC_STATUS_LEFT 2 // left half of double-wide char
#define PC_STATUS_SET 3 // pc_bytes was filled
static char_u pc_bytes[MB_MAXBYTES + 1]; // saved bytes
static int pc_attr;
@@ -1685,7 +1694,7 @@ static void init_prompt(int cmdchar_todo)
// Insert always starts after the prompt, allow editing text after it.
if (Insstart_orig.lnum != curwin->w_cursor.lnum || Insstart_orig.col != (colnr_T)STRLEN(prompt)) {
Insstart.lnum = curwin->w_cursor.lnum;
- Insstart.col = STRLEN(prompt);
+ Insstart.col = (colnr_T)STRLEN(prompt);
Insstart_orig = Insstart;
Insstart_textlen = Insstart.col;
Insstart_blank_vcol = MAXCOL;
@@ -1696,7 +1705,7 @@ static void init_prompt(int cmdchar_todo)
coladvance(MAXCOL);
}
if (curwin->w_cursor.col < (colnr_T)STRLEN(prompt)) {
- curwin->w_cursor.col = STRLEN(prompt);
+ curwin->w_cursor.col = (colnr_T)STRLEN(prompt);
}
// Make sure the cursor is in a valid position.
check_cursor();
@@ -3613,7 +3622,7 @@ static bool ins_compl_prep(int c)
// Ignore end of Select mode mapping and mouse scroll buttons.
if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
|| c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_EVENT
- || c == K_COMMAND) {
+ || c == K_COMMAND || c == K_LUA) {
return retval;
}
@@ -4979,7 +4988,7 @@ void ins_compl_check_keys(int frequency, int in_compl_func)
*/
static int ins_compl_key2dir(int c)
{
- if (c == K_EVENT || c == K_COMMAND) {
+ if (c == K_EVENT || c == K_COMMAND || c == K_LUA) {
return pum_want.item < pum_selected_item ? BACKWARD : FORWARD;
}
if (c == Ctrl_P || c == Ctrl_L
@@ -5009,7 +5018,7 @@ static int ins_compl_key2count(int c)
{
int h;
- if (c == K_EVENT || c == K_COMMAND) {
+ if (c == K_EVENT || c == K_COMMAND || c == K_LUA) {
int offset = pum_want.item - pum_selected_item;
return abs(offset);
}
@@ -5043,6 +5052,7 @@ static bool ins_compl_use_match(int c)
return false;
case K_EVENT:
case K_COMMAND:
+ case K_LUA:
return pum_want.active && pum_want.insert;
}
return true;
@@ -6807,7 +6817,7 @@ void free_last_insert(void)
/// Add character "c" to buffer "s"
///
-/// Escapes the special meaning of K_SPECIAL and CSI, handles multi-byte
+/// Escapes the special meaning of K_SPECIAL, handles multi-byte
/// characters.
///
/// @param[in] c Character to add.
@@ -6821,7 +6831,7 @@ char_u *add_char2buf(int c, char_u *s)
const int len = utf_char2bytes(c, temp);
for (int i = 0; i < len; i++) {
c = temp[i];
- // Need to escape K_SPECIAL and CSI like in the typeahead buffer.
+ // Need to escape K_SPECIAL like in the typeahead buffer.
if (c == K_SPECIAL) {
*s++ = K_SPECIAL;
*s++ = KS_SPECIAL;
diff --git a/src/nvim/eval.c b/src/nvim/eval.c
index 86384bc5b2..6dbdc09c3b 100644
--- a/src/nvim/eval.c
+++ b/src/nvim/eval.c
@@ -7299,12 +7299,19 @@ void mapblock_fill_dict(dict_T *const dict, const mapblock_T *const mp, long buf
noremap_value = mp->m_noremap == REMAP_SCRIPT ? 2 : !!mp->m_noremap;
}
- if (compatible) {
- tv_dict_add_str(dict, S_LEN("rhs"), (const char *)mp->m_orig_str);
+ if (mp->m_luaref != LUA_NOREF) {
+ tv_dict_add_nr(dict, S_LEN("callback"), mp->m_luaref);
} else {
- tv_dict_add_allocated_str(dict, S_LEN("rhs"),
- str2special_save((const char *)mp->m_str, false,
- true));
+ if (compatible) {
+ tv_dict_add_str(dict, S_LEN("rhs"), (const char *)mp->m_orig_str);
+ } else {
+ tv_dict_add_allocated_str(dict, S_LEN("rhs"),
+ str2special_save((const char *)mp->m_str, false,
+ true));
+ }
+ }
+ if (mp->m_desc != NULL) {
+ tv_dict_add_allocated_str(dict, S_LEN("desc"), xstrdup(mp->m_desc));
}
tv_dict_add_allocated_str(dict, S_LEN("lhs"), lhs);
tv_dict_add_nr(dict, S_LEN("noremap"), noremap_value);
diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua
index 9a76b67de6..e445a08227 100644
--- a/src/nvim/eval.lua
+++ b/src/nvim/eval.lua
@@ -133,6 +133,7 @@ return {
foldtext={},
foldtextresult={args=1, base=1},
foreground={},
+ fullcommand={args=1, base=1},
funcref={args={1, 3}, base=1},
['function']={args={1, 3}, base=1},
garbagecollect={args={0, 1}},
@@ -277,6 +278,7 @@ return {
readfile={args={1, 3}, base=1},
reg_executing={},
reg_recording={},
+ reg_recorded={},
reltime={args={0, 2}, base=1},
reltimefloat={args=1, base=1},
reltimestr={args=1, base=1},
diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c
index 6d43097ddd..4a07f6a850 100644
--- a/src/nvim/eval/funcs.c
+++ b/src/nvim/eval/funcs.c
@@ -1082,15 +1082,13 @@ static void f_chdir(typval_T *argvars, typval_T *rettv, FunPtr fptr)
// Return the current directory
cwd = xmalloc(MAXPATHL);
- if (cwd != NULL) {
- if (os_dirname(cwd, MAXPATHL) != FAIL) {
+ if (os_dirname(cwd, MAXPATHL) != FAIL) {
#ifdef BACKSLASH_IN_FILENAME
- slash_adjust(cwd);
+ slash_adjust(cwd);
#endif
- rettv->vval.v_string = vim_strsave(cwd);
- }
- xfree(cwd);
+ rettv->vval.v_string = vim_strsave(cwd);
}
+ xfree(cwd);
if (curwin->w_localdir != NULL) {
scope = kCdScopeWindow;
@@ -3920,34 +3918,46 @@ static void f_getqflist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
get_qf_loc_list(true, NULL, &argvars[0], rettv);
}
-/// "getreg()" function
-static void f_getreg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
+/// Common between getreg(), getreginfo() and getregtype(): get the register
+/// name from the first argument.
+/// Returns zero on error.
+static int getreg_get_regname(typval_T *argvars)
{
- const char *strregname;
- int arg2 = false;
- bool return_list = false;
- bool error = false;
+ const char_u *strregname;
if (argvars[0].v_type != VAR_UNKNOWN) {
- strregname = tv_get_string_chk(&argvars[0]);
- error = strregname == NULL;
- if (argvars[1].v_type != VAR_UNKNOWN) {
- arg2 = tv_get_number_chk(&argvars[1], &error);
- if (!error && argvars[2].v_type != VAR_UNKNOWN) {
- return_list = tv_get_number_chk(&argvars[2], &error);
- }
+ strregname = (const char_u *)tv_get_string_chk(&argvars[0]);
+ if (strregname == NULL) { // type error; errmsg already given
+ return 0;
}
} else {
- strregname = _(get_vim_var_str(VV_REG));
+ // Default to v:register
+ strregname = get_vim_var_str(VV_REG);
}
- if (error) {
+ return *strregname == 0 ? '"' : *strregname;
+}
+
+/// "getreg()" function
+static void f_getreg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
+{
+ int arg2 = false;
+ bool return_list = false;
+
+ int regname = getreg_get_regname(argvars);
+ if (regname == 0) {
return;
}
- int regname = (uint8_t)(strregname == NULL ? '"' : *strregname);
- if (regname == 0) {
- regname = '"';
+ if (argvars[0].v_type != VAR_UNKNOWN && argvars[1].v_type != VAR_UNKNOWN) {
+ bool error = false;
+ arg2 = (int)tv_get_number_chk(&argvars[1], &error);
+ if (!error && argvars[2].v_type != VAR_UNKNOWN) {
+ return_list = (bool)tv_get_number_chk(&argvars[2], &error);
+ }
+ if (error) {
+ return;
+ }
}
if (return_list) {
@@ -3964,28 +3974,16 @@ static void f_getreg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "getregtype()" function
- */
+/// "getregtype()" function
static void f_getregtype(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
- const char *strregname;
-
- if (argvars[0].v_type != VAR_UNKNOWN) {
- strregname = tv_get_string_chk(&argvars[0]);
- if (strregname == NULL) { // Type error; errmsg already given.
- rettv->v_type = VAR_STRING;
- rettv->vval.v_string = NULL;
- return;
- }
- } else {
- // Default to v:register.
- strregname = _(get_vim_var_str(VV_REG));
- }
+ // on error return an empty string
+ rettv->v_type = VAR_STRING;
+ rettv->vval.v_string = NULL;
- int regname = (uint8_t)(strregname == NULL ? '"' : *strregname);
+ int regname = getreg_get_regname(argvars);
if (regname == 0) {
- regname = '"';
+ return;
}
colnr_T reglen = 0;
@@ -3993,7 +3991,6 @@ static void f_getregtype(typval_T *argvars, typval_T *rettv, FunPtr fptr)
MotionType reg_type = get_reg_type(regname, &reglen);
format_reg_type(reg_type, reglen, buf, ARRAY_SIZE(buf));
- rettv->v_type = VAR_STRING;
rettv->vval.v_string = (char_u *)xstrdup(buf);
}
@@ -5982,6 +5979,7 @@ static void get_maparg(typval_T *argvars, typval_T *rettv, int exact)
{
char_u *keys_buf = NULL;
char_u *rhs;
+ LuaRef rhs_lua;
int mode;
int abbr = FALSE;
int get_dict = FALSE;
@@ -6018,7 +6016,7 @@ static void get_maparg(typval_T *argvars, typval_T *rettv, int exact)
keys = replace_termcodes(keys, STRLEN(keys), &keys_buf, true, true, true,
CPO_TO_CPO_FLAGS);
- rhs = check_map(keys, mode, exact, false, abbr, &mp, &buffer_local);
+ rhs = check_map(keys, mode, exact, false, abbr, &mp, &buffer_local, &rhs_lua);
xfree(keys_buf);
if (!get_dict) {
@@ -6029,10 +6027,15 @@ static void get_maparg(typval_T *argvars, typval_T *rettv, int exact)
} else {
rettv->vval.v_string = (char_u *)str2special_save((char *)rhs, false, false);
}
+ } else if (rhs_lua != LUA_NOREF) {
+ size_t msglen = 100;
+ char *msg = (char *)xmalloc(msglen);
+ snprintf(msg, msglen, "<Lua function %d>", mp->m_luaref);
+ rettv->vval.v_string = (char_u *)msg;
}
} else {
tv_dict_alloc_ret(rettv);
- if (rhs != NULL) {
+ if (mp != NULL && (rhs != NULL || rhs_lua != LUA_NOREF)) {
// Return a dictionary.
mapblock_fill_dict(rettv->vval.v_dict, mp, buffer_local, true);
}
@@ -7333,18 +7336,12 @@ static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
/// "getreginfo()" function
static void f_getreginfo(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
- const char *strregname;
- if (argvars[0].v_type != VAR_UNKNOWN) {
- strregname = tv_get_string_chk(&argvars[0]);
- if (strregname == NULL) {
- return;
- }
- } else {
- strregname = (const char *)get_vim_var_str(VV_REG);
+ int regname = getreg_get_regname(argvars);
+ if (regname == 0) {
+ return;
}
- int regname = (strregname == NULL ? '"' : *strregname);
- if (regname == 0 || regname == '@') {
+ if (regname == '@') {
regname = '"';
}
@@ -7398,6 +7395,11 @@ static void f_reg_recording(typval_T *argvars, typval_T *rettv, FunPtr fptr)
return_register(reg_recording, rettv);
}
+static void f_reg_recorded(typval_T *argvars, typval_T *rettv, FunPtr fptr)
+{
+ return_register(reg_recorded, rettv);
+}
+
/// list2proftime - convert a List to proftime_T
///
/// @param arg The input list, must be of type VAR_LIST and have
diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c
index 11bbaaed9c..42ac1839e6 100644
--- a/src/nvim/eval/typval.c
+++ b/src/nvim/eval/typval.c
@@ -2455,13 +2455,11 @@ static inline void _nothing_conv_dict_end(typval_T *const tv, dict_T **const dic
#define TYPVAL_ENCODE_NAME nothing
#define TYPVAL_ENCODE_FIRST_ARG_TYPE const void *const
#define TYPVAL_ENCODE_FIRST_ARG_NAME ignored
-#define TYPVAL_ENCODE_TRANSLATE_OBJECT_NAME
#include "nvim/eval/typval_encode.c.h"
#undef TYPVAL_ENCODE_SCOPE
#undef TYPVAL_ENCODE_NAME
#undef TYPVAL_ENCODE_FIRST_ARG_TYPE
#undef TYPVAL_ENCODE_FIRST_ARG_NAME
-#undef TYPVAL_ENCODE_TRANSLATE_OBJECT_NAME
#undef TYPVAL_ENCODE_ALLOW_SPECIALS
#undef TYPVAL_ENCODE_CONV_NIL
diff --git a/src/nvim/event/loop.c b/src/nvim/event/loop.c
index 892c46dd04..89fced59c5 100644
--- a/src/nvim/event/loop.c
+++ b/src/nvim/event/loop.c
@@ -75,7 +75,7 @@ bool loop_poll_events(Loop *loop, int ms)
/// @note Event is queued into `fast_events`, which is processed outside of the
/// primary `events` queue by loop_poll_events(). For `main_loop`, that
/// means `fast_events` is NOT processed in an "editor mode"
-/// (VimState.execute), so redraw and other side-effects are likely to be
+/// (VimState.execute), so redraw and other side effects are likely to be
/// skipped.
/// @see loop_schedule_deferred
void loop_schedule_fast(Loop *loop, Event event)
diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c
index c0cb17fa61..95390b1a70 100644
--- a/src/nvim/ex_cmds.c
+++ b/src/nvim/ex_cmds.c
@@ -3006,7 +3006,12 @@ void ex_append(exarg_T *eap)
did_undo = true;
ml_append(lnum, theline, (colnr_T)0, false);
- appended_lines_mark(lnum + (empty ? 1 : 0), 1L);
+ if (empty) {
+ // there are no marks below the inserted lines
+ appended_lines(lnum, 1L);
+ } else {
+ appended_lines_mark(lnum, 1L);
+ }
xfree(theline);
++lnum;
@@ -3025,7 +3030,7 @@ void ex_append(exarg_T *eap)
// "start" is set to eap->line2+1 unless that position is invalid (when
// eap->line2 pointed to the end of the buffer and nothing was appended)
// "end" is set to lnum when something has been appended, otherwise
- // it is the same than "start" -- Acevedo
+ // it is the same as "start" -- Acevedo
curbuf->b_op_start.lnum = (eap->line2 < curbuf->b_ml.ml_line_count) ?
eap->line2 + 1 : curbuf->b_ml.ml_line_count;
if (eap->cmdidx != CMD_append) {
@@ -4584,6 +4589,9 @@ void ex_global(exarg_T *eap)
// a match on this line?
match = vim_regexec_multi(&regmatch, curwin, curbuf, lnum,
(colnr_T)0, NULL, NULL);
+ if (regmatch.regprog == NULL) {
+ break; // re-compiling regprog failed
+ }
if ((type == 'g' && match) || (type == 'v' && !match)) {
ml_setmarked(lnum);
ndone++;
diff --git a/src/nvim/ex_cmds2.c b/src/nvim/ex_cmds2.c
index 33f9477608..267f5616f5 100644
--- a/src/nvim/ex_cmds2.c
+++ b/src/nvim/ex_cmds2.c
@@ -1613,7 +1613,7 @@ void ex_compiler(exarg_T *eap)
if (old_cur_comp != NULL) {
old_cur_comp = vim_strsave(old_cur_comp);
}
- do_cmdline_cmd("command -nargs=* CompilerSet setlocal <args>");
+ do_cmdline_cmd("command -nargs=* -keepscript CompilerSet setlocal <args>");
}
do_unlet(S_LEN("g:current_compiler"), true);
do_unlet(S_LEN("b:current_compiler"), true);
@@ -2162,7 +2162,7 @@ int do_source(char *fname, int check_other, int is_vimrc)
funccal_entry_T funccalp_entry;
save_funccal(&funccalp_entry);
- // Check if this script was sourced before to finds its SID.
+ // Check if this script was sourced before to find its SID.
// If it's new, generate a new SID.
// Always use a new sequence number.
const sctx_T save_current_sctx = current_sctx;
diff --git a/src/nvim/ex_cmds_defs.h b/src/nvim/ex_cmds_defs.h
index ea899b660b..eaf5f627b6 100644
--- a/src/nvim/ex_cmds_defs.h
+++ b/src/nvim/ex_cmds_defs.h
@@ -61,6 +61,7 @@
// current buffer is locked
#define EX_MODIFY 0x100000 // forbidden in non-'modifiable' buffer
#define EX_FLAGS 0x200000 // allow flags after count in argument
+#define EX_KEEPSCRIPT 0x4000000 // keep sctx of where command was invoked
#define EX_FILES (EX_XFILE | EX_EXTRA) // multiple extra files allowed
#define EX_FILE1 (EX_FILES | EX_NOSPC) // 1 file, defaults to current file
#define EX_WORD1 (EX_EXTRA | EX_NOSPC) // one extra word allowed
@@ -192,6 +193,7 @@ struct expand {
int xp_context; // type of expansion
size_t xp_pattern_len; // bytes in xp_pattern before cursor
char_u *xp_arg; // completion function
+ LuaRef xp_luaref; // Ref to Lua completion function
sctx_T xp_script_ctx; // SCTX for completion function
int xp_backslash; // one of the XP_BS_ values
#ifndef BACKSLASH_IN_FILENAME
diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c
index 9f0f8d93a3..a4b43e598d 100644
--- a/src/nvim/ex_docmd.c
+++ b/src/nvim/ex_docmd.c
@@ -67,8 +67,8 @@
#include "nvim/sign.h"
#include "nvim/spell.h"
#include "nvim/spellfile.h"
-#include "nvim/strings.h"
#include "nvim/state.h"
+#include "nvim/strings.h"
#include "nvim/syntax.h"
#include "nvim/tag.h"
#include "nvim/terminal.h"
@@ -81,23 +81,7 @@
static int quitmore = 0;
static bool ex_pressedreturn = false;
-typedef struct ucmd {
- char_u *uc_name; // The command name
- uint32_t uc_argt; // The argument type
- char_u *uc_rep; // The command's replacement string
- long uc_def; // The default value for a range/count
- int uc_compl; // completion type
- cmd_addr_T uc_addr_type; // The command's address type
- sctx_T uc_script_ctx; // SCTX where the command was defined
- char_u *uc_compl_arg; // completion argument if any
-} ucmd_T;
-
-#define UC_BUFFER 1 // -buffer: local to current buffer
-
-static garray_T ucmds = { 0, 0, sizeof(ucmd_T), 4, NULL };
-
-#define USER_CMD(i) (&((ucmd_T *)(ucmds.ga_data))[i])
-#define USER_CMD_GA(gap, i) (&((ucmd_T *)((gap)->ga_data))[i])
+garray_T ucmds = { 0, 0, sizeof(ucmd_T), 4, NULL };
// Whether a command index indicates a user command.
#define IS_USER_CMDIDX(idx) ((int)(idx) < 0)
@@ -2761,6 +2745,7 @@ static char_u *find_ucmd(exarg_T *eap, char_u *p, int *full, expand_T *xp, int *
*complp = uc->uc_compl;
}
if (xp != NULL) {
+ xp->xp_luaref = uc->uc_compl_luaref;
xp->xp_arg = uc->uc_compl_arg;
xp->xp_script_ctx = uc->uc_script_ctx;
xp->xp_script_ctx.sc_lnum += sourcing_lnum;
@@ -2900,6 +2885,31 @@ int cmd_exists(const char *const name)
return ea.cmdidx == CMD_SIZE ? 0 : (full ? 2 : 1);
}
+// "fullcommand" function
+void f_fullcommand(typval_T *argvars, typval_T *rettv, FunPtr fptr)
+{
+ exarg_T ea;
+ char_u *name = argvars[0].vval.v_string;
+
+ while (name[0] != NUL && name[0] == ':') {
+ name++;
+ }
+ name = skip_range(name, NULL);
+
+ rettv->v_type = VAR_STRING;
+
+ ea.cmd = (*name == '2' || *name == '3') ? name + 1 : name;
+ ea.cmdidx = (cmdidx_T)0;
+ char_u *p = find_command(&ea, NULL);
+ if (p == NULL || ea.cmdidx == CMD_SIZE) {
+ return;
+ }
+
+ rettv->vval.v_string = vim_strsave(IS_USER_CMDIDX(ea.cmdidx)
+ ? get_user_commands(NULL, ea.useridx)
+ : cmdnames[ea.cmdidx].cmd_name);
+}
+
/// This is all pretty much copied from do_one_cmd(), with all the extra stuff
/// we don't need/want deleted. Maybe this could be done better if we didn't
/// repeat all this stuff. The only problem is that they may not stay
@@ -4360,7 +4370,7 @@ static char_u *replace_makeprg(exarg_T *eap, char_u *p, char_u **cmdlinep)
++i;
}
len = (int)STRLEN(p);
- new_cmdline = xmalloc(STRLEN(program) + i * (len - 2) + 1);
+ new_cmdline = xmalloc(STRLEN(program) + (size_t)i * (len - 2) + 1);
ptr = new_cmdline;
while ((pos = (char_u *)strstr((char *)program, "$*")) != NULL) {
i = (int)(pos - program);
@@ -5146,8 +5156,9 @@ char_u *get_command_name(expand_T *xp, int idx)
return cmdnames[idx].cmd_name;
}
-static int uc_add_command(char_u *name, size_t name_len, char_u *rep, uint32_t argt, long def,
- int flags, int compl, char_u *compl_arg, cmd_addr_T addr_type, bool force)
+int uc_add_command(char_u *name, size_t name_len, char_u *rep, uint32_t argt, long def, int flags,
+ int compl, char_u *compl_arg, LuaRef compl_luaref, cmd_addr_T addr_type,
+ LuaRef luaref, bool force)
FUNC_ATTR_NONNULL_ARG(1, 3)
{
ucmd_T *cmd = NULL;
@@ -5201,6 +5212,8 @@ static int uc_add_command(char_u *name, size_t name_len, char_u *rep, uint32_t a
XFREE_CLEAR(cmd->uc_rep);
XFREE_CLEAR(cmd->uc_compl_arg);
+ NLUA_CLEAR_REF(cmd->uc_luaref);
+ NLUA_CLEAR_REF(cmd->uc_compl_luaref);
break;
}
@@ -5231,13 +5244,17 @@ static int uc_add_command(char_u *name, size_t name_len, char_u *rep, uint32_t a
cmd->uc_script_ctx = current_sctx;
cmd->uc_script_ctx.sc_lnum += sourcing_lnum;
cmd->uc_compl_arg = compl_arg;
+ cmd->uc_compl_luaref = compl_luaref;
cmd->uc_addr_type = addr_type;
+ cmd->uc_luaref = luaref;
return OK;
fail:
xfree(rep_buf);
xfree(compl_arg);
+ NLUA_CLEAR_REF(luaref);
+ NLUA_CLEAR_REF(compl_luaref);
return FAIL;
}
@@ -5276,6 +5293,7 @@ static const char *command_complete[] =
[EXPAND_CSCOPE] = "cscope",
[EXPAND_USER_DEFINED] = "custom",
[EXPAND_USER_LIST] = "customlist",
+ [EXPAND_USER_LUA] = "<Lua function>",
[EXPAND_DIFF_BUFFERS] = "diff_buffer",
[EXPAND_DIRECTORIES] = "dir",
[EXPAND_ENV_VARS] = "environment",
@@ -5499,6 +5517,8 @@ static int uc_scan_attr(char_u *attr, size_t len, uint32_t *argt, long *def, int
*flags |= UC_BUFFER;
} else if (STRNICMP(attr, "register", len) == 0) {
*argt |= EX_REGSTR;
+ } else if (STRNICMP(attr, "keepscript", len) == 0) {
+ *argt |= EX_KEEPSCRIPT;
} else if (STRNICMP(attr, "bar", len) == 0) {
*argt |= EX_TRLBAR;
} else {
@@ -5677,8 +5697,8 @@ static void ex_command(exarg_T *eap)
} else if (compl > 0 && (argt & EX_EXTRA) == 0) {
emsg(_(e_complete_used_without_nargs));
} else {
- uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg,
- addr_type_arg, eap->forceit);
+ uc_add_command(name, end - name, p, argt, def, flags, compl, compl_arg, LUA_NOREF,
+ addr_type_arg, LUA_NOREF, eap->forceit);
}
}
@@ -5692,11 +5712,13 @@ void ex_comclear(exarg_T *eap)
uc_clear(&curbuf->b_ucmds);
}
-static void free_ucmd(ucmd_T *cmd)
+void free_ucmd(ucmd_T *cmd)
{
xfree(cmd->uc_name);
xfree(cmd->uc_rep);
xfree(cmd->uc_compl_arg);
+ NLUA_CLEAR_REF(cmd->uc_compl_luaref);
+ NLUA_CLEAR_REF(cmd->uc_luaref);
}
/*
@@ -5734,9 +5756,7 @@ static void ex_delcommand(exarg_T *eap)
return;
}
- xfree(cmd->uc_name);
- xfree(cmd->uc_rep);
- xfree(cmd->uc_compl_arg);
+ free_ucmd(cmd);
--gap->ga_len;
@@ -5818,7 +5838,7 @@ static char_u *uc_split_args(char_u *arg, size_t *lenp)
return buf;
}
-static size_t add_cmd_modifier(char_u *buf, char *mod_str, bool *multi_mods)
+static size_t add_cmd_modifier(char *buf, char *mod_str, bool *multi_mods)
{
size_t result = STRLEN(mod_str);
if (*multi_mods) {
@@ -6010,7 +6030,7 @@ static size_t uc_check_code(char_u *code, size_t len, char_u *buf, ucmd_T *cmd,
break;
}
- case ct_MODS: {
+ case ct_MODS:
result = quote ? 2 : 0;
if (buf != NULL) {
if (quote) {
@@ -6019,76 +6039,13 @@ static size_t uc_check_code(char_u *code, size_t len, char_u *buf, ucmd_T *cmd,
*buf = '\0';
}
- bool multi_mods = false;
+ result += uc_mods((char *)buf);
- // :aboveleft and :leftabove
- if (cmdmod.split & WSP_ABOVE) {
- result += add_cmd_modifier(buf, "aboveleft", &multi_mods);
- }
- // :belowright and :rightbelow
- if (cmdmod.split & WSP_BELOW) {
- result += add_cmd_modifier(buf, "belowright", &multi_mods);
- }
- // :botright
- if (cmdmod.split & WSP_BOT) {
- result += add_cmd_modifier(buf, "botright", &multi_mods);
- }
-
- typedef struct {
- bool *set;
- char *name;
- } mod_entry_T;
- static mod_entry_T mod_entries[] = {
- { &cmdmod.browse, "browse" },
- { &cmdmod.confirm, "confirm" },
- { &cmdmod.hide, "hide" },
- { &cmdmod.keepalt, "keepalt" },
- { &cmdmod.keepjumps, "keepjumps" },
- { &cmdmod.keepmarks, "keepmarks" },
- { &cmdmod.keeppatterns, "keeppatterns" },
- { &cmdmod.lockmarks, "lockmarks" },
- { &cmdmod.noswapfile, "noswapfile" }
- };
- // the modifiers that are simple flags
- for (size_t i = 0; i < ARRAY_SIZE(mod_entries); i++) {
- if (*mod_entries[i].set) {
- result += add_cmd_modifier(buf, mod_entries[i].name, &multi_mods);
- }
- }
-
- // TODO(vim): How to support :noautocmd?
- // TODO(vim): How to support :sandbox?
-
- // :silent
- if (msg_silent > 0) {
- result += add_cmd_modifier(buf, emsg_silent > 0 ? "silent!" : "silent",
- &multi_mods);
- }
- // :tab
- if (cmdmod.tab > 0) {
- result += add_cmd_modifier(buf, "tab", &multi_mods);
- }
- // :topleft
- if (cmdmod.split & WSP_TOP) {
- result += add_cmd_modifier(buf, "topleft", &multi_mods);
- }
-
- // TODO(vim): How to support :unsilent?
-
- // :verbose
- if (p_verbose > 0) {
- result += add_cmd_modifier(buf, "verbose", &multi_mods);
- }
- // :vertical
- if (cmdmod.split & WSP_VERT) {
- result += add_cmd_modifier(buf, "vertical", &multi_mods);
- }
if (quote && buf != NULL) {
buf += result - 2;
*buf = '"';
}
break;
- }
case ct_REGISTER:
result = eap->regname ? 1 : 0;
@@ -6127,6 +6084,76 @@ static size_t uc_check_code(char_u *code, size_t len, char_u *buf, ucmd_T *cmd,
return result;
}
+size_t uc_mods(char *buf)
+{
+ size_t result = 0;
+ bool multi_mods = false;
+
+ // :aboveleft and :leftabove
+ if (cmdmod.split & WSP_ABOVE) {
+ result += add_cmd_modifier(buf, "aboveleft", &multi_mods);
+ }
+ // :belowright and :rightbelow
+ if (cmdmod.split & WSP_BELOW) {
+ result += add_cmd_modifier(buf, "belowright", &multi_mods);
+ }
+ // :botright
+ if (cmdmod.split & WSP_BOT) {
+ result += add_cmd_modifier(buf, "botright", &multi_mods);
+ }
+
+ typedef struct {
+ bool *set;
+ char *name;
+ } mod_entry_T;
+ static mod_entry_T mod_entries[] = {
+ { &cmdmod.browse, "browse" },
+ { &cmdmod.confirm, "confirm" },
+ { &cmdmod.hide, "hide" },
+ { &cmdmod.keepalt, "keepalt" },
+ { &cmdmod.keepjumps, "keepjumps" },
+ { &cmdmod.keepmarks, "keepmarks" },
+ { &cmdmod.keeppatterns, "keeppatterns" },
+ { &cmdmod.lockmarks, "lockmarks" },
+ { &cmdmod.noswapfile, "noswapfile" }
+ };
+ // the modifiers that are simple flags
+ for (size_t i = 0; i < ARRAY_SIZE(mod_entries); i++) {
+ if (*mod_entries[i].set) {
+ result += add_cmd_modifier(buf, mod_entries[i].name, &multi_mods);
+ }
+ }
+
+ // TODO(vim): How to support :noautocmd?
+ // TODO(vim): How to support :sandbox?
+
+ // :silent
+ if (msg_silent > 0) {
+ result += add_cmd_modifier(buf, emsg_silent > 0 ? "silent!" : "silent", &multi_mods);
+ }
+ // :tab
+ if (cmdmod.tab > 0) {
+ result += add_cmd_modifier(buf, "tab", &multi_mods);
+ }
+ // :topleft
+ if (cmdmod.split & WSP_TOP) {
+ result += add_cmd_modifier(buf, "topleft", &multi_mods);
+ }
+
+ // TODO(vim): How to support :unsilent?
+
+ // :verbose
+ if (p_verbose > 0) {
+ result += add_cmd_modifier(buf, "verbose", &multi_mods);
+ }
+ // :vertical
+ if (cmdmod.split & WSP_VERT) {
+ result += add_cmd_modifier(buf, "vertical", &multi_mods);
+ }
+
+ return result;
+}
+
static void do_ucmd(exarg_T *eap)
{
char_u *buf;
@@ -6149,6 +6176,11 @@ static void do_ucmd(exarg_T *eap)
cmd = USER_CMD_GA(&curbuf->b_ucmds, eap->useridx);
}
+ if (cmd->uc_luaref > 0) {
+ nlua_do_ucmd(cmd, eap);
+ return;
+ }
+
/*
* Replace <> in the command by the arguments.
* First round: "buf" is NULL, compute length, allocate "buf".
@@ -6174,7 +6206,6 @@ static void do_ucmd(exarg_T *eap)
// K_SPECIAL has been put in the buffer as K_SPECIAL
// KS_SPECIAL KE_FILLER, like for mappings, but
// do_cmdline() doesn't handle that, so convert it back.
- // Also change K_SPECIAL KS_EXTRA KE_CSI into CSI.
len = ksp - p;
if (len > 0) {
memmove(q, p, len);
@@ -6227,10 +6258,14 @@ static void do_ucmd(exarg_T *eap)
buf = xmalloc(totlen + 1);
}
- current_sctx.sc_sid = cmd->uc_script_ctx.sc_sid;
+ if ((cmd->uc_argt & EX_KEEPSCRIPT) == 0) {
+ current_sctx.sc_sid = cmd->uc_script_ctx.sc_sid;
+ }
(void)do_cmdline(buf, eap->getline, eap->cookie,
DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
- current_sctx = save_current_sctx;
+ if ((cmd->uc_argt & EX_KEEPSCRIPT) == 0) {
+ current_sctx = save_current_sctx;
+ }
xfree(buf);
xfree(split_buf);
}
@@ -6276,7 +6311,7 @@ char_u *get_user_cmd_flags(expand_T *xp, int idx)
{
static char *user_cmd_flags[] = { "addr", "bang", "bar",
"buffer", "complete", "count",
- "nargs", "range", "register" };
+ "nargs", "range", "register", "keepscript" };
if (idx >= (int)ARRAY_SIZE(user_cmd_flags)) {
return NULL;
@@ -7464,9 +7499,8 @@ void do_exedit(exarg_T *eap, win_T *old_curwin)
if ((eap->cmdidx == CMD_new
|| eap->cmdidx == CMD_tabnew
|| eap->cmdidx == CMD_tabedit
- || eap->cmdidx == CMD_vnew
- ) && *eap->arg == NUL) {
- // ":new" or ":tabnew" without argument: edit an new empty buffer
+ || eap->cmdidx == CMD_vnew) && *eap->arg == NUL) {
+ // ":new" or ":tabnew" without argument: edit a new empty buffer
setpcmark();
(void)do_ecmd(0, NULL, NULL, eap, ECMD_ONE,
ECMD_HIDE + (eap->forceit ? ECMD_FORCEIT : 0),
@@ -7807,17 +7841,21 @@ bool changedir_func(char_u *new_dir, CdScope scope)
prev_dir = pdir;
}
+ // For UNIX ":cd" means: go to home directory.
+ // On other systems too if 'cdhome' is set.
#if defined(UNIX)
- // On Unix ":cd" means: go to home directory.
if (*new_dir == NUL) {
+#else
+ if (*new_dir == NUL && p_cdh) {
+#endif
// Use NameBuff for home directory name.
expand_env((char_u *)"$HOME", NameBuff, MAXPATHL);
new_dir = NameBuff;
}
-#endif
- if (vim_chdir(new_dir) == 0) {
- bool dir_differs = pdir == NULL || pathcmp((char *)pdir, (char *)new_dir, -1) != 0;
+ bool dir_differs = new_dir == NULL || pdir == NULL
+ || pathcmp((char *)pdir, (char *)new_dir, -1) != 0;
+ if (new_dir != NULL && (!dir_differs || vim_chdir(new_dir) == 0)) {
post_chdir(scope, dir_differs);
retval = true;
} else {
@@ -7833,9 +7871,9 @@ void ex_cd(exarg_T *eap)
{
char_u *new_dir;
new_dir = eap->arg;
-#if !defined(UNIX) && !defined(VMS)
- // for non-UNIX ":cd" means: print current directory
- if (*new_dir == NUL) {
+#if !defined(UNIX)
+ // for non-UNIX ":cd" means: print current directory unless 'cdhome' is set
+ if (*new_dir == NUL && !p_cdh) {
ex_pwd(NULL);
} else
#endif
@@ -8594,7 +8632,7 @@ static void ex_normal(exarg_T *eap)
return;
}
- // vgetc() expects a CSI and K_SPECIAL to have been escaped. Don't do
+ // vgetc() expects K_SPECIAL to have been escaped. Don't do
// this for the K_SPECIAL leading byte, otherwise special keys will not
// work.
{
@@ -8603,8 +8641,7 @@ static void ex_normal(exarg_T *eap)
// Count the number of characters to be escaped.
for (p = eap->arg; *p != NUL; p++) {
for (l = utfc_ptr2len(p) - 1; l > 0; l--) {
- if (*++p == K_SPECIAL // trailbyte K_SPECIAL or CSI
- ) {
+ if (*++p == K_SPECIAL) { // trailbyte K_SPECIAL
len += 2;
}
}
@@ -9513,23 +9550,34 @@ static void ex_filetype(exarg_T *eap)
}
}
-/// Set all :filetype options ON if user did not explicitly set any to OFF.
-void filetype_maybe_enable(void)
+/// Source ftplugin.vim and indent.vim to create the necessary FileType
+/// autocommands. We do this separately from filetype.vim so that these
+/// autocommands will always fire first (and thus can be overriden) while still
+/// allowing general filetype detection to be disabled in the user's init file.
+void filetype_plugin_enable(void)
{
- if (filetype_detect == kNone) {
- source_runtime(FILETYPE_FILE, true);
- filetype_detect = kTrue;
- }
if (filetype_plugin == kNone) {
- source_runtime(FTPLUGIN_FILE, true);
+ source_runtime(FTPLUGIN_FILE, DIP_ALL);
filetype_plugin = kTrue;
}
if (filetype_indent == kNone) {
- source_runtime(INDENT_FILE, true);
+ source_runtime(INDENT_FILE, DIP_ALL);
filetype_indent = kTrue;
}
}
+/// Enable filetype detection if the user did not explicitly disable it.
+void filetype_maybe_enable(void)
+{
+ if (filetype_detect == kNone) {
+ // Normally .vim files are sourced before .lua files when both are
+ // supported, but we reverse the order here because we want the Lua
+ // autocommand to be defined first so that it runs first
+ source_runtime(FILETYPE_FILE, DIP_ALL);
+ filetype_detect = kTrue;
+ }
+}
+
/// ":setfiletype [FALLBACK] {name}"
static void ex_setfiletype(exarg_T *eap)
{
@@ -9802,6 +9850,7 @@ Dictionary commands_array(buf_T *buf)
PUT(d, "bang", BOOLEAN_OBJ(!!(cmd->uc_argt & EX_BANG)));
PUT(d, "bar", BOOLEAN_OBJ(!!(cmd->uc_argt & EX_TRLBAR)));
PUT(d, "register", BOOLEAN_OBJ(!!(cmd->uc_argt & EX_REGSTR)));
+ PUT(d, "keepscript", BOOLEAN_OBJ(!!(cmd->uc_argt & EX_KEEPSCRIPT)));
switch (cmd->uc_argt & (EX_EXTRA | EX_NOSPC | EX_NEEDARG)) {
case 0:
diff --git a/src/nvim/ex_docmd.h b/src/nvim/ex_docmd.h
index 7ec4fad277..abf6ec347b 100644
--- a/src/nvim/ex_docmd.h
+++ b/src/nvim/ex_docmd.h
@@ -2,6 +2,7 @@
#define NVIM_EX_DOCMD_H
#include "nvim/ex_cmds_defs.h"
+#include "nvim/eval/funcs.h"
#include "nvim/globals.h"
// flags for do_cmdline()
@@ -31,6 +32,26 @@ typedef struct {
tasave_T tabuf;
} save_state_T;
+typedef struct ucmd {
+ char_u *uc_name; // The command name
+ uint32_t uc_argt; // The argument type
+ char_u *uc_rep; // The command's replacement string
+ long uc_def; // The default value for a range/count
+ int uc_compl; // completion type
+ cmd_addr_T uc_addr_type; // The command's address type
+ sctx_T uc_script_ctx; // SCTX where the command was defined
+ char_u *uc_compl_arg; // completion argument if any
+ LuaRef uc_compl_luaref; // Reference to Lua completion function
+ LuaRef uc_luaref; // Reference to Lua function
+} ucmd_T;
+
+#define UC_BUFFER 1 // -buffer: local to current buffer
+
+extern garray_T ucmds;
+
+#define USER_CMD(i) (&((ucmd_T *)(ucmds.ga_data))[i])
+#define USER_CMD_GA(gap, i) (&((ucmd_T *)((gap)->ga_data))[i])
+
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "ex_docmd.h.generated.h"
#endif
diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c
index ba2238ace2..78b8e43e65 100644
--- a/src/nvim/ex_getln.c
+++ b/src/nvim/ex_getln.c
@@ -1024,11 +1024,13 @@ static int command_line_execute(VimState *state, int key)
CommandLineState *s = (CommandLineState *)state;
s->c = key;
- if (s->c == K_EVENT || s->c == K_COMMAND) {
+ if (s->c == K_EVENT || s->c == K_COMMAND || s->c == K_LUA) {
if (s->c == K_EVENT) {
state_handle_k_event();
- } else {
+ } else if (s->c == K_COMMAND) {
do_cmdline(NULL, getcmdkeycmd, NULL, DOCMD_NOWAIT);
+ } else {
+ map_execute_lua();
}
if (!cmdline_was_last_drawn) {
@@ -4983,6 +4985,9 @@ static int ExpandFromContext(expand_T *xp, char_u *pat, int *num_file, char_u **
if (xp->xp_context == EXPAND_USER_LIST) {
return ExpandUserList(xp, num_file, file);
}
+ if (xp->xp_context == EXPAND_USER_LUA) {
+ return ExpandUserLua(xp, num_file, file);
+ }
if (xp->xp_context == EXPAND_PACKADD) {
return ExpandPackAddDir(pat, num_file, file);
}
@@ -5411,6 +5416,35 @@ static int ExpandUserList(expand_T *xp, int *num_file, char_u ***file)
return OK;
}
+static int ExpandUserLua(expand_T *xp, int *num_file, char_u ***file)
+{
+ typval_T rettv;
+ nlua_call_user_expand_func(xp, &rettv);
+ if (rettv.v_type != VAR_LIST) {
+ tv_clear(&rettv);
+ return FAIL;
+ }
+
+ list_T *const retlist = rettv.vval.v_list;
+
+ garray_T ga;
+ ga_init(&ga, (int)sizeof(char *), 3);
+ // Loop over the items in the list.
+ TV_LIST_ITER_CONST(retlist, li, {
+ if (TV_LIST_ITEM_TV(li)->v_type != VAR_STRING
+ || TV_LIST_ITEM_TV(li)->vval.v_string == NULL) {
+ continue; // Skip non-string items and empty strings.
+ }
+
+ GA_APPEND(char *, &ga, xstrdup((const char *)TV_LIST_ITEM_TV(li)->vval.v_string));
+ });
+ tv_list_unref(retlist);
+
+ *file = ga.ga_data;
+ *num_file = ga.ga_len;
+ return OK;
+}
+
/// Expand color scheme, compiler or filetype names.
/// Search from 'runtimepath':
/// 'runtimepath'/{dirnames}/{pat}.vim
diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c
index c4d8f75a21..cee657c8c9 100644
--- a/src/nvim/extmark.c
+++ b/src/nvim/extmark.c
@@ -48,28 +48,29 @@
# include "extmark.c.generated.h"
#endif
-static ExtmarkNs *buf_ns_ref(buf_T *buf, uint64_t ns_id, bool put)
+static uint32_t *buf_ns_ref(buf_T *buf, uint32_t ns_id, bool put)
{
- return map_ref(uint64_t, ExtmarkNs)(buf->b_extmark_ns, ns_id, put);
+ return map_ref(uint32_t, uint32_t)(buf->b_extmark_ns, ns_id, put);
}
/// Create or update an extmark
///
/// must not be used during iteration!
-/// @returns the internal mark id
-uint64_t extmark_set(buf_T *buf, uint64_t ns_id, uint64_t *idp, int row, colnr_T col, int end_row,
- colnr_T end_col, Decoration *decor, bool right_gravity, bool end_right_gravity,
- ExtmarkOp op)
+void extmark_set(buf_T *buf, uint32_t ns_id, uint32_t *idp, int row, colnr_T col, int end_row,
+ colnr_T end_col, Decoration *decor, bool right_gravity, bool end_right_gravity,
+ ExtmarkOp op)
{
- ExtmarkNs *ns = buf_ns_ref(buf, ns_id, true);
- assert(ns != NULL);
- mtpos_t old_pos;
- uint64_t mark = 0;
- uint64_t id = idp ? *idp : 0;
+ uint32_t *ns = buf_ns_ref(buf, ns_id, true);
+ uint32_t id = idp ? *idp : 0;
+ bool decor_full = false;
uint8_t decor_level = kDecorLevelNone; // no decor
if (decor) {
+ if (kv_size(decor->virt_text) || kv_size(decor->virt_lines)) {
+ decor_full = true;
+ decor = xmemdup(decor, sizeof *decor);
+ }
decor_level = kDecorLevelVisible; // decor affects redraw
if (kv_size(decor->virt_lines)) {
decor_level = kDecorLevelVirtLine; // decor affects horizontal size
@@ -77,50 +78,64 @@ uint64_t extmark_set(buf_T *buf, uint64_t ns_id, uint64_t *idp, int row, colnr_T
}
if (id == 0) {
- id = ns->free_id++;
+ id = ++*ns;
} else {
- uint64_t old_mark = map_get(uint64_t, uint64_t)(ns->map, id);
- if (old_mark) {
- if (old_mark & MARKTREE_PAIRED_FLAG || end_row > -1) {
+ MarkTreeIter itr[1] = { 0 };
+ mtkey_t old_mark = marktree_lookup_ns(buf->b_marktree, ns_id, id, false, itr);
+ if (old_mark.id) {
+ if (mt_paired(old_mark) || end_row > -1) {
extmark_del(buf, ns_id, id);
} else {
- MarkTreeIter itr[1] = { 0 };
- old_pos = marktree_lookup(buf->b_marktree, old_mark, itr);
+ // TODO(bfredl): we need to do more if "revising" a decoration mark.
assert(itr->node);
- if (old_pos.row == row && old_pos.col == col) {
- ExtmarkItem it = map_del(uint64_t, ExtmarkItem)(buf->b_extmark_index,
- old_mark);
- if (it.decor) {
- decor_remove(buf, row, row, it.decor);
+ if (old_mark.pos.row == row && old_mark.pos.col == col) {
+ if (marktree_decor_level(old_mark) > kDecorLevelNone) {
+ decor_remove(buf, row, row, old_mark.decor_full);
+ old_mark.decor_full = NULL;
+ }
+ old_mark.flags = 0;
+ if (decor_full) {
+ old_mark.decor_full = decor;
+ } else if (decor) {
+ old_mark.hl_id = decor->hl_id;
+ // Workaround: the gcc compiler of functionaltest-lua build
+ // apparently incapable of handling basic integer constants.
+ // This can be underanged as soon as we bump minimal gcc version.
+ old_mark.flags = (uint16_t)(old_mark.flags
+ | (decor->hl_eol ? (uint16_t)MT_FLAG_HL_EOL : (uint16_t)0));
+ old_mark.priority = decor->priority;
}
- mark = marktree_revise(buf->b_marktree, itr, decor_level);
+ marktree_revise(buf->b_marktree, itr, decor_level, old_mark);
goto revised;
}
marktree_del_itr(buf->b_marktree, itr, false);
}
} else {
- ns->free_id = MAX(ns->free_id, id+1);
+ *ns = MAX(*ns, id);
}
}
- if (end_row > -1) {
- mark = marktree_put_pair(buf->b_marktree,
- row, col, right_gravity,
- end_row, end_col, end_right_gravity, decor_level);
- } else {
- mark = marktree_put(buf->b_marktree, row, col, right_gravity, decor_level);
+ mtkey_t mark = { { row, col }, ns_id, id, 0,
+ mt_flags(right_gravity, decor_level), 0, NULL };
+ if (decor_full) {
+ mark.decor_full = decor;
+ } else if (decor) {
+ mark.hl_id = decor->hl_id;
+ // workaround: see above
+ mark.flags = (uint16_t)(mark.flags | (decor->hl_eol ? (uint16_t)MT_FLAG_HL_EOL : (uint16_t)0));
+ mark.priority = decor->priority;
}
-revised:
- map_put(uint64_t, ExtmarkItem)(buf->b_extmark_index, mark,
- (ExtmarkItem){ ns_id, id, decor });
- map_put(uint64_t, uint64_t)(ns->map, id, mark);
+ marktree_put(buf->b_marktree, mark, end_row, end_col, end_right_gravity);
+revised:
if (op != kExtmarkNoUndo) {
// TODO(bfredl): this doesn't cover all the cases and probably shouldn't
// be done "prematurely". Any movement in undo history might necessitate
- // adding new marks to old undo headers.
- u_extmark_set(buf, mark, row, col);
+ // adding new marks to old undo headers. add a test case for this (doesn't
+ // fail extmark_spec.lua, and it should)
+ uint64_t mark_id = mt_lookup_id(ns_id, id, false);
+ u_extmark_set(buf, mark_id, row, col);
}
if (decor) {
@@ -133,18 +148,17 @@ revised:
if (idp) {
*idp = id;
}
- return mark;
}
static bool extmark_setraw(buf_T *buf, uint64_t mark, int row, colnr_T col)
{
MarkTreeIter itr[1] = { 0 };
- mtpos_t pos = marktree_lookup(buf->b_marktree, mark, itr);
- if (pos.row == -1) {
+ mtkey_t key = marktree_lookup(buf->b_marktree, mark, itr);
+ if (key.pos.row == -1) {
return false;
}
- if (pos.row == row && pos.col == col) {
+ if (key.pos.row == row && key.pos.col == col) {
return true;
}
@@ -154,45 +168,35 @@ static bool extmark_setraw(buf_T *buf, uint64_t mark, int row, colnr_T col)
// Remove an extmark
// Returns 0 on missing id
-bool extmark_del(buf_T *buf, uint64_t ns_id, uint64_t id)
+bool extmark_del(buf_T *buf, uint32_t ns_id, uint32_t id)
{
- ExtmarkNs *ns = buf_ns_ref(buf, ns_id, false);
- if (!ns) {
- return false;
- }
-
- uint64_t mark = map_get(uint64_t, uint64_t)(ns->map, id);
- if (!mark) {
+ MarkTreeIter itr[1] = { 0 };
+ mtkey_t key = marktree_lookup_ns(buf->b_marktree, ns_id, id, false, itr);
+ if (!key.id) {
return false;
}
-
- MarkTreeIter itr[1] = { 0 };
- mtpos_t pos = marktree_lookup(buf->b_marktree, mark, itr);
- assert(pos.row >= 0);
+ assert(key.pos.row >= 0);
marktree_del_itr(buf->b_marktree, itr, false);
- ExtmarkItem item = map_get(uint64_t, ExtmarkItem)(buf->b_extmark_index, mark);
- mtpos_t pos2 = pos;
- if (mark & MARKTREE_PAIRED_FLAG) {
- pos2 = marktree_lookup(buf->b_marktree, mark|MARKTREE_END_FLAG, itr);
- assert(pos2.row >= 0);
+ mtkey_t key2 = key;
+
+ if (mt_paired(key)) {
+ key2 = marktree_lookup_ns(buf->b_marktree, ns_id, id, true, itr);
+ assert(key2.pos.row >= 0);
marktree_del_itr(buf->b_marktree, itr, false);
}
- if (item.decor) {
- decor_remove(buf, pos.row, pos2.row, item.decor);
+ if (marktree_decor_level(key) > kDecorLevelNone) {
+ decor_remove(buf, key.pos.row, key2.pos.row, key.decor_full);
}
- map_del(uint64_t, uint64_t)(ns->map, id);
- map_del(uint64_t, ExtmarkItem)(buf->b_extmark_index, mark);
-
// TODO(bfredl): delete it from current undo header, opportunistically?
return true;
}
// Free extmarks in a ns between lines
// if ns = 0, it means clear all namespaces
-bool extmark_clear(buf_T *buf, uint64_t ns_id, int l_row, colnr_T l_col, int u_row, colnr_T u_col)
+bool extmark_clear(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_row, colnr_T u_col)
{
if (!map_size(buf->b_extmark_ns)) {
return false;
@@ -201,68 +205,58 @@ bool extmark_clear(buf_T *buf, uint64_t ns_id, int l_row, colnr_T l_col, int u_r
bool marks_cleared = false;
bool all_ns = (ns_id == 0);
- ExtmarkNs *ns = NULL;
+ uint32_t *ns = NULL;
if (!all_ns) {
ns = buf_ns_ref(buf, ns_id, false);
if (!ns) {
// nothing to do
return false;
}
-
- // TODO(bfredl): if map_size(ns->map) << buf->b_marktree.n_nodes
- // it could be faster to iterate over the map instead
}
// the value is either zero or the lnum (row+1) if highlight was present.
static Map(uint64_t, ssize_t) delete_set = MAP_INIT;
- typedef struct { Decoration *decor; int row1; } DecorItem;
+ typedef struct { int row1; } DecorItem;
static kvec_t(DecorItem) decors;
MarkTreeIter itr[1] = { 0 };
marktree_itr_get(buf->b_marktree, l_row, l_col, itr);
while (true) {
- mtmark_t mark = marktree_itr_current(itr);
- if (mark.row < 0
- || mark.row > u_row
- || (mark.row == u_row && mark.col > u_col)) {
+ mtkey_t mark = marktree_itr_current(itr);
+ if (mark.pos.row < 0
+ || mark.pos.row > u_row
+ || (mark.pos.row == u_row && mark.pos.col > u_col)) {
break;
}
- ssize_t *del_status = map_ref(uint64_t, ssize_t)(&delete_set, mark.id,
+ ssize_t *del_status = map_ref(uint64_t, ssize_t)(&delete_set, mt_lookup_key(mark),
false);
if (del_status) {
marktree_del_itr(buf->b_marktree, itr, false);
if (*del_status >= 0) { // we had a decor_id
DecorItem it = kv_A(decors, *del_status);
- decor_remove(buf, it.row1, mark.row, it.decor);
+ decor_remove(buf, it.row1, mark.pos.row, mark.decor_full);
}
- map_del(uint64_t, ssize_t)(&delete_set, mark.id);
+ map_del(uint64_t, ssize_t)(&delete_set, mt_lookup_key(mark));
continue;
}
- uint64_t start_id = mark.id & ~MARKTREE_END_FLAG;
- ExtmarkItem item = map_get(uint64_t, ExtmarkItem)(buf->b_extmark_index,
- start_id);
-
- assert(item.ns_id > 0 && item.mark_id > 0);
- if (item.mark_id > 0 && (item.ns_id == ns_id || all_ns)) {
+ assert(mark.ns > 0 && mark.id > 0);
+ if (mark.ns == ns_id || all_ns) {
marks_cleared = true;
- if (mark.id & MARKTREE_PAIRED_FLAG) {
- uint64_t other = mark.id ^ MARKTREE_END_FLAG;
+ if (mt_paired(mark)) {
+ uint64_t other = mt_lookup_id(mark.ns, mark.id, !mt_end(mark));
ssize_t decor_id = -1;
- if (item.decor) {
+ if (marktree_decor_level(mark) > kDecorLevelNone) {
// Save the decoration and the first pos. Clear the decoration
// later when we know the full range.
decor_id = (ssize_t)kv_size(decors);
kv_push(decors,
- ((DecorItem) { .decor = item.decor, .row1 = mark.row }));
+ ((DecorItem) { .row1 = mark.pos.row }));
}
map_put(uint64_t, ssize_t)(&delete_set, other, decor_id);
- } else if (item.decor) {
- decor_remove(buf, mark.row, mark.row, item.decor);
+ } else if (mark.decor_full) {
+ decor_remove(buf, mark.pos.row, mark.pos.row, mark.decor_full);
}
- ExtmarkNs *my_ns = all_ns ? buf_ns_ref(buf, item.ns_id, false) : ns;
- map_del(uint64_t, uint64_t)(my_ns->map, item.mark_id);
- map_del(uint64_t, ExtmarkItem)(buf->b_extmark_index, start_id);
marktree_del_itr(buf->b_marktree, itr, false);
} else {
marktree_itr_next(buf->b_marktree, itr);
@@ -271,12 +265,12 @@ bool extmark_clear(buf_T *buf, uint64_t ns_id, int l_row, colnr_T l_col, int u_r
uint64_t id;
ssize_t decor_id;
map_foreach(&delete_set, id, decor_id, {
- mtpos_t pos = marktree_lookup(buf->b_marktree, id, itr);
+ mtkey_t mark = marktree_lookup(buf->b_marktree, id, itr);
assert(itr->node);
marktree_del_itr(buf->b_marktree, itr, false);
if (decor_id >= 0) {
DecorItem it = kv_A(decors, decor_id);
- decor_remove(buf, it.row1, pos.row, it.decor);
+ decor_remove(buf, it.row1, mark.pos.row, mark.decor_full);
}
});
map_clear(uint64_t, ssize_t)(&delete_set);
@@ -290,7 +284,7 @@ bool extmark_clear(buf_T *buf, uint64_t ns_id, int l_row, colnr_T l_col, int u_r
// will be searched to the start, or end
// dir can be set to control the order of the array
// amount = amount of marks to find or -1 for all
-ExtmarkInfoArray extmark_get(buf_T *buf, uint64_t ns_id, int l_row, colnr_T l_col, int u_row,
+ExtmarkInfoArray extmark_get(buf_T *buf, uint32_t ns_id, int l_row, colnr_T l_col, int u_row,
colnr_T u_col, int64_t amount, bool reverse)
{
ExtmarkInfoArray array = KV_INITIAL_VALUE;
@@ -300,30 +294,24 @@ ExtmarkInfoArray extmark_get(buf_T *buf, uint64_t ns_id, int l_row, colnr_T l_co
itr, reverse, false, NULL);
int order = reverse ? -1 : 1;
while ((int64_t)kv_size(array) < amount) {
- mtmark_t mark = marktree_itr_current(itr);
- mtpos_t endpos = { -1, -1 };
- if (mark.row < 0
- || (mark.row - u_row) * order > 0
- || (mark.row == u_row && (mark.col - u_col) * order > 0)) {
+ mtkey_t mark = marktree_itr_current(itr);
+ if (mark.pos.row < 0
+ || (mark.pos.row - u_row) * order > 0
+ || (mark.pos.row == u_row && (mark.pos.col - u_col) * order > 0)) {
break;
}
- if (mark.id & MARKTREE_END_FLAG) {
+ if (mt_end(mark)) {
goto next_mark;
- } else if (mark.id & MARKTREE_PAIRED_FLAG) {
- endpos = marktree_lookup(buf->b_marktree, mark.id | MARKTREE_END_FLAG,
- NULL);
}
-
- ExtmarkItem item = map_get(uint64_t, ExtmarkItem)(buf->b_extmark_index,
- mark.id);
- if (item.ns_id == ns_id) {
- kv_push(array, ((ExtmarkInfo) { .ns_id = item.ns_id,
- .mark_id = item.mark_id,
- .row = mark.row, .col = mark.col,
+ if (mark.ns == ns_id) {
+ mtpos_t endpos = marktree_get_altpos(buf->b_marktree, mark, NULL);
+ kv_push(array, ((ExtmarkInfo) { .ns_id = mark.ns,
+ .mark_id = mark.id,
+ .row = mark.pos.row, .col = mark.pos.col,
.end_row = endpos.row,
.end_col = endpos.col,
- .decor = item.decor }));
+ .decor = get_decor(mark) }));
}
next_mark:
if (reverse) {
@@ -336,36 +324,23 @@ next_mark:
}
// Lookup an extmark by id
-ExtmarkInfo extmark_from_id(buf_T *buf, uint64_t ns_id, uint64_t id)
+ExtmarkInfo extmark_from_id(buf_T *buf, uint32_t ns_id, uint32_t id)
{
- ExtmarkNs *ns = buf_ns_ref(buf, ns_id, false);
- ExtmarkInfo ret = { 0, 0, -1, -1, -1, -1, NULL };
- if (!ns) {
+ ExtmarkInfo ret = { 0, 0, -1, -1, -1, -1, DECORATION_INIT };
+ mtkey_t mark = marktree_lookup_ns(buf->b_marktree, ns_id, id, false, NULL);
+ if (!mark.id) {
return ret;
}
-
- uint64_t mark = map_get(uint64_t, uint64_t)(ns->map, id);
- if (!mark) {
- return ret;
- }
-
- mtpos_t pos = marktree_lookup(buf->b_marktree, mark, NULL);
- mtpos_t endpos = { -1, -1 };
- if (mark & MARKTREE_PAIRED_FLAG) {
- endpos = marktree_lookup(buf->b_marktree, mark | MARKTREE_END_FLAG, NULL);
- }
- assert(pos.row >= 0);
-
- ExtmarkItem item = map_get(uint64_t, ExtmarkItem)(buf->b_extmark_index,
- mark);
+ assert(mark.pos.row >= 0);
+ mtpos_t endpos = marktree_get_altpos(buf->b_marktree, mark, NULL);
ret.ns_id = ns_id;
ret.mark_id = id;
- ret.row = pos.row;
- ret.col = pos.col;
+ ret.row = mark.pos.row;
+ ret.col = mark.pos.col;
ret.end_row = endpos.row;
ret.end_col = endpos.col;
- ret.decor = item.decor;
+ ret.decor = get_decor(mark);
return ret;
}
@@ -378,25 +353,26 @@ void extmark_free_all(buf_T *buf)
return;
}
- uint64_t id;
- ExtmarkNs ns;
- ExtmarkItem item;
+ MarkTreeIter itr[1] = { 0 };
+ marktree_itr_get(buf->b_marktree, 0, 0, itr);
+ while (true) {
+ mtkey_t mark = marktree_itr_current(itr);
+ if (mark.pos.row < 0) {
+ break;
+ }
- marktree_clear(buf->b_marktree);
+ // don't free mark.decor_full twice for a paired mark.
+ if (!(mt_paired(mark) && mt_end(mark))) {
+ decor_free(mark.decor_full);
+ }
- map_foreach(buf->b_extmark_ns, id, ns, {
- (void)id;
- map_destroy(uint64_t, uint64_t)(ns.map);
- });
- map_destroy(uint64_t, ExtmarkNs)(buf->b_extmark_ns);
- map_init(uint64_t, ExtmarkNs, buf->b_extmark_ns);
+ marktree_itr_next(buf->b_marktree, itr);
+ }
- map_foreach(buf->b_extmark_index, id, item, {
- (void)id;
- decor_free(item.decor);
- });
- map_destroy(uint64_t, ExtmarkItem)(buf->b_extmark_index);
- map_init(uint64_t, ExtmarkItem, buf->b_extmark_index);
+ marktree_clear(buf->b_marktree);
+
+ map_destroy(uint32_t, uint32_t)(buf->b_extmark_ns);
+ map_init(uint32_t, uint32_t, buf->b_extmark_ns);
}
@@ -437,16 +413,16 @@ void u_extmark_copy(buf_T *buf, int l_row, colnr_T l_col, int u_row, colnr_T u_c
MarkTreeIter itr[1] = { 0 };
marktree_itr_get(buf->b_marktree, l_row, l_col, itr);
while (true) {
- mtmark_t mark = marktree_itr_current(itr);
- if (mark.row < 0
- || mark.row > u_row
- || (mark.row == u_row && mark.col > u_col)) {
+ mtkey_t mark = marktree_itr_current(itr);
+ if (mark.pos.row < 0
+ || mark.pos.row > u_row
+ || (mark.pos.row == u_row && mark.pos.col > u_col)) {
break;
}
ExtmarkSavePos pos;
- pos.mark = mark.id;
- pos.old_row = mark.row;
- pos.old_col = mark.col;
+ pos.mark = mt_lookup_key(mark);
+ pos.old_row = mark.pos.row;
+ pos.old_col = mark.pos.col;
pos.row = -1;
pos.col = -1;
diff --git a/src/nvim/extmark.h b/src/nvim/extmark.h
index c70db9f7aa..c6ec1d0aa8 100644
--- a/src/nvim/extmark.h
+++ b/src/nvim/extmark.h
@@ -3,6 +3,7 @@
#include "nvim/buffer_defs.h"
#include "nvim/extmark_defs.h"
+#include "nvim/decoration.h"
#include "nvim/marktree.h"
#include "nvim/pos.h"
@@ -15,7 +16,7 @@ typedef struct {
colnr_T col;
int end_row;
colnr_T end_col;
- Decoration *decor;
+ Decoration decor; // TODO(bfredl): CHONKY
} ExtmarkInfo;
typedef kvec_t(ExtmarkInfo) ExtmarkInfoArray;
diff --git a/src/nvim/extmark_defs.h b/src/nvim/extmark_defs.h
index bbe8504ebf..5570b5c71e 100644
--- a/src/nvim/extmark_defs.h
+++ b/src/nvim/extmark_defs.h
@@ -4,23 +4,11 @@
#include "nvim/lib/kvec.h"
#include "nvim/types.h"
-typedef struct Decoration Decoration;
-
typedef struct {
char *text;
int hl_id;
} VirtTextChunk;
-
-typedef struct {
- uint64_t ns_id;
- uint64_t mark_id;
- // TODO(bfredl): a lot of small allocations. Should probably use
- // kvec_t(Decoration) as an arena. Alternatively, store ns_id/mark_id
- // _inline_ in MarkTree and use the map only for decorations.
- Decoration *decor;
-} ExtmarkItem;
-
typedef struct undo_object ExtmarkUndoObject;
typedef kvec_t(ExtmarkUndoObject) extmark_undo_vec_t;
diff --git a/src/nvim/file_search.c b/src/nvim/file_search.c
index d31021b3ef..b2cd5c510b 100644
--- a/src/nvim/file_search.c
+++ b/src/nvim/file_search.c
@@ -607,7 +607,7 @@ char_u *vim_findfile(void *search_ctx_arg)
for (;;) {
// downward search loop
for (;;) {
- // check if user user wants to stop the search
+ // check if user wants to stop the search
os_breakcheck();
if (got_int) {
break;
@@ -1139,7 +1139,7 @@ static int ff_check_visited(ff_visited_T **visited_list, char_u *fname, char_u *
bool url = false;
FileID file_id;
- // For an URL we only compare the name, otherwise we compare the
+ // For a URL we only compare the name, otherwise we compare the
// device/inode.
if (path_with_url((char *)fname)) {
STRLCPY(ff_expand_buffer, fname, MAXPATHL);
@@ -1667,14 +1667,19 @@ int vim_chdirfile(char_u *fname, CdCause cause)
NameBuff[0] = NUL;
}
- if (os_chdir(dir) == 0) {
- if (cause != kCdCauseOther && pathcmp(dir, (char *)NameBuff, -1) != 0) {
- do_autocmd_dirchanged(dir, kCdScopeWindow, cause);
- }
- } else {
+ if (pathcmp(dir, (char *)NameBuff, -1) == 0) {
+ // nothing to do
+ return OK;
+ }
+
+ if (os_chdir(dir) != 0) {
return FAIL;
}
+ if (cause != kCdCauseOther) {
+ do_autocmd_dirchanged(dir, kCdScopeWindow, cause);
+ }
+
return OK;
}
diff --git a/src/nvim/fold.c b/src/nvim/fold.c
index b1d4321d4c..546345eeac 100644
--- a/src/nvim/fold.c
+++ b/src/nvim/fold.c
@@ -2332,7 +2332,7 @@ static linenr_T foldUpdateIEMSRecurse(garray_T *const gap, const int level,
* firstlnum.
*/
while (!got_int) {
- // set concat to 1 if it's allowed to concatenated this fold
+ // set concat to 1 if it's allowed to concatenate this fold
// with a previous one that touches it.
if (flp->start != 0 || flp->had_end <= MAX_LEVEL) {
concat = 0;
diff --git a/src/nvim/generators/gen_api_dispatch.lua b/src/nvim/generators/gen_api_dispatch.lua
index 21f8c3855e..c6dd25154b 100644
--- a/src/nvim/generators/gen_api_dispatch.lua
+++ b/src/nvim/generators/gen_api_dispatch.lua
@@ -441,8 +441,8 @@ local function process_function(fn)
local cparam = string.format('arg%u', j)
local param_type = real_type(param[1])
local lc_param_type = real_type(param[1]):lower()
- local extra = ((param_type == "Object" or param_type == "Dictionary") and "false, ") or ""
- if param[1] == "DictionaryOf(LuaRef)" then
+ local extra = param_type == "Dictionary" and "false, " or ""
+ if param[1] == "Object" or param[1] == "DictionaryOf(LuaRef)" then
extra = "true, "
end
local errshift = 0
diff --git a/src/nvim/generators/gen_char_blob.lua b/src/nvim/generators/gen_char_blob.lua
index a7dad50d48..3ec1ff2caf 100644
--- a/src/nvim/generators/gen_char_blob.lua
+++ b/src/nvim/generators/gen_char_blob.lua
@@ -1,12 +1,26 @@
if arg[1] == '--help' then
print('Usage:')
- print(' '..arg[0]..' target source varname [source varname]...')
+ print(' '..arg[0]..' [-c] target source varname [source varname]...')
print('')
print('Generates C file with big uint8_t blob.')
print('Blob will be stored in a static const array named varname.')
os.exit()
end
+-- Recognized options:
+-- -c compile Lua bytecode
+local options = {}
+
+while true do
+ local opt = string.match(arg[1], "^-(%w)")
+ if not opt then
+ break
+ end
+
+ options[opt] = true
+ table.remove(arg, 1)
+end
+
assert(#arg >= 3 and (#arg - 1) % 2 == 0)
local target_file = arg[1] or error('Need a target file')
@@ -14,6 +28,7 @@ local target = io.open(target_file, 'w')
target:write('#include <stdint.h>\n\n')
+local warn_on_missing_compiler = true
local varnames = {}
for argi = 2, #arg, 2 do
local source_file = arg[argi]
@@ -23,11 +38,26 @@ for argi = 2, #arg, 2 do
end
varnames[varname] = source_file
- local source = io.open(source_file, 'r')
- or error(string.format("source_file %q doesn't exist", source_file))
-
target:write(('static const uint8_t %s[] = {\n'):format(varname))
+ local output
+ if options.c then
+ local luac = os.getenv("LUAC_PRG")
+ if luac and luac ~= "" then
+ output = io.popen(luac:format(source_file), "r"):read("*a")
+ elseif warn_on_missing_compiler then
+ print("LUAC_PRG is missing, embedding raw source")
+ warn_on_missing_compiler = false
+ end
+ end
+
+ if not output then
+ local source = io.open(source_file, "r")
+ or error(string.format("source_file %q doesn't exist", source_file))
+ output = source:read("*a")
+ source:close()
+ end
+
local num_bytes = 0
local MAX_NUM_BYTES = 15 -- 78 / 5: maximum number of bytes on one line
target:write(' ')
@@ -41,19 +71,13 @@ for argi = 2, #arg, 2 do
end
end
- for line in source:lines() do
- for i = 1, string.len(line) do
- local byte = line:byte(i)
- assert(byte ~= 0)
- target:write(string.format(' %3u,', byte))
- increase_num_bytes()
- end
- target:write(string.format(' %3u,', string.byte('\n', 1)))
+ for i = 1, string.len(output) do
+ local byte = output:byte(i)
+ target:write(string.format(' %3u,', byte))
increase_num_bytes()
end
- target:write(' 0};\n')
- source:close()
+ target:write(' 0};\n')
end
target:close()
diff --git a/src/nvim/generators/gen_keysets.lua b/src/nvim/generators/gen_keysets.lua
index 63ef202fe1..01d8c1d357 100644
--- a/src/nvim/generators/gen_keysets.lua
+++ b/src/nvim/generators/gen_keysets.lua
@@ -26,6 +26,17 @@ local defspipe = io.open(defs_file, 'wb')
local keysets = require'api.keysets'
+local keywords = {
+ register = true,
+}
+
+local function sanitize(key)
+ if keywords[key] then
+ return key .. "_"
+ end
+ return key
+end
+
for name, keys in pairs(keysets) do
local neworder, hashfun = hashy.hashy_hash(name, keys, function (idx)
return name.."_table["..idx.."].str"
@@ -33,7 +44,7 @@ for name, keys in pairs(keysets) do
defspipe:write("typedef struct {\n")
for _, key in ipairs(neworder) do
- defspipe:write(" Object "..key..";\n")
+ defspipe:write(" Object "..sanitize(key)..";\n")
end
defspipe:write("} KeyDict_"..name..";\n\n")
@@ -41,7 +52,7 @@ for name, keys in pairs(keysets) do
funcspipe:write("KeySetLink "..name.."_table[] = {\n")
for _, key in ipairs(neworder) do
- funcspipe:write(' {"'..key..'", offsetof(KeyDict_'..name..", "..key..")},\n")
+ funcspipe:write(' {"'..key..'", offsetof(KeyDict_'..name..", "..sanitize(key)..")},\n")
end
funcspipe:write(' {NULL, 0},\n')
funcspipe:write("};\n\n")
diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c
index 05c38a5233..ef590adb3a 100644
--- a/src/nvim/getchar.c
+++ b/src/nvim/getchar.c
@@ -15,6 +15,7 @@
#include <stdbool.h>
#include <string.h>
+#include "nvim/api/private/helpers.h"
#include "nvim/ascii.h"
#include "nvim/assert.h"
#include "nvim/buffer_defs.h"
@@ -58,25 +59,18 @@
static int curscript = 0;
FileDescriptor *scriptin[NSCRIPT] = { NULL };
-/*
- * These buffers are used for storing:
- * - stuffed characters: A command that is translated into another command.
- * - redo characters: will redo the last change.
- * - recorded characters: for the "q" command.
- *
- * The bytes are stored like in the typeahead buffer:
- * - K_SPECIAL introduces a special key (two more bytes follow). A literal
- * K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER.
- * - CSI introduces a GUI termcap code (also when gui.in_use is FALSE,
- * otherwise switching the GUI on would make mappings invalid).
- * A literal CSI is stored as CSI KS_EXTRA KE_CSI.
- * These translations are also done on multi-byte characters!
- *
- * Escaping CSI bytes is done by the system-specific input functions, called
- * by ui_inchar().
- * Escaping K_SPECIAL is done by inchar().
- * Un-escaping is done by vgetc().
- */
+// These buffers are used for storing:
+// - stuffed characters: A command that is translated into another command.
+// - redo characters: will redo the last change.
+// - recorded characters: for the "q" command.
+//
+// The bytes are stored like in the typeahead buffer:
+// - K_SPECIAL introduces a special key (two more bytes follow). A literal
+// K_SPECIAL is stored as K_SPECIAL KS_SPECIAL KE_FILLER.
+// These translations are also done on multi-byte characters!
+//
+// Escaping K_SPECIAL is done by inchar().
+// Un-escaping is done by vgetc().
#define MINIMAL_SIZE 20 // minimal size for b_str
@@ -146,7 +140,7 @@ static int KeyNoremap = 0; // remapping flags
// typebuf.tb_buf has three parts: room in front (for result of mappings), the
// middle for typeahead and room for new characters (which needs to be 3 *
-// MAXMAPLEN) for the Amiga).
+// MAXMAPLEN for the Amiga).
#define TYPELEN_INIT (5 * (MAXMAPLEN + 3))
static char_u typebuf_init[TYPELEN_INIT]; // initial typebuf.tb_buf
static char_u noremapbuf_init[TYPELEN_INIT]; // initial typebuf.tb_noremap
@@ -172,7 +166,7 @@ void free_buff(buffheader_T *buf)
}
/// Return the contents of a buffer as a single string.
-/// K_SPECIAL and CSI in the returned string are escaped.
+/// K_SPECIAL in the returned string is escaped.
///
/// @param dozero count == zero is not an error
static char_u *get_buffcont(buffheader_T *buffer, int dozero)
@@ -201,11 +195,9 @@ static char_u *get_buffcont(buffheader_T *buffer, int dozero)
return p;
}
-/*
- * Return the contents of the record buffer as a single string
- * and clear the record buffer.
- * K_SPECIAL and CSI in the returned string are escaped.
- */
+/// Return the contents of the record buffer as a single string
+/// and clear the record buffer.
+/// K_SPECIAL in the returned string is escaped.
char_u *get_recorded(void)
{
char_u *p;
@@ -235,10 +227,8 @@ char_u *get_recorded(void)
return p;
}
-/*
- * Return the contents of the redo buffer as a single string.
- * K_SPECIAL and CSI in the returned string are escaped.
- */
+/// Return the contents of the redo buffer as a single string.
+/// K_SPECIAL in the returned string is escaped.
char_u *get_inserted(void)
{
return get_buffcont(&redobuff, FALSE);
@@ -246,7 +236,7 @@ char_u *get_inserted(void)
/// Add string after the current block of the given buffer
///
-/// K_SPECIAL and CSI should have been escaped already.
+/// K_SPECIAL should have been escaped already.
///
/// @param[out] buf Buffer to add to.
/// @param[in] s String to add.
@@ -304,10 +294,8 @@ static void add_num_buff(buffheader_T *buf, long n)
add_buff(buf, number, -1L);
}
-/*
- * Add character 'c' to buffer "buf".
- * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
- */
+/// Add character 'c' to buffer "buf".
+/// Translates special keys, NUL, K_SPECIAL and multibyte characters.
static void add_char_buff(buffheader_T *buf, int c)
{
uint8_t bytes[MB_MAXBYTES + 1];
@@ -339,12 +327,10 @@ static void add_char_buff(buffheader_T *buf, int c)
}
}
-/*
- * Get one byte from the read buffers. Use readbuf1 one first, use readbuf2
- * if that one is empty.
- * If advance == TRUE go to the next char.
- * No translation is done K_SPECIAL and CSI are escaped.
- */
+/// Get one byte from the read buffers. Use readbuf1 one first, use readbuf2
+/// if that one is empty.
+/// If advance == TRUE go to the next char.
+/// No translation is done K_SPECIAL is escaped.
static int read_readbuffers(int advance)
{
int c;
@@ -523,10 +509,8 @@ void restoreRedobuff(save_redo_T *save_redo)
old_redobuff = save_redo->sr_old_redobuff;
}
-/*
- * Append "s" to the redo buffer.
- * K_SPECIAL and CSI should already have been escaped.
- */
+/// Append "s" to the redo buffer.
+/// K_SPECIAL should already have been escaped.
void AppendToRedobuff(const char *s)
{
if (!block_redo) {
@@ -535,7 +519,7 @@ void AppendToRedobuff(const char *s)
}
/// Append to Redo buffer literally, escaping special characters with CTRL-V.
-/// K_SPECIAL and CSI are escaped as well.
+/// K_SPECIAL is escaped as well.
///
/// @param str String to append
/// @param len Length of `str` or -1 for up to the NUL.
@@ -583,10 +567,8 @@ void AppendToRedobuffLit(const char_u *str, int len)
}
}
-/*
- * Append a character to the redo buffer.
- * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
- */
+/// Append a character to the redo buffer.
+/// Translates special keys, NUL, K_SPECIAL and multibyte characters.
void AppendCharToRedobuff(int c)
{
if (!block_redo) {
@@ -604,17 +586,15 @@ void AppendNumberToRedobuff(long n)
}
}
-/*
- * Append string "s" to the stuff buffer.
- * CSI and K_SPECIAL must already have been escaped.
- */
+/// Append string "s" to the stuff buffer.
+/// K_SPECIAL must already have been escaped.
void stuffReadbuff(const char *s)
{
add_buff(&readbuf1, s, -1L);
}
/// Append string "s" to the redo stuff buffer.
-/// @remark CSI and K_SPECIAL must already have been escaped.
+/// @remark K_SPECIAL must already have been escaped.
void stuffRedoReadbuff(const char *s)
{
add_buff(&readbuf2, s, -1L);
@@ -625,11 +605,9 @@ void stuffReadbuffLen(const char *s, long len)
add_buff(&readbuf1, s, len);
}
-/*
- * Stuff "s" into the stuff buffer, leaving special key codes unmodified and
- * escaping other K_SPECIAL and CSI bytes.
- * Change CR, LF and ESC into a space.
- */
+/// Stuff "s" into the stuff buffer, leaving special key codes unmodified and
+/// escaping other K_SPECIAL bytes.
+/// Change CR, LF and ESC into a space.
void stuffReadbuffSpec(const char *s)
{
while (*s != NUL) {
@@ -647,10 +625,8 @@ void stuffReadbuffSpec(const char *s)
}
}
-/*
- * Append a character to the stuff buffer.
- * Translates special keys, NUL, CSI, K_SPECIAL and multibyte characters.
- */
+/// Append a character to the stuff buffer.
+/// Translates special keys, NUL, K_SPECIAL and multibyte characters.
void stuffcharReadbuff(int c)
{
add_char_buff(&readbuf1, c);
@@ -664,12 +640,12 @@ void stuffnumReadbuff(long n)
add_num_buff(&readbuf1, n);
}
-// Read a character from the redo buffer. Translates K_SPECIAL, CSI and
-// multibyte characters.
-// The redo buffer is left as it is.
-// If init is true, prepare for redo, return FAIL if nothing to redo, OK
-// otherwise.
-// If old_redo is true, use old_redobuff instead of redobuff.
+/// Read a character from the redo buffer. Translates K_SPECIAL and
+/// multibyte characters.
+/// The redo buffer is left as it is.
+/// If init is true, prepare for redo, return FAIL if nothing to redo, OK
+/// otherwise.
+/// If old_redo is true, use old_redobuff instead of redobuff.
static int read_redo(bool init, bool old_redo)
{
static buffblock_T *bp;
@@ -723,9 +699,9 @@ static int read_redo(bool init, bool old_redo)
return c;
}
-// Copy the rest of the redo buffer into the stuff buffer (in a slow way).
-// If old_redo is true, use old_redobuff instead of redobuff.
-// The escaped K_SPECIAL and CSI are copied without translation.
+/// Copy the rest of the redo buffer into the stuff buffer (in a slow way).
+/// If old_redo is true, use old_redobuff instead of redobuff.
+/// The escaped K_SPECIAL is copied without translation.
static void copy_redo(bool old_redo)
{
int c;
@@ -861,7 +837,7 @@ void init_default_mappings(void)
//
// If noremap is REMAP_YES, new string can be mapped again.
// If noremap is REMAP_NONE, new string cannot be mapped again.
-// If noremap is REMAP_SKIP, fist char of new string cannot be mapped again,
+// If noremap is REMAP_SKIP, first char of new string cannot be mapped again,
// but abbreviations are allowed.
// If noremap is REMAP_SCRIPT, new string cannot be mapped again, except for
// script-local mappings.
@@ -997,28 +973,35 @@ int ins_typebuf(char_u *str, int noremap, int offset, bool nottyped, bool silent
* Uses cmd_silent, KeyTyped and KeyNoremap to restore the flags belonging to
* the char.
*/
-void ins_char_typebuf(int c)
+void ins_char_typebuf(int c, int modifier)
{
- char_u buf[MB_MAXBYTES + 1];
- if (IS_SPECIAL(c)) {
+ char_u buf[MB_MAXBYTES + 4];
+ int idx = 0;
+ if (modifier != 0) {
buf[0] = K_SPECIAL;
- buf[1] = (char_u)K_SECOND(c);
- buf[2] = (char_u)K_THIRD(c);
+ buf[1] = KS_MODIFIER;
+ buf[2] = (char_u)modifier;
buf[3] = NUL;
+ idx = 3;
+ }
+ if (IS_SPECIAL(c)) {
+ buf[idx] = K_SPECIAL;
+ buf[idx + 1] = (char_u)K_SECOND(c);
+ buf[idx + 2] = (char_u)K_THIRD(c);
+ buf[idx + 3] = NUL;
} else {
- buf[utf_char2bytes(c, buf)] = NUL;
- char_u *p = buf;
- while (*p) {
- if ((uint8_t)(*p) == CSI || (uint8_t)(*p) == K_SPECIAL) {
- bool is_csi = (uint8_t)(*p) == CSI;
- memmove(p + 3, p + 1, STRLEN(p + 1) + 1);
+ char_u *p = buf + idx;
+ int char_len = utf_char2bytes(c, p);
+ // If the character contains K_SPECIAL bytes they need escaping.
+ for (int i = char_len; --i >= 0; p++) {
+ if ((uint8_t)(*p) == K_SPECIAL) {
+ memmove(p + 3, p + 1, (size_t)i);
*p++ = K_SPECIAL;
- *p++ = is_csi ? KS_EXTRA : KS_SPECIAL;
- *p++ = is_csi ? KE_CSI : KE_FILLER;
- } else {
- p++;
+ *p++ = KS_SPECIAL;
+ *p = KE_FILLER;
}
}
+ *p = NUL;
}
(void)ins_typebuf(buf, KeyNoremap, 0, !KeyTyped, cmd_silent);
}
@@ -1426,15 +1409,13 @@ static void updatescript(int c)
}
}
-/*
- * Get the next input character.
- * Can return a special key or a multi-byte character.
- * Can return NUL when called recursively, use safe_vgetc() if that's not
- * wanted.
- * This translates escaped K_SPECIAL and CSI bytes to a K_SPECIAL or CSI byte.
- * Collects the bytes of a multibyte character into the whole character.
- * Returns the modifiers in the global "mod_mask".
- */
+/// Get the next input character.
+/// Can return a special key or a multi-byte character.
+/// Can return NUL when called recursively, use safe_vgetc() if that's not
+/// wanted.
+/// This translates escaped K_SPECIAL bytes to a K_SPECIAL byte.
+/// Collects the bytes of a multibyte character into the whole character.
+/// Returns the modifiers in the global "mod_mask".
int vgetc(void)
{
int c, c2;
@@ -1460,8 +1441,9 @@ int vgetc(void)
mouse_row = old_mouse_row;
mouse_col = old_mouse_col;
} else {
- mod_mask = 0x0;
+ mod_mask = 0;
last_recorded_len = 0;
+
for (;;) { // this is done twice if there are modifiers
bool did_inc = false;
if (mod_mask) { // no mapping after modifier has been read
@@ -1571,14 +1553,9 @@ int vgetc(void)
buf[i] = (char_u)vgetorpeek(true);
if (buf[i] == K_SPECIAL) {
// Must be a K_SPECIAL - KS_SPECIAL - KE_FILLER sequence,
- // which represents a K_SPECIAL (0x80),
- // or a CSI - KS_EXTRA - KE_CSI sequence, which represents
- // a CSI (0x9B),
- // of a K_SPECIAL - KS_EXTRA - KE_CSI, which is CSI too.
- c = vgetorpeek(true);
- if (vgetorpeek(true) == KE_CSI && c == KS_EXTRA) {
- buf[i] = CSI;
- }
+ // which represents a K_SPECIAL (0x80).
+ (void)vgetorpeek(true); // skip KS_SPECIAL
+ (void)vgetorpeek(true); // skip KE_FILLER
}
}
no_mapping--;
@@ -1592,8 +1569,8 @@ int vgetc(void)
if (!no_mapping && KeyTyped && !(State & TERM_FOCUS)
&& (mod_mask == MOD_MASK_ALT || mod_mask == MOD_MASK_META)) {
mod_mask = 0;
- ins_char_typebuf(c);
- ins_char_typebuf(ESC);
+ ins_char_typebuf(c, 0);
+ ins_char_typebuf(ESC, 0);
continue;
}
@@ -1693,7 +1670,7 @@ typedef enum {
map_result_fail, // failed, break loop
map_result_get, // get a character from typeahead
map_result_retry, // try to map again
- map_result_nomatch // no matching mapping, get char
+ map_result_nomatch, // no matching mapping, get char
} map_result_T;
/// Handle mappings in the typeahead buffer.
@@ -1894,7 +1871,7 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
// buffer right here. Otherwise, use the mapping (loop around).
if (mp == NULL) {
*keylenp = keylen;
- return map_result_get; // got character, break for loop
+ return map_result_get; // get character from typeahead
} else {
keylen = mp_match_len;
}
@@ -1902,7 +1879,7 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
// complete match
if (keylen >= 0 && keylen <= typebuf.tb_len) {
- char_u *map_str;
+ char_u *map_str = NULL;
int save_m_expr;
int save_m_noremap;
int save_m_silent;
@@ -1947,6 +1924,7 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
save_m_silent = mp->m_silent;
char_u *save_m_keys = NULL; // only saved when needed
char_u *save_m_str = NULL; // only saved when needed
+ LuaRef save_m_luaref = mp->m_luaref;
// Handle ":map <expr>": evaluate the {rhs} as an
// expression. Also save and restore the command line
@@ -1959,8 +1937,10 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
may_garbage_collect = false;
save_m_keys = vim_strsave(mp->m_keys);
- save_m_str = vim_strsave(mp->m_str);
- map_str = eval_map_expr(save_m_str, NUL);
+ if (save_m_luaref == LUA_NOREF) {
+ save_m_str = vim_strsave(mp->m_str);
+ }
+ map_str = eval_map_expr(mp, NUL);
vgetc_busy = save_vgetc_busy;
may_garbage_collect = save_may_garbage_collect;
} else {
@@ -2039,7 +2019,7 @@ void vungetc(int c)
///
/// When `no_mapping` (global) is zero, checks for mappings in the current mode.
/// Only returns one byte (of a multi-byte character).
-/// K_SPECIAL and CSI may be escaped, need to get two more bytes then.
+/// K_SPECIAL may be escaped, need to get two more bytes then.
static int vgetorpeek(bool advance)
{
int c, c1;
@@ -2166,7 +2146,7 @@ static int vgetorpeek(bool advance)
KeyNoremap = typebuf.tb_noremap[typebuf.tb_off];
del_typebuf(1, 0);
}
- break;
+ break; // got character, break the for loop
}
// not enough characters, get more
@@ -2470,7 +2450,7 @@ static int vgetorpeek(bool advance)
/// Return the number of obtained characters.
/// Return -1 when end of input script reached.
///
-/// @param wait_time milli seconds
+/// @param wait_time milliseconds
int inchar(char_u *buf, int maxlen, long wait_time)
{
int len = 0; // Init for GCC.
@@ -2569,7 +2549,7 @@ int fix_input_buffer(char_u *buf, int len)
FUNC_ATTR_NONNULL_ALL
{
if (!using_script()) {
- // Should not escape K_SPECIAL/CSI reading input from the user because vim
+ // Should not escape K_SPECIAL reading input from the user because vim
// key codes keys are processed in input.c/input_enqueue.
buf[len] = NUL;
return len;
@@ -2580,9 +2560,8 @@ int fix_input_buffer(char_u *buf, int len)
char_u *p = buf;
// Two characters are special: NUL and K_SPECIAL.
- // Replace NUL by K_SPECIAL KS_ZERO KE_FILLER
+ // Replace NUL by K_SPECIAL KS_ZERO KE_FILLER
// Replace K_SPECIAL by K_SPECIAL KS_SPECIAL KE_FILLER
- // Replace CSI by K_SPECIAL KS_EXTRA KE_CSI
for (i = len; --i >= 0; ++p) {
if (p[0] == NUL
|| (p[0] == K_SPECIAL
@@ -2618,11 +2597,13 @@ int fix_input_buffer(char_u *buf, int len)
/// @param[in] orig_lhs Original mapping LHS, with characters to replace.
/// @param[in] orig_lhs_len `strlen` of orig_lhs.
/// @param[in] orig_rhs Original mapping RHS, with characters to replace.
+/// @param[in] rhs_lua Lua reference for Lua maps.
/// @param[in] orig_rhs_len `strlen` of orig_rhs.
/// @param[in] cpo_flags See param docs for @ref replace_termcodes.
/// @param[out] mapargs MapArguments struct holding the replaced strings.
-void set_maparg_lhs_rhs(const char_u *orig_lhs, const size_t orig_lhs_len, const char_u *orig_rhs,
- const size_t orig_rhs_len, int cpo_flags, MapArguments *mapargs)
+void set_maparg_lhs_rhs(const char_u *orig_lhs, const size_t orig_lhs_len,
+ const char_u *orig_rhs, const size_t orig_rhs_len,
+ LuaRef rhs_lua, int cpo_flags, MapArguments *mapargs)
{
char_u *lhs_buf = NULL;
char_u *rhs_buf = NULL;
@@ -2638,22 +2619,34 @@ void set_maparg_lhs_rhs(const char_u *orig_lhs, const size_t orig_lhs_len, const
true, true, true, cpo_flags);
mapargs->lhs_len = STRLEN(replaced);
STRLCPY(mapargs->lhs, replaced, sizeof(mapargs->lhs));
+ mapargs->rhs_lua = rhs_lua;
- mapargs->orig_rhs_len = orig_rhs_len;
- mapargs->orig_rhs = xcalloc(mapargs->orig_rhs_len + 1, sizeof(char_u));
- STRLCPY(mapargs->orig_rhs, orig_rhs, mapargs->orig_rhs_len + 1);
+ if (rhs_lua == LUA_NOREF) {
+ mapargs->orig_rhs_len = orig_rhs_len;
+ mapargs->orig_rhs = xcalloc(mapargs->orig_rhs_len + 1, sizeof(char_u));
+ STRLCPY(mapargs->orig_rhs, orig_rhs, mapargs->orig_rhs_len + 1);
- if (STRICMP(orig_rhs, "<nop>") == 0) { // "<Nop>" means nothing
- mapargs->rhs = xcalloc(1, sizeof(char_u)); // single null-char
- mapargs->rhs_len = 0;
- mapargs->rhs_is_noop = true;
+ if (STRICMP(orig_rhs, "<nop>") == 0) { // "<Nop>" means nothing
+ mapargs->rhs = xcalloc(1, sizeof(char_u)); // single null-char
+ mapargs->rhs_len = 0;
+ mapargs->rhs_is_noop = true;
+ } else {
+ replaced = replace_termcodes(orig_rhs, orig_rhs_len, &rhs_buf,
+ false, true, true, cpo_flags);
+ mapargs->rhs_len = STRLEN(replaced);
+ mapargs->rhs_is_noop = false;
+ mapargs->rhs = xcalloc(mapargs->rhs_len + 1, sizeof(char_u));
+ STRLCPY(mapargs->rhs, replaced, mapargs->rhs_len + 1);
+ }
} else {
- replaced = replace_termcodes(orig_rhs, orig_rhs_len, &rhs_buf,
- false, true, true, cpo_flags);
- mapargs->rhs_len = STRLEN(replaced);
- mapargs->rhs_is_noop = false;
- mapargs->rhs = xcalloc(mapargs->rhs_len + 1, sizeof(char_u));
- STRLCPY(mapargs->rhs, replaced, mapargs->rhs_len + 1);
+ char tmp_buf[64];
+ // stores <lua>ref_no<cr> in map_str
+ mapargs->orig_rhs_len = (size_t)vim_snprintf(S_LEN(tmp_buf), "<LUA>%d<CR>", rhs_lua);
+ mapargs->orig_rhs = vim_strsave((char_u *)tmp_buf);
+ mapargs->rhs_len = (size_t)vim_snprintf(S_LEN(tmp_buf), "%c%c%c%d\r", K_SPECIAL,
+ (char_u)KEY2TERMCAP0(K_LUA), KEY2TERMCAP1(K_LUA),
+ rhs_lua);
+ mapargs->rhs = vim_strsave((char_u *)tmp_buf);
}
xfree(lhs_buf);
@@ -2765,7 +2758,7 @@ int str_to_mapargs(const char_u *strargs, bool is_unmap, MapArguments *mapargs)
size_t orig_rhs_len = STRLEN(rhs_start);
set_maparg_lhs_rhs(lhs_to_replace, orig_lhs_len,
- rhs_start, orig_rhs_len,
+ rhs_start, orig_rhs_len, LUA_NOREF,
CPO_TO_CPO_FLAGS, &parsed_args);
xfree(lhs_to_replace);
@@ -2827,7 +2820,7 @@ int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev, buf_T
validate_maphash();
bool has_lhs = (args->lhs[0] != NUL);
- bool has_rhs = (args->rhs[0] != NUL) || args->rhs_is_noop;
+ bool has_rhs = args->rhs_lua != LUA_NOREF || (args->rhs[0] != NUL) || args->rhs_is_noop;
// check for :unmap without argument
if (maptype == 1 && !has_lhs) {
@@ -3017,10 +3010,14 @@ int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev, buf_T
} else { // new rhs for existing entry
mp->m_mode &= ~mode; // remove mode bits
if (mp->m_mode == 0 && !did_it) { // reuse entry
- xfree(mp->m_str);
+ XFREE_CLEAR(mp->m_str);
+ XFREE_CLEAR(mp->m_orig_str);
+ XFREE_CLEAR(mp->m_desc);
+ NLUA_CLEAR_REF(mp->m_luaref);
+
mp->m_str = vim_strsave(rhs);
- xfree(mp->m_orig_str);
mp->m_orig_str = vim_strsave(orig_rhs);
+ mp->m_luaref = args->rhs_lua;
mp->m_noremap = noremap;
mp->m_nowait = args->nowait;
mp->m_silent = args->silent;
@@ -3028,6 +3025,9 @@ int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev, buf_T
mp->m_expr = args->expr;
mp->m_script_ctx = current_sctx;
mp->m_script_ctx.sc_lnum += sourcing_lnum;
+ if (args->desc != NULL) {
+ mp->m_desc = xstrdup(args->desc);
+ }
did_it = true;
}
}
@@ -3096,6 +3096,7 @@ int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev, buf_T
mp->m_keys = vim_strsave(lhs);
mp->m_str = vim_strsave(rhs);
mp->m_orig_str = vim_strsave(orig_rhs);
+ mp->m_luaref = args->rhs_lua;
mp->m_keylen = (int)STRLEN(mp->m_keys);
mp->m_noremap = noremap;
mp->m_nowait = args->nowait;
@@ -3104,6 +3105,10 @@ int buf_do_map(int maptype, MapArguments *args, int mode, bool is_abbrev, buf_T
mp->m_expr = args->expr;
mp->m_script_ctx = current_sctx;
mp->m_script_ctx.sc_lnum += sourcing_lnum;
+ mp->m_desc = NULL;
+ if (args->desc != NULL) {
+ mp->m_desc = xstrdup(args->desc);
+ }
// add the new entry in front of the abbrlist or maphash[] list
if (is_abbrev) {
@@ -3200,8 +3205,10 @@ static void mapblock_free(mapblock_T **mpp)
mp = *mpp;
xfree(mp->m_keys);
- xfree(mp->m_str);
- xfree(mp->m_orig_str);
+ NLUA_CLEAR_REF(mp->m_luaref);
+ XFREE_CLEAR(mp->m_str);
+ XFREE_CLEAR(mp->m_orig_str);
+ XFREE_CLEAR(mp->m_desc);
*mpp = mp->m_next;
xfree(mp);
}
@@ -3392,7 +3399,8 @@ static void showmap(mapblock_T *mp, bool local)
{
size_t len = 1;
- if (message_filtered(mp->m_keys) && message_filtered(mp->m_str)) {
+ if (message_filtered(mp->m_keys)
+ && mp->m_str != NULL && message_filtered(mp->m_str)) {
return;
}
@@ -3437,16 +3445,25 @@ static void showmap(mapblock_T *mp, bool local)
/* Use FALSE below if we only want things like <Up> to show up as such on
* the rhs, and not M-x etc, TRUE gets both -- webb */
- if (*mp->m_str == NUL) {
+ if (mp->m_luaref != LUA_NOREF) {
+ char msg[100];
+ snprintf(msg, sizeof(msg), "<Lua function %d>", mp->m_luaref);
+ msg_puts_attr(msg, HL_ATTR(HLF_8));
+ } else if (mp->m_str == NULL) {
msg_puts_attr("<Nop>", HL_ATTR(HLF_8));
} else {
- // Remove escaping of CSI, because "m_str" is in a format to be used
+ // Remove escaping of K_SPECIAL, because "m_str" is in a format to be used
// as typeahead.
char_u *s = vim_strsave(mp->m_str);
- vim_unescape_csi(s);
+ vim_unescape_ks(s);
msg_outtrans_special(s, false, 0);
xfree(s);
}
+
+ if (mp->m_desc != NULL) {
+ msg_puts("\n "); // Shift line to same level as rhs.
+ msg_puts(mp->m_desc);
+ }
if (p_verbose > 0) {
last_set_msg(mp->m_script_ctx);
}
@@ -3533,7 +3550,7 @@ int map_to_exists_mode(const char *const rhs, const int mode, const bool abbr)
}
for (; mp; mp = mp->m_next) {
if ((mp->m_mode & mode)
- && strstr((char *)mp->m_str, rhs) != NULL) {
+ && mp->m_str != NULL && strstr((char *)mp->m_str, rhs) != NULL) {
return true;
}
}
@@ -3818,9 +3835,9 @@ bool check_abbr(int c, char_u *ptr, int col, int mincol)
int match;
if (strchr((const char *)mp->m_keys, K_SPECIAL) != NULL) {
- // Might have CSI escaped mp->m_keys.
+ // Might have K_SPECIAL escaped mp->m_keys.
q = vim_strsave(mp->m_keys);
- vim_unescape_csi(q);
+ vim_unescape_ks(q);
qlen = (int)STRLEN(q);
}
// find entries with right mode and keys
@@ -3866,7 +3883,7 @@ bool check_abbr(int c, char_u *ptr, int col, int mincol)
int newlen = utf_char2bytes(c, tb + j);
tb[j + newlen] = NUL;
// Need to escape K_SPECIAL.
- char_u *escaped = vim_strsave_escape_csi(tb + j);
+ char_u *escaped = vim_strsave_escape_ks(tb + j);
if (escaped != NULL) {
newlen = (int)STRLEN(escaped);
memmove(tb + j, escaped, (size_t)newlen);
@@ -3879,7 +3896,7 @@ bool check_abbr(int c, char_u *ptr, int col, int mincol)
(void)ins_typebuf(tb, 1, 0, true, mp->m_silent);
}
if (mp->m_expr) {
- s = eval_map_expr(mp->m_str, c);
+ s = eval_map_expr(mp, c);
} else {
s = mp->m_str;
}
@@ -3909,20 +3926,22 @@ bool check_abbr(int c, char_u *ptr, int col, int mincol)
/// special characters.
///
/// @param c NUL or typed character for abbreviation
-static char_u *eval_map_expr(char_u *str, int c)
+static char_u *eval_map_expr(mapblock_T *mp, int c)
{
char_u *res;
- char_u *p;
- char_u *expr;
+ char_u *p = NULL;
+ char_u *expr = NULL;
char_u *save_cmd;
pos_T save_cursor;
int save_msg_col;
int save_msg_row;
- /* Remove escaping of CSI, because "str" is in a format to be used as
- * typeahead. */
- expr = vim_strsave(str);
- vim_unescape_csi(expr);
+ // Remove escaping of K_SPECIAL, because "str" is in a format to be used as
+ // typeahead.
+ if (mp->m_luaref == LUA_NOREF) {
+ expr = vim_strsave(mp->m_str);
+ vim_unescape_ks(expr);
+ }
save_cmd = save_cmdline_alloc();
@@ -3934,7 +3953,22 @@ static char_u *eval_map_expr(char_u *str, int c)
save_cursor = curwin->w_cursor;
save_msg_col = msg_col;
save_msg_row = msg_row;
- p = eval_to_string(expr, NULL, false);
+ if (mp->m_luaref != LUA_NOREF) {
+ Error err = ERROR_INIT;
+ Array args = ARRAY_DICT_INIT;
+ Object ret = nlua_call_ref(mp->m_luaref, NULL, args, true, &err);
+ if (ret.type == kObjectTypeString) {
+ p = (char_u *)xstrndup(ret.data.string.data, ret.data.string.size);
+ }
+ api_free_object(ret);
+ if (err.type != kErrorTypeNone) {
+ semsg_multiline("E5108: %s", err.msg);
+ api_clear_error(&err);
+ }
+ } else {
+ p = eval_to_string(expr, NULL, false);
+ xfree(expr);
+ }
textlock--;
ex_normal_lock--;
curwin->w_cursor = save_cursor;
@@ -3942,23 +3976,20 @@ static char_u *eval_map_expr(char_u *str, int c)
msg_row = save_msg_row;
restore_cmdline_alloc(save_cmd);
- xfree(expr);
if (p == NULL) {
return NULL;
}
- // Escape CSI in the result to be able to use the string as typeahead.
- res = vim_strsave_escape_csi(p);
+ // Escape K_SPECIAL in the result to be able to use the string as typeahead.
+ res = vim_strsave_escape_ks(p);
xfree(p);
return res;
}
-/*
- * Copy "p" to allocated memory, escaping K_SPECIAL and CSI so that the result
- * can be put in the typeahead buffer.
- */
-char_u *vim_strsave_escape_csi(char_u *p)
+/// Copy "p" to allocated memory, escaping K_SPECIAL so that the result
+/// can be put in the typeahead buffer.
+char_u *vim_strsave_escape_ks(char_u *p)
{
// Need a buffer to hold up to three times as much. Four in case of an
// illegal utf-8 byte:
@@ -3973,7 +4004,7 @@ char_u *vim_strsave_escape_csi(char_u *p)
*d++ = *s++;
} else {
// Add character, possibly multi-byte to destination, escaping
- // CSI and K_SPECIAL. Be careful, it can be an illegal byte!
+ // K_SPECIAL. Be careful, it can be an illegal byte!
d = add_char2buf(utf_ptr2char(s), d);
s += utf_ptr2len(s);
}
@@ -3983,11 +4014,9 @@ char_u *vim_strsave_escape_csi(char_u *p)
return res;
}
-/*
- * Remove escaping from CSI and K_SPECIAL characters. Reverse of
- * vim_strsave_escape_csi(). Works in-place.
- */
-void vim_unescape_csi(char_u *p)
+/// Remove escaping from K_SPECIAL characters. Reverse of
+/// vim_strsave_escape_ks(). Works in-place.
+void vim_unescape_ks(char_u *p)
{
char_u *s = p, *d = p;
@@ -3995,10 +4024,6 @@ void vim_unescape_csi(char_u *p)
if (s[0] == K_SPECIAL && s[1] == KS_SPECIAL && s[2] == KE_FILLER) {
*d++ = K_SPECIAL;
s += 3;
- } else if ((s[0] == K_SPECIAL || s[0] == CSI)
- && s[1] == KS_EXTRA && s[2] == (int)KE_CSI) {
- *d++ = CSI;
- s += 3;
} else {
*d++ = *s++;
}
@@ -4049,8 +4074,11 @@ int makemap(FILE *fd, buf_T *buf)
continue;
}
- // skip mappings that contain a <SNR> (script-local thing),
+ // skip lua mappings and mappings that contain a <SNR> (script-local thing),
// they probably don't work when loaded again
+ if (mp->m_luaref != LUA_NOREF) {
+ continue;
+ }
for (p = mp->m_str; *p != NUL; p++) {
if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
&& p[2] == (int)KE_SNR) {
@@ -4238,7 +4266,7 @@ int put_escstr(FILE *fd, char_u *strstart, int what)
for (; *str != NUL; str++) {
// Check for a multi-byte character, which may contain escaped
- // K_SPECIAL and CSI bytes.
+ // K_SPECIAL bytes.
const char *p = mb_unescape((const char **)&str);
if (p != NULL) {
while (*p != NUL) {
@@ -4331,10 +4359,11 @@ int put_escstr(FILE *fd, char_u *strstart, int what)
/// @param mp_ptr return: pointer to mapblock or NULL
/// @param local_ptr return: buffer-local mapping or NULL
char_u *check_map(char_u *keys, int mode, int exact, int ign_mod, int abbr, mapblock_T **mp_ptr,
- int *local_ptr)
+ int *local_ptr, int *rhs_lua)
{
int len, minlen;
mapblock_T *mp;
+ *rhs_lua = LUA_NOREF;
validate_maphash();
@@ -4375,7 +4404,8 @@ char_u *check_map(char_u *keys, int mode, int exact, int ign_mod, int abbr, mapb
if (local_ptr != NULL) {
*local_ptr = local;
}
- return mp->m_str;
+ *rhs_lua = mp->m_luaref;
+ return mp->m_luaref == LUA_NOREF ? mp->m_str : NULL;
}
}
}
@@ -4560,3 +4590,47 @@ char_u *getcmdkeycmd(int promptc, void *cookie, int indent, bool do_concat)
return (char_u *)line_ga.ga_data;
}
+
+bool map_execute_lua(void)
+{
+ garray_T line_ga;
+ int c1 = -1;
+ bool aborted = false;
+
+ ga_init(&line_ga, 1, 32);
+
+ no_mapping++;
+
+ got_int = false;
+ while (c1 != NUL && !aborted) {
+ ga_grow(&line_ga, 32);
+ // Get one character at a time.
+ c1 = vgetorpeek(true);
+ if (got_int) {
+ aborted = true;
+ } else if (c1 == '\r' || c1 == '\n') {
+ c1 = NUL; // end the line
+ } else {
+ ga_append(&line_ga, (char)c1);
+ }
+ }
+
+ no_mapping--;
+
+ if (aborted) {
+ ga_clear(&line_ga);
+ return false;
+ }
+
+ LuaRef ref = (LuaRef)atoi(line_ga.ga_data);
+ Error err = ERROR_INIT;
+ Array args = ARRAY_DICT_INIT;
+ nlua_call_ref(ref, NULL, args, false, &err);
+ if (err.type != kErrorTypeNone) {
+ semsg_multiline("E5108: %s", err.msg);
+ api_clear_error(&err);
+ }
+
+ ga_clear(&line_ga);
+ return true;
+}
diff --git a/src/nvim/getchar.h b/src/nvim/getchar.h
index 5950611d3f..be10e150e5 100644
--- a/src/nvim/getchar.h
+++ b/src/nvim/getchar.h
@@ -50,14 +50,16 @@ struct map_arguments {
char_u *rhs; /// The {rhs} of the mapping.
size_t rhs_len;
+ LuaRef rhs_lua; /// lua function as rhs
bool rhs_is_noop; /// True when the {orig_rhs} is <nop>.
char_u *orig_rhs; /// The original text of the {rhs}.
size_t orig_rhs_len;
+ char *desc; /// map escription
};
typedef struct map_arguments MapArguments;
#define MAP_ARGUMENTS_INIT { false, false, false, false, false, false, false, \
- { 0 }, 0, NULL, 0, false, NULL, 0 }
+ { 0 }, 0, NULL, 0, LUA_NOREF, false, NULL, 0, NULL }
#define KEYLEN_PART_KEY -1 // keylen value for incomplete key-code
#define KEYLEN_PART_MAP -2 // keylen value for incomplete mapping
diff --git a/src/nvim/globals.h b/src/nvim/globals.h
index dfbc80066e..31a09b3969 100644
--- a/src/nvim/globals.h
+++ b/src/nvim/globals.h
@@ -28,7 +28,7 @@
#endif
#ifndef FILETYPE_FILE
-# define FILETYPE_FILE "filetype.vim"
+# define FILETYPE_FILE "filetype.lua filetype.vim"
#endif
#ifndef FTPLUGIN_FILE
@@ -127,7 +127,7 @@ typedef off_t off_T;
// When vgetc() is called, it sets mod_mask to the set of modifiers that are
// held down based on the MOD_MASK_* symbols that are read first.
-EXTERN int mod_mask INIT(= 0x0); // current key modifiers
+EXTERN int mod_mask INIT(= 0); // current key modifiers
// Cmdline_row is the row where the command line starts, just below the
@@ -632,6 +632,7 @@ EXTERN bool ex_no_reprint INIT(=false); // No need to print after z or p.
EXTERN int reg_recording INIT(= 0); // register for recording or zero
EXTERN int reg_executing INIT(= 0); // register being executed or zero
+EXTERN int reg_recorded INIT(= 0); // last recorded register or zero
EXTERN int no_mapping INIT(= false); // currently no mapping allowed
EXTERN int no_zero_mapping INIT(= 0); // mapping zero not allowed
diff --git a/src/nvim/indent_c.c b/src/nvim/indent_c.c
index faa9b38cf7..0f0cab33ea 100644
--- a/src/nvim/indent_c.c
+++ b/src/nvim/indent_c.c
@@ -923,11 +923,10 @@ static int cin_isfuncdecl(char_u **sp, linenr_T first_lnum, linenr_T min_lnum)
while (*s && *s != ';' && *s != '\'' && *s != '"') {
if (*s == ')' && cin_nocode(s + 1)) {
- /* ')' at the end: may have found a match
- * Check for he previous line not to end in a backslash:
- * #if defined(x) && \
- * defined(y)
- */
+ // ')' at the end: may have found a match
+ // Check for the previous line not to end in a backslash:
+ // #if defined(x) && {backslash}
+ // defined(y)
lnum = first_lnum - 1;
s = ml_get(lnum);
if (*s == NUL || s[STRLEN(s) - 1] != '\\')
@@ -1634,8 +1633,8 @@ void parse_cino(buf_T *buf)
* itself is also unclosed. */
buf->b_ind_unclosed2 = sw;
- /* Suppress ignoring spaces from the indent of a line starting with an
- * unclosed parentheses. */
+ // Suppress ignoring spaces from the indent of a line starting with an
+ // unclosed parenthesis.
buf->b_ind_unclosed_noignore = 0;
/* If the opening paren is the last nonwhite character on the line, and
@@ -1647,11 +1646,11 @@ void parse_cino(buf_T *buf)
* an unclosed parentheses. */
buf->b_ind_unclosed_whiteok = 0;
- /* Indent a closing parentheses under the line start of the matching
- * opening parentheses. */
+ // Indent a closing parenthesis under the line start of the matching
+ // opening parenthesis.
buf->b_ind_matching_paren = 0;
- // Indent a closing parentheses under the previous line.
+ // Indent a closing parenthesis under the previous line.
buf->b_ind_paren_prev = 0;
// Extra indent for comments.
diff --git a/src/nvim/input.c b/src/nvim/input.c
index 2f7c5c2c16..5fa9b8b343 100644
--- a/src/nvim/input.c
+++ b/src/nvim/input.c
@@ -105,7 +105,7 @@ int get_keystroke(MultiQueue *events)
// terminal code to complete.
n = os_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0, events);
if (n > 0) {
- // Replace zero and CSI by a special key code.
+ // Replace zero and K_SPECIAL by a special key code.
n = fix_input_buffer(buf + len, n);
len += n;
waited = 0;
diff --git a/src/nvim/keymap.c b/src/nvim/keymap.c
index abf016b832..32f2158d7b 100644
--- a/src/nvim/keymap.c
+++ b/src/nvim/keymap.c
@@ -158,7 +158,6 @@ static const struct key_name_entry {
{ ESC, "Esc" },
{ ESC, "Escape" }, // Alternative name
{ CSI, "CSI" },
- { K_CSI, "xCSI" },
{ '|', "Bar" },
{ '\\', "Bslash" },
{ K_DEL, "Del" },
@@ -964,7 +963,6 @@ char_u *replace_termcodes(const char_u *from, const size_t from_len, char_u **bu
for (i = utfc_ptr2len_len(src, (int)(end - src) + 1); i > 0; i--) {
// If the character is K_SPECIAL, replace it with K_SPECIAL
// KS_SPECIAL KE_FILLER.
- // If compiled with the GUI replace CSI with K_CSI.
if (*src == K_SPECIAL) {
result[dlen++] = K_SPECIAL;
result[dlen++] = KS_SPECIAL;
diff --git a/src/nvim/keymap.h b/src/nvim/keymap.h
index 5ff5a38614..42cae0c35e 100644
--- a/src/nvim/keymap.h
+++ b/src/nvim/keymap.h
@@ -220,7 +220,7 @@ enum key_extra {
KE_KINS = 79, // keypad Insert key
KE_KDEL = 80, // keypad Delete key
- KE_CSI = 81, // CSI typed directly
+ // KE_CSI = 81, // Nvim doesn't need escaping CSI
KE_SNR = 82, // <SNR>
KE_PLUG = 83, // <Plug>
KE_CMDWIN = 84, // open command-line window from Command-line Mode
@@ -245,6 +245,7 @@ enum key_extra {
KE_MOUSEMOVE = 100, // mouse moved with no button down
// , KE_CANCEL = 101 // return from vgetc
KE_EVENT = 102, // event
+ KE_LUA = 103, // lua special key
KE_COMMAND = 104, // <Cmd> special key
};
@@ -434,7 +435,6 @@ enum key_extra {
#define K_MOUSELEFT TERMCAP2KEY(KS_EXTRA, KE_MOUSELEFT)
#define K_MOUSERIGHT TERMCAP2KEY(KS_EXTRA, KE_MOUSERIGHT)
-#define K_CSI TERMCAP2KEY(KS_EXTRA, KE_CSI)
#define K_SNR TERMCAP2KEY(KS_EXTRA, KE_SNR)
#define K_PLUG TERMCAP2KEY(KS_EXTRA, KE_PLUG)
#define K_CMDWIN TERMCAP2KEY(KS_EXTRA, KE_CMDWIN)
@@ -443,6 +443,7 @@ enum key_extra {
#define K_EVENT TERMCAP2KEY(KS_EXTRA, KE_EVENT)
#define K_COMMAND TERMCAP2KEY(KS_EXTRA, KE_COMMAND)
+#define K_LUA TERMCAP2KEY(KS_EXTRA, KE_LUA)
// Bits for modifier mask
// 0x01 cannot be used, because the modifier must be 0x02 or higher
diff --git a/src/nvim/lua/converter.c b/src/nvim/lua/converter.c
index b6792a5a97..0fbd56ed53 100644
--- a/src/nvim/lua/converter.c
+++ b/src/nvim/lua/converter.c
@@ -617,6 +617,14 @@ bool nlua_push_typval(lua_State *lstate, typval_T *const tv, bool special)
semsg(_("E1502: Lua failed to grow stack to %i"), initial_size + 4);
return false;
}
+ if (tv->v_type == VAR_FUNC) {
+ ufunc_T *fp = find_func(tv->vval.v_string);
+ assert(fp != NULL);
+ if (fp->uf_cb == nlua_CFunction_func_call) {
+ nlua_pushref(lstate, ((LuaCFunctionState *)fp->uf_cb_state)->lua_callable.func_ref);
+ return true;
+ }
+ }
if (encode_vim_to_lua(lstate, tv, "nlua_push_typval argument") == FAIL) {
return false;
}
@@ -1242,7 +1250,12 @@ LuaRef nlua_pop_LuaRef(lua_State *const lstate, Error *err)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT \
{ \
type ret; \
- ret = (type)lua_tonumber(lstate, -1); \
+ if (lua_type(lstate, -1) != LUA_TNUMBER) { \
+ api_set_error(err, kErrorTypeValidation, "Expected Lua number"); \
+ ret = (type)-1; \
+ } else { \
+ ret = (type)lua_tonumber(lstate, -1); \
+ } \
lua_pop(lstate, 1); \
return ret; \
}
diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c
index b09d133495..cfdbe7b344 100644
--- a/src/nvim/lua/executor.c
+++ b/src/nvim/lua/executor.c
@@ -18,6 +18,7 @@
#include "nvim/event/loop.h"
#include "nvim/event/time.h"
#include "nvim/ex_cmds2.h"
+#include "nvim/ex_docmd.h"
#include "nvim/ex_getln.h"
#include "nvim/extmark.h"
#include "nvim/func_attr.h"
@@ -404,9 +405,9 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL
{
const char *code = (char *)&shared_module[0];
- if (luaL_loadbuffer(lstate, code, strlen(code), "@vim/shared.lua")
+ if (luaL_loadbuffer(lstate, code, sizeof(shared_module) - 1, "@vim/shared.lua")
|| nlua_pcall(lstate, 0, 0)) {
- nlua_error(lstate, _("E5106: Error while creating shared module: %.*s"));
+ nlua_error(lstate, _("E5106: Error while creating shared module: %.*s\n"));
return 1;
}
}
@@ -416,31 +417,40 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL
lua_getfield(lstate, -1, "loaded"); // [package, loaded]
const char *code = (char *)&inspect_module[0];
- if (luaL_loadbuffer(lstate, code, strlen(code), "@vim/inspect.lua")
+ if (luaL_loadbuffer(lstate, code, sizeof(inspect_module) - 1, "@vim/inspect.lua")
|| nlua_pcall(lstate, 0, 1)) {
- nlua_error(lstate, _("E5106: Error while creating inspect module: %.*s"));
+ nlua_error(lstate, _("E5106: Error while creating inspect module: %.*s\n"));
return 1;
}
// [package, loaded, inspect]
lua_setfield(lstate, -2, "vim.inspect"); // [package, loaded]
code = (char *)&lua_F_module[0];
- if (luaL_loadbuffer(lstate, code, strlen(code), "@vim/F.lua")
+ if (luaL_loadbuffer(lstate, code, sizeof(lua_F_module) - 1, "@vim/F.lua")
|| nlua_pcall(lstate, 0, 1)) {
- nlua_error(lstate, _("E5106: Error while creating vim.F module: %.*s"));
+ nlua_error(lstate, _("E5106: Error while creating vim.F module: %.*s\n"));
return 1;
}
// [package, loaded, module]
lua_setfield(lstate, -2, "vim.F"); // [package, loaded]
+ code = (char *)&lua_filetype_module[0];
+ if (luaL_loadbuffer(lstate, code, sizeof(lua_filetype_module) - 1, "@vim/filetype.lua")
+ || nlua_pcall(lstate, 0, 1)) {
+ nlua_error(lstate, _("E5106: Error while creating vim.filetype module: %.*s"));
+ return 1;
+ }
+ // [package, loaded, module]
+ lua_setfield(lstate, -2, "vim.filetype"); // [package, loaded]
+
lua_pop(lstate, 2); // []
}
{
const char *code = (char *)&vim_module[0];
- if (luaL_loadbuffer(lstate, code, strlen(code), "@vim.lua")
+ if (luaL_loadbuffer(lstate, code, sizeof(vim_module) - 1, "@vim.lua")
|| nlua_pcall(lstate, 0, 0)) {
- nlua_error(lstate, _("E5106: Error while creating vim module: %.*s"));
+ nlua_error(lstate, _("E5106: Error while creating vim module: %.*s\n"));
return 1;
}
}
@@ -450,9 +460,9 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL
lua_getfield(lstate, -1, "loaded"); // [package, loaded]
const char *code = (char *)&lua_meta_module[0];
- if (luaL_loadbuffer(lstate, code, strlen(code), "@vim/_meta.lua")
+ if (luaL_loadbuffer(lstate, code, sizeof(lua_meta_module) - 1, "@vim/_meta.lua")
|| nlua_pcall(lstate, 0, 1)) {
- nlua_error(lstate, _("E5106: Error while creating vim._meta module: %.*s"));
+ nlua_error(lstate, _("E5106: Error while creating vim._meta module: %.*s\n"));
return 1;
}
// [package, loaded, module]
@@ -914,6 +924,24 @@ void nlua_typval_call(const char *str, size_t len, typval_T *const args, int arg
}
}
+void nlua_call_user_expand_func(expand_T *xp, typval_T *ret_tv)
+ FUNC_ATTR_NONNULL_ALL
+{
+ lua_State *const lstate = global_lstate;
+
+ nlua_pushref(lstate, xp->xp_luaref);
+ lua_pushstring(lstate, (char *)xp->xp_pattern);
+ lua_pushstring(lstate, (char *)xp->xp_line);
+ lua_pushinteger(lstate, xp->xp_col);
+
+ if (nlua_pcall(lstate, 3, 1)) {
+ nlua_error(lstate, _("E5108: Error executing Lua function: %.*s"));
+ return;
+ }
+
+ nlua_pop_typval(lstate, ret_tv);
+}
+
static void nlua_typval_exec(const char *lcmd, size_t lcmd_len, const char *name,
typval_T *const args, int argcount, bool special, typval_T *ret_tv)
{
@@ -1096,11 +1124,23 @@ void ex_lua(exarg_T *const eap)
FUNC_ATTR_NONNULL_ALL
{
size_t len;
- char *const code = script_get(eap, &len);
+ char *code = script_get(eap, &len);
if (eap->skip) {
xfree(code);
return;
}
+ // When =expr is used transform it to print(vim.inspect(expr))
+ if (code[0] == '=') {
+ len += sizeof("vim.pretty_print()") - sizeof("=");
+ // code_buf needs to be 1 char larger then len for null byte in the end.
+ // lua nlua_typval_exec doesn't expect null terminated string so len
+ // needs to end before null byte.
+ char *code_buf = xmallocz(len);
+ vim_snprintf(code_buf, len+1, "vim.pretty_print(%s)", code+1);
+ xfree(code);
+ code = code_buf;
+ }
+
nlua_typval_exec(code, len, ":lua", NULL, 0, false, NULL);
xfree(code);
@@ -1432,3 +1472,48 @@ void nlua_execute_on_key(int c)
#endif
}
+void nlua_do_ucmd(ucmd_T *cmd, exarg_T *eap)
+{
+ lua_State *const lstate = global_lstate;
+
+ nlua_pushref(lstate, cmd->uc_luaref);
+
+ lua_newtable(lstate);
+ lua_pushboolean(lstate, eap->forceit == 1);
+ lua_setfield(lstate, -2, "bang");
+
+ lua_pushinteger(lstate, eap->line1);
+ lua_setfield(lstate, -2, "line1");
+
+ lua_pushinteger(lstate, eap->line2);
+ lua_setfield(lstate, -2, "line2");
+
+ lua_pushstring(lstate, (const char *)eap->arg);
+ lua_setfield(lstate, -2, "args");
+
+ lua_pushstring(lstate, (const char *)&eap->regname);
+ lua_setfield(lstate, -2, "reg");
+
+ lua_pushinteger(lstate, eap->addr_count);
+ lua_setfield(lstate, -2, "range");
+
+ if (eap->addr_count > 0) {
+ lua_pushinteger(lstate, eap->line2);
+ } else {
+ lua_pushinteger(lstate, cmd->uc_def);
+ }
+ lua_setfield(lstate, -2, "count");
+
+ // The size of this buffer is chosen empirically to be large enough to hold
+ // every possible modifier (with room to spare). If the list of possible
+ // modifiers grows this may need to be updated.
+ char buf[200] = { 0 };
+ (void)uc_mods(buf);
+ lua_pushstring(lstate, buf);
+ lua_setfield(lstate, -2, "mods");
+
+ if (nlua_pcall(lstate, 1, 0)) {
+ nlua_error(lstate, _("Error executing Lua callback: %.*s"));
+ }
+}
+
diff --git a/src/nvim/lua/executor.h b/src/nvim/lua/executor.h
index a1f66bd02b..bf78f7ec5e 100644
--- a/src/nvim/lua/executor.h
+++ b/src/nvim/lua/executor.h
@@ -7,6 +7,7 @@
#include "nvim/api/private/defs.h"
#include "nvim/eval/typval.h"
#include "nvim/ex_cmds_defs.h"
+#include "nvim/ex_docmd.h"
#include "nvim/func_attr.h"
#include "nvim/lua/converter.h"
diff --git a/src/nvim/lua/spell.c b/src/nvim/lua/spell.c
new file mode 100644
index 0000000000..3a63f61200
--- /dev/null
+++ b/src/nvim/lua/spell.c
@@ -0,0 +1,101 @@
+// This is an open source non-commercial project. Dear PVS-Studio, please check
+// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
+
+#include <lua.h>
+#include <lauxlib.h>
+
+#include "nvim/spell.h"
+#include "nvim/vim.h"
+#include "nvim/lua/spell.h"
+
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+# include "lua/spell.c.generated.h"
+#endif
+
+int nlua_spell_check(lua_State *lstate)
+{
+ if (lua_gettop(lstate) < 1) {
+ return luaL_error(lstate, "Expected 1 argument");
+ }
+
+ if (lua_type(lstate, 1) != LUA_TSTRING) {
+ luaL_argerror(lstate, 1, "expected string");
+ }
+
+ const char *str = lua_tolstring(lstate, 1, NULL);
+
+ // spell.c requires that 'spell' is enabled, so we need to temporarily enable
+ // it before we can call spell functions.
+ const int wo_spell_save = curwin->w_p_spell;
+
+ if (!curwin->w_p_spell) {
+ did_set_spelllang(curwin);
+ curwin->w_p_spell = true;
+ }
+
+ // Check 'spelllang'
+ if (*curwin->w_s->b_p_spl == NUL) {
+ emsg(_(e_no_spell));
+ curwin->w_p_spell = wo_spell_save;
+ return 0;
+ }
+
+ hlf_T attr = HLF_COUNT;
+ size_t len = 0;
+ size_t pos = 0;
+ int capcol = -1;
+ int no_res = 0;
+ const char * result;
+
+ lua_createtable(lstate, 0, 0);
+
+ while (*str != NUL) {
+ attr = HLF_COUNT;
+ len = spell_check(curwin, (char_u *)str, &attr, &capcol, false);
+ assert(len <= INT_MAX);
+
+ if (attr != HLF_COUNT) {
+ lua_createtable(lstate, 3, 0);
+
+ lua_pushlstring(lstate, str, len);
+ lua_rawseti(lstate, -2, 1);
+
+ result = attr == HLF_SPB ? "bad" :
+ attr == HLF_SPR ? "rare" :
+ attr == HLF_SPL ? "local" :
+ attr == HLF_SPC ? "caps" :
+ NULL;
+
+ assert(result != NULL);
+
+ lua_pushstring(lstate, result);
+ lua_rawseti(lstate, -2, 2);
+
+ // +1 for 1-indexing
+ lua_pushinteger(lstate, (long)pos + 1);
+ lua_rawseti(lstate, -2, 3);
+
+ lua_rawseti(lstate, -2, ++no_res);
+ }
+
+ str += len;
+ pos += len;
+ capcol -= (int)len;
+ }
+
+ // Restore 'spell'
+ curwin->w_p_spell = wo_spell_save;
+ return 1;
+}
+
+static const luaL_Reg spell_functions[] = {
+ { "check", nlua_spell_check },
+ { NULL , NULL }
+};
+
+int luaopen_spell(lua_State *L)
+{
+ lua_newtable(L);
+ luaL_register(L, NULL, spell_functions);
+ return 1;
+}
diff --git a/src/nvim/lua/spell.h b/src/nvim/lua/spell.h
new file mode 100644
index 0000000000..8f798a5191
--- /dev/null
+++ b/src/nvim/lua/spell.h
@@ -0,0 +1,12 @@
+#ifndef NVIM_LUA_SPELL_H
+#define NVIM_LUA_SPELL_H
+
+#include <lauxlib.h>
+#include <lua.h>
+#include <lualib.h>
+
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+# include "lua/spell.h.generated.h"
+#endif
+
+#endif // NVIM_LUA_SPELL_H
diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c
index 0d6789317c..18a579ed0f 100644
--- a/src/nvim/lua/stdlib.c
+++ b/src/nvim/lua/stdlib.c
@@ -30,6 +30,7 @@
#include "nvim/lua/stdlib.h"
#include "nvim/lua/treesitter.h"
#include "nvim/lua/xdiff.h"
+#include "nvim/lua/spell.h"
#include "nvim/macros.h"
#include "nvim/map.h"
#include "nvim/memline.h"
@@ -518,6 +519,10 @@ void nlua_state_add_stdlib(lua_State *const lstate)
lua_pushcfunction(lstate, &nlua_xdl_diff);
lua_setfield(lstate, -2, "diff");
+ // vim.spell
+ luaopen_spell(lstate);
+ lua_setfield(lstate, -2, "spell");
+
lua_cjson_new(lstate);
lua_setfield(lstate, -2, "json");
}
diff --git a/src/nvim/lua/treesitter.c b/src/nvim/lua/treesitter.c
index 60a000843f..f4067ad02f 100644
--- a/src/nvim/lua/treesitter.c
+++ b/src/nvim/lua/treesitter.c
@@ -129,6 +129,10 @@ void tslua_init(lua_State *L)
build_meta(L, TS_META_QUERY, query_meta);
build_meta(L, TS_META_QUERYCURSOR, querycursor_meta);
build_meta(L, TS_META_TREECURSOR, treecursor_meta);
+
+#ifdef NVIM_TS_HAS_SET_ALLOCATOR
+ ts_set_allocator(xmalloc, xcalloc, xrealloc, xfree);
+#endif
}
int tslua_has_language(lua_State *L)
diff --git a/src/nvim/lua/vim.lua b/src/nvim/lua/vim.lua
index c1a1e7f162..731e7d8d36 100644
--- a/src/nvim/lua/vim.lua
+++ b/src/nvim/lua/vim.lua
@@ -40,6 +40,9 @@ assert(vim)
vim.inspect = package.loaded['vim.inspect']
assert(vim.inspect)
+vim.filetype = package.loaded['vim.filetype']
+assert(vim.filetype)
+
local pathtrails = {}
vim._so_trails = {}
for s in (package.cpath..';'):gmatch('[^;]*;') do
@@ -112,6 +115,9 @@ setmetatable(vim, {
elseif key == 'ui' then
t.ui = require('vim.ui')
return t.ui
+ elseif key == 'keymap' then
+ t.keymap = require('vim.keymap')
+ return t.keymap
end
end
})
@@ -419,23 +425,43 @@ function vim.defer_fn(fn, timeout)
end
---- Notification provider
+--- Display a notification to the user.
+---
+--- This function can be overridden by plugins to display notifications using a
+--- custom provider (such as the system notification provider). By default,
+--- writes to |:messages|.
---
---- Without a runtime, writes to :Messages
----@see :help nvim_notify
----@param msg string Content of the notification to show to the user
----@param log_level number|nil enum from vim.log.levels
----@param opts table|nil additional options (timeout, etc)
-function vim.notify(msg, log_level, opts) -- luacheck: no unused
- if log_level == vim.log.levels.ERROR then
+---@param msg string Content of the notification to show to the user.
+---@param level number|nil One of the values from |vim.log.levels|.
+---@param opts table|nil Optional parameters. Unused by default.
+function vim.notify(msg, level, opts) -- luacheck: no unused args
+ if level == vim.log.levels.ERROR then
vim.api.nvim_err_writeln(msg)
- elseif log_level == vim.log.levels.WARN then
+ elseif level == vim.log.levels.WARN then
vim.api.nvim_echo({{msg, 'WarningMsg'}}, true, {})
else
vim.api.nvim_echo({{msg}}, true, {})
end
end
+do
+ local notified = {}
+
+ --- Display a notification only one time.
+ ---
+ --- Like |vim.notify()|, but subsequent calls with the same message will not
+ --- display a notification.
+ ---
+ ---@param msg string Content of the notification to show to the user.
+ ---@param level number|nil One of the values from |vim.log.levels|.
+ ---@param opts table|nil Optional parameters. Unused by default.
+ function vim.notify_once(msg, level, opts) -- luacheck: no unused args
+ if not notified[msg] then
+ vim.notify(msg, level, opts)
+ notified[msg] = true
+ end
+ end
+end
---@private
function vim.register_keystroke_callback()
@@ -663,4 +689,23 @@ vim._expand_pat_get_parts = function(lua_string)
return parts, search_index
end
+---Prints given arguments in human-readable format.
+---Example:
+---<pre>
+--- -- Print highlight group Normal and store it's contents in a variable.
+--- local hl_normal = vim.pretty_print(vim.api.nvim_get_hl_by_name("Normal", true))
+---</pre>
+---@see |vim.inspect()|
+---@return given arguments.
+function vim.pretty_print(...)
+ local objects = {}
+ for i = 1, select('#', ...) do
+ local v = select(i, ...)
+ table.insert(objects, vim.inspect(v))
+ end
+
+ print(table.concat(objects, ' '))
+ return ...
+end
+
return module
diff --git a/src/nvim/main.c b/src/nvim/main.c
index cbd1f53727..748f5098fd 100644
--- a/src/nvim/main.c
+++ b/src/nvim/main.c
@@ -341,9 +341,11 @@ int main(int argc, char **argv)
init_default_autocmds();
TIME_MSG("init default autocommands");
+ bool vimrc_none = params.use_vimrc != NULL && strequal(params.use_vimrc, "NONE");
+
// Reset 'loadplugins' for "-u NONE" before "--cmd" arguments.
// Allows for setting 'loadplugins' there.
- if (params.use_vimrc != NULL && strequal(params.use_vimrc, "NONE")) {
+ if (vimrc_none) {
// When using --clean we still want to load plugins
p_lpl = params.clean;
}
@@ -351,14 +353,23 @@ int main(int argc, char **argv)
// Execute --cmd arguments.
exe_pre_commands(&params);
+ if (!vimrc_none) {
+ // Sources ftplugin.vim and indent.vim. We do this *before* the user startup scripts to ensure
+ // ftplugins run before FileType autocommands defined in the init file (which allows those
+ // autocommands to overwrite settings from ftplugins).
+ filetype_plugin_enable();
+ }
+
// Source startup scripts.
source_startup_scripts(&params);
// If using the runtime (-u is not NONE), enable syntax & filetype plugins.
- if (params.use_vimrc == NULL || !strequal(params.use_vimrc, "NONE")) {
- // Does ":filetype plugin indent on".
+ if (!vimrc_none) {
+ // Sources filetype.lua and filetype.vim unless the user explicitly disabled it with :filetype
+ // off.
filetype_maybe_enable();
- // Sources syntax/syntax.vim, which calls `:filetype on`.
+ // Sources syntax/syntax.vim. We do this *after* the user startup scripts so that users can
+ // disable syntax highlighting with `:syntax off` if they wish.
syn_maybe_enable();
}
diff --git a/src/nvim/map.c b/src/nvim/map.c
index 1d9abe3ef2..77ebc2a387 100644
--- a/src/nvim/map.c
+++ b/src/nvim/map.c
@@ -29,8 +29,6 @@
#define uint32_t_eq kh_int_hash_equal
#define int_hash kh_int_hash_func
#define int_eq kh_int_hash_equal
-#define linenr_T_hash kh_int_hash_func
-#define linenr_T_eq kh_int_hash_equal
#define handle_T_hash kh_int_hash_func
#define handle_T_eq kh_int_hash_equal
@@ -173,10 +171,7 @@ MAP_IMPL(ptr_t, ptr_t, DEFAULT_INITIALIZER)
MAP_IMPL(uint64_t, ptr_t, DEFAULT_INITIALIZER)
MAP_IMPL(uint64_t, ssize_t, SSIZE_INITIALIZER)
MAP_IMPL(uint64_t, uint64_t, DEFAULT_INITIALIZER)
-#define EXTMARK_NS_INITIALIZER { { MAP_INIT }, 1 }
-MAP_IMPL(uint64_t, ExtmarkNs, EXTMARK_NS_INITIALIZER)
-#define EXTMARK_ITEM_INITIALIZER { 0, 0, NULL }
-MAP_IMPL(uint64_t, ExtmarkItem, EXTMARK_ITEM_INITIALIZER)
+MAP_IMPL(uint32_t, uint32_t, DEFAULT_INITIALIZER)
MAP_IMPL(handle_T, ptr_t, DEFAULT_INITIALIZER)
#define MSGPACK_HANDLER_INITIALIZER { .fn = NULL, .fast = false }
MAP_IMPL(String, MsgpackRpcRequestHandler, MSGPACK_HANDLER_INITIALIZER)
diff --git a/src/nvim/map.h b/src/nvim/map.h
index dbd85a4e1f..5e56f4dd65 100644
--- a/src/nvim/map.h
+++ b/src/nvim/map.h
@@ -40,16 +40,8 @@ MAP_DECLS(ptr_t, ptr_t)
MAP_DECLS(uint64_t, ptr_t)
MAP_DECLS(uint64_t, ssize_t)
MAP_DECLS(uint64_t, uint64_t)
+MAP_DECLS(uint32_t, uint32_t)
-// NB: this is the only way to define a struct both containing and contained
-// in a map...
-typedef struct ExtmarkNs { // For namespacing extmarks
- Map(uint64_t, uint64_t) map[1]; // For fast lookup
- uint64_t free_id; // For automatically assigning id's
-} ExtmarkNs;
-
-MAP_DECLS(uint64_t, ExtmarkNs)
-MAP_DECLS(uint64_t, ExtmarkItem)
MAP_DECLS(handle_T, ptr_t)
MAP_DECLS(String, MsgpackRpcRequestHandler)
MAP_DECLS(HlEntry, int)
diff --git a/src/nvim/marktree.c b/src/nvim/marktree.c
index 38014ab375..8ae138b2eb 100644
--- a/src/nvim/marktree.c
+++ b/src/nvim/marktree.c
@@ -56,12 +56,6 @@
#define T MT_BRANCH_FACTOR
#define ILEN (sizeof(mtnode_t)+(2 * T) * sizeof(void *))
-#define RIGHT_GRAVITY (((uint64_t)1) << 63)
-#define ANTIGRAVITY(id) ((id)&(RIGHT_GRAVITY-1))
-#define IS_RIGHT(id) ((id)&RIGHT_GRAVITY)
-
-#define PAIRED MARKTREE_PAIRED_FLAG
-#define END_FLAG MARKTREE_END_FLAG
#define ID_INCR (((uint64_t)1) << 2)
#define rawkey(itr) (itr->node->key[itr->i])
@@ -119,7 +113,7 @@ static int key_cmp(mtkey_t a, mtkey_t b)
}
// NB: keeping the events at the same pos sorted by id is actually not
// necessary only make sure that START is before END etc.
- return mt_generic_cmp(a.id, b.id);
+ return mt_generic_cmp(a.flags, b.flags);
}
static inline int marktree_getp_aux(const mtnode_t *x, mtkey_t k, int *r)
@@ -148,7 +142,7 @@ static inline int marktree_getp_aux(const mtnode_t *x, mtkey_t k, int *r)
static inline void refkey(MarkTree *b, mtnode_t *x, int i)
{
- pmap_put(uint64_t)(b->id2node, ANTIGRAVITY(x->key[i].id), x);
+ pmap_put(uint64_t)(b->id2node, mt_lookup_key(x->key[i]), x);
}
// put functions
@@ -221,38 +215,28 @@ static inline void marktree_putp_aux(MarkTree *b, mtnode_t *x, mtkey_t k)
}
}
-uint64_t marktree_put(MarkTree *b, int row, int col, bool right_gravity, uint8_t decor_level)
+void marktree_put(MarkTree *b, mtkey_t key, int end_row, int end_col, bool end_right)
{
- uint64_t id = (b->next_id+=ID_INCR);
- assert(decor_level < DECOR_LEVELS);
- id = id | ((uint64_t)decor_level << DECOR_OFFSET);
- uint64_t keyid = id;
- if (right_gravity) {
- // order all right gravity keys after the left ones, for effortless
- // insertion (but not deletion!)
- keyid |= RIGHT_GRAVITY;
- }
- marktree_put_key(b, row, col, keyid);
- return id;
-}
+ assert(!(key.flags & ~MT_FLAG_EXTERNAL_MASK));
+ if (end_row >= 0) {
+ key.flags |= MT_FLAG_PAIRED;
+ }
-uint64_t marktree_put_pair(MarkTree *b, int start_row, int start_col, bool start_right, int end_row,
- int end_col, bool end_right, uint8_t decor_level)
-{
- uint64_t id = (b->next_id+=ID_INCR)|PAIRED;
- assert(decor_level < DECOR_LEVELS);
- id = id | ((uint64_t)decor_level << DECOR_OFFSET);
- uint64_t start_id = id|(start_right?RIGHT_GRAVITY:0);
- uint64_t end_id = id|END_FLAG|(end_right?RIGHT_GRAVITY:0);
- marktree_put_key(b, start_row, start_col, start_id);
- marktree_put_key(b, end_row, end_col, end_id);
- return id;
+ marktree_put_key(b, key);
+
+ if (end_row >= 0) {
+ mtkey_t end_key = key;
+ end_key.flags = (uint16_t)((uint16_t)(key.flags & ~MT_FLAG_RIGHT_GRAVITY)
+ |(uint16_t)MT_FLAG_END
+ |(uint16_t)(end_right ? MT_FLAG_RIGHT_GRAVITY : 0));
+ end_key.pos = (mtpos_t){ end_row, end_col };
+ marktree_put_key(b, end_key);
+ }
}
-void marktree_put_key(MarkTree *b, int row, int col, uint64_t id)
+void marktree_put_key(MarkTree *b, mtkey_t k)
{
- mtkey_t k = { .pos = { .row = row, .col = col }, .id = id };
-
+ k.flags |= MT_FLAG_REAL; // let's be real.
if (!b->root) {
b->root = (mtnode_t *)xcalloc(1, ILEN);
b->n_nodes++;
@@ -302,7 +286,7 @@ void marktree_del_itr(MarkTree *b, MarkTreeIter *itr, bool rev)
mtnode_t *cur = itr->node;
int curi = itr->i;
- uint64_t id = cur->key[curi].id;
+ uint64_t id = mt_lookup_key(cur->key[curi]);
// fprintf(stderr, "\nDELET %lu\n", id);
if (itr->node->level) {
@@ -364,7 +348,7 @@ void marktree_del_itr(MarkTree *b, MarkTreeIter *itr, bool rev)
}
b->n_keys--;
- pmap_del(uint64_t)(b->id2node, ANTIGRAVITY(id));
+ pmap_del(uint64_t)(b->id2node, id);
// 5.
bool itr_dirty = false;
@@ -570,23 +554,29 @@ void marktree_free_node(mtnode_t *x)
}
/// NB: caller must check not pair!
-uint64_t marktree_revise(MarkTree *b, MarkTreeIter *itr, uint8_t decor_level)
+void marktree_revise(MarkTree *b, MarkTreeIter *itr, uint8_t decor_level, mtkey_t key)
{
- uint64_t old_id = rawkey(itr).id;
- pmap_del(uint64_t)(b->id2node, ANTIGRAVITY(old_id));
- uint64_t new_id = (b->next_id += ID_INCR) + ((uint64_t)decor_level << DECOR_OFFSET);
- rawkey(itr).id = new_id + (RIGHT_GRAVITY&old_id);
- refkey(b, itr->node, itr->i);
- return new_id;
+ // TODO(bfredl): clean up this mess and re-instantiate &= and |= forms
+ // once we upgrade to a non-broken version of gcc in functionaltest-lua CI
+ rawkey(itr).flags = (uint16_t)((uint16_t)rawkey(itr).flags & (uint16_t)~MT_FLAG_DECOR_MASK);
+ rawkey(itr).flags = (uint16_t)((uint16_t)rawkey(itr).flags
+ | (uint16_t)(decor_level << MT_FLAG_DECOR_OFFSET)
+ | (uint16_t)(key.flags & MT_FLAG_DECOR_MASK));
+ rawkey(itr).decor_full = key.decor_full;
+ rawkey(itr).hl_id = key.hl_id;
+ rawkey(itr).priority = key.priority;
}
void marktree_move(MarkTree *b, MarkTreeIter *itr, int row, int col)
{
- uint64_t old_id = rawkey(itr).id;
+ mtkey_t key = rawkey(itr);
// TODO(bfredl): optimize when moving a mark within a leaf without moving it
// across neighbours!
marktree_del_itr(b, itr, false);
- marktree_put_key(b, row, col, old_id);
+ key.pos = (mtpos_t){ row, col };
+
+
+ marktree_put_key(b, key);
itr->node = NULL; // itr might become invalid by put
}
@@ -602,14 +592,15 @@ bool marktree_itr_get(MarkTree *b, int row, int col, MarkTreeIter *itr)
bool marktree_itr_get_ext(MarkTree *b, mtpos_t p, MarkTreeIter *itr, bool last, bool gravity,
mtpos_t *oldbase)
{
- mtkey_t k = { .pos = p, .id = gravity ? RIGHT_GRAVITY : 0 };
- if (last && !gravity) {
- k.id = UINT64_MAX;
- }
if (b->n_keys == 0) {
itr->node = NULL;
return false;
}
+
+ mtkey_t k = { .pos = p, .flags = gravity ? MT_FLAG_RIGHT_GRAVITY : 0 };
+ if (last && !gravity) {
+ k.flags = MT_FLAG_LAST;
+ }
itr->pos = (mtpos_t){ 0, 0 };
itr->node = b->root;
itr->lvl = 0;
@@ -816,25 +807,29 @@ mtpos_t marktree_itr_pos(MarkTreeIter *itr)
return pos;
}
-mtmark_t marktree_itr_current(MarkTreeIter *itr)
+mtkey_t marktree_itr_current(MarkTreeIter *itr)
{
if (itr->node) {
- uint64_t keyid = rawkey(itr).id;
- mtpos_t pos = marktree_itr_pos(itr);
- mtmark_t mark = { .row = pos.row,
- .col = pos.col,
- .id = ANTIGRAVITY(keyid),
- .right_gravity = keyid & RIGHT_GRAVITY };
- return mark;
- }
- return (mtmark_t){ -1, -1, 0, false };
+ mtkey_t key = rawkey(itr);
+ key.pos = marktree_itr_pos(itr);
+ return key;
+ }
+ return MT_INVALID_KEY;
}
-static void swap_id(uint64_t *id1, uint64_t *id2)
+static bool itr_eq(MarkTreeIter *itr1, MarkTreeIter *itr2)
{
- uint64_t temp = *id1;
- *id1 = *id2;
- *id2 = temp;
+ return (&rawkey(itr1) == &rawkey(itr2));
+}
+
+static void itr_swap(MarkTreeIter *itr1, MarkTreeIter *itr2)
+{
+ mtkey_t key1 = rawkey(itr1);
+ mtkey_t key2 = rawkey(itr2);
+ rawkey(itr1) = key2;
+ rawkey(itr1).pos = key1.pos;
+ rawkey(itr2) = key1;
+ rawkey(itr2).pos = key2.pos;
}
bool marktree_splice(MarkTree *b, int start_line, int start_col, int old_extent_line,
@@ -865,7 +860,7 @@ bool marktree_splice(MarkTree *b, int start_line, int start_col, int old_extent_
mtpos_t ipos = marktree_itr_pos(itr);
if (!pos_leq(old_extent, ipos)
|| (old_extent.row == ipos.row && old_extent.col == ipos.col
- && !IS_RIGHT(rawkey(itr).id))) {
+ && !mt_right(rawkey(itr)))) {
marktree_itr_get_ext(b, old_extent, enditr, true, true, NULL);
assert(enditr->node);
// "assert" (itr <= enditr)
@@ -895,13 +890,13 @@ continue_same_node:
break;
}
- if (IS_RIGHT(rawkey(itr).id)) {
- while (rawkey(itr).id != rawkey(enditr).id
- && IS_RIGHT(rawkey(enditr).id)) {
+ if (mt_right(rawkey(itr))) {
+ while (!itr_eq(itr, enditr)
+ && mt_right(rawkey(enditr))) {
marktree_itr_prev(b, enditr);
}
- if (!IS_RIGHT(rawkey(enditr).id)) {
- swap_id(&rawkey(itr).id, &rawkey(enditr).id);
+ if (!mt_right(rawkey(enditr))) {
+ itr_swap(itr, enditr);
refkey(b, itr->node, itr->i);
refkey(b, enditr->node, enditr->i);
} else {
@@ -911,7 +906,7 @@ continue_same_node:
}
}
- if (rawkey(itr).id == rawkey(enditr).id) {
+ if (itr_eq(itr, enditr)) {
// actually, will be past_right after this key
past_right = true;
}
@@ -1006,13 +1001,13 @@ void marktree_move_region(MarkTree *b, int start_row, colnr_T start_col, int ext
marktree_itr_get_ext(b, start, itr, false, true, NULL);
kvec_t(mtkey_t) saved = KV_INITIAL_VALUE;
while (itr->node) {
- mtpos_t pos = marktree_itr_pos(itr);
- if (!pos_leq(pos, end) || (pos.row == end.row && pos.col == end.col
- && rawkey(itr).id & RIGHT_GRAVITY)) {
+ mtkey_t k = marktree_itr_current(itr);
+ if (!pos_leq(k.pos, end) || (k.pos.row == end.row && k.pos.col == end.col
+ && mt_right(k))) {
break;
}
- relative(start, &pos);
- kv_push(saved, ((mtkey_t){ .pos = pos, .id = rawkey(itr).id }));
+ relative(start, &k.pos);
+ kv_push(saved, k);
marktree_del_itr(b, itr, false);
}
@@ -1024,30 +1019,36 @@ void marktree_move_region(MarkTree *b, int start_row, colnr_T start_col, int ext
for (size_t i = 0; i < kv_size(saved); i++) {
mtkey_t item = kv_A(saved, i);
unrelative(new, &item.pos);
- marktree_put_key(b, item.pos.row, item.pos.col, item.id);
+ marktree_put_key(b, item);
}
kv_destroy(saved);
}
/// @param itr OPTIONAL. set itr to pos.
-mtpos_t marktree_lookup(MarkTree *b, uint64_t id, MarkTreeIter *itr)
+mtkey_t marktree_lookup_ns(MarkTree *b, uint32_t ns, uint32_t id, bool end, MarkTreeIter *itr)
+{
+ return marktree_lookup(b, mt_lookup_id(ns, id, end), itr);
+}
+
+/// @param itr OPTIONAL. set itr to pos.
+mtkey_t marktree_lookup(MarkTree *b, uint64_t id, MarkTreeIter *itr)
{
mtnode_t *n = pmap_get(uint64_t)(b->id2node, id);
if (n == NULL) {
if (itr) {
itr->node = NULL;
}
- return (mtpos_t){ -1, -1 };
+ return MT_INVALID_KEY;
}
int i = 0;
for (i = 0; i < n->n; i++) {
- if (ANTIGRAVITY(n->key[i].id) == id) {
+ if (mt_lookup_key(n->key[i]) == id) {
goto found;
}
}
abort();
found: {}
- mtpos_t pos = n->key[i].pos;
+ mtkey_t key = n->key[i];
if (itr) {
itr->i = i;
itr->node = n;
@@ -1066,14 +1067,23 @@ found_node:
itr->s[b->root->level-p->level].i = i;
}
if (i > 0) {
- unrelative(p->key[i-1].pos, &pos);
+ unrelative(p->key[i-1].pos, &key.pos);
}
n = p;
}
if (itr) {
marktree_itr_fix_pos(b, itr);
}
- return pos;
+ return key;
+}
+
+mtpos_t marktree_get_altpos(MarkTree *b, mtkey_t mark, MarkTreeIter *itr)
+{
+ mtkey_t end = MT_INVALID_KEY;
+ if (mt_paired(mark)) {
+ end = marktree_lookup_ns(b, mark.ns, mark.id, !mt_end(mark), itr);
+ }
+ return end.pos;
}
static void marktree_itr_fix_pos(MarkTree *b, MarkTreeIter *itr)
@@ -1092,6 +1102,20 @@ static void marktree_itr_fix_pos(MarkTree *b, MarkTreeIter *itr)
assert(x == itr->node);
}
+// for unit test
+void marktree_put_test(MarkTree *b, uint32_t id, int row, int col, bool right_gravity)
+{
+ mtkey_t key = { { row, col }, UINT32_MAX, id, 0,
+ mt_flags(right_gravity, 0), 0, NULL };
+ marktree_put(b, key, -1, -1, false);
+}
+
+// for unit test
+bool mt_right_test(mtkey_t key)
+{
+ return mt_right(key);
+}
+
void marktree_check(MarkTree *b)
{
#ifndef NDEBUG
@@ -1134,11 +1158,11 @@ static size_t check_node(MarkTree *b, mtnode_t *x, mtpos_t *last, bool *last_rig
}
assert(pos_leq(*last, x->key[i].pos));
if (last->row == x->key[i].pos.row && last->col == x->key[i].pos.col) {
- assert(!*last_right || IS_RIGHT(x->key[i].id));
+ assert(!*last_right || mt_right(x->key[i]));
}
- *last_right = IS_RIGHT(x->key[i].id);
+ *last_right = mt_right(x->key[i]);
assert(x->key[i].pos.col >= 0);
- assert(pmap_get(uint64_t)(b->id2node, ANTIGRAVITY(x->key[i].id)) == x);
+ assert(pmap_get(uint64_t)(b->id2node, mt_lookup_key(x->key[i])) == x);
}
if (x->level) {
diff --git a/src/nvim/marktree.h b/src/nvim/marktree.h
index a1dcdf5164..95d63dd14a 100644
--- a/src/nvim/marktree.h
+++ b/src/nvim/marktree.h
@@ -3,8 +3,10 @@
#include <stdint.h>
+#include "nvim/assert.h"
#include "nvim/garray.h"
#include "nvim/map.h"
+#include "nvim/types.h"
#include "nvim/pos.h"
#define MT_MAX_DEPTH 20
@@ -15,13 +17,6 @@ typedef struct {
int32_t col;
} mtpos_t;
-typedef struct {
- int32_t row;
- int32_t col;
- uint64_t id;
- bool right_gravity;
-} mtmark_t;
-
typedef struct mtnode_s mtnode_t;
typedef struct {
int oldcol;
@@ -39,12 +34,75 @@ typedef struct {
// Internal storage
//
-// NB: actual marks have id > 0, so we can use (row,col,0) pseudo-key for
+// NB: actual marks have flags > 0, so we can use (row,col,0) pseudo-key for
// "space before (row,col)"
typedef struct {
mtpos_t pos;
- uint64_t id;
+ uint32_t ns;
+ uint32_t id;
+ int32_t hl_id;
+ uint16_t flags;
+ uint16_t priority;
+ Decoration *decor_full;
} mtkey_t;
+#define MT_INVALID_KEY (mtkey_t) { { -1, -1 }, 0, 0, 0, 0, 0, NULL }
+
+#define MT_FLAG_REAL (((uint16_t)1) << 0)
+#define MT_FLAG_END (((uint16_t)1) << 1)
+#define MT_FLAG_PAIRED (((uint16_t)1) << 2)
+#define MT_FLAG_HL_EOL (((uint16_t)1) << 3)
+
+#define DECOR_LEVELS 4
+#define MT_FLAG_DECOR_OFFSET 4
+#define MT_FLAG_DECOR_MASK (((uint16_t)(DECOR_LEVELS-1)) << MT_FLAG_DECOR_OFFSET)
+
+// next flag is (((uint16_t)1) << 6)
+
+// These _must_ be last to preserve ordering of marks
+#define MT_FLAG_RIGHT_GRAVITY (((uint16_t)1) << 14)
+#define MT_FLAG_LAST (((uint16_t)1) << 15)
+
+#define MT_FLAG_EXTERNAL_MASK (MT_FLAG_DECOR_MASK | MT_FLAG_RIGHT_GRAVITY | MT_FLAG_HL_EOL)
+
+#define MARKTREE_END_FLAG (((uint64_t)1) << 63)
+static inline uint64_t mt_lookup_id(uint32_t ns, uint32_t id, bool enda)
+{
+ return (uint64_t)ns << 32 | id | (enda?MARKTREE_END_FLAG:0);
+}
+#undef MARKTREE_END_FLAG
+
+static inline uint64_t mt_lookup_key(mtkey_t key)
+{
+ return mt_lookup_id(key.ns, key.id, key.flags & MT_FLAG_END);
+}
+
+static inline bool mt_paired(mtkey_t key)
+{
+ return key.flags & MT_FLAG_PAIRED;
+}
+
+static inline bool mt_end(mtkey_t key)
+{
+ return key.flags & MT_FLAG_END;
+}
+
+static inline bool mt_right(mtkey_t key)
+{
+ return key.flags & MT_FLAG_RIGHT_GRAVITY;
+}
+
+static inline uint8_t marktree_decor_level(mtkey_t key)
+{
+ return (uint8_t)((key.flags&MT_FLAG_DECOR_MASK) >> MT_FLAG_DECOR_OFFSET);
+}
+
+static inline uint16_t mt_flags(bool right_gravity, uint8_t decor_level)
+{
+ assert(decor_level < DECOR_LEVELS);
+ return (uint16_t)((right_gravity ? MT_FLAG_RIGHT_GRAVITY : 0)
+ | (decor_level << MT_FLAG_DECOR_OFFSET));
+}
+
struct mtnode_s {
int32_t n;
@@ -61,7 +119,6 @@ struct mtnode_s {
typedef struct {
mtnode_t *root;
size_t n_keys, n_nodes;
- uint64_t next_id;
// TODO(bfredl): the pointer to node could be part of the larger
// Map(uint64_t, ExtmarkItem) essentially;
PMap(uint64_t) id2node[1];
@@ -72,16 +129,4 @@ typedef struct {
# include "marktree.h.generated.h"
#endif
-#define MARKTREE_PAIRED_FLAG (((uint64_t)1) << 1)
-#define MARKTREE_END_FLAG (((uint64_t)1) << 0)
-
-#define DECOR_LEVELS 4
-#define DECOR_OFFSET 61
-#define DECOR_MASK (((uint64_t)(DECOR_LEVELS-1)) << DECOR_OFFSET)
-
-static inline uint8_t marktree_decor_level(uint64_t id)
-{
- return (uint8_t)((id&DECOR_MASK) >> DECOR_OFFSET);
-}
-
#endif // NVIM_MARKTREE_H
diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c
index ce44f6c619..1d1cd5e271 100644
--- a/src/nvim/mbyte.c
+++ b/src/nvim/mbyte.c
@@ -1609,7 +1609,8 @@ void show_utf8(void)
msg((char *)IObuff);
}
-/// Return offset from "p" to the first byte of the character it points into.
+/// Return offset from "p" to the start of a character, including composing characters.
+/// "base" must be the start of the string, which must be NUL terminated.
/// If "p" points to the NUL at the end of the string return 0.
/// Returns 0 when already at the first byte of a character.
int utf_head_off(const char_u *base, const char_u *p)
@@ -1850,10 +1851,9 @@ int mb_off_next(char_u *base, char_u *p)
return i;
}
-/*
- * Return the offset from "p" to the last byte of the character it points
- * into. Can start anywhere in a stream of bytes.
- */
+/// Return the offset from "p" to the last byte of the character it points
+/// into. Can start anywhere in a stream of bytes.
+/// Composing characters are not included.
int mb_tail_off(char_u *base, char_u *p)
{
int i;
@@ -2089,8 +2089,7 @@ const char *mb_unescape(const char **const pp)
size_t buf_idx = 0;
uint8_t *str = (uint8_t *)(*pp);
- // Must translate K_SPECIAL KS_SPECIAL KE_FILLER to K_SPECIAL and CSI
- // KS_EXTRA KE_CSI to CSI.
+ // Must translate K_SPECIAL KS_SPECIAL KE_FILLER to K_SPECIAL.
// Maximum length of a utf-8 character is 4 bytes.
for (size_t str_idx = 0; str[str_idx] != NUL && buf_idx < 4; str_idx++) {
if (str[str_idx] == K_SPECIAL
@@ -2098,11 +2097,6 @@ const char *mb_unescape(const char **const pp)
&& str[str_idx + 2] == KE_FILLER) {
buf[buf_idx++] = (char)K_SPECIAL;
str_idx += 2;
- } else if ((str[str_idx] == K_SPECIAL)
- && str[str_idx + 1] == KS_EXTRA
- && str[str_idx + 2] == KE_CSI) {
- buf[buf_idx++] = (char)CSI;
- str_idx += 2;
} else if (str[str_idx] == K_SPECIAL) {
break; // A special key can't be a multibyte char.
} else {
diff --git a/src/nvim/memfile.c b/src/nvim/memfile.c
index 3397296b3a..2a72d1e6a0 100644
--- a/src/nvim/memfile.c
+++ b/src/nvim/memfile.c
@@ -247,7 +247,7 @@ bhdr_T *mf_new(memfile_T *mfp, bool negative, unsigned page_count)
} else { // need to allocate memory for this block
// If the number of pages matches use the bhdr_T from the free list and
// allocate the data.
- void *p = xmalloc(mfp->mf_page_size * page_count);
+ void *p = xmalloc((size_t)mfp->mf_page_size * page_count);
hp = mf_rem_free(mfp);
hp->bh_data = p;
}
@@ -269,7 +269,7 @@ bhdr_T *mf_new(memfile_T *mfp, bool negative, unsigned page_count)
// Init the data to all zero, to avoid reading uninitialized data.
// This also avoids that the passwd file ends up in the swap file!
- (void)memset(hp->bh_data, 0, mfp->mf_page_size * page_count);
+ (void)memset(hp->bh_data, 0, (size_t)mfp->mf_page_size * page_count);
return hp;
}
@@ -528,7 +528,7 @@ bool mf_release_all(void)
static bhdr_T *mf_alloc_bhdr(memfile_T *mfp, unsigned page_count)
{
bhdr_T *hp = xmalloc(sizeof(bhdr_T));
- hp->bh_data = xmalloc(mfp->mf_page_size * page_count);
+ hp->bh_data = xmalloc((size_t)mfp->mf_page_size * page_count);
hp->bh_page_count = page_count;
return hp;
}
diff --git a/src/nvim/memline.c b/src/nvim/memline.c
index 08521c0dc3..9925971783 100644
--- a/src/nvim/memline.c
+++ b/src/nvim/memline.c
@@ -1032,9 +1032,9 @@ void ml_recover(bool checkext)
line_count = 0;
idx = 0; // start with first index in block 1
error = 0;
- buf->b_ml.ml_stack_top = 0;
+ buf->b_ml.ml_stack_top = 0; // -V1048
buf->b_ml.ml_stack = NULL;
- buf->b_ml.ml_stack_size = 0; // no stack yet
+ buf->b_ml.ml_stack_size = 0; // -V1048
if (curbuf->b_ffname == NULL) {
cannot_open = true;
@@ -4139,7 +4139,7 @@ long ml_find_line_or_offset(buf_T *buf, linenr_T lnum, long *offp, bool no_ff)
|| (offset != 0
&& offset > size +
buf->b_ml.ml_chunksize[curix].mlcs_totalsize
- + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines))) {
+ + (long)ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines))) {
curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
if (offset && ffdos) {
diff --git a/src/nvim/menu.c b/src/nvim/menu.c
index ac4d52c392..0db9d69a7e 100644
--- a/src/nvim/menu.c
+++ b/src/nvim/menu.c
@@ -361,7 +361,7 @@ static int add_menu_path(const char_u *const menu_path, vimmenu_T *menuarg,
goto erret;
}
- // Not already there, so lets add it
+ // Not already there, so let's add it
menu = xcalloc(1, sizeof(vimmenu_T));
menu->modes = modes;
diff --git a/src/nvim/message.c b/src/nvim/message.c
index 76aa863bde..e1e253cd2e 100644
--- a/src/nvim/message.c
+++ b/src/nvim/message.c
@@ -1215,7 +1215,7 @@ void wait_return(int redraw)
} else if (vim_strchr((char_u *)"\r\n ", c) == NULL && c != Ctrl_C) {
// Put the character back in the typeahead buffer. Don't use the
// stuff buffer, because lmaps wouldn't work.
- ins_char_typebuf(c);
+ ins_char_typebuf(c, mod_mask);
do_redraw = true; // need a redraw even though there is
// typeahead
}
@@ -1269,7 +1269,7 @@ static void hit_return_msg(void)
{
int save_p_more = p_more;
- p_more = FALSE; // don't want see this message when scrolling back
+ p_more = false; // don't want to see this message when scrolling back
if (msg_didout) { // start on a new line
msg_putchar('\n');
}
@@ -3508,7 +3508,7 @@ int do_dialog(int type, char_u *title, char_u *message, char_u *buttons, int dfl
}
if (c == ':' && ex_cmd) {
retval = dfltbutton;
- ins_char_typebuf(':');
+ ins_char_typebuf(':', 0);
break;
}
diff --git a/src/nvim/move.c b/src/nvim/move.c
index 0a672000e4..67ec19903f 100644
--- a/src/nvim/move.c
+++ b/src/nvim/move.c
@@ -909,7 +909,7 @@ void curs_columns(win_T *wp, int may_scroll)
}
wp->w_skipcol = n * width;
} else if (extra == 1) {
- // less then 'scrolloff' lines above, decrease skipcol
+ // less than 'scrolloff' lines above, decrease skipcol
assert(so <= INT_MAX);
extra = (wp->w_skipcol + (int)so * width - wp->w_virtcol
+ width - 1) / width;
@@ -920,7 +920,7 @@ void curs_columns(win_T *wp, int may_scroll)
wp->w_skipcol -= extra * width;
}
} else if (extra == 2) {
- // less then 'scrolloff' lines below, increase skipcol
+ // less than 'scrolloff' lines below, increase skipcol
endcol = (n - wp->w_height_inner + 1) * width;
while (endcol > wp->w_virtcol) {
endcol -= width;
@@ -1011,7 +1011,7 @@ void textpos2screenpos(win_T *wp, pos_T *pos, int *rowp, int *scolp, int *ccolp,
col -= wp->w_leftcol;
if (col >= 0 && col < wp->w_width) {
- coloff = col - scol + (local ? 0 : wp->w_wincol) + 1;
+ coloff = col - scol + (local ? 0 : wp->w_wincol + wp->w_border_adj[3]) + 1;
} else {
scol = ccol = ecol = 0;
// character is left or right of the window
@@ -1022,7 +1022,7 @@ void textpos2screenpos(win_T *wp, pos_T *pos, int *rowp, int *scolp, int *ccolp,
}
}
}
- *rowp = (local ? 0 : wp->w_winrow) + row + rowoff;
+ *rowp = (local ? 0 : wp->w_winrow + wp->w_border_adj[0]) + row + rowoff;
*scolp = scol + coloff;
*ccolp = ccol + coloff;
*ecolp = ecol + coloff;
diff --git a/src/nvim/normal.c b/src/nvim/normal.c
index 95a521c0d8..c3b7e81d17 100644
--- a/src/nvim/normal.c
+++ b/src/nvim/normal.c
@@ -229,7 +229,7 @@ static const struct nv_cmd {
{ 'N', nv_next, 0, SEARCH_REV },
{ 'O', nv_open, 0, 0 },
{ 'P', nv_put, 0, 0 },
- { 'Q', nv_exmode, NV_NCW, 0 },
+ { 'Q', nv_regreplay, 0, 0 },
{ 'R', nv_Replace, 0, false },
{ 'S', nv_subst, NV_KEEPREG, 0 },
{ 'T', nv_csearch, NV_NCH_ALW|NV_LANG, BACKWARD },
@@ -334,6 +334,7 @@ static const struct nv_cmd {
{ K_SELECT, nv_select, 0, 0 },
{ K_EVENT, nv_event, NV_KEEPREG, 0 },
{ K_COMMAND, nv_colon, 0, 0 },
+ { K_LUA, nv_colon, 0, 0 },
};
// Number of commands in nv_cmds[].
@@ -1009,7 +1010,7 @@ static int normal_execute(VimState *state, int key)
// restart automatically.
// Insert the typed character in the typeahead buffer, so that it can
// be mapped in Insert mode. Required for ":lmap" to work.
- ins_char_typebuf(s->c);
+ ins_char_typebuf(s->c, mod_mask);
if (restart_edit != 0) {
s->c = 'd';
} else {
@@ -4028,33 +4029,37 @@ dozet:
/*
* "Q" command.
*/
-static void nv_exmode(cmdarg_T *cap)
+static void nv_regreplay(cmdarg_T *cap)
{
- /*
- * Ignore 'Q' in Visual mode, just give a beep.
- */
- if (VIsual_active) {
- vim_beep(BO_EX);
- } else if (!checkclearop(cap->oap)) {
- do_exmode();
+ if (checkclearop(cap->oap)) {
+ return;
+ }
+
+ while (cap->count1-- && !got_int) {
+ if (do_execreg(reg_recorded, false, false, false) == false) {
+ clearopbeep(cap->oap);
+ break;
+ }
+ line_breakcheck();
}
}
-/// Handle a ":" command and <Cmd>.
+/// Handle a ":" command and <Cmd> or Lua keymaps.
static void nv_colon(cmdarg_T *cap)
{
int old_p_im;
bool cmd_result;
bool is_cmdkey = cap->cmdchar == K_COMMAND;
+ bool is_lua = cap->cmdchar == K_LUA;
- if (VIsual_active && !is_cmdkey) {
+ if (VIsual_active && !is_cmdkey && !is_lua) {
nv_operator(cap);
} else {
if (cap->oap->op_type != OP_NOP) {
// Using ":" as a movement is charwise exclusive.
cap->oap->motion_type = kMTCharWise;
cap->oap->inclusive = false;
- } else if (cap->count0 && !is_cmdkey) {
+ } else if (cap->count0 && !is_cmdkey && !is_lua) {
// translate "count:" into ":.,.+(count - 1)"
stuffcharReadbuff('.');
if (cap->count0 > 1) {
@@ -4070,9 +4075,13 @@ static void nv_colon(cmdarg_T *cap)
old_p_im = p_im;
+ if (is_lua) {
+ cmd_result = map_execute_lua();
+ } else {
// get a command line and execute it
- cmd_result = do_cmdline(NULL, is_cmdkey ? getcmdkeycmd : getexline, NULL,
- cap->oap->op_type != OP_NOP ? DOCMD_KEEPLINE : 0);
+ cmd_result = do_cmdline(NULL, is_cmdkey ? getcmdkeycmd : getexline, NULL,
+ cap->oap->op_type != OP_NOP ? DOCMD_KEEPLINE : 0);
+ }
// If 'insertmode' changed, enter or exit Insert mode
if (p_im != old_p_im) {
@@ -4428,11 +4437,7 @@ static void nv_ident(cmdarg_T *cap)
// Start insert mode in terminal buffer
restart_edit = 'i';
- add_map((char_u *)"<buffer> <esc> <Cmd>call jobstop(&channel)<CR>", TERM_FOCUS, true);
- do_cmdline_cmd("autocmd TermClose <buffer> "
- " if !v:event.status |"
- " exec 'bdelete! ' .. expand('<abuf>') |"
- " endif");
+ add_map((char_u *)"<buffer> <esc> <Cmd>bdelete!<CR>", TERM_FOCUS, true);
}
}
diff --git a/src/nvim/ops.c b/src/nvim/ops.c
index 9bc63477e9..2bc92ce295 100644
--- a/src/nvim/ops.c
+++ b/src/nvim/ops.c
@@ -912,30 +912,44 @@ int do_record(int c)
showmode();
regname = c;
retval = OK;
+ apply_autocmds(EVENT_RECORDINGENTER, NULL, NULL, false, curbuf);
}
- } else { // stop recording
- /*
- * Get the recorded key hits. K_SPECIAL and CSI will be escaped, this
- * needs to be removed again to put it in a register. exec_reg then
- * adds the escaping back later.
- */
+ } else { // stop recording
+ save_v_event_T save_v_event;
+ // Set the v:event dictionary with information about the recording.
+ dict_T *dict = get_v_event(&save_v_event);
+
+ // The recorded text contents.
+ p = get_recorded();
+ if (p != NULL) {
+ // Remove escaping for K_SPECIAL in multi-byte chars.
+ vim_unescape_ks(p);
+ (void)tv_dict_add_str(dict, S_LEN("regcontents"), (const char *)p);
+ }
+
+ // Name of requested register, or empty string for unnamed operation.
+ char buf[NUMBUFLEN+2];
+ buf[0] = (char)regname;
+ buf[1] = NUL;
+ (void)tv_dict_add_str(dict, S_LEN("regname"), buf);
+
+ // Get the recorded key hits. K_SPECIAL will be escaped, this
+ // needs to be removed again to put it in a register. exec_reg then
+ // adds the escaping back later.
+ apply_autocmds(EVENT_RECORDINGLEAVE, NULL, NULL, false, curbuf);
+ restore_v_event(dict, &save_v_event);
+ reg_recorded = reg_recording;
reg_recording = 0;
if (ui_has(kUIMessages)) {
showmode();
} else {
msg("");
}
- p = get_recorded();
if (p == NULL) {
retval = FAIL;
} else {
- // Remove escaping for CSI and K_SPECIAL in multi-byte chars.
- vim_unescape_csi(p);
-
- /*
- * We don't want to change the default register here, so save and
- * restore the current register name.
- */
+ // We don't want to change the default register here, so save and
+ // restore the current register name.
old_y_previous = y_previous;
retval = stuff_yank(regname, p);
@@ -1085,7 +1099,7 @@ int do_execreg(int regname, int colon, int addcr, int silent)
return FAIL;
}
}
- escaped = vim_strsave_escape_csi(reg->y_array[i]);
+ escaped = vim_strsave_escape_ks(reg->y_array[i]);
retval = ins_typebuf(escaped, remap, 0, true, silent);
xfree(escaped);
if (retval == FAIL) {
@@ -1127,7 +1141,7 @@ static void put_reedit_in_typebuf(int silent)
/// Insert register contents "s" into the typeahead buffer, so that it will be
/// executed again.
///
-/// @param esc when true then it is to be taken literally: Escape CSI
+/// @param esc when true then it is to be taken literally: Escape K_SPECIAL
/// characters and no remapping.
/// @param colon add ':' before the line
static int put_in_typebuf(char_u *s, bool esc, bool colon, int silent)
@@ -1142,7 +1156,7 @@ static int put_in_typebuf(char_u *s, bool esc, bool colon, int silent)
char_u *p;
if (esc) {
- p = vim_strsave_escape_csi(s);
+ p = vim_strsave_escape_ks(s);
} else {
p = s;
}
@@ -3140,11 +3154,12 @@ void do_put(int regname, yankreg_T *reg, int dir, long count, int flags)
if (ve_flags == VE_ALL && y_type == kMTCharWise) {
if (gchar_cursor() == TAB) {
- /* Don't need to insert spaces when "p" on the last position of a
- * tab or "P" on the first position. */
int viscol = getviscol();
+ long ts = curbuf->b_p_ts;
+ // Don't need to insert spaces when "p" on the last position of a
+ // tab or "P" on the first position.
if (dir == FORWARD
- ? tabstop_padding(viscol, curbuf->b_p_ts, curbuf->b_p_vts_array) != 1
+ ? tabstop_padding(viscol, ts, curbuf->b_p_vts_array) != 1
: curwin->w_cursor.coladd > 0) {
coladvance_force(viscol);
} else {
@@ -4124,7 +4139,7 @@ static int same_leader(linenr_T lnum, int leader1_len, char_u *leader1_flags, in
* If first leader has 'f' flag, the lines can be joined only if the
* second line does not have a leader.
* If first leader has 'e' flag, the lines can never be joined.
- * If fist leader has 's' flag, the lines can only be joined if there is
+ * If first leader has 's' flag, the lines can only be joined if there is
* some text after it and the second line has the 'm' flag.
*/
if (leader1_flags != NULL) {
diff --git a/src/nvim/option.c b/src/nvim/option.c
index 2ceb1bd992..659965b64c 100644
--- a/src/nvim/option.c
+++ b/src/nvim/option.c
@@ -1345,7 +1345,7 @@ int do_set(char_u *arg, int opt_flags)
if (nextchar == '&') { // set to default val
newval = options[opt_idx].def_val;
- // expand environment variables and ~ (since the
+ // expand environment variables and ~ since the
// default value was already expanded, only
// required when an environment variable was set
// later
@@ -2991,7 +2991,7 @@ ambw_end:
}
} else if (varp == &curwin->w_p_fdc || varp == &curwin->w_allbuf_opt.wo_fdc) {
// 'foldcolumn'
- if (check_opt_strings(*varp, p_fdc_values, false) != OK) {
+ if (**varp == NUL || check_opt_strings(*varp, p_fdc_values, false) != OK) {
errmsg = e_invarg;
}
} else if (varp == &p_pt) {
@@ -3370,6 +3370,9 @@ static int int_cmp(const void *a, const void *b)
/// @return OK when the value is valid, FAIL otherwise
int check_signcolumn(char_u *val)
{
+ if (*val == NUL) {
+ return FAIL;
+ }
// check for basic match
if (check_opt_strings(val, p_scl_values, false) == OK) {
return OK;
@@ -3610,7 +3613,7 @@ static char *set_chars_option(win_T *wp, char_u **varp, bool set)
c2 = c3 = 0;
s = p + len + 1;
c1 = get_encoded_char_adv(&s);
- if (c1 == 0 || utf_char2cells(c1) > 1) {
+ if (c1 == 0 || char2cells(c1) > 1) {
return e_invarg;
}
if (tab[i].cp == &wp->w_p_lcs_chars.tab2) {
@@ -3618,12 +3621,12 @@ static char *set_chars_option(win_T *wp, char_u **varp, bool set)
return e_invarg;
}
c2 = get_encoded_char_adv(&s);
- if (c2 == 0 || utf_char2cells(c2) > 1) {
+ if (c2 == 0 || char2cells(c2) > 1) {
return e_invarg;
}
if (!(*s == ',' || *s == NUL)) {
c3 = get_encoded_char_adv(&s);
- if (c3 == 0 || utf_char2cells(c3) > 1) {
+ if (c3 == 0 || char2cells(c3) > 1) {
return e_invarg;
}
}
@@ -3657,7 +3660,7 @@ static char *set_chars_option(win_T *wp, char_u **varp, bool set)
multispace_len = 0;
while (*s != NUL && *s != ',') {
c1 = get_encoded_char_adv(&s);
- if (c1 == 0 || utf_char2cells(c1) > 1) {
+ if (c1 == 0 || char2cells(c1) > 1) {
return e_invarg;
}
multispace_len++;
@@ -4129,7 +4132,7 @@ static char *set_bool_option(const int opt_idx, char_u *const varp, const int va
}
}
- // Arabic requires a utf-8 encoding, inform the user if its not
+ // Arabic requires a utf-8 encoding, inform the user if it's not
// set.
if (STRCMP(p_enc, "utf-8") != 0) {
static char *w_arabic = N_("W17: Arabic requires UTF-8, do ':set encoding=utf-8'");
@@ -5059,6 +5062,9 @@ int get_option_value_strict(char *name, int64_t *numval, char **stringval, int o
/// @param[in] number New value for the number or boolean option.
/// @param[in] string New value for string option.
/// @param[in] opt_flags Flags: OPT_LOCAL, OPT_GLOBAL, or 0 (both).
+/// If OPT_CLEAR is set, the value of the option
+/// is cleared (the exact semantics of this depend
+/// on the option).
///
/// @return NULL on success, error message on error.
char *set_option_value(const char *const name, const long number, const char *const string,
@@ -5084,7 +5090,7 @@ char *set_option_value(const char *const name, const long number, const char *co
}
if (flags & P_STRING) {
const char *s = string;
- if (s == NULL) {
+ if (s == NULL || opt_flags & OPT_CLEAR) {
s = "";
}
return set_string_option(opt_idx, s, opt_flags);
@@ -5106,10 +5112,23 @@ char *set_option_value(const char *const name, const long number, const char *co
return NULL; // do nothing as we hit an error
}
}
+ long numval = number;
+ if (opt_flags & OPT_CLEAR) {
+ if ((int *)varp == &curbuf->b_p_ar) {
+ numval = -1;
+ } else if ((long *)varp == &curbuf->b_p_ul) {
+ numval = NO_LOCAL_UNDOLEVEL;
+ } else if ((long *)varp == &curwin->w_p_so || (long *)varp == &curwin->w_p_siso) {
+ numval = -1;
+ } else {
+ char *s = NULL;
+ (void)get_option_value(name, &numval, (char_u **)&s, OPT_GLOBAL);
+ }
+ }
if (flags & P_NUM) {
- return set_num_option(opt_idx, varp, number, NULL, 0, opt_flags);
+ return set_num_option(opt_idx, varp, numval, NULL, 0, opt_flags);
} else {
- return set_bool_option(opt_idx, varp, (int)number, opt_flags);
+ return set_bool_option(opt_idx, varp, (int)numval, opt_flags);
}
}
}
diff --git a/src/nvim/option.h b/src/nvim/option.h
index 452494172f..f7dbaafeec 100644
--- a/src/nvim/option.h
+++ b/src/nvim/option.h
@@ -22,6 +22,7 @@ typedef enum {
OPT_ONECOLUMN = 64, ///< list options one per line
OPT_NO_REDRAW = 128, ///< ignore redraw flags on option
OPT_SKIPRTP = 256, ///< "skiprtp" in 'sessionoptions'
+ OPT_CLEAR = 512, ///< Clear local value of an option.
} OptionFlags;
#ifdef INCLUDE_GENERATED_DECLARATIONS
diff --git a/src/nvim/option_defs.h b/src/nvim/option_defs.h
index 19cb33a354..09c3bf3800 100644
--- a/src/nvim/option_defs.h
+++ b/src/nvim/option_defs.h
@@ -743,6 +743,7 @@ EXTERN int p_write; // 'write'
EXTERN int p_wa; // 'writeany'
EXTERN int p_wb; // 'writebackup'
EXTERN long p_wd; // 'writedelay'
+EXTERN int p_cdh; // 'cdhome'
EXTERN int p_force_on; ///< options that cannot be turned off.
EXTERN int p_force_off; ///< options that cannot be turned on.
diff --git a/src/nvim/options.lua b/src/nvim/options.lua
index 71208dfc68..5133fe7ac8 100644
--- a/src/nvim/options.lua
+++ b/src/nvim/options.lua
@@ -275,6 +275,14 @@ return {
defaults={if_true="internal,keepascii"}
},
{
+ full_name='cdhome', abbreviation='cdh',
+ short_desc=N_(":cd without argument goes to the home directory"),
+ type='bool', scope={'global'},
+ secure=true,
+ varname='p_cdh',
+ defaults={if_true=false}
+ },
+ {
full_name='cdpath', abbreviation='cd',
short_desc=N_("list of directories searched with \":cd\""),
type='string', list='comma', scope={'global'},
@@ -403,7 +411,7 @@ return {
},
{
full_name='compatible', abbreviation='cp',
- short_desc=N_("No description"),
+ short_desc=N_("No description"),
type='bool', scope={'global'},
redraw={'all_windows'},
varname='p_force_off',
@@ -657,14 +665,14 @@ return {
},
{
full_name='edcompatible', abbreviation='ed',
- short_desc=N_("No description"),
+ short_desc=N_("No description"),
type='bool', scope={'global'},
varname='p_force_off',
defaults={if_true=false}
},
{
full_name='emoji', abbreviation='emo',
- short_desc=N_("No description"),
+ short_desc=N_("No description"),
type='bool', scope={'global'},
redraw={'all_windows', 'ui_option'},
varname='p_emoji',
@@ -1176,7 +1184,7 @@ return {
},
{
full_name='inccommand', abbreviation='icm',
- short_desc=N_("Live preview of substitution"),
+ short_desc=N_("Live preview of substitution"),
type='string', scope={'global'},
redraw={'all_windows'},
varname='p_icm',
@@ -2491,7 +2499,7 @@ return {
},
{
full_name='termencoding', abbreviation='tenc',
- short_desc=N_("Terminal encodig"),
+ short_desc=N_("Terminal encoding"),
type='string', scope={'global'},
defaults={if_true=""}
},
@@ -2614,7 +2622,7 @@ return {
},
{
full_name='ttyfast', abbreviation='tf',
- short_desc=N_("No description"),
+ short_desc=N_("No description"),
type='bool', scope={'global'},
no_mkrc=true,
varname='p_force_on',
diff --git a/src/nvim/os/input.c b/src/nvim/os/input.c
index 3790eba212..54cfaee80a 100644
--- a/src/nvim/os/input.c
+++ b/src/nvim/os/input.c
@@ -234,9 +234,9 @@ size_t input_enqueue(String keys)
while (rbuffer_space(input_buffer) >= 19 && ptr < end) {
// A "<x>" form occupies at least 1 characters, and produces up
// to 19 characters (1 + 5 * 3 for the char and 3 for a modifier).
- // In the case of K_SPECIAL(0x80) or CSI(0x9B), 3 bytes are escaped and
- // needed, but since the keys are UTF-8, so the first byte cannot be
- // K_SPECIAL(0x80) or CSI(0x9B).
+ // In the case of K_SPECIAL(0x80), 3 bytes are escaped and needed,
+ // but since the keys are UTF-8, so the first byte cannot be
+ // K_SPECIAL(0x80).
uint8_t buf[19] = { 0 };
unsigned int new_size
= trans_special((const uint8_t **)&ptr, (size_t)(end - ptr), buf, true,
@@ -263,12 +263,8 @@ size_t input_enqueue(String keys)
continue;
}
- // copy the character, escaping CSI and K_SPECIAL
- if ((uint8_t)*ptr == CSI) {
- rbuffer_write(input_buffer, (char *)&(uint8_t){ K_SPECIAL }, 1);
- rbuffer_write(input_buffer, (char *)&(uint8_t){ KS_EXTRA }, 1);
- rbuffer_write(input_buffer, (char *)&(uint8_t){ KE_CSI }, 1);
- } else if ((uint8_t)*ptr == K_SPECIAL) {
+ // copy the character, escaping K_SPECIAL
+ if ((uint8_t)(*ptr) == K_SPECIAL) {
rbuffer_write(input_buffer, (char *)&(uint8_t){ K_SPECIAL }, 1);
rbuffer_write(input_buffer, (char *)&(uint8_t){ KS_SPECIAL }, 1);
rbuffer_write(input_buffer, (char *)&(uint8_t){ KE_FILLER }, 1);
diff --git a/src/nvim/os/pty_process_unix.c b/src/nvim/os/pty_process_unix.c
index 450bc75ffb..3459646bad 100644
--- a/src/nvim/os/pty_process_unix.c
+++ b/src/nvim/os/pty_process_unix.c
@@ -15,7 +15,13 @@
# include <libutil.h>
#elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
# include <util.h>
-#elif !defined(__sun)
+#elif defined(__sun)
+# include <sys/stream.h>
+# include <sys/syscall.h>
+# include <fcntl.h>
+# include <unistd.h>
+# include <signal.h>
+#else
# include <pty.h>
#endif
@@ -38,6 +44,118 @@
# include "os/pty_process_unix.c.generated.h"
#endif
+#if defined(__sun) && !defined(HAVE_FORKPTY)
+
+// this header defines STR, just as nvim.h, but it is defined as ('S'<<8),
+// to avoid #undef STR, #undef STR, #define STR ('S'<<8) just delay the
+// inclusion of the header even though it gets include out of order.
+#include <sys/stropts.h>
+
+static int openpty(int *amaster, int *aslave, char *name,
+ struct termios *termp, struct winsize *winp)
+{
+ int slave = -1;
+ int master = open("/dev/ptmx", O_RDWR);
+ if (master == -1) {
+ goto error;
+ }
+
+ // grantpt will invoke a setuid program to change permissions
+ // and might fail if SIGCHLD handler is set, temporarily reset
+ // while running
+ void(*sig_saved)(int) = signal(SIGCHLD, SIG_DFL);
+ int res = grantpt(master);
+ signal(SIGCHLD, sig_saved);
+
+ if (res == -1 || unlockpt(master) == -1) {
+ goto error;
+ }
+
+ char *slave_name = ptsname(master);
+ if (slave_name == NULL) {
+ goto error;
+ }
+
+ slave = open(slave_name, O_RDWR|O_NOCTTY);
+ if (slave == -1) {
+ goto error;
+ }
+
+ // ptem emulates a terminal when used on a pseudo terminal driver,
+ // must be pushed before ldterm
+ ioctl(slave, I_PUSH, "ptem");
+ // ldterm provides most of the termio terminal interface
+ ioctl(slave, I_PUSH, "ldterm");
+ // ttcompat compatability with older terminal ioctls
+ ioctl(slave, I_PUSH, "ttcompat");
+
+ if (termp) {
+ tcsetattr(slave, TCSAFLUSH, termp);
+ }
+ if (winp) {
+ ioctl(slave, TIOCSWINSZ, winp);
+ }
+
+ *amaster = master;
+ *aslave = slave;
+ // ignoring name, not passed and size is unknown in the API
+
+ return 0;
+
+error:
+ if (slave != -1) {
+ close(slave);
+ }
+ if (master != -1) {
+ close(master);
+ }
+ return -1;
+}
+
+static int login_tty(int fd)
+{
+ setsid();
+ if (ioctl(fd, TIOCSCTTY, NULL) == -1) {
+ return -1;
+ }
+
+ dup2(fd, STDIN_FILENO);
+ dup2(fd, STDOUT_FILENO);
+ dup2(fd, STDERR_FILENO);
+ if (fd > STDERR_FILENO) {
+ close(fd);
+ }
+
+ return 0;
+}
+
+static pid_t forkpty(int *amaster, char *name,
+ struct termios *termp, struct winsize *winp)
+{
+ int master, slave;
+ if (openpty(&master, &slave, name, termp, winp) == -1) {
+ return -1;
+ }
+
+ pid_t pid = fork();
+ switch (pid) {
+ case -1:
+ close(master);
+ close(slave);
+ return -1;
+ case 0:
+ close(master);
+ login_tty(slave);
+ return 0;
+ default:
+ close(slave);
+ *amaster = master;
+ return pid;
+ }
+}
+
+#endif
+
/// termios saved at startup (for TUI) or initialized by pty_process_spawn().
static struct termios termios_default;
diff --git a/src/nvim/plines.c b/src/nvim/plines.c
index a061f76f34..a572f747df 100644
--- a/src/nvim/plines.c
+++ b/src/nvim/plines.c
@@ -83,7 +83,7 @@ int plines_win_nofill(win_T *wp, linenr_T lnum, bool winheight)
return 1;
}
- // A folded lines is handled just like an empty line.
+ // Folded lines are handled just like an empty line.
if (lineFolded(wp, lnum)) {
return 1;
}
diff --git a/src/nvim/po/ja.euc-jp.po b/src/nvim/po/ja.euc-jp.po
index 5dda7c59f5..9633bec9f2 100644
--- a/src/nvim/po/ja.euc-jp.po
+++ b/src/nvim/po/ja.euc-jp.po
@@ -1644,15 +1644,6 @@ msgstr " [w]"
msgid " written"
msgstr " "
-msgid "E205: Patchmode: can't save original file"
-msgstr "E205: patchmode: ܥե¸Ǥޤ"
-
-msgid "E206: patchmode: can't touch empty original file"
-msgstr "E206: patchmode: θܥեtouchǤޤ"
-
-msgid "E207: Can't delete backup file"
-msgstr "E207: Хååץեäޤ"
-
msgid ""
"\n"
"WARNING: Original file may be lost or damaged\n"
diff --git a/src/nvim/po/ja.po b/src/nvim/po/ja.po
index a169bd3589..c363c00fa6 100644
--- a/src/nvim/po/ja.po
+++ b/src/nvim/po/ja.po
@@ -1644,15 +1644,6 @@ msgstr " [w]"
msgid " written"
msgstr " 書込み"
-msgid "E205: Patchmode: can't save original file"
-msgstr "E205: patchmode: 原本ファイルを保存できません"
-
-msgid "E206: patchmode: can't touch empty original file"
-msgstr "E206: patchmode: 空の原本ファイルをtouchできません"
-
-msgid "E207: Can't delete backup file"
-msgstr "E207: バックアップファイルを消せません"
-
msgid ""
"\n"
"WARNING: Original file may be lost or damaged\n"
diff --git a/src/nvim/popupmnu.c b/src/nvim/popupmnu.c
index 606c03f838..da2ada791f 100644
--- a/src/nvim/popupmnu.c
+++ b/src/nvim/popupmnu.c
@@ -386,7 +386,7 @@ void pum_display(pumitem_T *array, int size, int selected, bool array_changed, i
void pum_redraw(void)
{
int row = 0;
- int col;
+ int grid_col;
int attr_norm = win_hl_attr(curwin, HLF_PNI);
int attr_select = win_hl_attr(curwin, HLF_PSI);
int attr_scroll = win_hl_attr(curwin, HLF_PSB);
@@ -479,7 +479,7 @@ void pum_redraw(void)
// Display each entry, use two spaces for a Tab.
// Do this 3 times: For the main text, kind and extra info
- col = col_off;
+ grid_col = col_off;
totwidth = 0;
for (round = 1; round <= 3; ++round) {
@@ -537,24 +537,15 @@ void pum_redraw(void)
}
}
grid_puts_len(&pum_grid, rt, (int)STRLEN(rt), row,
- col - size + 1, attr);
+ grid_col - size + 1, attr);
xfree(rt_start);
xfree(st);
- col -= width;
+ grid_col -= width;
} else {
- int size = (int)STRLEN(st);
- int cells = (int)mb_string2cells(st);
-
- // only draw the text that fits
- while (size > 0 && col + cells > pum_width + pum_col) {
- size--;
- size -= utf_head_off(st, st + size);
- cells -= utf_ptr2cells(st + size);
- }
-
- grid_puts_len(&pum_grid, st, size, row, col, attr);
+ // use grid_puts_len() to truncate the text
+ grid_puts(&pum_grid, st, row, grid_col, attr);
xfree(st);
- col += width;
+ grid_col += width;
}
if (*p != TAB) {
@@ -563,12 +554,12 @@ void pum_redraw(void)
// Display two spaces for a Tab.
if (pum_rl) {
- grid_puts_len(&pum_grid, (char_u *)" ", 2, row, col - 1,
+ grid_puts_len(&pum_grid, (char_u *)" ", 2, row, grid_col - 1,
attr);
- col -= 2;
+ grid_col -= 2;
} else {
- grid_puts_len(&pum_grid, (char_u *)" ", 2, row, col, attr);
- col += 2;
+ grid_puts_len(&pum_grid, (char_u *)" ", 2, row, grid_col, attr);
+ grid_col += 2;
}
totwidth += 2;
// start text at next char
@@ -599,21 +590,21 @@ void pum_redraw(void)
if (pum_rl) {
grid_fill(&pum_grid, row, row + 1, col_off - pum_base_width - n + 1,
- col + 1, ' ', ' ', attr);
- col = col_off - pum_base_width - n + 1;
+ grid_col + 1, ' ', ' ', attr);
+ grid_col = col_off - pum_base_width - n + 1;
} else {
- grid_fill(&pum_grid, row, row + 1, col,
+ grid_fill(&pum_grid, row, row + 1, grid_col,
col_off + pum_base_width + n, ' ', ' ', attr);
- col = col_off + pum_base_width + n;
+ grid_col = col_off + pum_base_width + n;
}
totwidth = pum_base_width + n;
}
if (pum_rl) {
- grid_fill(&pum_grid, row, row + 1, col_off - pum_width + 1, col + 1,
+ grid_fill(&pum_grid, row, row + 1, col_off - pum_width + 1, grid_col + 1,
' ', ' ', attr);
} else {
- grid_fill(&pum_grid, row, row + 1, col, col_off + pum_width, ' ', ' ',
+ grid_fill(&pum_grid, row, row + 1, grid_col, col_off + pum_width, ' ', ' ',
attr);
}
diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c
index 32d0ebe8eb..0196e05455 100644
--- a/src/nvim/quickfix.c
+++ b/src/nvim/quickfix.c
@@ -3947,7 +3947,7 @@ static int qf_buf_add_line(qf_list_T *qfl, buf_T *buf, linenr_T lnum, const qfli
int len;
buf_T *errbuf;
- // If the 'quickfixtextfunc' function returned an non-empty custom string
+ // If the 'quickfixtextfunc' function returned a non-empty custom string
// for this entry, then use it.
if (qftf_str != NULL && *qftf_str != NUL) {
STRLCPY(IObuff, qftf_str, IOSIZE);
diff --git a/src/nvim/regexp_nfa.c b/src/nvim/regexp_nfa.c
index 3e7306bad3..cafffc0319 100644
--- a/src/nvim/regexp_nfa.c
+++ b/src/nvim/regexp_nfa.c
@@ -18,22 +18,20 @@
#include "nvim/garray.h"
#include "nvim/os/input.h"
-/*
- * Logging of NFA engine.
- *
- * The NFA engine can write four log files:
- * - Error log: Contains NFA engine's fatal errors.
- * - Dump log: Contains compiled NFA state machine's information.
- * - Run log: Contains information of matching procedure.
- * - Debug log: Contains detailed information of matching procedure. Can be
- * disabled by undefining NFA_REGEXP_DEBUG_LOG.
- * The first one can also be used without debug mode.
- * The last three are enabled when compiled as debug mode and individually
- * disabled by commenting them out.
- * The log files can get quite big!
- * Do disable all of this when compiling Vim for debugging, undefine REGEXP_DEBUG in
- * regexp.c
- */
+// Logging of NFA engine.
+//
+// The NFA engine can write four log files:
+// - Error log: Contains NFA engine's fatal errors.
+// - Dump log: Contains compiled NFA state machine's information.
+// - Run log: Contains information of matching procedure.
+// - Debug log: Contains detailed information of matching procedure. Can be
+// disabled by undefining NFA_REGEXP_DEBUG_LOG.
+// The first one can also be used without debug mode.
+// The last three are enabled when compiled as debug mode and individually
+// disabled by commenting them out.
+// The log files can get quite big!
+// To disable all of this when compiling Vim for debugging, undefine REGEXP_DEBUG in
+// regexp.c
#ifdef REGEXP_DEBUG
# define NFA_REGEXP_ERROR_LOG "nfa_regexp_error.log"
# define NFA_REGEXP_DUMP_LOG "nfa_regexp_dump.log"
@@ -2015,7 +2013,7 @@ static int nfa_regpiece(void)
// will emit NFA_STAR.
// Bail out if we can use the other engine, but only, when the
// pattern does not need the NFA engine like (e.g. [[:upper:]]\{2,\}
- // does not work with with characters > 8 bit with the BT engine)
+ // does not work with characters > 8 bit with the BT engine)
if ((nfa_re_flags & RE_AUTO)
&& (maxval > 500 || maxval > minval + 200)
&& (maxval != MAX_LIMIT && minval < 200)
@@ -2567,20 +2565,20 @@ static void nfa_print_state2(FILE *debugf, nfa_state_T *state, garray_T *indent)
ga_concat(indent, (char_u *)"| ");
else
ga_concat(indent, (char_u *)" ");
- ga_append(indent, '\0');
+ ga_append(indent, NUL);
nfa_print_state2(debugf, state->out, indent);
/* replace last part of indent for state->out1 */
indent->ga_len -= 3;
ga_concat(indent, (char_u *)" ");
- ga_append(indent, '\0');
+ ga_append(indent, NUL);
nfa_print_state2(debugf, state->out1, indent);
/* shrink indent */
indent->ga_len -= 3;
- ga_append(indent, '\0');
+ ga_append(indent, NUL);
}
/*
@@ -4369,7 +4367,7 @@ static regsubs_T *addstate_here(
// First add the state(s) at the end, so that we know how many there are.
// Pass the listidx as offset (avoids adding another argument to
- // addstate().
+ // addstate()).
regsubs_T *r = addstate(l, state, subs, pim, -listidx - ADDSTATE_HERE_OFFSET);
if (r == NULL) {
return NULL;
diff --git a/src/nvim/screen.c b/src/nvim/screen.c
index a938a3b062..538604cf79 100644
--- a/src/nvim/screen.c
+++ b/src/nvim/screen.c
@@ -3771,7 +3771,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc
// Make sure, the highlighting for the tab char will be
// correctly set further below (effectively reverts the
- // FIX_FOR_BOGSUCOLS macro.
+ // FIX_FOR_BOGSUCOLS macro).
if (n_extra == tab_len + vc_saved && wp->w_p_list
&& wp->w_p_lcs_chars.tab1) {
tab_len += vc_saved;
@@ -4130,7 +4130,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc
if (((wp->w_p_cuc
&& (int)wp->w_virtcol >= VCOL_HLC - eol_hl_off
&& (int)wp->w_virtcol <
- grid->Columns * (row - startrow + 1) + v
+ (long)grid->Columns * (row - startrow + 1) + v
&& lnum != wp->w_cursor.lnum)
|| draw_color_col || line_attr_lowprio || line_attr
|| diff_hlf != (hlf_T)0 || has_virttext)) {
@@ -4294,7 +4294,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc
// Store the character.
//
if (wp->w_p_rl && utf_char2cells(mb_c) > 1) {
- // A double-wide character is: put first halve in left cell.
+ // A double-wide character is: put first half in left cell.
off--;
col--;
}
@@ -4637,8 +4637,8 @@ void screen_adjust_grid(ScreenGrid **grid, int *row_off, int *col_off)
static bool use_cursor_line_sign(win_T *wp, linenr_T lnum)
{
return wp->w_p_cul
- && lnum == wp->w_cursor.lnum
- && (wp->w_p_culopt_flags & CULOPT_NBR);
+ && lnum == wp->w_cursor.lnum
+ && (wp->w_p_culopt_flags & CULOPT_NBR);
}
// Get information needed to display the sign in line 'lnum' in window 'wp'.
@@ -4834,9 +4834,9 @@ static void grid_put_linebuf(ScreenGrid *grid, int row, int coloff, int endcol,
end_dirty = col + char_cells;
// When writing a single-width character over a double-width
// character and at the end of the redrawn text, need to clear out
- // the right halve of the old character.
- // Also required when writing the right halve of a double-width
- // char over the left halve of an existing one
+ // the right half of the old character.
+ // Also required when writing the right half of a double-width
+ // char over the left half of an existing one
if (col + char_cells == endcol
&& ((char_cells == 1
&& grid_off2cells(grid, off_to, max_off_to) > 1)
@@ -5887,8 +5887,8 @@ void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col
}
off = grid->line_offset[row] + col;
- /* When drawing over the right halve of a double-wide char clear out the
- * left halve. Only needed in a terminal. */
+ // When drawing over the right half of a double-wide char clear out the
+ // left half. Only needed in a terminal.
if (grid != &default_grid && col == 0 && grid_invalid_row(grid, row)) {
// redraw the previous cell, make it empty
put_dirty_first = -1;
@@ -5933,6 +5933,8 @@ void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col
// Only 1 cell left, but character requires 2 cells:
// display a '>' in the last column to avoid wrapping. */
c = '>';
+ u8c = '>';
+ u8cc[0] = 0;
mbyte_cells = 1;
}
@@ -5948,9 +5950,9 @@ void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col
if (need_redraw) {
// When at the end of the text and overwriting a two-cell
// character with a one-cell character, need to clear the next
- // cell. Also when overwriting the left halve of a two-cell char
- // with the right halve of a two-cell char. Do this only once
- // (utf8_off2cells() may return 2 on the right halve).
+ // cell. Also when overwriting the left half of a two-cell char
+ // with the right half of a two-cell char. Do this only once
+ // (utf8_off2cells() may return 2 on the right half).
if (clear_next_cell) {
clear_next_cell = false;
} else if ((len < 0 ? ptr[mbyte_blen] == NUL
@@ -5963,6 +5965,13 @@ void grid_puts_len(ScreenGrid *grid, char_u *text, int textlen, int row, int col
clear_next_cell = true;
}
+ // When at the start of the text and overwriting the right half of a
+ // two-cell character in the same grid, truncate that into a '>'.
+ if (ptr == text && col > 0 && grid->chars[off][0] == 0) {
+ grid->chars[off - 1][0] = '>';
+ grid->chars[off - 1][1] = 0;
+ }
+
schar_copy(grid->chars[off], buf);
grid->attrs[off] = attr;
if (mbyte_cells == 2) {
@@ -6342,9 +6351,9 @@ void grid_fill(ScreenGrid *grid, int start_row, int end_row, int start_col, int
}
for (int row = start_row; row < end_row; row++) {
- // When drawing over the right halve of a double-wide char clear
- // out the left halve. When drawing over the left halve of a
- // double wide-char clear out the right halve. Only needed in a
+ // When drawing over the right half of a double-wide char clear
+ // out the left half. When drawing over the left half of a
+ // double wide-char clear out the right half. Only needed in a
// terminal.
if (start_col > 0 && grid_fix_col(grid, start_col, row) != start_col) {
grid_puts_len(grid, (char_u *)" ", 1, row, start_col - 1, 0);
@@ -6753,7 +6762,7 @@ void grid_clear_line(ScreenGrid *grid, unsigned off, int width, bool valid)
void grid_invalidate(ScreenGrid *grid)
{
- (void)memset(grid->attrs, -1, grid->Rows * grid->Columns * sizeof(sattr_T));
+ (void)memset(grid->attrs, -1, sizeof(sattr_T) * grid->Rows * grid->Columns);
}
bool grid_invalid_row(ScreenGrid *grid, int row)
diff --git a/src/nvim/sign.c b/src/nvim/sign.c
index 32be714184..a308df07d1 100644
--- a/src/nvim/sign.c
+++ b/src/nvim/sign.c
@@ -1740,7 +1740,7 @@ char_u *get_sign_name(expand_T *xp, int idx)
case EXP_SUBCMD:
return (char_u *)cmds[idx];
case EXP_DEFINE: {
- char *define_arg[] = { "icon=", "linehl=", "text=", "texthl=", "numhl=",
+ char *define_arg[] = { "culhl=", "icon=", "linehl=", "numhl=", "text=", "texthl=",
NULL };
return (char_u *)define_arg[idx];
}
@@ -1849,6 +1849,7 @@ void set_context_in_sign_cmd(expand_T *xp, char_u *arg)
case SIGNCMD_DEFINE:
if (STRNCMP(last, "texthl", 6) == 0
|| STRNCMP(last, "linehl", 6) == 0
+ || STRNCMP(last, "culhl", 5) == 0
|| STRNCMP(last, "numhl", 5) == 0) {
xp->xp_context = EXPAND_HIGHLIGHT;
} else if (STRNCMP(last, "icon", 4) == 0) {
diff --git a/src/nvim/spell.c b/src/nvim/spell.c
index bd31e98faa..1296d410f6 100644
--- a/src/nvim/spell.c
+++ b/src/nvim/spell.c
@@ -219,7 +219,7 @@ typedef struct {
#define SCORE_THRES3 100 // word count threshold for COMMON3
// When trying changed soundfold words it becomes slow when trying more than
-// two changes. With less then two changes it's slightly faster but we miss a
+// two changes. With less than two changes it's slightly faster but we miss a
// few good suggestions. In rare cases we need to try three of four changes.
#define SCORE_SFMAX1 200 // maximum score for first try
#define SCORE_SFMAX2 300 // maximum score for second try
@@ -1628,7 +1628,7 @@ size_t spell_move_to(win_T *wp, int dir, bool allwords, bool curline, hlf_T *att
}
// For spell checking: concatenate the start of the following line "line" into
-// "buf", blanking-out special characters. Copy less then "maxlen" bytes.
+// "buf", blanking-out special characters. Copy less than "maxlen" bytes.
// Keep the blanks at the start of the next line, this is used in win_line()
// to skip those bytes if the word was OK.
void spell_cat_line(char_u *buf, char_u *line, int maxlen)
@@ -4082,7 +4082,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
// char, e.g., "thes," -> "these".
p = fword + sp->ts_fidx;
MB_PTR_BACK(fword, p);
- if (!spell_iswordp(p, curwin)) {
+ if (!spell_iswordp(p, curwin) && *preword != NUL) {
p = preword + STRLEN(preword);
MB_PTR_BACK(preword, p);
if (spell_iswordp(p, curwin)) {
@@ -6106,7 +6106,7 @@ static void spell_soundfold_wsal(slang_T *slang, char_u *inword, char_u *res)
for (; ((ws = smp[n].sm_lead_w)[0] & 0xff) == (c & 0xff)
&& ws[0] != NUL; ++n) {
// Quickly skip entries that don't match the word. Most
- // entries are less then three chars, optimize for that.
+ // entries are less than three chars, optimize for that.
if (c != ws[0]) {
continue;
}
@@ -7057,7 +7057,7 @@ void spell_dump_compl(char_u *pat, int ic, Direction *dir, int dumpflags_arg)
arridx[depth] = idxs[n];
curi[depth] = 1;
- // Check if this characters matches with the pattern.
+ // Check if this character matches with the pattern.
// If not skip the whole tree below it.
// Always ignore case here, dump_word() will check
// proper case later. This isn't exactly right when
diff --git a/src/nvim/spellfile.c b/src/nvim/spellfile.c
index 42bb3c61a5..f6b95f37b1 100644
--- a/src/nvim/spellfile.c
+++ b/src/nvim/spellfile.c
@@ -4395,7 +4395,7 @@ static int write_vim_spell(spellinfo_T *spin, char_u *fname)
//
// The table with character flags and the table for case folding.
// This makes sure the same characters are recognized as word characters
- // when generating an when using a spell file.
+ // when generating and when using a spell file.
// Skip this for ASCII, the table may conflict with the one used for
// 'encoding'.
// Also skip this for an .add.spl file, the main spell file must contain
@@ -5122,7 +5122,7 @@ static int sug_filltable(spellinfo_T *spin, wordnode_T *node, int startwordnr, g
wordnr++;
// Remove extra NUL entries, we no longer need them. We don't
- // bother freeing the nodes, the won't be reused anyway.
+ // bother freeing the nodes, they won't be reused anyway.
while (p->wn_sibling != NULL && p->wn_sibling->wn_byte == NUL) {
p->wn_sibling = p->wn_sibling->wn_sibling;
}
diff --git a/src/nvim/state.c b/src/nvim/state.c
index 68bc76660d..1fe8bb671d 100644
--- a/src/nvim/state.c
+++ b/src/nvim/state.c
@@ -180,7 +180,7 @@ char *get_mode(void)
buf[1] = 'x';
}
}
- } else if (State & CMDLINE) {
+ } else if ((State & CMDLINE) || exmode_active) {
buf[0] = 'c';
if (exmode_active) {
buf[1] = 'v';
diff --git a/src/nvim/terminal.c b/src/nvim/terminal.c
index d97c24dcf7..a2d855244c 100644
--- a/src/nvim/terminal.c
+++ b/src/nvim/terminal.c
@@ -135,7 +135,6 @@ struct terminal {
int row, col;
bool visible;
} cursor;
- int pressed_button; // which mouse button is pressed
bool pending_resize; // pending width/height
bool color_set[16];
@@ -529,6 +528,10 @@ static int terminal_execute(VimState *state, int key)
do_cmdline(NULL, getcmdkeycmd, NULL, 0);
break;
+ case K_LUA:
+ map_execute_lua();
+ break;
+
case Ctrl_N:
if (s->got_bsl) {
return 0;
@@ -1209,21 +1212,12 @@ static VTermKey convert_key(int key, VTermModifier *statep)
}
}
-static void mouse_action(Terminal *term, int button, int row, int col, bool drag, VTermModifier mod)
+static void mouse_action(Terminal *term, int button, int row, int col, bool pressed,
+ VTermModifier mod)
{
- if (term->pressed_button && (term->pressed_button != button || !drag)) {
- // release the previous button
- vterm_mouse_button(term->vt, term->pressed_button, 0, mod);
- term->pressed_button = 0;
- }
-
- // move the mouse
vterm_mouse_move(term->vt, row, col, mod);
-
- if (!term->pressed_button) {
- // press the button if not already pressed
- vterm_mouse_button(term->vt, button, 1, mod);
- term->pressed_button = button;
+ if (button) {
+ vterm_mouse_button(term->vt, button, pressed, mod);
}
}
@@ -1242,32 +1236,35 @@ static bool send_mouse_event(Terminal *term, int c)
// event in the terminal window and mouse events was enabled by the
// program. translate and forward the event
int button;
- bool drag = false;
+ bool pressed = false;
switch (c) {
case K_LEFTDRAG:
- drag = true; FALLTHROUGH;
case K_LEFTMOUSE:
+ pressed = true; FALLTHROUGH;
+ case K_LEFTRELEASE:
button = 1; break;
case K_MOUSEMOVE:
- drag = true; button = 0; break;
+ button = 0; break;
case K_MIDDLEDRAG:
- drag = true; FALLTHROUGH;
case K_MIDDLEMOUSE:
+ pressed = true; FALLTHROUGH;
+ case K_MIDDLERELEASE:
button = 2; break;
case K_RIGHTDRAG:
- drag = true; FALLTHROUGH;
case K_RIGHTMOUSE:
+ pressed = true; FALLTHROUGH;
+ case K_RIGHTRELEASE:
button = 3; break;
case K_MOUSEDOWN:
- button = 4; break;
+ pressed = true; button = 4; break;
case K_MOUSEUP:
- button = 5; break;
+ pressed = true; button = 5; break;
default:
return false;
}
- mouse_action(term, button, row, col - offset, drag, 0);
+ mouse_action(term, button, row, col - offset, pressed, 0);
size_t len = vterm_output_read(term->vt, term->textbuf,
sizeof(term->textbuf));
terminal_send(term, term->textbuf, len);
@@ -1295,8 +1292,14 @@ static bool send_mouse_event(Terminal *term, int c)
return mouse_win == curwin;
}
+ // ignore left release action if it was not proccessed above
+ // to prevent leaving Terminal mode after entering to it using a mouse
+ if (c == K_LEFTRELEASE && mouse_win->w_buffer->terminal == term) {
+ return false;
+ }
+
end:
- ins_char_typebuf(c);
+ ins_char_typebuf(c, mod_mask);
return true;
}
diff --git a/src/nvim/testdir/runnvim.sh b/src/nvim/testdir/runnvim.sh
index 25cb8437b4..fdd3f3144b 100755
--- a/src/nvim/testdir/runnvim.sh
+++ b/src/nvim/testdir/runnvim.sh
@@ -66,7 +66,7 @@ main() {(
fi
fi
if test "$FAILED" = 1 ; then
- ci_fold start "$NVIM_TEST_CURRENT_SUITE/$test_name"
+ ci_fold start "$test_name"
fi
valgrind_check .
if test -n "$LOG_DIR" ; then
@@ -78,7 +78,7 @@ main() {(
fi
rm -f "$tlog"
if test "$FAILED" = 1 ; then
- ci_fold end "$NVIM_TEST_CURRENT_SUITE/$test_name"
+ ci_fold end ""
fi
if test "$FAILED" = 1 ; then
echo "Test $test_name failed, see output above and summary for more details" >> test.log
diff --git a/src/nvim/testdir/runtest.vim b/src/nvim/testdir/runtest.vim
index ab047fd2a8..b0d872e392 100644
--- a/src/nvim/testdir/runtest.vim
+++ b/src/nvim/testdir/runtest.vim
@@ -64,6 +64,9 @@ if has('reltime')
let s:start_time = reltime()
endif
+" Always use forward slashes.
+set shellslash
+
" Common with all tests on all systems.
source setup.vim
@@ -104,9 +107,6 @@ lang mess C
" Nvim: append runtime from build dir, which contains the generated doc/tags.
let &runtimepath .= ','.expand($BUILD_DIR).'/runtime/'
-" Always use forward slashes.
-set shellslash
-
let s:t_bold = &t_md
let s:t_normal = &t_me
if has('win32')
diff --git a/src/nvim/testdir/setup.vim b/src/nvim/testdir/setup.vim
index b3df8c63e6..fdae0697c3 100644
--- a/src/nvim/testdir/setup.vim
+++ b/src/nvim/testdir/setup.vim
@@ -13,7 +13,7 @@ set fillchars=vert:\|,fold:-
set laststatus=1
set listchars=eol:$
set joinspaces
-set nohidden smarttab noautoindent noautoread complete-=i noruler noshowcmd
+set nohidden nosmarttab noautoindent noautoread complete-=i noruler noshowcmd
set nrformats+=octal
set shortmess-=F
set sidescroll=0
diff --git a/src/nvim/testdir/test_alot.vim b/src/nvim/testdir/test_alot.vim
index cc767a9bcf..c0ac4393c4 100644
--- a/src/nvim/testdir/test_alot.vim
+++ b/src/nvim/testdir/test_alot.vim
@@ -27,6 +27,7 @@ source test_join.vim
source test_jumps.vim
source test_fileformat.vim
source test_filetype.vim
+source test_filetype_lua.vim
source test_lambda.vim
source test_menu.vim
source test_messages.vim
diff --git a/src/nvim/testdir/test_autocmd.vim b/src/nvim/testdir/test_autocmd.vim
index 4e1a24af61..45285b69a1 100644
--- a/src/nvim/testdir/test_autocmd.vim
+++ b/src/nvim/testdir/test_autocmd.vim
@@ -2380,95 +2380,7 @@ func Test_autocmd_was_using_freed_memory()
pclose
endfunc
-func Test_FileChangedShell_reload()
- if !has('unix')
- return
- endif
- augroup testreload
- au FileChangedShell Xchanged let g:reason = v:fcs_reason | let v:fcs_choice = 'reload'
- augroup END
- new Xchanged
- call setline(1, 'reload this')
- write
- " Need to wait until the timestamp would change by at least a second.
- sleep 2
- silent !echo 'extra line' >>Xchanged
- checktime
- call assert_equal('changed', g:reason)
- call assert_equal(2, line('$'))
- call assert_equal('extra line', getline(2))
-
- " Only triggers once
- let g:reason = ''
- checktime
- call assert_equal('', g:reason)
-
- " When deleted buffer is not reloaded
- silent !rm Xchanged
- let g:reason = ''
- checktime
- call assert_equal('deleted', g:reason)
- call assert_equal(2, line('$'))
- call assert_equal('extra line', getline(2))
-
- " When recreated buffer is reloaded
- call setline(1, 'buffer is changed')
- silent !echo 'new line' >>Xchanged
- let g:reason = ''
- checktime
- call assert_equal('conflict', g:reason)
- call assert_equal(1, line('$'))
- call assert_equal('new line', getline(1))
-
- " Only mode changed
- silent !chmod +x Xchanged
- let g:reason = ''
- checktime
- call assert_equal('mode', g:reason)
- call assert_equal(1, line('$'))
- call assert_equal('new line', getline(1))
-
- " Only time changed
- sleep 2
- silent !touch Xchanged
- let g:reason = ''
- checktime
- call assert_equal('time', g:reason)
- call assert_equal(1, line('$'))
- call assert_equal('new line', getline(1))
-
- if has('persistent_undo')
- " With an undo file the reload can be undone and a change before the
- " reload.
- set undofile
- call setline(2, 'before write')
- write
- call setline(2, 'after write')
- sleep 2
- silent !echo 'different line' >>Xchanged
- let g:reason = ''
- checktime
- call assert_equal('conflict', g:reason)
- call assert_equal(3, line('$'))
- call assert_equal('before write', getline(2))
- call assert_equal('different line', getline(3))
- " undo the reload
- undo
- call assert_equal(2, line('$'))
- call assert_equal('after write', getline(2))
- " undo the change before reload
- undo
- call assert_equal(2, line('$'))
- call assert_equal('before write', getline(2))
-
- set noundofile
- endif
-
-
- au! testreload
- bwipe!
- call delete('Xchanged')
-endfunc
+" FileChangedShell tested in test_filechanged.vim
func LogACmd()
call add(g:logged, line('$'))
diff --git a/src/nvim/testdir/test_blob.vim b/src/nvim/testdir/test_blob.vim
index 20758b0c0a..af42b3857d 100644
--- a/src/nvim/testdir/test_blob.vim
+++ b/src/nvim/testdir/test_blob.vim
@@ -346,4 +346,12 @@ func Test_blob_sort()
endif
endfunc
+" The following used to cause an out-of-bounds memory access
+func Test_blob2string()
+ let v = '0z' .. repeat('01010101.', 444)
+ let v ..= '01'
+ exe 'let b = ' .. v
+ call assert_equal(v, string(b))
+endfunc
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim
index 49a5386337..1672b0e840 100644
--- a/src/nvim/testdir/test_cmdline.vim
+++ b/src/nvim/testdir/test_cmdline.vim
@@ -467,6 +467,43 @@ func Test_getcompletion()
call assert_fails('call getcompletion("abc", [])', 'E475:')
endfunc
+func Test_fullcommand()
+ let tests = {
+ \ '': '',
+ \ ':': '',
+ \ ':::': '',
+ \ ':::5': '',
+ \ 'not_a_cmd': '',
+ \ 'Check': '',
+ \ 'syntax': 'syntax',
+ \ ':syntax': 'syntax',
+ \ '::::syntax': 'syntax',
+ \ 'sy': 'syntax',
+ \ 'syn': 'syntax',
+ \ 'synt': 'syntax',
+ \ ':sy': 'syntax',
+ \ '::::sy': 'syntax',
+ \ 'match': 'match',
+ \ '2match': 'match',
+ \ '3match': 'match',
+ \ 'aboveleft': 'aboveleft',
+ \ 'abo': 'aboveleft',
+ \ 's': 'substitute',
+ \ '5s': 'substitute',
+ \ ':5s': 'substitute',
+ \ "'<,'>s": 'substitute',
+ \ ":'<,'>s": 'substitute',
+ \ 'CheckUni': 'CheckUnix',
+ \ 'CheckUnix': 'CheckUnix',
+ \ }
+
+ for [in, want] in items(tests)
+ call assert_equal(want, fullcommand(in))
+ endfor
+
+ call assert_equal('syntax', 'syn'->fullcommand())
+endfunc
+
func Test_shellcmd_completion()
let save_path = $PATH
diff --git a/src/nvim/testdir/test_compiler.vim b/src/nvim/testdir/test_compiler.vim
index aaa2301bca..c0c572ce65 100644
--- a/src/nvim/testdir/test_compiler.vim
+++ b/src/nvim/testdir/test_compiler.vim
@@ -19,6 +19,9 @@ func Test_compiler()
call assert_equal('perl', b:current_compiler)
call assert_fails('let g:current_compiler', 'E121:')
+ let verbose_efm = execute('verbose set efm')
+ call assert_match('Last set from .*[/\\]compiler[/\\]perl.vim ', verbose_efm)
+
call setline(1, ['#!/usr/bin/perl -w', 'use strict;', 'my $foo=1'])
w!
call feedkeys(":make\<CR>\<CR>", 'tx')
diff --git a/src/nvim/testdir/test_display.vim b/src/nvim/testdir/test_display.vim
index 12327f34d6..c2a9683f7c 100644
--- a/src/nvim/testdir/test_display.vim
+++ b/src/nvim/testdir/test_display.vim
@@ -263,6 +263,31 @@ func Test_display_scroll_at_topline()
call StopVimInTerminal(buf)
endfunc
+" Test for 'eob' (EndOfBuffer) item in 'fillchars'
+func Test_eob_fillchars()
+ " default value (skipped)
+ " call assert_match('eob:\~', &fillchars)
+ " invalid values
+ call assert_fails(':set fillchars=eob:', 'E474:')
+ call assert_fails(':set fillchars=eob:xy', 'E474:')
+ call assert_fails(':set fillchars=eob:\255', 'E474:')
+ call assert_fails(':set fillchars=eob:<ff>', 'E474:')
+ call assert_fails(":set fillchars=eob:\x01", 'E474:')
+ call assert_fails(':set fillchars=eob:\\x01', 'E474:')
+ " default is ~
+ new
+ redraw
+ call assert_equal('~', Screenline(2))
+ set fillchars=eob:+
+ redraw
+ call assert_equal('+', Screenline(2))
+ set fillchars=eob:\
+ redraw
+ call assert_equal(' ', nr2char(screenchar(2, 1)))
+ set fillchars&
+ close
+endfunc
+
func Test_display_linebreak_breakat()
new
vert resize 25
diff --git a/src/nvim/testdir/test_edit.vim b/src/nvim/testdir/test_edit.vim
index 37786f3ca0..fc4e80f0d6 100644
--- a/src/nvim/testdir/test_edit.vim
+++ b/src/nvim/testdir/test_edit.vim
@@ -1294,6 +1294,7 @@ func Test_edit_forbidden()
call assert_fails(':Sandbox', 'E48:')
delcom Sandbox
call assert_equal(['a'], getline(1,'$'))
+
" 2) edit with textlock set
fu! DoIt()
call feedkeys("i\<del>\<esc>", 'tnix')
@@ -1313,6 +1314,7 @@ func Test_edit_forbidden()
catch /^Vim\%((\a\+)\)\=:E117/ " catch E117: unknown function
endtry
au! InsertCharPre
+
" 3) edit when completion is shown
fun! Complete(findstart, base)
if a:findstart
@@ -1330,6 +1332,7 @@ func Test_edit_forbidden()
endtry
delfu Complete
set completefunc=
+
if has("rightleft") && exists("+fkmap")
" 4) 'R' when 'fkmap' and 'revins' is set.
set revins fkmap
diff --git a/src/nvim/testdir/test_ex_mode.vim b/src/nvim/testdir/test_ex_mode.vim
index 1c645ad0f8..92e0559618 100644
--- a/src/nvim/testdir/test_ex_mode.vim
+++ b/src/nvim/testdir/test_ex_mode.vim
@@ -85,7 +85,7 @@ endfunc
func Test_ex_mode_count_overflow()
" this used to cause a crash
let lines =<< trim END
- call feedkeys("\<Esc>Q\<CR>")
+ call feedkeys("\<Esc>gQ\<CR>")
v9|9silent! vi|333333233333y32333333%O
call writefile(['done'], 'Xdidexmode')
qall!
diff --git a/src/nvim/testdir/test_excmd.vim b/src/nvim/testdir/test_excmd.vim
index 2d01cbba83..1c053c824f 100644
--- a/src/nvim/testdir/test_excmd.vim
+++ b/src/nvim/testdir/test_excmd.vim
@@ -1,6 +1,8 @@
" Tests for various Ex commands.
source check.vim
+source shared.vim
+source term_util.vim
func Test_ex_delete()
new
@@ -122,6 +124,27 @@ func Test_append_cmd()
close!
endfunc
+func Test_append_cmd_empty_buf()
+ CheckRunVimInTerminal
+ let lines =<< trim END
+ func Timer(timer)
+ append
+ aaaaa
+ bbbbb
+ .
+ endfunc
+ call timer_start(10, 'Timer')
+ END
+ call writefile(lines, 'Xtest_append_cmd_empty_buf')
+ let buf = RunVimInTerminal('-S Xtest_append_cmd_empty_buf', {'rows': 6})
+ call WaitForAssert({-> assert_equal('bbbbb', term_getline(buf, 2))})
+ call WaitForAssert({-> assert_equal('aaaaa', term_getline(buf, 1))})
+
+ " clean up
+ call StopVimInTerminal(buf)
+ call delete('Xtest_append_cmd_empty_buf')
+endfunc
+
" Test for the :insert command
func Test_insert_cmd()
set noautoindent " test assumes noautoindent, but it's on by default in Nvim
@@ -151,6 +174,27 @@ func Test_insert_cmd()
close!
endfunc
+func Test_insert_cmd_empty_buf()
+ CheckRunVimInTerminal
+ let lines =<< trim END
+ func Timer(timer)
+ insert
+ aaaaa
+ bbbbb
+ .
+ endfunc
+ call timer_start(10, 'Timer')
+ END
+ call writefile(lines, 'Xtest_insert_cmd_empty_buf')
+ let buf = RunVimInTerminal('-S Xtest_insert_cmd_empty_buf', {'rows': 6})
+ call WaitForAssert({-> assert_equal('bbbbb', term_getline(buf, 2))})
+ call WaitForAssert({-> assert_equal('aaaaa', term_getline(buf, 1))})
+
+ " clean up
+ call StopVimInTerminal(buf)
+ call delete('Xtest_insert_cmd_empty_buf')
+endfunc
+
" Test for the :change command
func Test_change_cmd()
set noautoindent " test assumes noautoindent, but it's on by default in Nvim
diff --git a/src/nvim/testdir/test_filechanged.vim b/src/nvim/testdir/test_filechanged.vim
new file mode 100644
index 0000000000..b95cd5faf8
--- /dev/null
+++ b/src/nvim/testdir/test_filechanged.vim
@@ -0,0 +1,149 @@
+" Tests for when a file was changed outside of Vim.
+
+func Test_FileChangedShell_reload()
+ if !has('unix')
+ return
+ endif
+ augroup testreload
+ au FileChangedShell Xchanged_r let g:reason = v:fcs_reason | let v:fcs_choice = 'reload'
+ augroup END
+ new Xchanged_r
+ call setline(1, 'reload this')
+ write
+ " Need to wait until the timestamp would change by at least a second.
+ sleep 2
+ silent !echo 'extra line' >>Xchanged_r
+ checktime
+ call assert_equal('changed', g:reason)
+ call assert_equal(2, line('$'))
+ call assert_equal('extra line', getline(2))
+
+ " Only triggers once
+ let g:reason = ''
+ checktime
+ call assert_equal('', g:reason)
+
+ " When deleted buffer is not reloaded
+ silent !rm Xchanged_r
+ let g:reason = ''
+ checktime
+ call assert_equal('deleted', g:reason)
+ call assert_equal(2, line('$'))
+ call assert_equal('extra line', getline(2))
+
+ " When recreated buffer is reloaded
+ call setline(1, 'buffer is changed')
+ silent !echo 'new line' >>Xchanged_r
+ let g:reason = ''
+ checktime
+ call assert_equal('conflict', g:reason)
+ call assert_equal(1, line('$'))
+ call assert_equal('new line', getline(1))
+
+ " Only mode changed
+ silent !chmod +x Xchanged_r
+ let g:reason = ''
+ checktime
+ call assert_equal('mode', g:reason)
+ call assert_equal(1, line('$'))
+ call assert_equal('new line', getline(1))
+
+ " Only time changed
+ sleep 2
+ silent !touch Xchanged_r
+ let g:reason = ''
+ checktime
+ call assert_equal('time', g:reason)
+ call assert_equal(1, line('$'))
+ call assert_equal('new line', getline(1))
+
+ if has('persistent_undo')
+ " With an undo file the reload can be undone and a change before the
+ " reload.
+ set undofile
+ call setline(2, 'before write')
+ write
+ call setline(2, 'after write')
+ sleep 2
+ silent !echo 'different line' >>Xchanged_r
+ let g:reason = ''
+ checktime
+ call assert_equal('conflict', g:reason)
+ call assert_equal(3, line('$'))
+ call assert_equal('before write', getline(2))
+ call assert_equal('different line', getline(3))
+ " undo the reload
+ undo
+ call assert_equal(2, line('$'))
+ call assert_equal('after write', getline(2))
+ " undo the change before reload
+ undo
+ call assert_equal(2, line('$'))
+ call assert_equal('before write', getline(2))
+
+ set noundofile
+ endif
+
+ au! testreload
+ bwipe!
+ call delete(undofile('Xchanged_r'))
+ call delete('Xchanged_r')
+endfunc
+
+func Test_file_changed_dialog()
+ throw 'skipped: TODO: '
+ if !has('unix') || has('gui_running')
+ return
+ endif
+ au! FileChangedShell
+
+ new Xchanged_d
+ call setline(1, 'reload this')
+ write
+ " Need to wait until the timestamp would change by at least a second.
+ sleep 2
+ silent !echo 'extra line' >>Xchanged_d
+ call feedkeys('L', 'L')
+ checktime
+ call assert_match('W11:', v:warningmsg)
+ call assert_equal(2, line('$'))
+ call assert_equal('reload this', getline(1))
+ call assert_equal('extra line', getline(2))
+
+ " delete buffer, only shows an error, no prompt
+ silent !rm Xchanged_d
+ checktime
+ call assert_match('E211:', v:warningmsg)
+ call assert_equal(2, line('$'))
+ call assert_equal('extra line', getline(2))
+ let v:warningmsg = 'empty'
+
+ " change buffer, recreate the file and reload
+ call setline(1, 'buffer is changed')
+ silent !echo 'new line' >Xchanged_d
+ call feedkeys('L', 'L')
+ checktime
+ call assert_match('W12:', v:warningmsg)
+ call assert_equal(1, line('$'))
+ call assert_equal('new line', getline(1))
+
+ " Only mode changed, reload
+ silent !chmod +x Xchanged_d
+ call feedkeys('L', 'L')
+ checktime
+ call assert_match('W16:', v:warningmsg)
+ call assert_equal(1, line('$'))
+ call assert_equal('new line', getline(1))
+
+ " Only time changed, no prompt
+ sleep 2
+ silent !touch Xchanged_d
+ let v:warningmsg = ''
+ checktime
+ call assert_equal('', v:warningmsg)
+ call assert_equal(1, line('$'))
+ call assert_equal('new line', getline(1))
+
+ bwipe!
+ call delete('Xchanged_d')
+endfunc
diff --git a/src/nvim/testdir/test_fileformat.vim b/src/nvim/testdir/test_fileformat.vim
index 465613f1cf..81127ea59a 100644
--- a/src/nvim/testdir/test_fileformat.vim
+++ b/src/nvim/testdir/test_fileformat.vim
@@ -1,5 +1,4 @@
" Test behavior of fileformat after bwipeout of last buffer
-
func Test_fileformat_after_bw()
bwipeout
set fileformat&
@@ -32,6 +31,251 @@ func Test_fileformat_autocommand()
bw!
endfunc
+" Convert the contents of a file into a literal string
+func s:file2str(fname)
+ let b = readfile(a:fname, 'B')
+ let s = ''
+ for c in b
+ let s .= nr2char(c)
+ endfor
+ return s
+endfunc
+
+" Concatenate the contents of files 'f1' and 'f2' and create 'destfile'
+func s:concat_files(f1, f2, destfile)
+ let b1 = readfile(a:f1, 'B')
+ let b2 = readfile(a:f2, 'B')
+ let b3 = b1 + b2
+ call writefile(b3, a:destfile)
+endfun
+
+" Test for a lot of variations of the 'fileformats' option
+func Test_fileformats()
+ " create three test files, one in each format
+ call writefile(['unix', 'unix'], 'XXUnix')
+ call writefile(["dos\r", "dos\r"], 'XXDos')
+ call writefile(["mac\rmac\r"], 'XXMac', 'b')
+ " create a file with no End Of Line
+ call writefile(["noeol"], 'XXEol', 'b')
+ " create mixed format files
+ call s:concat_files('XXUnix', 'XXDos', 'XXUxDs')
+ call s:concat_files('XXUnix', 'XXMac', 'XXUxMac')
+ call s:concat_files('XXDos', 'XXMac', 'XXDosMac')
+ call s:concat_files('XXMac', 'XXEol', 'XXMacEol')
+ call s:concat_files('XXUxDs', 'XXMac', 'XXUxDsMc')
+
+ new
+
+ " Test 1: try reading and writing with 'fileformats' empty
+ set fileformats=
+
+ " try with 'fileformat' set to 'unix'
+ set fileformat=unix
+ e! XXUnix
+ w! Xtest
+ call assert_equal("unix\nunix\n", s:file2str('Xtest'))
+ e! XXDos
+ w! Xtest
+ call assert_equal("dos\r\ndos\r\n", s:file2str('Xtest'))
+ e! XXMac
+ w! Xtest
+ call assert_equal("mac\rmac\r\n", s:file2str('Xtest'))
+ bwipe XXUnix XXDos XXMac
+
+ " try with 'fileformat' set to 'dos'
+ set fileformat=dos
+ e! XXUnix
+ w! Xtest
+ call assert_equal("unix\r\nunix\r\n", s:file2str('Xtest'))
+ e! XXDos
+ w! Xtest
+ call assert_equal("dos\r\ndos\r\n", s:file2str('Xtest'))
+ e! XXMac
+ w! Xtest
+ call assert_equal("mac\rmac\r\r\n", s:file2str('Xtest'))
+ bwipe XXUnix XXDos XXMac
+
+ " try with 'fileformat' set to 'mac'
+ set fileformat=mac
+ e! XXUnix
+ w! Xtest
+ call assert_equal("unix\nunix\n\r", s:file2str('Xtest'))
+ e! XXDos
+ w! Xtest
+ call assert_equal("dos\r\ndos\r\n\r", s:file2str('Xtest'))
+ e! XXMac
+ w! Xtest
+ call assert_equal("mac\rmac\r", s:file2str('Xtest'))
+ bwipe XXUnix XXDos XXMac
+
+ " Test 2: try reading and writing with 'fileformats' set to one format
+
+ " try with 'fileformats' set to 'unix'
+ set fileformats=unix
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ " try with 'fileformats' set to 'dos'
+ set fileformats=dos
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\r\nunix\r\ndos\r\ndos\r\nmac\rmac\r\r\n",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ " try with 'fileformats' set to 'mac'
+ set fileformats=mac
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ " Test 3: try reading and writing with 'fileformats' set to two formats
+
+ " try with 'fileformats' set to 'unix,dos'
+ set fileformats=unix,dos
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ e! XXUxMac
+ w! Xtest
+ call assert_equal("unix\nunix\nmac\rmac\r\n", s:file2str('Xtest'))
+ bwipe XXUxMac
+
+ e! XXDosMac
+ w! Xtest
+ call assert_equal("dos\r\ndos\r\nmac\rmac\r\r\n", s:file2str('Xtest'))
+ bwipe XXDosMac
+
+ " try with 'fileformats' set to 'unix,mac'
+ set fileformats=unix,mac
+ e! XXUxDs
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\n", s:file2str('Xtest'))
+ bwipe XXUxDs
+
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ e! XXDosMac
+ w! Xtest
+ call assert_equal("dos\r\ndos\r\nmac\rmac\r", s:file2str('Xtest'))
+ bwipe XXDosMac
+
+ e! XXEol
+ exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
+ w! Xtest
+ call assert_equal("unix,mac:unix\nnoeol\n", s:file2str('Xtest'))
+ bwipe! XXEol
+
+ " try with 'fileformats' set to 'dos,mac'
+ set fileformats=dos,mac
+ e! XXUxDs
+ w! Xtest
+ call assert_equal("unix\r\nunix\r\ndos\r\ndos\r\n", s:file2str('Xtest'))
+ bwipe XXUxDs
+
+ e! XXUxMac
+ exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
+ w! Xtest
+ call assert_equal("dos,mac:dos\r\nunix\r\nunix\r\nmac\rmac\r\r\n",
+ \ s:file2str('Xtest'))
+ bwipe! XXUxMac
+
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\r\nunix\r\ndos\r\ndos\r\nmac\rmac\r\r\n",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ e! XXMacEol
+ exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
+ w! Xtest
+ call assert_equal("dos,mac:mac\rmac\rmac\rnoeol\r", s:file2str('Xtest'))
+ bwipe! XXMacEol
+
+ " Test 4: try reading and writing with 'fileformats' set to three formats
+ set fileformats=unix,dos,mac
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ e! XXEol
+ exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
+ w! Xtest
+ call assert_equal("unix,dos,mac:unix\nnoeol\n", s:file2str('Xtest'))
+ bwipe! XXEol
+
+ set fileformats=mac,dos,unix
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r\n",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ e! XXEol
+ exe "normal ggO\<C-R>=&ffs\<CR>:\<C-R>=&ff\<CR>"
+ w! Xtest
+ call assert_equal("mac,dos,unix:mac\rnoeol\r", s:file2str('Xtest'))
+ bwipe! XXEol
+
+ " Test 5: try with 'binary' set
+ set fileformats=mac,unix,dos
+ set binary
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ set fileformats=mac
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ set fileformats=dos
+ e! XXUxDsMc
+ w! Xtest
+ call assert_equal("unix\nunix\ndos\r\ndos\r\nmac\rmac\r",
+ \ s:file2str('Xtest'))
+ bwipe XXUxDsMc
+
+ e! XXUnix
+ w! Xtest
+ call assert_equal("unix\nunix\n", s:file2str('Xtest'))
+ bwipe! XXUnix
+
+ set nobinary ff& ffs&
+
+ " cleanup
+ only
+ %bwipe!
+ call delete('XXUnix')
+ call delete('XXDos')
+ call delete('XXMac')
+ call delete('XXEol')
+ call delete('XXUxDs')
+ call delete('XXUxMac')
+ call delete('XXDosMac')
+ call delete('XXMacEol')
+ call delete('XXUxDsMc')
+ call delete('Xtest')
+endfunc
+
" Test for changing the fileformat using ++read
func Test_fileformat_plusplus_read()
new
diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim
index 7ed9c68c96..8930d62fd3 100644
--- a/src/nvim/testdir/test_filetype.vim
+++ b/src/nvim/testdir/test_filetype.vim
@@ -76,6 +76,7 @@ let s:filename_checks = {
\ 'ave': ['file.ave'],
\ 'awk': ['file.awk', 'file.gawk'],
\ 'b': ['file.mch', 'file.ref', 'file.imp'],
+ \ 'basic': ['file.bas', 'file.bi', 'file.bm'],
\ 'bzl': ['file.bazel', 'file.bzl', 'WORKSPACE'],
\ 'bc': ['file.bc'],
\ 'bdf': ['file.bdf'],
@@ -146,7 +147,7 @@ let s:filename_checks = {
\ 'diff': ['file.diff', 'file.rej'],
\ 'dircolors': ['.dir_colors', '.dircolors', '/etc/DIR_COLORS', 'any/etc/DIR_COLORS'],
\ 'dnsmasq': ['/etc/dnsmasq.conf', '/etc/dnsmasq.d/file', 'any/etc/dnsmasq.conf', 'any/etc/dnsmasq.d/file'],
- \ 'dockerfile': ['Containerfile', 'Dockerfile', 'file.Dockerfile'],
+ \ 'dockerfile': ['Containerfile', 'Dockerfile', 'file.Dockerfile', 'Dockerfile.debian', 'Containerfile.something'],
\ 'dosbatch': ['file.bat', 'file.sys'],
\ 'dosini': ['.editorconfig', '/etc/pacman.conf', '/etc/yum.conf', 'file.ini', 'npmrc', '.npmrc', 'php.ini', 'php.ini-5', 'php.ini-file', '/etc/yum.repos.d/file', 'any/etc/pacman.conf', 'any/etc/yum.conf', 'any/etc/yum.repos.d/file', 'file.wrap'],
\ 'dot': ['file.dot', 'file.gv'],
@@ -186,7 +187,7 @@ let s:filename_checks = {
\ 'fortran': ['file.f', 'file.for', 'file.fortran', 'file.fpp', 'file.ftn', 'file.f77', 'file.f90', 'file.f95', 'file.f03', 'file.f08'],
\ 'fpcmake': ['file.fpc'],
\ 'framescript': ['file.fsl'],
- \ 'freebasic': ['file.fb', 'file.bi'],
+ \ 'freebasic': ['file.fb'],
\ 'fsharp': ['file.fs', 'file.fsi', 'file.fsx'],
\ 'fstab': ['fstab', 'mtab'],
\ 'fvwm': ['/.fvwm/file', 'any/.fvwm/file'],
@@ -195,15 +196,16 @@ let s:filename_checks = {
\ 'gedcom': ['file.ged', 'lltxxxxx.txt', '/tmp/lltmp', '/tmp/lltmp-file', 'any/tmp/lltmp', 'any/tmp/lltmp-file'],
\ 'gemtext': ['file.gmi', 'file.gemini'],
\ 'gift': ['file.gift'],
- \ 'gitcommit': ['COMMIT_EDITMSG', 'MERGE_MSG', 'TAG_EDITMSG'],
- \ 'gitconfig': ['file.git/config', '.gitconfig', '.gitmodules', 'file.git/modules//config', '/.config/git/config', '/etc/gitconfig', '/etc/gitconfig.d/file', '/.gitconfig.d/file', 'any/.config/git/config', 'any/.gitconfig.d/file', 'some.git/config', 'some.git/modules/any/config'],
+ \ 'gitcommit': ['COMMIT_EDITMSG', 'MERGE_MSG', 'TAG_EDITMSG', 'NOTES_EDITMSG', 'EDIT_DESCRIPTION'],
+ \ 'gitconfig': ['file.git/config', 'file.git/config.worktree', 'file.git/worktrees/x/config.worktree', '.gitconfig', '.gitmodules', 'file.git/modules//config', '/.config/git/config', '/etc/gitconfig', '/usr/local/etc/gitconfig', '/etc/gitconfig.d/file', '/.gitconfig.d/file', 'any/.config/git/config', 'any/.gitconfig.d/file', 'some.git/config', 'some.git/modules/any/config'],
\ 'gitolite': ['gitolite.conf', '/gitolite-admin/conf/file', 'any/gitolite-admin/conf/file'],
\ 'gitrebase': ['git-rebase-todo'],
\ 'gitsendemail': ['.gitsendemail.msg.xxxxxx'],
\ 'gkrellmrc': ['gkrellmrc', 'gkrellmrc_x'],
\ 'gnash': ['gnashrc', '.gnashrc', 'gnashpluginrc', '.gnashpluginrc'],
- \ 'gnuplot': ['file.gpi'],
+ \ 'gnuplot': ['file.gpi', '.gnuplot'],
\ 'go': ['file.go'],
+ \ 'gomod': ['go.mod'],
\ 'gp': ['file.gp', '.gprc'],
\ 'gpg': ['/.gnupg/options', '/.gnupg/gpg.conf', '/usr/any/gnupg/options.skel', 'any/.gnupg/gpg.conf', 'any/.gnupg/options', 'any/usr/any/gnupg/options.skel'],
\ 'grads': ['file.gs'],
@@ -262,7 +264,8 @@ let s:filename_checks = {
\ 'jgraph': ['file.jgr'],
\ 'jovial': ['file.jov', 'file.j73', 'file.jovial'],
\ 'jproperties': ['file.properties', 'file.properties_xx', 'file.properties_xx_xx', 'some.properties_xx_xx_file'],
- \ 'json': ['file.json', 'file.jsonp', 'file.json-patch', 'file.webmanifest', 'Pipfile.lock', 'file.ipynb', '.babelrc', '.eslintrc', '.prettierrc', '.firebaserc'],
+ \ 'json': ['file.json', 'file.jsonp', 'file.json-patch', 'file.webmanifest', 'Pipfile.lock', 'file.ipynb', '.babelrc', '.eslintrc', '.prettierrc', '.firebaserc', 'file.slnf'],
+ \ 'json5': ['file.json5'],
\ 'jsonc': ['file.jsonc'],
\ 'jsp': ['file.jsp'],
\ 'julia': ['file.jl'],
@@ -285,7 +288,7 @@ let s:filename_checks = {
\ 'lilo': ['lilo.conf', 'lilo.conf-file'],
\ 'limits': ['/etc/limits', '/etc/anylimits.conf', '/etc/anylimits.d/file.conf', '/etc/limits.conf', '/etc/limits.d/file.conf', '/etc/some-limits.conf', '/etc/some-limits.d/file.conf', 'any/etc/limits', 'any/etc/limits.conf', 'any/etc/limits.d/file.conf', 'any/etc/some-limits.conf', 'any/etc/some-limits.d/file.conf'],
\ 'liquid': ['file.liquid'],
- \ 'lisp': ['file.lsp', 'file.lisp', 'file.el', 'file.cl', '.emacs', '.sawfishrc', 'sbclrc', '.sbclrc'],
+ \ 'lisp': ['file.lsp', 'file.lisp', 'file.asd', 'file.el', 'file.cl', '.emacs', '.sawfishrc', 'sbclrc', '.sbclrc'],
\ 'lite': ['file.lite', 'file.lt'],
\ 'litestep': ['/LiteStep/any/file.rc', 'any/LiteStep/any/file.rc'],
\ 'loginaccess': ['/etc/login.access', 'any/etc/login.access'],
@@ -435,7 +438,7 @@ let s:filename_checks = {
\ 'sather': ['file.sa'],
\ 'sbt': ['file.sbt'],
\ 'scala': ['file.scala', 'file.sc'],
- \ 'scheme': ['file.scm', 'file.ss', 'file.rkt', 'file.rktd', 'file.rktl'],
+ \ 'scheme': ['file.scm', 'file.ss', 'file.sld', 'file.rkt', 'file.rktd', 'file.rktl'],
\ 'scilab': ['file.sci', 'file.sce'],
\ 'screen': ['.screenrc', 'screenrc'],
\ 'sexplib': ['file.sexp'],
@@ -445,7 +448,7 @@ let s:filename_checks = {
\ 'sdc': ['file.sdc'],
\ 'sdl': ['file.sdl', 'file.pr'],
\ 'sed': ['file.sed'],
- \ 'sensors': ['/etc/sensors.conf', '/etc/sensors3.conf', 'any/etc/sensors.conf', 'any/etc/sensors3.conf'],
+ \ 'sensors': ['/etc/sensors.conf', '/etc/sensors3.conf', '/etc/sensors.d/file', 'any/etc/sensors.conf', 'any/etc/sensors3.conf', 'any/etc/sensors.d/file'],
\ 'services': ['/etc/services', 'any/etc/services'],
\ 'setserial': ['/etc/serial.conf', 'any/etc/serial.conf'],
\ 'sh': ['.bashrc', 'file.bash', '/usr/share/doc/bash-completion/filter.sh','/etc/udev/cdsymlinks.conf', 'any/etc/udev/cdsymlinks.conf'],
@@ -480,7 +483,7 @@ let s:filename_checks = {
\ 'squid': ['squid.conf'],
\ 'squirrel': ['file.nut'],
\ 'srec': ['file.s19', 'file.s28', 'file.s37', 'file.mot', 'file.srec'],
- \ 'sshconfig': ['ssh_config', '/.ssh/config', '/etc/ssh/ssh_config.d/file.conf', 'any/etc/ssh/ssh_config.d/file.conf', 'any/.ssh/config'],
+ \ 'sshconfig': ['ssh_config', '/.ssh/config', '/etc/ssh/ssh_config.d/file.conf', 'any/etc/ssh/ssh_config.d/file.conf', 'any/.ssh/config', 'any/.ssh/file.conf'],
\ 'sshdconfig': ['sshd_config', '/etc/ssh/sshd_config.d/file.conf', 'any/etc/ssh/sshd_config.d/file.conf'],
\ 'st': ['file.st'],
\ 'stata': ['file.ado', 'file.do', 'file.imata', 'file.mata'],
@@ -652,7 +655,7 @@ let s:script_checks = {
\ ['#!/path/nodejs'],
\ ['#!/path/rhino']],
\ 'bc': [['#!/path/bc']],
- \ 'sed': [['#!/path/sed']],
+ \ 'sed': [['#!/path/sed'], ['#n'], ['#n comment']],
\ 'ocaml': [['#!/path/ocaml']],
\ 'awk': [['#!/path/awk'],
\ ['#!/path/gawk']],
@@ -1004,4 +1007,206 @@ func Test_fs_file()
filetype off
endfunc
+func Test_dep3patch_file()
+ filetype on
+
+ call assert_true(mkdir('debian/patches', 'p'))
+
+ " series files are not patches
+ call writefile(['Description: some awesome patch'], 'debian/patches/series')
+ split debian/patches/series
+ call assert_notequal('dep3patch', &filetype)
+ bwipe!
+
+ " diff/patch files without the right headers should still show up as ft=diff
+ call writefile([], 'debian/patches/foo.diff')
+ split debian/patches/foo.diff
+ call assert_equal('diff', &filetype)
+ bwipe!
+
+ " Files with the right headers are detected as dep3patch, even if they don't
+ " have a diff/patch extension
+ call writefile(['Subject: dep3patches'], 'debian/patches/bar')
+ split debian/patches/bar
+ call assert_equal('dep3patch', &filetype)
+ bwipe!
+
+ " Files in sub-directories are detected
+ call assert_true(mkdir('debian/patches/s390x', 'p'))
+ call writefile(['Subject: dep3patches'], 'debian/patches/s390x/bar')
+ split debian/patches/s390x/bar
+ call assert_equal('dep3patch', &filetype)
+ bwipe!
+
+ " The detection stops when seeing the "header end" marker
+ call writefile(['---', 'Origin: the cloud'], 'debian/patches/baz')
+ split debian/patches/baz
+ call assert_notequal('dep3patch', &filetype)
+ bwipe!
+
+ call delete('debian', 'rf')
+endfunc
+
+func Test_patch_file()
+ filetype on
+
+ call writefile([], 'Xfile.patch')
+ split Xfile.patch
+ call assert_equal('diff', &filetype)
+ bwipe!
+
+ call writefile(['From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001'], 'Xfile.patch')
+ split Xfile.patch
+ call assert_equal('gitsendemail', &filetype)
+ bwipe!
+
+ call writefile(['From 0000000000000000000000000000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001'], 'Xfile.patch')
+ split Xfile.patch
+ call assert_equal('gitsendemail', &filetype)
+ bwipe!
+
+ call delete('Xfile.patch')
+ filetype off
+endfunc
+
+func Test_git_file()
+ filetype on
+
+ call assert_true(mkdir('Xrepo.git', 'p'))
+
+ call writefile([], 'Xrepo.git/HEAD')
+ split Xrepo.git/HEAD
+ call assert_equal('', &filetype)
+ bwipe!
+
+ call writefile(['0000000000000000000000000000000000000000'], 'Xrepo.git/HEAD')
+ split Xrepo.git/HEAD
+ call assert_equal('git', &filetype)
+ bwipe!
+
+ call writefile(['0000000000000000000000000000000000000000000000000000000000000000'], 'Xrepo.git/HEAD')
+ split Xrepo.git/HEAD
+ call assert_equal('git', &filetype)
+ bwipe!
+
+ call writefile(['ref: refs/heads/master'], 'Xrepo.git/HEAD')
+ split Xrepo.git/HEAD
+ call assert_equal('git', &filetype)
+ bwipe!
+
+ call delete('Xrepo.git', 'rf')
+ filetype off
+endfunc
+
+func Test_foam_file()
+ filetype on
+ call assert_true(mkdir('0', 'p'))
+ call assert_true(mkdir('0.orig', 'p'))
+
+ call writefile(['FoamFile {', ' object something;'], 'Xfile1Dict')
+ split Xfile1Dict
+ call assert_equal('foam', &filetype)
+ bwipe!
+
+ call writefile(['FoamFile {', ' object something;'], 'Xfile1Dict.something')
+ split Xfile1Dict.something
+ call assert_equal('foam', &filetype)
+ bwipe!
+
+ call writefile(['FoamFile {', ' object something;'], 'XfileProperties')
+ split XfileProperties
+ call assert_equal('foam', &filetype)
+ bwipe!
+
+ call writefile(['FoamFile {', ' object something;'], 'XfileProperties.something')
+ split XfileProperties.something
+ call assert_equal('foam', &filetype)
+ bwipe!
+
+ call writefile(['FoamFile {', ' object something;'], 'XfileProperties')
+ split XfileProperties
+ call assert_equal('foam', &filetype)
+ bwipe!
+
+ call writefile(['FoamFile {', ' object something;'], 'XfileProperties.something')
+ split XfileProperties.something
+ call assert_equal('foam', &filetype)
+ bwipe!
+
+ call writefile(['FoamFile {', ' object something;'], '0/Xfile')
+ split 0/Xfile
+ call assert_equal('foam', &filetype)
+ bwipe!
+
+ call writefile(['FoamFile {', ' object something;'], '0.orig/Xfile')
+ split 0.orig/Xfile
+ call assert_equal('foam', &filetype)
+ bwipe!
+
+ call delete('0', 'rf')
+ call delete('0.orig', 'rf')
+ filetype off
+endfunc
+
+func Test_bas_file()
+ filetype on
+
+ call writefile(['looks like BASIC'], 'Xfile.bas')
+ split Xfile.bas
+ call assert_equal('basic', &filetype)
+ bwipe!
+
+ " Test dist#ft#FTbas()
+
+ let g:filetype_bas = 'freebasic'
+ split Xfile.bas
+ call assert_equal('freebasic', &filetype)
+ bwipe!
+ unlet g:filetype_bas
+
+ " FreeBASIC
+
+ call writefile(["/' FreeBASIC multiline comment '/"], 'Xfile.bas')
+ split Xfile.bas
+ call assert_equal('freebasic', &filetype)
+ bwipe!
+
+ call writefile(['#define TESTING'], 'Xfile.bas')
+ split Xfile.bas
+ call assert_equal('freebasic', &filetype)
+ bwipe!
+
+ call writefile(['option byval'], 'Xfile.bas')
+ split Xfile.bas
+ call assert_equal('freebasic', &filetype)
+ bwipe!
+
+ call writefile(['extern "C"'], 'Xfile.bas')
+ split Xfile.bas
+ call assert_equal('freebasic', &filetype)
+ bwipe!
+
+ " QB64
+
+ call writefile(['$LET TESTING = 1'], 'Xfile.bas')
+ split Xfile.bas
+ call assert_equal('qb64', &filetype)
+ bwipe!
+
+ call writefile(['OPTION _EXPLICIT'], 'Xfile.bas')
+ split Xfile.bas
+ call assert_equal('qb64', &filetype)
+ bwipe!
+
+ " Visual Basic
+
+ call writefile(['Attribute VB_NAME = "Testing"'], 'Xfile.bas')
+ split Xfile.bas
+ call assert_equal('vb', &filetype)
+ bwipe!
+
+ call delete('Xfile.bas')
+ filetype off
+endfunc
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_filetype_lua.vim b/src/nvim/testdir/test_filetype_lua.vim
new file mode 100644
index 0000000000..f73e4ca33f
--- /dev/null
+++ b/src/nvim/testdir/test_filetype_lua.vim
@@ -0,0 +1,2 @@
+let g:do_filetype_lua = 1
+source test_filetype.vim
diff --git a/src/nvim/testdir/test_listchars.vim b/src/nvim/testdir/test_listchars.vim
index f4ee539803..0bcbd9c4a5 100644
--- a/src/nvim/testdir/test_listchars.vim
+++ b/src/nvim/testdir/test_listchars.vim
@@ -331,7 +331,7 @@ func Test_listchars_invalid()
call assert_fails('set listchars=space:xx', 'E474:')
call assert_fails('set listchars=tab:xxxx', 'E474:')
- " Has non-single width character
+ " Has double-width character
call assert_fails('set listchars=space:·', 'E474:')
call assert_fails('set listchars=tab:·x', 'E474:')
call assert_fails('set listchars=tab:x·', 'E474:')
@@ -339,6 +339,20 @@ func Test_listchars_invalid()
call assert_fails('set listchars=multispace:·', 'E474:')
call assert_fails('set listchars=multispace:xxx·', 'E474:')
+ " Has control character
+ call assert_fails("set listchars=space:\x01", 'E474:')
+ call assert_fails("set listchars=tab:\x01x", 'E474:')
+ call assert_fails("set listchars=tab:x\x01", 'E474:')
+ call assert_fails("set listchars=tab:xx\x01", 'E474:')
+ call assert_fails("set listchars=multispace:\x01", 'E474:')
+ call assert_fails("set listchars=multispace:xxx\x01", 'E474:')
+ call assert_fails('set listchars=space:\\x01', 'E474:')
+ call assert_fails('set listchars=tab:\\x01x', 'E474:')
+ call assert_fails('set listchars=tab:x\\x01', 'E474:')
+ call assert_fails('set listchars=tab:xx\\x01', 'E474:')
+ call assert_fails('set listchars=multispace:\\x01', 'E474:')
+ call assert_fails('set listchars=multispace:xxx\\x01', 'E474:')
+
enew!
set ambiwidth& listchars& ff&
endfunction
diff --git a/src/nvim/testdir/test_messages.vim b/src/nvim/testdir/test_messages.vim
index 2140fe21ea..e0286548d9 100644
--- a/src/nvim/testdir/test_messages.vim
+++ b/src/nvim/testdir/test_messages.vim
@@ -108,3 +108,11 @@ func Test_echospace()
set ruler& showcmd&
endfunc
+
+" this was missing a terminating NUL
+func Test_echo_string_partial()
+ function CountSpaces()
+ endfunction
+ call assert_equal("function('CountSpaces', [{'ccccccccccc': ['ab', 'cd'], 'aaaaaaaaaaa': v:false, 'bbbbbbbbbbbb': ''}])", string(function('CountSpaces', [#{aaaaaaaaaaa: v:false, bbbbbbbbbbbb: '', ccccccccccc: ['ab', 'cd']}])))
+endfunc
+
diff --git a/src/nvim/testdir/test_options.vim b/src/nvim/testdir/test_options.vim
index 7d9cada074..5946732937 100644
--- a/src/nvim/testdir/test_options.vim
+++ b/src/nvim/testdir/test_options.vim
@@ -732,4 +732,25 @@ func Test_opt_reset_scroll()
call delete('Xscroll')
endfunc
+" Test for the 'cdhome' option
+func Test_opt_cdhome()
+ if has('unix') || has('vms')
+ throw 'Skipped: only works on non-Unix'
+ endif
+
+ set cdhome&
+ call assert_equal(0, &cdhome)
+ set cdhome
+
+ " This paragraph is copied from Test_cd_no_arg().
+ let path = getcwd()
+ cd
+ call assert_equal($HOME, getcwd())
+ call assert_notequal(path, getcwd())
+ exe 'cd ' .. fnameescape(path)
+ call assert_equal(path, getcwd())
+
+ set cdhome&
+endfunc
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_put.vim b/src/nvim/testdir/test_put.vim
index f42b177c50..440717eaa8 100644
--- a/src/nvim/testdir/test_put.vim
+++ b/src/nvim/testdir/test_put.vim
@@ -113,14 +113,14 @@ func Test_put_p_indent_visual()
endfunc
func Test_multibyte_op_end_mark()
- new
- call setline(1, 'тест')
- normal viwdp
- call assert_equal([0, 1, 7, 0], getpos("'>"))
- call assert_equal([0, 1, 7, 0], getpos("']"))
-
- normal Vyp
- call assert_equal([0, 1, 2147483647, 0], getpos("'>"))
- call assert_equal([0, 2, 7, 0], getpos("']"))
- bwipe!
- endfunc
+ new
+ call setline(1, 'тест')
+ normal viwdp
+ call assert_equal([0, 1, 7, 0], getpos("'>"))
+ call assert_equal([0, 1, 7, 0], getpos("']"))
+
+ normal Vyp
+ call assert_equal([0, 1, 2147483647, 0], getpos("'>"))
+ call assert_equal([0, 2, 7, 0], getpos("']"))
+ bwipe!
+endfunc
diff --git a/src/nvim/testdir/test_regexp_utf8.vim b/src/nvim/testdir/test_regexp_utf8.vim
index d8d5797dcf..c568805f87 100644
--- a/src/nvim/testdir/test_regexp_utf8.vim
+++ b/src/nvim/testdir/test_regexp_utf8.vim
@@ -590,4 +590,12 @@ func Test_match_char_class_upper()
bwipe!
endfunc
+func Test_match_invalid_byte()
+ call writefile(0z630a.765d30aa0a.2e0a.790a.4030, 'Xinvalid')
+ new
+ source Xinvalid
+ bwipe!
+ call delete('Xinvalid')
+endfunc
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_registers.vim b/src/nvim/testdir/test_registers.vim
index 84a5aca3d5..4371828a72 100644
--- a/src/nvim/testdir/test_registers.vim
+++ b/src/nvim/testdir/test_registers.vim
@@ -13,6 +13,8 @@ func Test_aaa_empty_reg_test()
call assert_fails('normal @!', 'E354:')
call assert_fails('normal @:', 'E30:')
call assert_fails('normal @.', 'E29:')
+ call assert_fails('put /', 'E35:')
+ call assert_fails('put .', 'E29:')
endfunc
func Test_yank_shows_register()
@@ -141,6 +143,14 @@ func Test_last_used_exec_reg()
normal @@
call assert_equal('EditEdit', a)
+ " Test for repeating the last command-line in visual mode
+ call append(0, 'register')
+ normal gg
+ let @r = ''
+ call feedkeys("v:yank R\<CR>", 'xt')
+ call feedkeys("v@:", 'xt')
+ call assert_equal("\nregister\nregister\n", @r)
+
enew!
endfunc
@@ -164,6 +174,28 @@ func Test_get_register()
call assert_equal('', getregtype('!'))
+ " Test for clipboard registers (* and +)
+ if has("clipboard_working")
+ call append(0, "text for clipboard test")
+ normal gg"*yiw
+ call assert_equal('text', getreg('*'))
+ normal gg2w"+yiw
+ call assert_equal('clipboard', getreg('+'))
+ endif
+
+ " Test for inserting an invalid register content
+ call assert_beeps('exe "normal i\<C-R>!"')
+
+ " Test for inserting a register with multiple lines
+ call deletebufline('', 1, '$')
+ call setreg('r', ['a', 'b'])
+ exe "normal i\<C-R>r"
+ call assert_equal(['a', 'b', ''], getline(1, '$'))
+
+ " Test for inserting a multi-line register in the command line
+ call feedkeys(":\<C-R>r\<Esc>", 'xt')
+ call assert_equal("a\rb", histget(':', -1)) " Modified because of #6137
+
enew!
endfunc
@@ -187,6 +219,25 @@ func Test_set_register()
call setreg('=', 'b', 'a')
call assert_equal('regwrite', getreg('='))
+ " Test for settting a list of lines to special registers
+ call setreg('/', [])
+ call assert_equal('', @/)
+ call setreg('=', [])
+ call assert_equal('', @=)
+ call assert_fails("call setreg('/', ['a', 'b'])", 'E883:')
+ call assert_fails("call setreg('=', ['a', 'b'])", 'E883:')
+ call assert_equal(0, setreg('_', ['a', 'b']))
+
+ " Test for recording to a invalid register
+ call assert_beeps('normal q$')
+
+ " Appending to a register when recording
+ call append(0, "text for clipboard test")
+ normal gg
+ call feedkeys('qrllq', 'xt')
+ call feedkeys('qRhhq', 'xt')
+ call assert_equal('llhh', getreg('r'))
+
enew!
endfunc
diff --git a/src/nvim/testdir/test_search_stat.vim b/src/nvim/testdir/test_search_stat.vim
index 335a51268d..f7f7467e91 100644
--- a/src/nvim/testdir/test_search_stat.vim
+++ b/src/nvim/testdir/test_search_stat.vim
@@ -73,7 +73,6 @@ func Test_search_stat()
let stat = '\[2/50\]'
let g:a = execute(':unsilent :norm! n')
call assert_notmatch(pat .. stat, g:a)
- call writefile(getline(1, '$'), 'sample.txt')
" n does not update search stat
call assert_equal(
\ #{current: 50, exact_match: 1, total: 50, incomplete: 0, maxcount: 99},
diff --git a/src/nvim/testdir/test_signs.vim b/src/nvim/testdir/test_signs.vim
index 799e6cb57b..ff9ba3d8ed 100644
--- a/src/nvim/testdir/test_signs.vim
+++ b/src/nvim/testdir/test_signs.vim
@@ -218,15 +218,13 @@ func Test_sign_completion()
call assert_equal('"sign define jump list place undefine unplace', @:)
call feedkeys(":sign define Sign \<C-A>\<C-B>\"\<CR>", 'tx')
- call assert_equal('"sign define Sign icon= linehl= numhl= text= texthl=', @:)
+ call assert_equal('"sign define Sign culhl= icon= linehl= numhl= text= texthl=', @:)
- call feedkeys(":sign define Sign linehl=Spell\<C-A>\<C-B>\"\<CR>", 'tx')
- call assert_equal('"sign define Sign linehl=SpellBad SpellCap ' .
- \ 'SpellLocal SpellRare', @:)
-
- call feedkeys(":sign define Sign texthl=Spell\<C-A>\<C-B>\"\<CR>", 'tx')
- call assert_equal('"sign define Sign texthl=SpellBad SpellCap ' .
- \ 'SpellLocal SpellRare', @:)
+ for hl in ['culhl', 'linehl', 'numhl', 'texthl']
+ call feedkeys(":sign define Sign "..hl.."=Spell\<C-A>\<C-B>\"\<CR>", 'tx')
+ call assert_equal('"sign define Sign '..hl..'=SpellBad SpellCap ' .
+ \ 'SpellLocal SpellRare', @:)
+ endfor
call writefile(repeat(["Sun is shining"], 30), "XsignOne")
call writefile(repeat(["Sky is blue"], 30), "XsignTwo")
@@ -417,20 +415,21 @@ func Test_sign_funcs()
" Tests for sign_define()
let attr = {'text' : '=>', 'linehl' : 'Search', 'texthl' : 'Error',
- \ 'culhl': 'Visual'}
+ \ 'culhl': 'Visual', 'numhl': 'Number'}
call assert_equal(0, "sign1"->sign_define(attr))
- call assert_equal([{'name' : 'sign1', 'texthl' : 'Error',
- \ 'linehl' : 'Search', 'culhl': 'Visual', 'text' : '=>'}],
+ call assert_equal([{'name' : 'sign1', 'texthl' : 'Error', 'linehl': 'Search',
+ \ 'culhl': 'Visual', 'numhl': 'Number', 'text' : '=>'}],
\ sign_getdefined())
" Define a new sign without attributes and then update it
call sign_define("sign2")
let attr = {'text' : '!!', 'linehl' : 'DiffAdd', 'texthl' : 'DiffChange',
- \ 'culhl': 'DiffDelete', 'icon' : 'sign2.ico'}
+ \ 'culhl': 'DiffDelete', 'numhl': 'Number', 'icon' : 'sign2.ico'}
call Sign_define_ignore_error("sign2", attr)
call assert_equal([{'name' : 'sign2', 'texthl' : 'DiffChange',
\ 'linehl' : 'DiffAdd', 'culhl' : 'DiffDelete', 'text' : '!!',
- \ 'icon' : 'sign2.ico'}], "sign2"->sign_getdefined())
+ \ 'numhl': 'Number', 'icon' : 'sign2.ico'}],
+ \ "sign2"->sign_getdefined())
" Test for a sign name with digits
call assert_equal(0, sign_define(0002, {'linehl' : 'StatusLine'}))
diff --git a/src/nvim/testdir/test_spell.vim b/src/nvim/testdir/test_spell.vim
index cf0faeee31..1ecb5c8070 100644
--- a/src/nvim/testdir/test_spell.vim
+++ b/src/nvim/testdir/test_spell.vim
@@ -768,6 +768,14 @@ func Test_spell_screendump()
call delete('XtestSpell')
endfunc
+func Test_spell_single_word()
+ new
+ silent! norm 0R00
+ spell!
+ silent 0norm 0r$ Dvz=
+ bwipe!
+endfunc
+
let g:test_data_aff1 = [
\"SET ISO8859-1",
\"TRY esianrtolcdugmphbyfvkwjkqxz-\xEB\xE9\xE8\xEA\xEF\xEE\xE4\xE0\xE2\xF6\xFC\xFB'ESIANRTOLCDUGMPHBYFVKWJKQXZ",
diff --git a/src/nvim/testdir/test_substitute.vim b/src/nvim/testdir/test_substitute.vim
index 113c85acef..20b760ac15 100644
--- a/src/nvim/testdir/test_substitute.vim
+++ b/src/nvim/testdir/test_substitute.vim
@@ -137,7 +137,7 @@ func Test_substitute_repeat()
" This caused an invalid memory access.
split Xfile
s/^/x
- call feedkeys("Qsc\<CR>y", 'tx')
+ call feedkeys("gQsc\<CR>y", 'tx')
bwipe!
endfunc
diff --git a/src/nvim/testdir/test_timers.vim b/src/nvim/testdir/test_timers.vim
index 5cc0da2586..aae315b2c5 100644
--- a/src/nvim/testdir/test_timers.vim
+++ b/src/nvim/testdir/test_timers.vim
@@ -279,7 +279,7 @@ func Test_ex_mode()
endfunc
let timer = timer_start(40, function('g:Foo'), {'repeat':-1})
" This used to throw error E749.
- exe "normal Qsleep 100m\rvi\r"
+ exe "normal gQsleep 100m\rvi\r"
call timer_stop(timer)
endfunc
diff --git a/src/nvim/testdir/test_usercommands.vim b/src/nvim/testdir/test_usercommands.vim
index 29e578ac6d..481959d43d 100644
--- a/src/nvim/testdir/test_usercommands.vim
+++ b/src/nvim/testdir/test_usercommands.vim
@@ -269,10 +269,10 @@ endfunc
func Test_CmdCompletion()
call feedkeys(":com -\<C-A>\<C-B>\"\<CR>", 'tx')
- call assert_equal('"com -addr bang bar buffer complete count nargs range register', @:)
+ call assert_equal('"com -addr bang bar buffer complete count keepscript nargs range register', @:)
call feedkeys(":com -nargs=0 -\<C-A>\<C-B>\"\<CR>", 'tx')
- call assert_equal('"com -nargs=0 -addr bang bar buffer complete count nargs range register', @:)
+ call assert_equal('"com -nargs=0 -addr bang bar buffer complete count keepscript nargs range register', @:)
call feedkeys(":com -nargs=\<C-A>\<C-B>\"\<CR>", 'tx')
call assert_equal('"com -nargs=* + 0 1 ?', @:)
diff --git a/src/nvim/testdir/test_virtualedit.vim b/src/nvim/testdir/test_virtualedit.vim
index 8f992f7501..0a218898ed 100644
--- a/src/nvim/testdir/test_virtualedit.vim
+++ b/src/nvim/testdir/test_virtualedit.vim
@@ -81,6 +81,48 @@ func Test_edit_change()
normal Cx
call assert_equal('x', getline(1))
bwipe!
+ set virtualedit=
+endfunc
+
+" Test for pasting before and after a tab character
+func Test_paste_in_tab()
+ new
+ let @" = 'xyz'
+ set virtualedit=all
+ call append(0, "a\tb")
+ call cursor(1, 2, 6)
+ normal p
+ call assert_equal("a\txyzb", getline(1))
+ call setline(1, "a\tb")
+ call cursor(1, 2)
+ normal P
+ call assert_equal("axyz\tb", getline(1))
+
+ " Test for virtual block paste
+ call setreg('"', 'xyz', 'b')
+ call setline(1, "a\tb")
+ call cursor(1, 2, 6)
+ normal p
+ call assert_equal("a\txyzb", getline(1))
+ call setline(1, "a\tb")
+ call cursor(1, 2, 6)
+ normal P
+ call assert_equal("a xyz b", getline(1))
+
+ " Test for virtual block paste with gp and gP
+ call setline(1, "a\tb")
+ call cursor(1, 2, 6)
+ normal gp
+ call assert_equal("a\txyzb", getline(1))
+ call assert_equal([0, 1, 6, 0, 12], getcurpos())
+ call setline(1, "a\tb")
+ call cursor(1, 2, 6)
+ normal gP
+ call assert_equal("a xyz b", getline(1))
+ call assert_equal([0, 1, 12, 0 ,12], getcurpos())
+
+ bwipe!
+ set virtualedit=
endfunc
" Insert "keyword keyw", ESC, C CTRL-N, shows "keyword ykeyword".
diff --git a/src/nvim/testdir/test_visual.vim b/src/nvim/testdir/test_visual.vim
index dbabdcf427..d58ca92a2f 100644
--- a/src/nvim/testdir/test_visual.vim
+++ b/src/nvim/testdir/test_visual.vim
@@ -144,7 +144,6 @@ endfun
" Test Virtual replace mode.
func Test_virtual_replace()
- throw 'skipped: TODO: '
if exists('&t_kD')
let save_t_kD = &t_kD
endif
@@ -166,7 +165,6 @@ func Test_virtual_replace()
\ ], getline(1, 6))
normal G
mark a
- inoremap <C-D> <Del>
exe "normal o0\<C-D>\nabcdefghi\njk\tlmn\n opq\trst\n\<C-D>uvwxyz\n"
exe "normal 'ajgR0\<C-D> 1\nA\nBCDEFGHIJ\n\tKL\nMNO\nPQR" . repeat("\<BS>", 29)
call assert_equal([' 1',
@@ -435,6 +433,19 @@ func Test_Visual_Block()
close!
endfunc
+" Test for 'p'ut in visual block mode
+func Test_visual_block_put()
+ enew
+
+ call append(0, ['One', 'Two', 'Three'])
+ normal gg
+ yank
+ call feedkeys("jl\<C-V>ljp", 'xt')
+ call assert_equal(['One', 'T', 'Tee', 'One', ''], getline(1, '$'))
+
+ enew!
+endfunc
+
func Test_visual_put_in_block()
new
call setline(1, ['xxxx', 'y∞yy', 'zzzz'])
diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c
index bb75286369..58061f020d 100644
--- a/src/nvim/tui/tui.c
+++ b/src/nvim/tui/tui.c
@@ -308,23 +308,39 @@ static void terminfo_start(UI *ui)
// Enable bracketed paste
unibi_out_ext(ui, data->unibi_ext.enable_bracketed_paste);
+ int ret;
uv_loop_init(&data->write_loop);
if (data->out_isatty) {
- uv_tty_init(&data->write_loop, &data->output_handle.tty, data->out_fd, 0);
+ ret = uv_tty_init(&data->write_loop, &data->output_handle.tty, data->out_fd, 0);
+ if (ret) {
+ ELOG("uv_tty_init failed: %s", uv_strerror(ret));
+ }
#ifdef WIN32
- uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_RAW);
+ ret = uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_RAW);
+ if (ret) {
+ ELOG("uv_tty_set_mode failed: %s", uv_strerror(ret));
+ }
#else
int retry_count = 10;
// A signal may cause uv_tty_set_mode() to fail (e.g., SIGCONT). Retry a
// few times. #12322
- while (uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_IO) == UV_EINTR
+ while ((ret = uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_IO)) == UV_EINTR
&& retry_count > 0) {
retry_count--;
}
+ if (ret) {
+ ELOG("uv_tty_set_mode failed: %s", uv_strerror(ret));
+ }
#endif
} else {
- uv_pipe_init(&data->write_loop, &data->output_handle.pipe, 0);
- uv_pipe_open(&data->output_handle.pipe, data->out_fd);
+ ret = uv_pipe_init(&data->write_loop, &data->output_handle.pipe, 0);
+ if (ret) {
+ ELOG("uv_pipe_init failed: %s", uv_strerror(ret));
+ }
+ ret = uv_pipe_open(&data->output_handle.pipe, data->out_fd);
+ if (ret) {
+ ELOG("uv_pipe_open failed: %s", uv_strerror(ret));
+ }
}
flush_buf(ui);
}
@@ -1086,8 +1102,14 @@ static void tui_mode_change(UI *ui, String mode, Integer mode_idx)
// after calling uv_tty_set_mode. So, set the mode of the TTY again here.
// #13073
if (data->is_starting && data->input.in_fd == STDERR_FILENO) {
- uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_NORMAL);
- uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_IO);
+ int ret = uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_NORMAL);
+ if (ret) {
+ ELOG("uv_tty_set_mode failed: %s", uv_strerror(ret));
+ }
+ ret = uv_tty_set_mode(&data->output_handle.tty, UV_TTY_MODE_IO);
+ if (ret) {
+ ELOG("uv_tty_set_mode failed: %s", uv_strerror(ret));
+ }
}
#endif
tui_set_mode(ui, (ModeShape)mode_idx);
@@ -1855,7 +1877,7 @@ static void patch_terminfo_bugs(TUIData *data, const char *term, const char *col
"\x1b[?c");
} else if (konsolev > 0 && konsolev < 180770) {
// Konsole before version 18.07.70: set up a nonce profile. This has
- // side-effects on temporary font resizing. #6798
+ // side effects on temporary font resizing. #6798
data->unibi_ext.set_cursor_style = (int)unibi_add_ext_str(ut, "Ss",
TMUX_WRAP(tmux,
"\x1b]50;CursorShape=%?"
@@ -2081,8 +2103,11 @@ static void flush_buf(UI *ui)
fwrite(bufs[i].base, bufs[i].len, 1, data->screenshot);
}
} else {
- uv_write(&req, STRUCT_CAST(uv_stream_t, &data->output_handle),
- bufs, (unsigned)(bufp - bufs), NULL);
+ int ret = uv_write(&req, STRUCT_CAST(uv_stream_t, &data->output_handle),
+ bufs, (unsigned)(bufp - bufs), NULL);
+ if (ret) {
+ ELOG("uv_write failed: %s", uv_strerror(ret));
+ }
uv_run(&data->write_loop, UV_RUN_DEFAULT);
}
data->bufpos = 0;
diff --git a/src/nvim/types.h b/src/nvim/types.h
index 604155c33e..73cd2204d6 100644
--- a/src/nvim/types.h
+++ b/src/nvim/types.h
@@ -32,4 +32,6 @@ typedef enum {
kTrue = 1,
} TriState;
+typedef struct Decoration Decoration;
+
#endif // NVIM_TYPES_H
diff --git a/src/nvim/vim.h b/src/nvim/vim.h
index 2f8ddd1e88..6e0e9922a6 100644
--- a/src/nvim/vim.h
+++ b/src/nvim/vim.h
@@ -143,6 +143,7 @@ enum {
EXPAND_COMPILER,
EXPAND_USER_DEFINED,
EXPAND_USER_LIST,
+ EXPAND_USER_LUA,
EXPAND_SHELLCMD,
EXPAND_CSCOPE,
EXPAND_SIGN,
diff --git a/src/nvim/viml/parser/expressions.c b/src/nvim/viml/parser/expressions.c
index ba6cfab98b..8a14710351 100644
--- a/src/nvim/viml/parser/expressions.c
+++ b/src/nvim/viml/parser/expressions.c
@@ -1536,7 +1536,7 @@ static inline void east_set_error(const ParserState *const pstate, ExprASTError
/* TODO(ZyX-I): Extend syntax to allow ${expr}. This is needed to */ \
/* handle environment variables like those bash uses for */ \
/* `export -f`: their names consist not only of alphanumeric */ \
- /* characetrs. */ \
+ /* characters. */ \
case kExprNodeComplexIdentifier: \
case kExprNodePlainIdentifier: \
case kExprNodeCurlyBracesIdentifier: { \
diff --git a/src/nvim/viml/parser/expressions.h b/src/nvim/viml/parser/expressions.h
index fe9327b27d..9d0bc9d468 100644
--- a/src/nvim/viml/parser/expressions.h
+++ b/src/nvim/viml/parser/expressions.h
@@ -57,7 +57,7 @@ typedef enum {
} LexExprTokenType;
typedef enum {
- kExprCmpEqual, ///< Equality, unequality.
+ kExprCmpEqual, ///< Equality, inequality.
kExprCmpMatches, ///< Matches regex, not matches regex.
kExprCmpGreater, ///< `>` or `<=`
kExprCmpGreaterOrEqual, ///< `>=` or `<`.
diff --git a/src/nvim/window.c b/src/nvim/window.c
index c711f462d1..1e747a67e9 100644
--- a/src/nvim/window.c
+++ b/src/nvim/window.c
@@ -1591,7 +1591,7 @@ int make_windows(int count, bool vertical)
int todo;
if (vertical) {
- // Each windows needs at least 'winminwidth' lines and a separator
+ // Each window needs at least 'winminwidth' lines and a separator
// column.
maxcount = (curwin->w_width + curwin->w_vsep_width
- (p_wiw - p_wmw)) / (p_wmw + 1);
@@ -2119,7 +2119,7 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int
m = frame_minheight(topfr, next_curwin);
room = height - m;
if (room < 0) {
- // The room is less then 'winheight', use all space for the
+ // The room is less than 'winheight', use all space for the
// current window.
next_curwin_size = p_wh + room;
room = 0;
diff --git a/test/README.md b/test/README.md
index 37aa54c157..cc630cb8bf 100644
--- a/test/README.md
+++ b/test/README.md
@@ -38,7 +38,7 @@ Layout
- `/test/functional` : functional tests
- `/test/unit` : unit tests
- `/test/config` : contains `*.in` files which are transformed into `*.lua`
- files using `configure_file` CMake command: this is for acessing CMake
+ files using `configure_file` CMake command: this is for accessing CMake
variables in lua tests.
- `/test/includes` : include-files for use by luajit `ffi.cdef` C definitions
parser: normally used to make macros not accessible via this mechanism
@@ -116,7 +116,7 @@ Filtering Tests
### Filter by name
-Another filter method is by setting a pattern of test name to `TEST_FILTER`.
+Another filter method is by setting a pattern of test name to `TEST_FILTER` or `TEST_FILTER_OUT`.
``` lua
it('foo api',function()
@@ -131,6 +131,10 @@ To run only test with filter name:
TEST_FILTER='foo.*api' make functionaltest
+To run all tests except ones matching a filter:
+
+ TEST_FILTER_OUT='foo.*api' make functionaltest
+
### Filter by file
To run a *specific* unit test:
@@ -193,7 +197,7 @@ Guidelines
(success + fail + error + pending) is the same in all environments.
- *Note:* `pending()` is ignored if it is missing an argument, unless it is
[contained in an `it()` block](https://github.com/neovim/neovim/blob/d21690a66e7eb5ebef18046c7a79ef898966d786/test/functional/ex_cmds/grep_spec.lua#L11).
- Provide empty function argument if the `pending()` call is outside of `it()`
+ Provide empty function argument if the `pending()` call is outside `it()`
([example](https://github.com/neovim/neovim/commit/5c1dc0fbe7388528875aff9d7b5055ad718014de#diff-bf80b24c724b0004e8418102f68b0679R18)).
- Really long `source([=[...]=])` blocks may break Vim's Lua syntax
highlighting. Try `:syntax sync fromstart` to fix it.
diff --git a/test/functional/api/command_spec.lua b/test/functional/api/command_spec.lua
index 6f929ad1ca..d64d324a88 100644
--- a/test/functional/api/command_spec.lua
+++ b/test/functional/api/command_spec.lua
@@ -6,12 +6,18 @@ local command = helpers.command
local curbufmeths = helpers.curbufmeths
local eq = helpers.eq
local meths = helpers.meths
+local bufmeths = helpers.bufmeths
+local matches = helpers.matches
local source = helpers.source
local pcall_err = helpers.pcall_err
+local exec_lua = helpers.exec_lua
+local assert_alive = helpers.assert_alive
+local feed = helpers.feed
+local funcs = helpers.funcs
describe('nvim_get_commands', function()
- local cmd_dict = { addr=NIL, bang=false, bar=false, complete=NIL, complete_arg=NIL, count=NIL, definition='echo "Hello World"', name='Hello', nargs='1', range=NIL, register=false, script_id=0, }
- local cmd_dict2 = { addr=NIL, bang=false, bar=false, complete=NIL, complete_arg=NIL, count=NIL, definition='pwd', name='Pwd', nargs='?', range=NIL, register=false, script_id=0, }
+ local cmd_dict = { addr=NIL, bang=false, bar=false, complete=NIL, complete_arg=NIL, count=NIL, definition='echo "Hello World"', name='Hello', nargs='1', range=NIL, register=false, keepscript=false, script_id=0, }
+ local cmd_dict2 = { addr=NIL, bang=false, bar=false, complete=NIL, complete_arg=NIL, count=NIL, definition='pwd', name='Pwd', nargs='?', range=NIL, register=false, keepscript=false, script_id=0, }
before_each(clear)
it('gets empty list if no commands were defined', function()
@@ -53,11 +59,11 @@ describe('nvim_get_commands', function()
end)
it('gets various command attributes', function()
- local cmd0 = { addr='arguments', bang=false, bar=false, complete='dir', complete_arg=NIL, count='10', definition='pwd <args>', name='TestCmd', nargs='1', range='10', register=false, script_id=0, }
- local cmd1 = { addr=NIL, bang=false, bar=false, complete='custom', complete_arg='ListUsers', count=NIL, definition='!finger <args>', name='Finger', nargs='+', range=NIL, register=false, script_id=1, }
- local cmd2 = { addr=NIL, bang=true, bar=false, complete=NIL, complete_arg=NIL, count=NIL, definition='call \128\253R2_foo(<q-args>)', name='Cmd2', nargs='*', range=NIL, register=false, script_id=2, }
- local cmd3 = { addr=NIL, bang=false, bar=true, complete=NIL, complete_arg=NIL, count=NIL, definition='call \128\253R3_ohyeah()', name='Cmd3', nargs='0', range=NIL, register=false, script_id=3, }
- local cmd4 = { addr=NIL, bang=false, bar=false, complete=NIL, complete_arg=NIL, count=NIL, definition='call \128\253R4_just_great()', name='Cmd4', nargs='0', range=NIL, register=true, script_id=4, }
+ local cmd0 = { addr='arguments', bang=false, bar=false, complete='dir', complete_arg=NIL, count='10', definition='pwd <args>', name='TestCmd', nargs='1', range='10', register=false, keepscript=false, script_id=0, }
+ local cmd1 = { addr=NIL, bang=false, bar=false, complete='custom', complete_arg='ListUsers', count=NIL, definition='!finger <args>', name='Finger', nargs='+', range=NIL, register=false, keepscript=false, script_id=1, }
+ local cmd2 = { addr=NIL, bang=true, bar=false, complete=NIL, complete_arg=NIL, count=NIL, definition='call \128\253R2_foo(<q-args>)', name='Cmd2', nargs='*', range=NIL, register=false, keepscript=false, script_id=2, }
+ local cmd3 = { addr=NIL, bang=false, bar=true, complete=NIL, complete_arg=NIL, count=NIL, definition='call \128\253R3_ohyeah()', name='Cmd3', nargs='0', range=NIL, register=false, keepscript=false, script_id=3, }
+ local cmd4 = { addr=NIL, bang=false, bar=false, complete=NIL, complete_arg=NIL, count=NIL, definition='call \128\253R4_just_great()', name='Cmd4', nargs='0', range=NIL, register=true, keepscript=false, script_id=4, }
source([[
command -complete=custom,ListUsers -nargs=+ Finger !finger <args>
]])
@@ -78,3 +84,118 @@ describe('nvim_get_commands', function()
eq({Cmd2=cmd2, Cmd3=cmd3, Cmd4=cmd4, Finger=cmd1, TestCmd=cmd0}, meths.get_commands({builtin=false}))
end)
end)
+
+describe('nvim_add_user_command', function()
+ before_each(clear)
+
+ it('works with strings', function()
+ meths.add_user_command('SomeCommand', 'let g:command_fired = <args>', {nargs = 1})
+ meths.command('SomeCommand 42')
+ eq(42, meths.eval('g:command_fired'))
+ end)
+
+ it('works with Lua functions', function()
+ exec_lua [[
+ result = {}
+ vim.api.nvim_add_user_command('CommandWithLuaCallback', function(opts)
+ result = opts
+ end, {
+ nargs = "*",
+ bang = true,
+ count = 2,
+ })
+ ]]
+
+ eq({
+ args = "hello",
+ bang = false,
+ line1 = 1,
+ line2 = 1,
+ mods = "",
+ range = 0,
+ count = 2,
+ reg = "",
+ }, exec_lua [[
+ vim.api.nvim_command('CommandWithLuaCallback hello')
+ return result
+ ]])
+
+ eq({
+ args = "",
+ bang = true,
+ line1 = 10,
+ line2 = 10,
+ mods = "botright",
+ range = 1,
+ count = 10,
+ reg = "",
+ }, exec_lua [[
+ vim.api.nvim_command('botright 10CommandWithLuaCallback!')
+ return result
+ ]])
+
+ eq({
+ args = "",
+ bang = false,
+ line1 = 1,
+ line2 = 42,
+ mods = "",
+ range = 1,
+ count = 42,
+ reg = "",
+ }, exec_lua [[
+ vim.api.nvim_command('CommandWithLuaCallback 42')
+ return result
+ ]])
+ end)
+
+ it('can define buffer-local commands', function()
+ local bufnr = meths.create_buf(false, false)
+ bufmeths.add_user_command(bufnr, "Hello", "", {})
+ matches("Not an editor command: Hello", pcall_err(meths.command, "Hello"))
+ meths.set_current_buf(bufnr)
+ meths.command("Hello")
+ assert_alive()
+ end)
+
+ it('can use a Lua complete function', function()
+ exec_lua [[
+ vim.api.nvim_add_user_command('Test', '', {
+ nargs = "*",
+ complete = function(arg, cmdline, pos)
+ local options = {"aaa", "bbb", "ccc"}
+ local t = {}
+ for _, v in ipairs(options) do
+ if string.find(v, "^" .. arg) then
+ table.insert(t, v)
+ end
+ end
+ return t
+ end,
+ })
+ ]]
+
+ feed(':Test a<Tab>')
+ eq('Test aaa', funcs.getcmdline())
+ feed('<C-U>Test b<Tab>')
+ eq('Test bbb', funcs.getcmdline())
+ end)
+end)
+
+describe('nvim_del_user_command', function()
+ before_each(clear)
+
+ it('can delete global commands', function()
+ meths.add_user_command('Hello', 'echo "Hi"', {})
+ meths.command('Hello')
+ meths.del_user_command('Hello')
+ matches("Not an editor command: Hello", pcall_err(meths.command, "Hello"))
+ end)
+
+ it('can delete buffer-local commands', function()
+ bufmeths.add_user_command(0, 'Hello', 'echo "Hi"', {})
+ meths.command('Hello')
+ bufmeths.del_user_command(0, 'Hello')
+ matches("Not an editor command: Hello", pcall_err(meths.command, "Hello"))
+ end)
+end)
diff --git a/test/functional/api/extmark_spec.lua b/test/functional/api/extmark_spec.lua
index a8f538b951..3f79515949 100644
--- a/test/functional/api/extmark_spec.lua
+++ b/test/functional/api/extmark_spec.lua
@@ -110,6 +110,22 @@ describe('API/extmarks', function()
pcall_err(set_extmark, ns, marks[2], 0, 0, { end_col = 1, end_row = 1 }))
end)
+ it("can end extranges past final newline when strict mode is false", function()
+ set_extmark(ns, marks[1], 0, 0, {
+ end_col = 1,
+ end_row = 1,
+ strict = false,
+ })
+ end)
+
+ it("can end extranges past final column when strict mode is false", function()
+ set_extmark(ns, marks[1], 0, 0, {
+ end_col = 6,
+ end_row = 0,
+ strict = false,
+ })
+ end)
+
it('adds, updates and deletes marks', function()
local rv = set_extmark(ns, marks[1], positions[1][1], positions[1][2])
eq(marks[1], rv)
@@ -1432,6 +1448,49 @@ describe('API/extmarks', function()
})
eq({ {1, 0, 0, { end_col = 0, end_row = 1 }} }, get_extmarks(ns, 0, -1, {details=true}))
end)
+
+ it('can get details', function()
+ set_extmark(ns, marks[1], 0, 0, {
+ end_col = 0,
+ end_row = 1,
+ priority = 0,
+ hl_eol = true,
+ hl_mode = "blend",
+ hl_group = "String",
+ virt_text = { { "text", "Statement" } },
+ virt_text_pos = "right_align",
+ virt_text_hide = true,
+ virt_lines = { { { "lines", "Statement" } }},
+ virt_lines_above = true,
+ virt_lines_leftcol = true,
+ })
+ set_extmark(ns, marks[2], 0, 0, {
+ priority = 0,
+ virt_text = { { "text", "Statement" } },
+ virt_text_win_col = 1,
+ })
+ eq({0, 0, {
+ end_col = 0,
+ end_row = 1,
+ priority = 0,
+ hl_eol = true,
+ hl_mode = "blend",
+ hl_group = "String",
+ virt_text = { { "text", "Statement" } },
+ virt_text_pos = "right_align",
+ virt_text_hide = true,
+ virt_lines = { { { "lines", "Statement" } }},
+ virt_lines_above = true,
+ virt_lines_leftcol = true,
+ } }, get_extmark_by_id(ns, marks[1], { details = true }))
+ eq({0, 0, {
+ priority = 0,
+ virt_text = { { "text", "Statement" } },
+ virt_text_hide = false,
+ virt_text_pos = "win_col",
+ virt_text_win_col = 1,
+ } }, get_extmark_by_id(ns, marks[2], { details = true }))
+ end)
end)
describe('Extmarks buffer api with many marks', function()
diff --git a/test/functional/api/keymap_spec.lua b/test/functional/api/keymap_spec.lua
index dd8eef7ca0..450a76ddac 100644
--- a/test/functional/api/keymap_spec.lua
+++ b/test/functional/api/keymap_spec.lua
@@ -5,6 +5,7 @@ local clear = helpers.clear
local command = helpers.command
local curbufmeths = helpers.curbufmeths
local eq, neq = helpers.eq, helpers.neq
+local exec_lua = helpers.exec_lua
local feed = helpers.feed
local funcs = helpers.funcs
local meths = helpers.meths
@@ -316,6 +317,55 @@ describe('nvim_get_keymap', function()
command('nnoremap \\|<Char-0x20><Char-32><Space><Bar> \\|<Char-0x20><Char-32><Space> <Bar>')
eq({space_table}, meths.get_keymap('n'))
end)
+
+ it('can handle lua keymaps', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end })
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+ eq(1, exec_lua[[return GlobalCount]])
+
+ eq(2, exec_lua[[
+ vim.api.nvim_get_keymap('n')[1].callback()
+ return GlobalCount
+ ]])
+ local mapargs = meths.get_keymap('n')
+ assert.Truthy(type(mapargs[1].callback) == 'number', 'callback is not luaref number')
+ mapargs[1].callback = nil
+ eq({
+ lhs='asdf',
+ script=0,
+ silent=0,
+ expr=0,
+ sid=0,
+ buffer=0,
+ nowait=0,
+ mode='n',
+ noremap=0,
+ lnum=0,
+ }, mapargs[1])
+ end)
+
+ it ('can handle map descriptions', function()
+ meths.set_keymap('n', 'lhs', 'rhs', {desc="map description"})
+ eq({
+ lhs='lhs',
+ rhs='rhs',
+ script=0,
+ silent=0,
+ expr=0,
+ sid=0,
+ buffer=0,
+ nowait=0,
+ mode='n',
+ noremap=0,
+ lnum=0,
+ desc='map description'
+ }, meths.get_keymap('n')[1])
+ end)
end)
describe('nvim_set_keymap, nvim_del_keymap', function()
@@ -353,6 +403,7 @@ describe('nvim_set_keymap, nvim_del_keymap', function()
to_return.sid = not opts.sid and 0 or opts.sid
to_return.buffer = not opts.buffer and 0 or opts.buffer
to_return.lnum = not opts.lnum and 0 or opts.lnum
+ to_return.desc = opts.desc
return to_return
end
@@ -717,6 +768,115 @@ describe('nvim_set_keymap, nvim_del_keymap', function()
end)
end
end
+
+ it('can make lua mappings', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end })
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+
+ end)
+
+ it (':map command shows lua keymap correctly', function()
+ exec_lua [[
+ vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() print('jkl;') end })
+ ]]
+ assert.truthy(string.match(exec_lua[[return vim.api.nvim_exec(':nmap asdf', true)]],
+ "^\nn asdf <Lua function %d+>"))
+ end)
+
+ it ('mapcheck() returns lua keymap correctly', function()
+ exec_lua [[
+ vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() print('jkl;') end })
+ ]]
+ assert.truthy(string.match(funcs.mapcheck('asdf', 'n'),
+ "^<Lua function %d+>"))
+ end)
+
+ it ('maparg() returns lua keymap correctly', function()
+ exec_lua [[
+ vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() print('jkl;') end })
+ ]]
+ assert.truthy(string.match(funcs.maparg('asdf', 'n'),
+ "^<Lua function %d+>"))
+ local mapargs = funcs.maparg('asdf', 'n', false, true)
+ assert.Truthy(type(mapargs.callback) == 'number', 'callback is not luaref number')
+ mapargs.callback = nil
+ eq(generate_mapargs('n', 'asdf', nil, {}), mapargs)
+ end)
+
+ it('can make lua expr mappings', function()
+ exec_lua [[
+ vim.api.nvim_set_keymap ('n', 'aa', '', {callback = function() return vim.api.nvim_replace_termcodes(':lua SomeValue = 99<cr>', true, false, true) end, expr = true })
+ ]]
+
+ feed('aa')
+
+ eq(99, exec_lua[[return SomeValue]])
+ end)
+
+ it('does not reset pum in lua mapping', function()
+ eq(0, exec_lua [[
+ VisibleCount = 0
+ vim.api.nvim_set_keymap ('i', '<F2>', '', {callback = function() VisibleCount = VisibleCount + vim.fn.pumvisible() end})
+ return VisibleCount
+ ]])
+ feed('i<C-X><C-V><F2><F2><esc>')
+ eq(2, exec_lua[[return VisibleCount]])
+ end)
+
+ it('can overwrite lua mappings', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end })
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+
+ exec_lua [[
+ vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount - 1 end })
+ ]]
+
+ feed('asdf\n')
+
+ eq(0, exec_lua[[return GlobalCount]])
+ end)
+
+ it('can unmap lua mappings', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.api.nvim_set_keymap ('n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end })
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+
+ exec_lua [[
+ vim.api.nvim_del_keymap('n', 'asdf' )
+ ]]
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+ eq('\nNo mapping found', helpers.exec_capture('nmap asdf'))
+ end)
+
+ it('can set descriptions on keymaps', function()
+ meths.set_keymap('n', 'lhs', 'rhs', {desc="map description"})
+ eq(generate_mapargs('n', 'lhs', 'rhs', {desc="map description"}), get_mapargs('n', 'lhs'))
+ eq("\nn lhs rhs\n map description",
+ helpers.exec_capture("nmap lhs"))
+ end)
end)
describe('nvim_buf_set_keymap, nvim_buf_del_keymap', function()
@@ -814,4 +974,67 @@ describe('nvim_buf_set_keymap, nvim_buf_del_keymap', function()
pcall_err(bufmeths.set_keymap, 100, '', 'lsh', 'irhs<Esc>', {})
helpers.assert_alive()
end)
+
+ it('can make lua mappings', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.api.nvim_buf_set_keymap (0, 'n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end })
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+ end)
+
+ it('can make lua expr mappings', function()
+ exec_lua [[
+ vim.api.nvim_buf_set_keymap (0, 'n', 'aa', '', {callback = function() return vim.api.nvim_replace_termcodes(':lua SomeValue = 99<cr>', true, false, true) end, expr = true })
+ ]]
+
+ feed('aa')
+
+ eq(99, exec_lua[[return SomeValue ]])
+ end)
+
+ it('can overwrite lua mappings', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.api.nvim_buf_set_keymap (0, 'n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end })
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+
+ exec_lua [[
+ vim.api.nvim_buf_set_keymap (0, 'n', 'asdf', '', {callback = function() GlobalCount = GlobalCount - 1 end })
+ ]]
+
+ feed('asdf\n')
+
+ eq(0, exec_lua[[return GlobalCount]])
+ end)
+
+ it('can unmap lua mappings', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.api.nvim_buf_set_keymap (0, 'n', 'asdf', '', {callback = function() GlobalCount = GlobalCount + 1 end })
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+
+ exec_lua [[
+ vim.api.nvim_buf_del_keymap(0, 'n', 'asdf' )
+ ]]
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+ eq('\nNo mapping found', helpers.exec_capture('nmap asdf'))
+ end)
end)
diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua
index d53208a915..201ba45803 100644
--- a/test/functional/api/vim_spec.lua
+++ b/test/functional/api/vim_spec.lua
@@ -974,6 +974,40 @@ describe('API', function()
eq('hello', nvim('get_option_value', 'makeprg', {}))
eq('', nvim('get_option_value', 'makeprg', {scope = 'local'}))
end)
+
+ it('clears the local value of an option with nil', function()
+ -- Set global value
+ nvim('set_option_value', 'shiftwidth', 42, {})
+ eq(42, nvim('get_option_value', 'shiftwidth', {}))
+
+ -- Set local value
+ nvim('set_option_value', 'shiftwidth', 8, {scope = 'local'})
+ eq(8, nvim('get_option_value', 'shiftwidth', {}))
+ eq(8, nvim('get_option_value', 'shiftwidth', {scope = 'local'}))
+ eq(42, nvim('get_option_value', 'shiftwidth', {scope = 'global'}))
+
+ -- Clear value without scope
+ nvim('set_option_value', 'shiftwidth', NIL, {})
+ eq(42, nvim('get_option_value', 'shiftwidth', {}))
+ eq(42, nvim('get_option_value', 'shiftwidth', {scope = 'local'}))
+
+ -- Clear value with explicit scope
+ nvim('set_option_value', 'shiftwidth', 8, {scope = 'local'})
+ nvim('set_option_value', 'shiftwidth', NIL, {scope = 'local'})
+ eq(42, nvim('get_option_value', 'shiftwidth', {}))
+ eq(42, nvim('get_option_value', 'shiftwidth', {scope = 'local'}))
+
+ -- Now try with options with a special "local is unset" value (e.g. 'undolevels')
+ nvim('set_option_value', 'undolevels', 1000, {})
+ eq(1000, nvim('get_option_value', 'undolevels', {scope = 'local'}))
+ nvim('set_option_value', 'undolevels', NIL, {scope = 'local'})
+ eq(-123456, nvim('get_option_value', 'undolevels', {scope = 'local'}))
+
+ nvim('set_option_value', 'autoread', true, {})
+ eq(true, nvim('get_option_value', 'autoread', {scope = 'local'}))
+ nvim('set_option_value', 'autoread', NIL, {scope = 'local'})
+ eq(NIL, nvim('get_option_value', 'autoread', {scope = 'local'}))
+ end)
end)
describe('nvim_{get,set}_current_buf, nvim_list_bufs', function()
@@ -1120,8 +1154,8 @@ describe('API', function()
end)
end)
- describe('RPC (K_EVENT) #6166', function()
- it('does not complete ("interrupt") normal-mode operator-pending', function()
+ describe('RPC (K_EVENT)', function()
+ it('does not complete ("interrupt") normal-mode operator-pending #6166', function()
helpers.insert([[
FIRST LINE
SECOND LINE]])
@@ -1157,7 +1191,7 @@ describe('API', function()
]])
end)
- it('does not complete ("interrupt") normal-mode map-pending', function()
+ it('does not complete ("interrupt") normal-mode map-pending #6166', function()
command("nnoremap dd :let g:foo='it worked...'<CR>")
helpers.insert([[
FIRST LINE
@@ -1173,7 +1207,8 @@ describe('API', function()
SECOND LINE]])
eq('it worked...', helpers.eval('g:foo'))
end)
- it('does not complete ("interrupt") insert-mode map-pending', function()
+
+ it('does not complete ("interrupt") insert-mode map-pending #6166', function()
command('inoremap xx foo')
command('set timeoutlen=9999')
helpers.insert([[
@@ -1188,6 +1223,37 @@ describe('API', function()
FIRST LINE
SECOND LINfooE]])
end)
+
+ it('does not interrupt Insert mode i_CTRL-O #10035', function()
+ feed('iHello World<c-o>')
+ eq({mode='niI', blocking=false}, meths.get_mode()) -- fast event
+ eq(2, eval('1+1')) -- causes K_EVENT key
+ eq({mode='niI', blocking=false}, meths.get_mode()) -- still in ctrl-o mode
+ feed('dd')
+ eq({mode='i', blocking=false}, meths.get_mode()) -- left ctrl-o mode
+ expect('') -- executed the command
+ end)
+
+ it('does not interrupt Select mode v_CTRL-O #15688', function()
+ feed('iHello World<esc>gh<c-o>')
+ eq({mode='vs', blocking=false}, meths.get_mode()) -- fast event
+ eq({mode='vs', blocking=false}, meths.get_mode()) -- again #15288
+ eq(2, eval('1+1')) -- causes K_EVENT key
+ eq({mode='vs', blocking=false}, meths.get_mode()) -- still in ctrl-o mode
+ feed('^')
+ eq({mode='s', blocking=false}, meths.get_mode()) -- left ctrl-o mode
+ feed('h')
+ eq({mode='i', blocking=false}, meths.get_mode()) -- entered insert mode
+ expect('h') -- selection is the whole line and is replaced
+ end)
+
+ it('does not interrupt Insert mode i_0_CTRL-D #13997', function()
+ command('set timeoutlen=9999')
+ feed('i<Tab><Tab>a0')
+ eq(2, eval('1+1')) -- causes K_EVENT key
+ feed('<C-D>')
+ expect('a') -- recognized i_0_CTRL-D
+ end)
end)
describe('nvim_get_context', function()
@@ -1301,18 +1367,18 @@ describe('API', function()
end)
describe('nvim_feedkeys', function()
- it('CSI escaping', function()
+ it('K_SPECIAL escaping', function()
local function on_setup()
-- notice the special char(…) \xe2\80\xa6
nvim('feedkeys', ':let x1="…"\n', '', true)
-- Both nvim_replace_termcodes and nvim_feedkeys escape \x80
local inp = helpers.nvim('replace_termcodes', ':let x2="…"<CR>', true, true, true)
- nvim('feedkeys', inp, '', true) -- escape_csi=true
+ nvim('feedkeys', inp, '', true) -- escape_ks=true
- -- nvim_feedkeys with CSI escaping disabled
+ -- nvim_feedkeys with K_SPECIAL escaping disabled
inp = helpers.nvim('replace_termcodes', ':let x3="…"<CR>', true, true, true)
- nvim('feedkeys', inp, '', false) -- escape_csi=false
+ nvim('feedkeys', inp, '', false) -- escape_ks=false
helpers.stop()
end
diff --git a/test/functional/autocmd/cursormoved_spec.lua b/test/functional/autocmd/cursormoved_spec.lua
index d0f46e689b..9641d4b096 100644
--- a/test/functional/autocmd/cursormoved_spec.lua
+++ b/test/functional/autocmd/cursormoved_spec.lua
@@ -31,4 +31,12 @@ describe('CursorMoved', function()
eq({'aaa'}, funcs.nvim_buf_get_lines(eval('g:buf'), 0, -1, true))
eq(0, eval('g:cursormoved'))
end)
+
+ it("is not triggered by cursor movement prior to first CursorMoved instantiation", function()
+ source([[
+ let g:cursormoved = 0
+ autocmd CursorMoved * let g:cursormoved += 1
+ ]])
+ eq(0, eval('g:cursormoved'))
+ end)
end)
diff --git a/test/functional/autocmd/recording_spec.lua b/test/functional/autocmd/recording_spec.lua
new file mode 100644
index 0000000000..b9aec774f1
--- /dev/null
+++ b/test/functional/autocmd/recording_spec.lua
@@ -0,0 +1,72 @@
+local helpers = require('test.functional.helpers')(after_each)
+
+local clear = helpers.clear
+local eq = helpers.eq
+local eval = helpers.eval
+local source_vim = helpers.source
+
+describe('RecordingEnter', function()
+ before_each(clear)
+ it('works', function()
+ source_vim [[
+ let g:recorded = 0
+ autocmd RecordingEnter * let g:recorded += 1
+ call feedkeys("qqyyq", 'xt')
+ ]]
+ eq(1, eval('g:recorded'))
+ end)
+
+ it('gives a correct reg_recording()', function()
+ source_vim [[
+ let g:recording = ''
+ autocmd RecordingEnter * let g:recording = reg_recording()
+ call feedkeys("qqyyq", 'xt')
+ ]]
+ eq('q', eval('g:recording'))
+ end)
+end)
+
+describe('RecordingLeave', function()
+ before_each(clear)
+ it('works', function()
+ source_vim [[
+ let g:recorded = 0
+ autocmd RecordingLeave * let g:recorded += 1
+ call feedkeys("qqyyq", 'xt')
+ ]]
+ eq(1, eval('g:recorded'))
+ end)
+
+ it('gives the correct reg_recorded()', function()
+ source_vim [[
+ let g:recorded = 'a'
+ let g:recording = ''
+ autocmd RecordingLeave * let g:recording = reg_recording()
+ autocmd RecordingLeave * let g:recorded = reg_recorded()
+ call feedkeys("qqyyq", 'xt')
+ ]]
+ eq('q', eval 'g:recording')
+ eq('', eval 'g:recorded')
+ eq('q', eval 'reg_recorded()')
+ end)
+
+ it('populates v:event', function()
+ source_vim [[
+ let g:regname = ''
+ let g:regcontents = ''
+ autocmd RecordingLeave * let g:regname = v:event.regname
+ autocmd RecordingLeave * let g:regcontents = v:event.regcontents
+ call feedkeys("qqyyq", 'xt')
+ ]]
+ eq('q', eval 'g:regname')
+ eq('yy', eval 'g:regcontents')
+ end)
+
+ it('resets v:event', function()
+ source_vim [[
+ autocmd RecordingLeave * let g:event = v:event
+ call feedkeys("qqyyq", 'xt')
+ ]]
+ eq(0, eval 'len(v:event)')
+ end)
+end)
diff --git a/test/functional/core/startup_spec.lua b/test/functional/core/startup_spec.lua
index 4220d68ee1..2fa84e8313 100644
--- a/test/functional/core/startup_spec.lua
+++ b/test/functional/core/startup_spec.lua
@@ -224,6 +224,23 @@ describe('startup', function()
end
end)
+ it('-e sets ex mode', function()
+ local screen = Screen.new(25, 3)
+ clear('-e')
+ screen:attach()
+ -- Verify we set the proper mode both before and after :vi.
+ feed("put =mode(1)<CR>vi<CR>:put =mode(1)<CR>")
+ screen:expect([[
+ cv |
+ ^n |
+ :put =mode(1) |
+ ]])
+
+ eq('cv\n',
+ funcs.system({nvim_prog, '-n', '-es' },
+ { 'put =mode(1)', 'print', '' }))
+ end)
+
it('fails on --embed with -es/-Es', function()
matches('nvim[.exe]*: %-%-embed conflicts with %-es/%-Es',
funcs.system({nvim_prog, '--embed', '-es' }))
@@ -651,11 +668,7 @@ describe('runtime:', function()
mkdir_p(ftdetect_folder)
write_file(ftdetect_file , [[vim.g.lua_ftdetect = 1]])
- -- TODO(shadmansaleh): Figure out why this test fails without
- -- setting VIMRUNTIME
- clear{ args_rm={'-u'}, env={XDG_CONFIG_HOME=xconfig,
- XDG_DATA_HOME=xdata,
- VIMRUNTIME='runtime/'}}
+ clear{ args_rm={'-u'}, env=xenv }
eq(1, eval('g:lua_ftdetect'))
rmdir(ftdetect_folder)
diff --git a/test/functional/editor/K_spec.lua b/test/functional/editor/K_spec.lua
index 40f36491e4..8ad81ac3d6 100644
--- a/test/functional/editor/K_spec.lua
+++ b/test/functional/editor/K_spec.lua
@@ -33,6 +33,29 @@ describe('K', function()
feed('i'..test_file..'<ESC>K')
retry(nil, nil, function() eq(1, eval('filereadable("'..test_file..'")')) end)
eq({'fnord'}, eval("readfile('"..test_file.."')"))
+ -- Confirm that Neovim is still in terminal mode after K is pressed (#16692).
+ helpers.sleep(500)
+ eq('t', eval('mode()'))
+ feed('<space>') -- Any key, not just <space>, can be used here to escape.
+ eq('n', eval('mode()'))
+ end)
+
+ it("<esc> kills the buffer for a running 'keywordprg' command", function()
+ helpers.source('set keywordprg=less')
+ eval('writefile(["hello", "world"], "' .. test_file .. '")')
+ feed('i' .. test_file .. '<esc>K')
+ eq('t', eval('mode()'))
+ -- Confirm that an arbitrary keypress doesn't escape (i.e., the process is
+ -- still running). If the process were no longer running, an arbitrary
+ -- keypress would escape.
+ helpers.sleep(500)
+ feed('<space>')
+ eq('t', eval('mode()'))
+ -- Confirm that <esc> kills the buffer for the running command.
+ local bufnr = eval('bufnr()')
+ feed('<esc>')
+ eq('n', eval('mode()'))
+ helpers.neq(bufnr, eval('bufnr()'))
end)
end)
diff --git a/test/functional/editor/macro_spec.lua b/test/functional/editor/macro_spec.lua
index 102d8fc723..c0c9256af2 100644
--- a/test/functional/editor/macro_spec.lua
+++ b/test/functional/editor/macro_spec.lua
@@ -6,6 +6,8 @@ local feed = helpers.feed
local clear = helpers.clear
local expect = helpers.expect
local command = helpers.command
+local insert = helpers.insert
+local curbufmeths = helpers.curbufmeths
describe('macros', function()
before_each(clear)
@@ -27,4 +29,29 @@ describe('macros', function()
expect('llllll')
eq(eval('@i'), 'lxxx')
end)
+
+ it('can be replayed with Q', function()
+ insert [[hello
+hello
+hello]]
+ feed [[gg]]
+
+ feed [[qqAFOO<esc>q]]
+ eq({'helloFOO', 'hello', 'hello'}, curbufmeths.get_lines(0, -1, false))
+
+ feed[[Q]]
+ eq({'helloFOOFOO', 'hello', 'hello'}, curbufmeths.get_lines(0, -1, false))
+
+ feed[[G3Q]]
+ eq({'helloFOOFOO', 'hello', 'helloFOOFOOFOO'}, curbufmeths.get_lines(0, -1, false))
+ end)
+end)
+
+describe('reg_recorded()', function()
+ before_each(clear)
+
+ it('returns the correct value', function()
+ feed [[qqyyq]]
+ eq('q', eval('reg_recorded()'))
+ end)
end)
diff --git a/test/functional/editor/meta_key_spec.lua b/test/functional/editor/meta_key_spec.lua
index 2280f5bb24..f811b8ae8d 100644
--- a/test/functional/editor/meta_key_spec.lua
+++ b/test/functional/editor/meta_key_spec.lua
@@ -27,6 +27,14 @@ describe('meta-keys #8226 #13042', function()
command('nnoremap <A-j> Aalt-j<Esc>')
feed('<A-j><M-l>')
expect('llo<ESC>;<ESC>;alt-jmeta-l')
+ -- Unmapped ALT-chord with characters containing K_SPECIAL bytes
+ command('nnoremap … A…<Esc>')
+ feed('<A-…><M-…>')
+ expect('llo<ESC>;<ESC>;alt-jmeta-l<ESC>…<ESC>…')
+ command("execute 'nnoremap' nr2char(0x40000000) 'AMAX<Esc>'")
+ command("call nvim_input('<A-'.nr2char(0x40000000).'>')")
+ command("call nvim_input('<M-'.nr2char(0x40000000).'>')")
+ expect('llo<ESC>;<ESC>;alt-jmeta-l<ESC>…<ESC>…<ESC>MAX<ESC>MAX')
end)
it('ALT/META, visual-mode', function()
@@ -36,13 +44,20 @@ describe('meta-keys #8226 #13042', function()
expect('peach')
-- Unmapped ALT-chord resolves isolated (non-ALT) ESC mapping. #13086 #15869
command('vnoremap <ESC> A<lt>ESC>')
- feed('viw<A-;><ESC>viw<M-;><ESC>')
+ feed('viw<A-;><Esc>viw<M-;><Esc>')
expect('peach<ESC>;<ESC>;')
-- Mapped ALT-chord behaves as mapped.
command('vnoremap <M-l> Ameta-l<Esc>')
command('vnoremap <A-j> Aalt-j<Esc>')
feed('viw<A-j>viw<M-l>')
expect('peach<ESC>;<ESC>;alt-jmeta-l')
+ -- Unmapped ALT-chord with characters containing K_SPECIAL bytes
+ feed('viw<A-…><Esc>viw<M-…><Esc>')
+ expect('peach<ESC>;<ESC>;alt-jmeta-l<ESC>…<ESC>…')
+ command("execute 'inoremap' nr2char(0x40000000) 'MAX'")
+ command("call nvim_input('viw<A-'.nr2char(0x40000000).'><Esc>')")
+ command("call nvim_input('viw<M-'.nr2char(0x40000000).'><Esc>')")
+ expect('peach<ESC>;<ESC>;alt-jmeta-l<ESC>…<ESC>…<ESC>MAX<ESC>MAX')
end)
it('ALT/META insert-mode', function()
diff --git a/test/functional/editor/mode_insert_spec.lua b/test/functional/editor/mode_insert_spec.lua
index 46ab483036..f03508035d 100644
--- a/test/functional/editor/mode_insert_spec.lua
+++ b/test/functional/editor/mode_insert_spec.lua
@@ -6,7 +6,6 @@ local expect = helpers.expect
local command = helpers.command
local eq = helpers.eq
local eval = helpers.eval
-local meths = helpers.meths
describe('insert-mode', function()
before_each(function()
@@ -75,15 +74,5 @@ describe('insert-mode', function()
feed('ooo')
expect('hello oooworld')
end)
-
- it("doesn't cancel Ctrl-O mode when processing event", function()
- feed('iHello World<c-o>')
- eq({mode='niI', blocking=false}, meths.get_mode()) -- fast event
- eq(2, eval('1+1')) -- causes K_EVENT key
- eq({mode='niI', blocking=false}, meths.get_mode()) -- still in ctrl-o mode
- feed('dd')
- eq({mode='i', blocking=false}, meths.get_mode()) -- left ctrl-o mode
- expect('') -- executed the command
- end)
end)
end)
diff --git a/test/functional/editor/mode_visual_spec.lua b/test/functional/editor/mode_visual_spec.lua
deleted file mode 100644
index 468ae00e01..0000000000
--- a/test/functional/editor/mode_visual_spec.lua
+++ /dev/null
@@ -1,27 +0,0 @@
--- Visual-mode tests.
-
-local helpers = require('test.functional.helpers')(after_each)
-local clear = helpers.clear
-local eq = helpers.eq
-local eval = helpers.eval
-local expect = helpers.expect
-local feed = helpers.feed
-local meths = helpers.meths
-
-describe('visual-mode', function()
- before_each(clear)
-
- it("select-mode Ctrl-O doesn't cancel Ctrl-O mode when processing event #15688", function()
- feed('iHello World<esc>gh<c-o>')
- eq({mode='vs', blocking=false}, meths.get_mode()) -- fast event
- eq({mode='vs', blocking=false}, meths.get_mode()) -- again #15288
- eq(2, eval('1+1')) -- causes K_EVENT key
- eq({mode='vs', blocking=false}, meths.get_mode()) -- still in ctrl-o mode
- feed('^')
- eq({mode='s', blocking=false}, meths.get_mode()) -- left ctrl-o mode
- feed('h')
- eq({mode='i', blocking=false}, meths.get_mode()) -- entered insert mode
- expect('h') -- selection is the whole line and is replaced
- end)
-end)
-
diff --git a/test/functional/editor/put_spec.lua b/test/functional/editor/put_spec.lua
index 26967ecbba..fdda2be131 100644
--- a/test/functional/editor/put_spec.lua
+++ b/test/functional/editor/put_spec.lua
@@ -64,7 +64,7 @@ describe('put command', function()
-- one place to the right (unless we were at the end of the
-- line when we pasted).
if not (exception_table.undo_position and after_undo) then
- eq(funcs.getcurpos(), init_cursorpos)
+ eq(init_cursorpos, funcs.getcurpos())
end
end
@@ -86,7 +86,7 @@ describe('put command', function()
-- If we paste the ". register with a count we can't avoid
-- changing this register, hence avoid this check.
if not test.exception_table.dot_reg_changed then
- eq(funcs.getreg('.'), orig_dotstr)
+ eq(orig_dotstr, funcs.getreg('.'))
end
-- Doing something, undoing it, and then redoing it should
@@ -507,9 +507,9 @@ describe('put command', function()
return function(exception_table, after_redo)
test_expect(exception_table, after_redo)
if selection_string then
- eq(getreg('"'), selection_string)
+ eq(selection_string, getreg('"'))
else
- eq(getreg('"'), 'test_string"')
+ eq('test_string"', getreg('"'))
end
end
end
@@ -714,7 +714,7 @@ describe('put command', function()
expect_base, conversion_table)
return function(exception_table, after_redo)
test_expect(exception_table, after_redo)
- eq(getreg('"'), 'Line of words 1\n')
+ eq('Line of words 1\n', getreg('"'))
end
end
local base_expect_string = [[
@@ -748,7 +748,7 @@ describe('put command', function()
end, expect_base, conversion_table)
return function(e,c)
test_expect(e,c)
- eq(getreg('"'), 'Lin\nLin')
+ eq('Lin\nLin', getreg('"'))
end
end
@@ -800,9 +800,9 @@ describe('put command', function()
feed('u')
-- Have to use feed('u') here to set curswant, because
-- ex_undo() doesn't do that.
- eq(funcs.getcurpos(), {0, 1, 1, 0, 1})
+ eq({0, 1, 1, 0, 1}, funcs.getcurpos())
feed('<C-r>')
- eq(funcs.getcurpos(), {0, 1, 1, 0, 1})
+ eq({0, 1, 1, 0, 1}, funcs.getcurpos())
end
end
diff --git a/test/functional/ex_cmds/append_spec.lua b/test/functional/ex_cmds/append_spec.lua
index 0a4d701794..fadb5c9b42 100644
--- a/test/functional/ex_cmds/append_spec.lua
+++ b/test/functional/ex_cmds/append_spec.lua
@@ -1,23 +1,26 @@
local helpers = require('test.functional.helpers')(after_each)
local eq = helpers.eq
+local dedent = helpers.dedent
+local exec = helpers.exec
local feed = helpers.feed
local clear = helpers.clear
local funcs = helpers.funcs
local command = helpers.command
local curbufmeths = helpers.curbufmeths
-
-before_each(function()
- clear()
- curbufmeths.set_lines(0, 1, true, { 'foo', 'bar', 'baz' })
-end)
-
-local buffer_contents = function()
- return curbufmeths.get_lines(0, -1, false)
-end
+local Screen = require('test.functional.ui.screen')
local cmdtest = function(cmd, prep, ret1)
describe(':' .. cmd, function()
+ before_each(function()
+ clear()
+ curbufmeths.set_lines(0, 1, true, { 'foo', 'bar', 'baz' })
+ end)
+
+ local buffer_contents = function()
+ return curbufmeths.get_lines(0, -1, false)
+ end
+
it(cmd .. 's' .. prep .. ' the current line by default', function()
command(cmd .. '\nabc\ndef\n')
eq(ret1, buffer_contents())
@@ -52,3 +55,52 @@ end
cmdtest('insert', ' before', { 'abc', 'def', 'foo', 'bar', 'baz' })
cmdtest('append', ' after', { 'foo', 'abc', 'def', 'bar', 'baz' })
cmdtest('change', '', { 'abc', 'def', 'bar', 'baz' })
+
+describe('the first line is redrawn correctly after inserting text in an empty buffer', function()
+ local screen
+ before_each(function()
+ clear()
+ screen = Screen.new(20, 8)
+ screen:set_default_attr_ids({
+ [1] = {bold = true, foreground = Screen.colors.Blue},
+ [2] = {bold = true, reverse = true},
+ })
+ screen:attach()
+ end)
+
+ it('using :append', function()
+ exec(dedent([[
+ append
+ aaaaa
+ bbbbb
+ .]]))
+ screen:expect([[
+ aaaaa |
+ ^bbbbb |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ |
+ ]])
+ end)
+
+ it('using :insert', function()
+ exec(dedent([[
+ insert
+ aaaaa
+ bbbbb
+ .]]))
+ screen:expect([[
+ aaaaa |
+ ^bbbbb |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ |
+ ]])
+ end)
+end)
diff --git a/test/functional/helpers.lua b/test/functional/helpers.lua
index f152a487af..1845786c4b 100644
--- a/test/functional/helpers.lua
+++ b/test/functional/helpers.lua
@@ -451,6 +451,7 @@ function module.new_argv(...)
'GCOV_ERROR_FILE',
'XDG_DATA_DIRS',
'TMPDIR',
+ 'VIMRUNTIME',
}) do
if not env_tbl[k] then
env_tbl[k] = os.getenv(k)
diff --git a/test/functional/legacy/memory_usage_spec.lua b/test/functional/legacy/memory_usage_spec.lua
index d86caca0e9..8d25b9d927 100644
--- a/test/functional/legacy/memory_usage_spec.lua
+++ b/test/functional/legacy/memory_usage_spec.lua
@@ -195,10 +195,10 @@ describe('memory usage', function()
local after = monitor_memory_usage(pid)
source('bwipe!')
poke_eventloop()
- -- Allow for an increase of 5% in memory usage, which accommodates minor fluctuation,
+ -- Allow for an increase of 10% in memory usage, which accommodates minor fluctuation,
-- but is small enough that if memory were not released (prior to PR #14884), the test
-- would fail.
- local upper = before.last * 1.05
+ local upper = before.last * 1.10
check_result({before=before, after=after}, pcall(ok, after.last <= upper))
end)
end)
diff --git a/test/functional/legacy/options_spec.lua b/test/functional/legacy/options_spec.lua
index 023cdd4ae1..bd14f3bc53 100644
--- a/test/functional/legacy/options_spec.lua
+++ b/test/functional/legacy/options_spec.lua
@@ -83,4 +83,9 @@ describe('set', function()
Press ENTER or type command to continue^ |
]])
end)
+
+ it('foldcolumn and signcolumn to empty string is disallowed', function()
+ matches('E474: Invalid argument: fdc=', exc_exec('set fdc='))
+ matches('E474: Invalid argument: scl=', exc_exec('set scl='))
+ end)
end)
diff --git a/test/functional/lua/api_spec.lua b/test/functional/lua/api_spec.lua
index 81e00bba6d..cb37fb9a1c 100644
--- a/test/functional/lua/api_spec.lua
+++ b/test/functional/lua/api_spec.lua
@@ -8,6 +8,7 @@ local clear = helpers.clear
local eval = helpers.eval
local NIL = helpers.NIL
local eq = helpers.eq
+local exec_lua = helpers.exec_lua
before_each(clear)
@@ -111,6 +112,12 @@ describe('luaeval(vim.api.…)', function()
eq(7, eval([[type(luaeval('vim.api.nvim__id(nil)'))]]))
eq({foo=1, bar={42, {{baz=true}, 5}}}, funcs.luaeval('vim.api.nvim__id({foo=1, bar={42, {{baz=true}, 5}}})'))
+
+ eq(true, funcs.luaeval('vim.api.nvim__id(vim.api.nvim__id)(true)'))
+ eq(42, exec_lua [[
+ local f = vim.api.nvim__id({42, vim.api.nvim__id})
+ return f[2](f[1])
+ ]])
end)
it('correctly converts container objects with type_idx to API objects', function()
@@ -159,12 +166,8 @@ describe('luaeval(vim.api.…)', function()
it('errors out correctly when working with API', function()
-- Conversion errors
- eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Cannot convert given lua type',
- remove_trace(exc_exec([[call luaeval("vim.api.nvim__id(vim.api.nvim__id)")]])))
eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Cannot convert given lua table',
remove_trace(exc_exec([[call luaeval("vim.api.nvim__id({1, foo=42})")]])))
- eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Cannot convert given lua type',
- remove_trace(exc_exec([[call luaeval("vim.api.nvim__id({42, vim.api.nvim__id})")]])))
-- Errors in number of arguments
eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected 1 argument',
remove_trace(exc_exec([[call luaeval("vim.api.nvim__id()")]])))
@@ -180,6 +183,8 @@ describe('luaeval(vim.api.…)', function()
remove_trace(exc_exec([[call luaeval("vim.api.nvim_buf_get_lines(0, 'test', 1, false)")]])))
eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Number is not integral',
remove_trace(exc_exec([[call luaeval("vim.api.nvim_buf_get_lines(0, 1.5, 1, false)")]])))
+ eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected Lua number',
+ remove_trace(exc_exec([[call luaeval("vim.api.nvim_win_is_valid(nil)")]])))
eq('Vim(call):E5108: Error executing lua [string "luaeval()"]:1: Expected lua table',
remove_trace(exc_exec([[call luaeval("vim.api.nvim__id_float('test')")]])))
diff --git a/test/functional/lua/commands_spec.lua b/test/functional/lua/commands_spec.lua
index 9b9ba531b0..b8346df290 100644
--- a/test/functional/lua/commands_spec.lua
+++ b/test/functional/lua/commands_spec.lua
@@ -141,6 +141,24 @@ describe(':lua command', function()
{4:Press ENTER or type command to continue}^ |
]]}
end)
+
+ it('Can print results of =expr', function()
+ helpers.exec_lua("x = 5")
+ eq("5", helpers.exec_capture(':lua =x'))
+ helpers.exec_lua("function x() return 'hello' end")
+ eq([["hello"]], helpers.exec_capture(':lua = x()'))
+ helpers.exec_lua("x = {a = 1, b = 2}")
+ eq("{\n a = 1,\n b = 2\n}", helpers.exec_capture(':lua =x'))
+ helpers.exec_lua([[function x(success)
+ if success then
+ return true, "Return value"
+ else
+ return false, nil, "Error message"
+ end
+ end]])
+ eq([[true "Return value"]], helpers.exec_capture(':lua =x(true)'))
+ eq([[false nil "Error message"]], helpers.exec_capture(':lua =x(false)'))
+ end)
end)
describe(':luado command', function()
diff --git a/test/functional/lua/diagnostic_spec.lua b/test/functional/lua/diagnostic_spec.lua
index a88da63e90..b58fad1cab 100644
--- a/test/functional/lua/diagnostic_spec.lua
+++ b/test/functional/lua/diagnostic_spec.lua
@@ -208,10 +208,10 @@ describe('vim.diagnostic', function()
eq(all_highlights, exec_lua [[
local ns_1_diags = {
make_error("Error 1", 1, 1, 1, 5),
- make_warning("Warning on Server 1", 2, 1, 2, 5),
+ make_warning("Warning on Server 1", 2, 1, 2, 3),
}
local ns_2_diags = {
- make_warning("Warning 1", 2, 1, 2, 5),
+ make_warning("Warning 1", 2, 1, 2, 3),
}
vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, ns_1_diags)
@@ -255,10 +255,10 @@ describe('vim.diagnostic', function()
eq({0, 2}, exec_lua [[
local ns_1_diags = {
make_error("Error 1", 1, 1, 1, 5),
- make_warning("Warning on Server 1", 2, 1, 2, 5),
+ make_warning("Warning on Server 1", 2, 1, 2, 3),
}
local ns_2_diags = {
- make_warning("Warning 1", 2, 1, 2, 5),
+ make_warning("Warning 1", 2, 1, 2, 3),
}
vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, ns_1_diags)
@@ -599,10 +599,10 @@ describe('vim.diagnostic', function()
eq(all_highlights, exec_lua [[
local ns_1_diags = {
make_error("Error 1", 1, 1, 1, 5),
- make_warning("Warning on Server 1", 2, 1, 2, 5),
+ make_warning("Warning on Server 1", 2, 1, 2, 3),
}
local ns_2_diags = {
- make_warning("Warning 1", 2, 1, 2, 5),
+ make_warning("Warning 1", 2, 1, 2, 3),
}
vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, ns_1_diags)
@@ -787,7 +787,7 @@ describe('vim.diagnostic', function()
eq(2, exec_lua [[
vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, {
make_error("Error 1", 1, 1, 1, 5),
- make_warning("Warning on Server 1", 1, 1, 2, 5),
+ make_warning("Warning on Server 1", 1, 1, 2, 3),
})
return #vim.diagnostic.get(diagnostic_bufnr)
@@ -798,9 +798,9 @@ describe('vim.diagnostic', function()
eq({2, 3, 2}, exec_lua [[
vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, {
make_error("Error 1", 1, 1, 1, 5),
- make_warning("Warning on Server 1", 1, 1, 2, 5),
- make_info("Ignored information", 1, 1, 2, 5),
- make_hint("Here's a hint", 1, 1, 2, 5),
+ make_warning("Warning on Server 1", 1, 1, 2, 3),
+ make_info("Ignored information", 1, 1, 2, 3),
+ make_hint("Here's a hint", 1, 1, 2, 3),
})
return {
@@ -820,8 +820,8 @@ describe('vim.diagnostic', function()
eq(1, exec_lua [[
vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, {
make_error("Error 1", 1, 1, 1, 5),
- make_warning("Warning on Server 1", 1, 1, 2, 5),
- make_info("Ignored information", 1, 1, 2, 5),
+ make_warning("Warning on Server 1", 1, 1, 2, 3),
+ make_info("Ignored information", 1, 1, 2, 3),
make_error("Error On Other Line", 2, 1, 1, 5),
})
@@ -1119,6 +1119,11 @@ describe('vim.diagnostic', function()
end)
describe('set()', function()
+ it('validates its arguments', function()
+ matches("expected a list of diagnostics",
+ pcall_err(exec_lua, [[vim.diagnostic.set(1, 0, {lnum = 1, col = 2})]]))
+ end)
+
it('can perform updates after insert_leave', function()
exec_lua [[vim.api.nvim_set_current_buf(diagnostic_bufnr)]]
nvim("input", "o")
diff --git a/test/functional/lua/filetype_spec.lua b/test/functional/lua/filetype_spec.lua
new file mode 100644
index 0000000000..729ebc601b
--- /dev/null
+++ b/test/functional/lua/filetype_spec.lua
@@ -0,0 +1,98 @@
+local helpers = require('test.functional.helpers')(after_each)
+local exec_lua = helpers.exec_lua
+local eq = helpers.eq
+local clear = helpers.clear
+local pathroot = helpers.pathroot
+
+local root = pathroot()
+
+describe('vim.filetype', function()
+ before_each(function()
+ clear()
+
+ exec_lua [[
+ local bufnr = vim.api.nvim_create_buf(true, false)
+ vim.api.nvim_set_current_buf(bufnr)
+ ]]
+ end)
+
+ it('works with extensions', function()
+ eq('radicalscript', exec_lua [[
+ vim.filetype.add({
+ extension = {
+ rs = 'radicalscript',
+ },
+ })
+ vim.filetype.match('main.rs')
+ return vim.bo.filetype
+ ]])
+ end)
+
+ it('prioritizes filenames over extensions', function()
+ eq('somethingelse', exec_lua [[
+ vim.filetype.add({
+ extension = {
+ rs = 'radicalscript',
+ },
+ filename = {
+ ['main.rs'] = 'somethingelse',
+ },
+ })
+ vim.filetype.match('main.rs')
+ return vim.bo.filetype
+ ]])
+ end)
+
+ it('works with filenames', function()
+ eq('nim', exec_lua [[
+ vim.filetype.add({
+ filename = {
+ ['s_O_m_e_F_i_l_e'] = 'nim',
+ },
+ })
+ vim.filetype.match('s_O_m_e_F_i_l_e')
+ return vim.bo.filetype
+ ]])
+
+ eq('dosini', exec_lua([[
+ local root = ...
+ vim.filetype.add({
+ filename = {
+ ['config'] = 'toml',
+ [root .. '/.config/fun/config'] = 'dosini',
+ },
+ })
+ vim.filetype.match(root .. '/.config/fun/config')
+ return vim.bo.filetype
+ ]], root))
+ end)
+
+ it('works with patterns', function()
+ eq('markdown', exec_lua([[
+ local root = ...
+ vim.filetype.add({
+ pattern = {
+ ['~/blog/.*%.txt'] = 'markdown',
+ }
+ })
+ vim.filetype.match('~/blog/why_neovim_is_awesome.txt')
+ return vim.bo.filetype
+ ]], root))
+ end)
+
+ it('works with functions', function()
+ eq('foss', exec_lua [[
+ vim.filetype.add({
+ pattern = {
+ ["relevant_to_(%a+)"] = function(path, bufnr, capture)
+ if capture == "me" then
+ return "foss"
+ end
+ end,
+ }
+ })
+ vim.filetype.match('relevant_to_me')
+ return vim.bo.filetype
+ ]])
+ end)
+end)
diff --git a/test/functional/lua/spell_spec.lua b/test/functional/lua/spell_spec.lua
new file mode 100644
index 0000000000..7e831f16a7
--- /dev/null
+++ b/test/functional/lua/spell_spec.lua
@@ -0,0 +1,53 @@
+local helpers = require('test.functional.helpers')(after_each)
+local clear = helpers.clear
+local exec_lua = helpers.exec_lua
+local eq = helpers.eq
+local pcall_err = helpers.pcall_err
+
+describe('vim.spell', function()
+ before_each(function()
+ clear()
+ end)
+
+ describe('.check', function()
+ local check = function(x, exp)
+ return eq(exp, exec_lua("return vim.spell.check(...)", x))
+ end
+
+ it('can handle nil', function()
+ eq([[Error executing lua: [string "<nvim>"]:0: bad argument #1 to 'check' (expected string)]],
+ pcall_err(exec_lua, [[vim.spell.check(nil)]]))
+ end)
+
+ it('can check spellings', function()
+ check('hello', {})
+
+ check(
+ 'helloi',
+ {{"helloi", "bad", 1}}
+ )
+
+ check(
+ 'hello therei',
+ {{"therei", "bad", 7}}
+ )
+
+ check(
+ 'hello. there',
+ {{"there", "caps", 8}}
+ )
+
+ check(
+ 'neovim cna chkc spellins. okay?',
+ {
+ {"neovim" , "bad" , 1},
+ {"cna" , "bad" , 8},
+ {"chkc" , "bad" , 12},
+ {"spellins", "bad" , 17},
+ {"okay" , "caps", 27}
+ }
+ )
+ end)
+
+ end)
+end)
diff --git a/test/functional/lua/uri_spec.lua b/test/functional/lua/uri_spec.lua
index dbfbe2dbfe..fa11fdf794 100644
--- a/test/functional/lua/uri_spec.lua
+++ b/test/functional/lua/uri_spec.lua
@@ -155,6 +155,12 @@ describe('URI methods', function()
return pcall(vim.uri_to_fname, 'not_an_uri.txt')
]])
end)
+
+ it('uri_to_fname should not treat comma as a scheme character', function()
+ eq(false, exec_lua [[
+ return pcall(vim.uri_to_fname, 'foo,://bar')
+ ]])
+ end)
end)
end)
diff --git a/test/functional/lua/vim_spec.lua b/test/functional/lua/vim_spec.lua
index 2515b37beb..ddcf7687f5 100644
--- a/test/functional/lua/vim_spec.lua
+++ b/test/functional/lua/vim_spec.lua
@@ -131,9 +131,9 @@ describe('lua stdlib', function()
eq(false, funcs.luaeval('vim.startswith("123", "2")'))
eq(false, funcs.luaeval('vim.startswith("123", "1234")'))
- eq("Error executing lua: vim/shared.lua:0: prefix: expected string, got nil",
+ matches("prefix: expected string, got nil",
pcall_err(exec_lua, 'return vim.startswith("123", nil)'))
- eq("Error executing lua: vim/shared.lua:0: s: expected string, got nil",
+ matches("s: expected string, got nil",
pcall_err(exec_lua, 'return vim.startswith(nil, "123")'))
end)
@@ -147,9 +147,9 @@ describe('lua stdlib', function()
eq(false, funcs.luaeval('vim.endswith("123", "2")'))
eq(false, funcs.luaeval('vim.endswith("123", "1234")'))
- eq("Error executing lua: vim/shared.lua:0: suffix: expected string, got nil",
+ matches("suffix: expected string, got nil",
pcall_err(exec_lua, 'return vim.endswith("123", nil)'))
- eq("Error executing lua: vim/shared.lua:0: s: expected string, got nil",
+ matches("s: expected string, got nil",
pcall_err(exec_lua, 'return vim.endswith(nil, "123")'))
end)
@@ -220,9 +220,9 @@ describe('lua stdlib', function()
eq({"yy","xx"}, exec_lua("return test_table"))
-- Validates args.
- eq('Error executing lua: vim.schedule: expected function',
+ matches('vim.schedule: expected function',
pcall_err(exec_lua, "vim.schedule('stringly')"))
- eq('Error executing lua: vim.schedule: expected function',
+ matches('vim.schedule: expected function',
pcall_err(exec_lua, "vim.schedule()"))
exec_lua([[
@@ -232,7 +232,7 @@ describe('lua stdlib', function()
]])
feed("<cr>")
- eq('Error executing vim.schedule lua callback: [string "<nvim>"]:2: big failure\nvery async', remove_trace(eval("v:errmsg")))
+ matches('big failure\nvery async', remove_trace(eval("v:errmsg")))
local screen = Screen.new(60,5)
screen:set_default_attr_ids({
@@ -300,16 +300,16 @@ describe('lua stdlib', function()
}
for _, t in ipairs(loops) do
- eq("Error executing lua: vim/shared.lua:0: Infinite loop detected", pcall_err(split, t[1], t[2]))
+ matches("Infinite loop detected", pcall_err(split, t[1], t[2]))
end
-- Validates args.
eq(true, pcall(split, 'string', 'string'))
- eq('Error executing lua: vim/shared.lua:0: s: expected string, got number',
+ matches('s: expected string, got number',
pcall_err(split, 1, 'string'))
- eq('Error executing lua: vim/shared.lua:0: sep: expected string, got number',
+ matches('sep: expected string, got number',
pcall_err(split, 'string', 1))
- eq('Error executing lua: vim/shared.lua:0: kwargs: expected table, got number',
+ matches('kwargs: expected table, got number',
pcall_err(split, 'string', 'string', 1))
end)
@@ -330,7 +330,7 @@ describe('lua stdlib', function()
end
-- Validates args.
- eq('Error executing lua: vim/shared.lua:0: s: expected string, got number',
+ matches('s: expected string, got number',
pcall_err(trim, 2))
end)
@@ -410,7 +410,7 @@ describe('lua stdlib', function()
return getmetatable(t2) == mt
]]))
- eq('Error executing lua: vim/shared.lua:0: Cannot deepcopy object of type thread',
+ matches('Cannot deepcopy object of type thread',
pcall_err(exec_lua, [[
local thread = coroutine.create(function () return 0 end)
local t = {thr = thread}
@@ -423,7 +423,7 @@ describe('lua stdlib', function()
eq('foo%%%-bar', exec_lua([[return vim.pesc(vim.pesc('foo-bar'))]]))
-- Validates args.
- eq('Error executing lua: vim/shared.lua:0: s: expected string, got number',
+ matches('s: expected string, got number',
pcall_err(exec_lua, [[return vim.pesc(2)]]))
end)
@@ -548,19 +548,19 @@ describe('lua stdlib', function()
return c.x.a == 1 and c.x.b == 2 and c.x.c == nil and count == 1
]]))
- eq('Error executing lua: vim/shared.lua:0: invalid "behavior": nil',
+ matches('invalid "behavior": nil',
pcall_err(exec_lua, [[
return vim.tbl_extend()
]])
)
- eq('Error executing lua: vim/shared.lua:0: wrong number of arguments (given 1, expected at least 3)',
+ matches('wrong number of arguments %(given 1, expected at least 3%)',
pcall_err(exec_lua, [[
return vim.tbl_extend("keep")
]])
)
- eq('Error executing lua: vim/shared.lua:0: wrong number of arguments (given 2, expected at least 3)',
+ matches('wrong number of arguments %(given 2, expected at least 3%)',
pcall_err(exec_lua, [[
return vim.tbl_extend("keep", {})
]])
@@ -661,19 +661,19 @@ describe('lua stdlib', function()
return vim.tbl_deep_extend("force", a, b)
]]), {a = 123 })
- eq('Error executing lua: vim/shared.lua:0: invalid "behavior": nil',
+ matches('invalid "behavior": nil',
pcall_err(exec_lua, [[
return vim.tbl_deep_extend()
]])
)
- eq('Error executing lua: vim/shared.lua:0: wrong number of arguments (given 1, expected at least 3)',
+ matches('wrong number of arguments %(given 1, expected at least 3%)',
pcall_err(exec_lua, [[
return vim.tbl_deep_extend("keep")
]])
)
- eq('Error executing lua: vim/shared.lua:0: wrong number of arguments (given 2, expected at least 3)',
+ matches('wrong number of arguments %(given 2, expected at least 3%)',
pcall_err(exec_lua, [[
return vim.tbl_deep_extend("keep", {})
]])
@@ -706,7 +706,7 @@ describe('lua stdlib', function()
it('vim.list_extend', function()
eq({1,2,3}, exec_lua [[ return vim.list_extend({1}, {2,3}) ]])
- eq('Error executing lua: vim/shared.lua:0: src: expected table, got nil',
+ matches('src: expected table, got nil',
pcall_err(exec_lua, [[ return vim.list_extend({1}, nil) ]]))
eq({1,2}, exec_lua [[ return vim.list_extend({1}, {2;a=1}) ]])
eq(true, exec_lua [[ local a = {1} return vim.list_extend(a, {2;a=1}) == a ]])
@@ -730,7 +730,7 @@ describe('lua stdlib', function()
assert(vim.deep_equal(a, { A = 1; [1] = 'A'; }))
vim.tbl_add_reverse_lookup(a)
]]
- matches('^Error executing lua: vim/shared%.lua:0: The reverse lookup found an existing value for "[1A]" while processing key "[1A]"$',
+ matches('The reverse lookup found an existing value for "[1A]" while processing key "[1A]"$',
pcall_err(exec_lua, code))
end)
@@ -771,7 +771,7 @@ describe('lua stdlib', function()
end)
it('vim.fn should error when calling API function', function()
- eq('Error executing lua: vim.lua:0: Tried to call API function with vim.fn: use vim.api.nvim_get_current_line instead',
+ matches('Tried to call API function with vim.fn: use vim.api.nvim_get_current_line instead',
pcall_err(exec_lua, "vim.fn.nvim_get_current_line()"))
end)
@@ -906,38 +906,41 @@ describe('lua stdlib', function()
exec_lua("vim.validate{arg1={nil, 'thread', true }}")
exec_lua("vim.validate{arg1={{}, 't' }, arg2={ 'foo', 's' }}")
exec_lua("vim.validate{arg1={2, function(a) return (a % 2) == 0 end, 'even number' }}")
+ exec_lua("vim.validate{arg1={5, {'n', 's'} }, arg2={ 'foo', {'n', 's'} }}")
- eq('Error executing lua: [string "<nvim>"]:0: opt[1]: expected table, got number',
+ matches('expected table, got number',
pcall_err(exec_lua, "vim.validate{ 1, 'x' }"))
- eq('Error executing lua: [string "<nvim>"]:0: invalid type name: x',
+ matches('invalid type name: x',
pcall_err(exec_lua, "vim.validate{ arg1={ 1, 'x' }}"))
- eq('Error executing lua: [string "<nvim>"]:0: invalid type name: 1',
+ matches('invalid type name: 1',
pcall_err(exec_lua, "vim.validate{ arg1={ 1, 1 }}"))
- eq('Error executing lua: [string "<nvim>"]:0: invalid type name: nil',
+ matches('invalid type name: nil',
pcall_err(exec_lua, "vim.validate{ arg1={ 1 }}"))
-- Validated parameters are required by default.
- eq('Error executing lua: [string "<nvim>"]:0: arg1: expected string, got nil',
+ matches('arg1: expected string, got nil',
pcall_err(exec_lua, "vim.validate{ arg1={ nil, 's' }}"))
-- Explicitly required.
- eq('Error executing lua: [string "<nvim>"]:0: arg1: expected string, got nil',
+ matches('arg1: expected string, got nil',
pcall_err(exec_lua, "vim.validate{ arg1={ nil, 's', false }}"))
- eq('Error executing lua: [string "<nvim>"]:0: arg1: expected table, got number',
+ matches('arg1: expected table, got number',
pcall_err(exec_lua, "vim.validate{arg1={1, 't'}}"))
- eq('Error executing lua: [string "<nvim>"]:0: arg2: expected string, got number',
+ matches('arg2: expected string, got number',
pcall_err(exec_lua, "vim.validate{arg1={{}, 't'}, arg2={1, 's'}}"))
- eq('Error executing lua: [string "<nvim>"]:0: arg2: expected string, got nil',
+ matches('arg2: expected string, got nil',
pcall_err(exec_lua, "vim.validate{arg1={{}, 't'}, arg2={nil, 's'}}"))
- eq('Error executing lua: [string "<nvim>"]:0: arg2: expected string, got nil',
+ matches('arg2: expected string, got nil',
pcall_err(exec_lua, "vim.validate{arg1={{}, 't'}, arg2={nil, 's'}}"))
- eq('Error executing lua: [string "<nvim>"]:0: arg1: expected even number, got 3',
+ matches('arg1: expected even number, got 3',
pcall_err(exec_lua, "vim.validate{arg1={3, function(a) return a == 1 end, 'even number'}}"))
- eq('Error executing lua: [string "<nvim>"]:0: arg1: expected ?, got 3',
+ matches('arg1: expected %?, got 3',
pcall_err(exec_lua, "vim.validate{arg1={3, function(a) return a == 1 end}}"))
+ matches('arg1: expected number|string, got nil',
+ pcall_err(exec_lua, "vim.validate{ arg1={ nil, {'n', 's'} }}"))
-- Pass an additional message back.
- eq('Error executing lua: [string "<nvim>"]:0: arg1: expected ?, got 3. Info: TEST_MSG',
+ matches('arg1: expected %?, got 3. Info: TEST_MSG',
pcall_err(exec_lua, "vim.validate{arg1={3, function(a) return a == 1, 'TEST_MSG' end}}"))
end)
@@ -982,8 +985,40 @@ describe('lua stdlib', function()
]]
eq(NIL, funcs.luaeval "vim.g.to_delete")
- matches([[^Error executing lua: .*: attempt to index .* nil value]],
+ matches([[attempt to index .* nil value]],
pcall_err(exec_lua, 'return vim.g[0].testing'))
+
+ exec_lua [[
+ local counter = 0
+ vim.g.AddCounter = function() counter = counter + 1 end
+ vim.g.GetCounter = function() return counter end
+ ]]
+
+ eq(0, eval('g:GetCounter()'))
+ eval('g:AddCounter()')
+ eq(1, eval('g:GetCounter()'))
+ eval('g:AddCounter()')
+ eq(2, eval('g:GetCounter()'))
+ exec_lua([[vim.g.AddCounter()]])
+ eq(3, exec_lua([[return vim.g.GetCounter()]]))
+ exec_lua([[vim.api.nvim_get_var('AddCounter')()]])
+ eq(4, exec_lua([[return vim.api.nvim_get_var('GetCounter')()]]))
+
+ exec_lua [[
+ local counter = 0
+ vim.api.nvim_set_var('AddCounter', function() counter = counter + 1 end)
+ vim.api.nvim_set_var('GetCounter', function() return counter end)
+ ]]
+
+ eq(0, eval('g:GetCounter()'))
+ eval('g:AddCounter()')
+ eq(1, eval('g:GetCounter()'))
+ eval('g:AddCounter()')
+ eq(2, eval('g:GetCounter()'))
+ exec_lua([[vim.g.AddCounter()]])
+ eq(3, exec_lua([[return vim.g.GetCounter()]]))
+ exec_lua([[vim.api.nvim_get_var('AddCounter')()]])
+ eq(4, exec_lua([[return vim.api.nvim_get_var('GetCounter')()]]))
end)
it('vim.b', function()
@@ -1009,7 +1044,7 @@ describe('lua stdlib', function()
return {vim.b.nonexistant == vim.NIL, vim.b.nullvar == vim.NIL}
]])
- matches([[^Error executing lua: .*: attempt to index .* nil value]],
+ matches([[attempt to index .* nil value]],
pcall_err(exec_lua, 'return vim.b[BUF][0].testing'))
eq({hello="world"}, funcs.luaeval "vim.b.to_delete")
@@ -1019,6 +1054,38 @@ describe('lua stdlib', function()
eq(NIL, funcs.luaeval "vim.b.to_delete")
exec_lua [[
+ local counter = 0
+ vim.b.AddCounter = function() counter = counter + 1 end
+ vim.b.GetCounter = function() return counter end
+ ]]
+
+ eq(0, eval('b:GetCounter()'))
+ eval('b:AddCounter()')
+ eq(1, eval('b:GetCounter()'))
+ eval('b:AddCounter()')
+ eq(2, eval('b:GetCounter()'))
+ exec_lua([[vim.b.AddCounter()]])
+ eq(3, exec_lua([[return vim.b.GetCounter()]]))
+ exec_lua([[vim.api.nvim_buf_get_var(0, 'AddCounter')()]])
+ eq(4, exec_lua([[return vim.api.nvim_buf_get_var(0, 'GetCounter')()]]))
+
+ exec_lua [[
+ local counter = 0
+ vim.api.nvim_buf_set_var(0, 'AddCounter', function() counter = counter + 1 end)
+ vim.api.nvim_buf_set_var(0, 'GetCounter', function() return counter end)
+ ]]
+
+ eq(0, eval('b:GetCounter()'))
+ eval('b:AddCounter()')
+ eq(1, eval('b:GetCounter()'))
+ eval('b:AddCounter()')
+ eq(2, eval('b:GetCounter()'))
+ exec_lua([[vim.b.AddCounter()]])
+ eq(3, exec_lua([[return vim.b.GetCounter()]]))
+ exec_lua([[vim.api.nvim_buf_get_var(0, 'AddCounter')()]])
+ eq(4, exec_lua([[return vim.api.nvim_buf_get_var(0, 'GetCounter')()]]))
+
+ exec_lua [[
vim.cmd "vnew"
]]
@@ -1046,7 +1113,7 @@ describe('lua stdlib', function()
eq(NIL, funcs.luaeval "vim.w.nonexistant")
eq(NIL, funcs.luaeval "vim.w[WIN].nonexistant")
- matches([[^Error executing lua: .*: attempt to index .* nil value]],
+ matches([[attempt to index .* nil value]],
pcall_err(exec_lua, 'return vim.w[WIN][0].testing'))
eq({hello="world"}, funcs.luaeval "vim.w.to_delete")
@@ -1056,6 +1123,38 @@ describe('lua stdlib', function()
eq(NIL, funcs.luaeval "vim.w.to_delete")
exec_lua [[
+ local counter = 0
+ vim.w.AddCounter = function() counter = counter + 1 end
+ vim.w.GetCounter = function() return counter end
+ ]]
+
+ eq(0, eval('w:GetCounter()'))
+ eval('w:AddCounter()')
+ eq(1, eval('w:GetCounter()'))
+ eval('w:AddCounter()')
+ eq(2, eval('w:GetCounter()'))
+ exec_lua([[vim.w.AddCounter()]])
+ eq(3, exec_lua([[return vim.w.GetCounter()]]))
+ exec_lua([[vim.api.nvim_win_get_var(0, 'AddCounter')()]])
+ eq(4, exec_lua([[return vim.api.nvim_win_get_var(0, 'GetCounter')()]]))
+
+ exec_lua [[
+ local counter = 0
+ vim.api.nvim_win_set_var(0, 'AddCounter', function() counter = counter + 1 end)
+ vim.api.nvim_win_set_var(0, 'GetCounter', function() return counter end)
+ ]]
+
+ eq(0, eval('w:GetCounter()'))
+ eval('w:AddCounter()')
+ eq(1, eval('w:GetCounter()'))
+ eval('w:AddCounter()')
+ eq(2, eval('w:GetCounter()'))
+ exec_lua([[vim.w.AddCounter()]])
+ eq(3, exec_lua([[return vim.w.GetCounter()]]))
+ exec_lua([[vim.api.nvim_win_get_var(0, 'AddCounter')()]])
+ eq(4, exec_lua([[return vim.api.nvim_win_get_var(0, 'GetCounter')()]]))
+
+ exec_lua [[
vim.cmd "vnew"
]]
@@ -1078,7 +1177,7 @@ describe('lua stdlib', function()
eq(123, funcs.luaeval "vim.t[0].other")
eq(NIL, funcs.luaeval "vim.t[0].nonexistant")
- matches([[^Error executing lua: .*: attempt to index .* nil value]],
+ matches([[attempt to index .* nil value]],
pcall_err(exec_lua, 'return vim.t[0][0].testing'))
eq({hello="world"}, funcs.luaeval "vim.t.to_delete")
@@ -1088,6 +1187,38 @@ describe('lua stdlib', function()
eq(NIL, funcs.luaeval "vim.t.to_delete")
exec_lua [[
+ local counter = 0
+ vim.t.AddCounter = function() counter = counter + 1 end
+ vim.t.GetCounter = function() return counter end
+ ]]
+
+ eq(0, eval('t:GetCounter()'))
+ eval('t:AddCounter()')
+ eq(1, eval('t:GetCounter()'))
+ eval('t:AddCounter()')
+ eq(2, eval('t:GetCounter()'))
+ exec_lua([[vim.t.AddCounter()]])
+ eq(3, exec_lua([[return vim.t.GetCounter()]]))
+ exec_lua([[vim.api.nvim_tabpage_get_var(0, 'AddCounter')()]])
+ eq(4, exec_lua([[return vim.api.nvim_tabpage_get_var(0, 'GetCounter')()]]))
+
+ exec_lua [[
+ local counter = 0
+ vim.api.nvim_tabpage_set_var(0, 'AddCounter', function() counter = counter + 1 end)
+ vim.api.nvim_tabpage_set_var(0, 'GetCounter', function() return counter end)
+ ]]
+
+ eq(0, eval('t:GetCounter()'))
+ eval('t:AddCounter()')
+ eq(1, eval('t:GetCounter()'))
+ eval('t:AddCounter()')
+ eq(2, eval('t:GetCounter()'))
+ exec_lua([[vim.t.AddCounter()]])
+ eq(3, exec_lua([[return vim.t.GetCounter()]]))
+ exec_lua([[vim.api.nvim_tabpage_get_var(0, 'AddCounter')()]])
+ eq(4, exec_lua([[return vim.api.nvim_tabpage_get_var(0, 'GetCounter')()]]))
+
+ exec_lua [[
vim.cmd "tabnew"
]]
@@ -1108,7 +1239,7 @@ describe('lua stdlib', function()
eq(funcs.luaeval "vim.api.nvim_get_vvar('progpath')", funcs.luaeval "vim.v.progpath")
eq(false, funcs.luaeval "vim.v['false']")
eq(NIL, funcs.luaeval "vim.v.null")
- matches([[^Error executing lua: .*: attempt to index .* nil value]],
+ matches([[attempt to index .* nil value]],
pcall_err(exec_lua, 'return vim.v[0].progpath'))
end)
@@ -1128,9 +1259,9 @@ describe('lua stdlib', function()
]]
eq('', funcs.luaeval "vim.bo.filetype")
eq(true, funcs.luaeval "vim.bo[BUF].modifiable")
- matches("^Error executing lua: .*: Invalid option name: 'nosuchopt'$",
+ matches("Invalid option name: 'nosuchopt'$",
pcall_err(exec_lua, 'return vim.bo.nosuchopt'))
- matches("^Error executing lua: .*: Expected lua string$",
+ matches("Expected lua string$",
pcall_err(exec_lua, 'return vim.bo[0][0].autoread'))
end)
@@ -1147,9 +1278,9 @@ describe('lua stdlib', function()
eq(0, funcs.luaeval "vim.wo.cole")
eq(0, funcs.luaeval "vim.wo[0].cole")
eq(0, funcs.luaeval "vim.wo[1001].cole")
- matches("^Error executing lua: .*: Invalid option name: 'notanopt'$",
+ matches("Invalid option name: 'notanopt'$",
pcall_err(exec_lua, 'return vim.wo.notanopt'))
- matches("^Error executing lua: .*: Expected lua string$",
+ matches("Expected lua string$",
pcall_err(exec_lua, 'return vim.wo[0][0].list'))
eq(2, funcs.luaeval "vim.wo[1000].cole")
exec_lua [[
@@ -2200,6 +2331,40 @@ describe('lua stdlib', function()
end)
end)
+ it('vim.notify_once', function()
+ local screen = Screen.new(60,5)
+ screen:set_default_attr_ids({
+ [0] = {bold=true, foreground=Screen.colors.Blue},
+ [1] = {foreground=Screen.colors.Red},
+ })
+ screen:attach()
+ screen:expect{grid=[[
+ ^ |
+ {0:~ }|
+ {0:~ }|
+ {0:~ }|
+ |
+ ]]}
+ exec_lua [[vim.notify_once("I'll only tell you this once...", vim.log.levels.WARN)]]
+ screen:expect{grid=[[
+ ^ |
+ {0:~ }|
+ {0:~ }|
+ {0:~ }|
+ {1:I'll only tell you this once...} |
+ ]]}
+ feed('<C-l>')
+ screen:expect{grid=[[
+ ^ |
+ {0:~ }|
+ {0:~ }|
+ {0:~ }|
+ |
+ ]]}
+ exec_lua [[vim.notify_once("I'll only tell you this once...")]]
+ screen:expect_unchanged()
+ end)
+
describe('vim.schedule_wrap', function()
it('preserves argument lists', function()
exec_lua [[
@@ -2295,3 +2460,82 @@ describe('lua: require("mod") from packages', function()
eq('I am fancy_z.lua', exec_lua [[ return require'fancy_z' ]])
end)
end)
+
+describe('vim.keymap', function()
+ it('can make a mapping', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.keymap.set('n', 'asdf', function() GlobalCount = GlobalCount + 1 end)
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+ end)
+
+ it('can make an expr mapping', function()
+ exec_lua [[
+ vim.keymap.set('n', 'aa', function() return ':lua SomeValue = 99<cr>' end, {expr = true})
+ ]]
+
+ feed('aa')
+
+ eq(99, exec_lua[[return SomeValue]])
+ end)
+
+ it('can overwrite a mapping', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.keymap.set('n', 'asdf', function() GlobalCount = GlobalCount + 1 end)
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+
+ exec_lua [[
+ vim.keymap.set('n', 'asdf', function() GlobalCount = GlobalCount - 1 end)
+ ]]
+
+ feed('asdf\n')
+
+ eq(0, exec_lua[[return GlobalCount]])
+ end)
+
+ it('can unmap a mapping', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.keymap.set('n', 'asdf', function() GlobalCount = GlobalCount + 1 end)
+ return GlobalCount
+ ]])
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+
+ exec_lua [[
+ vim.keymap.del('n', 'asdf')
+ ]]
+
+ feed('asdf\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+ eq('\nNo mapping found', helpers.exec_capture('nmap asdf'))
+ end)
+
+ it('can do <Plug> mappings', function()
+ eq(0, exec_lua [[
+ GlobalCount = 0
+ vim.keymap.set('n', '<plug>(asdf)', function() GlobalCount = GlobalCount + 1 end)
+ vim.keymap.set('n', 'ww', '<plug>(asdf)')
+ return GlobalCount
+ ]])
+
+ feed('ww\n')
+
+ eq(1, exec_lua[[return GlobalCount]])
+ end)
+
+end)
diff --git a/test/functional/plugin/health_spec.lua b/test/functional/plugin/health_spec.lua
index b567b3e20c..37de5d0ce6 100644
--- a/test/functional/plugin/health_spec.lua
+++ b/test/functional/plugin/health_spec.lua
@@ -156,7 +156,7 @@ describe('health.vim', function()
test_plug.submodule_failed: require("test_plug.submodule_failed.health").check()
========================================================================
- ERROR: Failed to run healthcheck for "test_plug.submodule_failed" plugin. Exception:
- function health#check, line 24]])
+ function health#check, line 20]])
eq(expected, received)
end)
@@ -167,7 +167,7 @@ describe('health.vim', function()
broken: health#broken#check
========================================================================
- ERROR: Failed to run healthcheck for "broken" plugin. Exception:
- function health#check[24]..health#broken#check, line 1
+ function health#check[20]..health#broken#check, line 1
caused an error
]])
end)
@@ -186,7 +186,7 @@ describe('health.vim', function()
test_plug.submodule_failed: require("test_plug.submodule_failed.health").check()
========================================================================
- ERROR: Failed to run healthcheck for "test_plug.submodule_failed" plugin. Exception:
- function health#check, line 24]])
+ function health#check, line 20]])
eq(expected, received)
end)
diff --git a/test/functional/plugin/lsp/incremental_sync_spec.lua b/test/functional/plugin/lsp/incremental_sync_spec.lua
index 5dd34e7665..4e3eddb960 100644
--- a/test/functional/plugin/lsp/incremental_sync_spec.lua
+++ b/test/functional/plugin/lsp/incremental_sync_spec.lua
@@ -164,6 +164,201 @@ describe('incremental synchronization', function()
}
test_edit({"a"}, {"rb"}, expected_text_changes, 'utf-16', '\n')
end)
+ it('deleting a line', function()
+ local expected_text_changes = {
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 0
+ },
+ ['end'] = {
+ character = 0,
+ line = 1
+ }
+ },
+ rangeLength = 12,
+ text = ''
+ }
+ }
+ test_edit({"hello world"}, {"dd"}, expected_text_changes, 'utf-16', '\n')
+ end)
+ it('deleting an empty line', function()
+ local expected_text_changes = {
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 1
+ },
+ ['end'] = {
+ character = 0,
+ line = 2
+ }
+ },
+ rangeLength = 1,
+ text = ''
+ }
+ }
+ test_edit({"hello world", ""}, {"jdd"}, expected_text_changes, 'utf-16', '\n')
+ end)
+ it('adding a line', function()
+ local expected_text_changes = {
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 1
+ },
+ ['end'] = {
+ character = 0,
+ line = 1
+ }
+ },
+ rangeLength = 0,
+ text = 'hello world\n'
+ }
+ }
+ test_edit({"hello world"}, {"yyp"}, expected_text_changes, 'utf-16', '\n')
+ end)
+ it('adding an empty line', function()
+ local expected_text_changes = {
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 1
+ },
+ ['end'] = {
+ character = 0,
+ line = 1
+ }
+ },
+ rangeLength = 0,
+ text = '\n'
+ }
+ }
+ test_edit({"hello world"}, {"o"}, expected_text_changes, 'utf-16', '\n')
+ end)
+ end)
+ describe('multi line edit', function()
+ it('deletion and insertion', function()
+ local expected_text_changes = {
+ -- delete "_fsda" from end of line 1
+ {
+ range = {
+ ['start'] = {
+ character = 4,
+ line = 1
+ },
+ ['end'] = {
+ character = 9,
+ line = 1
+ }
+ },
+ rangeLength = 5,
+ text = ''
+ },
+ -- delete "hello world\n" from line 2
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 2
+ },
+ ['end'] = {
+ character = 0,
+ line = 3
+ }
+ },
+ rangeLength = 12,
+ text = ''
+ },
+ -- delete "1234" from beginning of line 2
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 2
+ },
+ ['end'] = {
+ character = 4,
+ line = 2
+ }
+ },
+ rangeLength = 4,
+ text = ''
+ },
+ -- add " asdf" to end of line 1
+ {
+ range = {
+ ['start'] = {
+ character = 4,
+ line = 1
+ },
+ ['end'] = {
+ character = 4,
+ line = 1
+ }
+ },
+ rangeLength = 0,
+ text = ' asdf'
+ },
+ -- delete " asdf\n" from line 2
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 2
+ },
+ ['end'] = {
+ character = 0,
+ line = 3
+ }
+ },
+ rangeLength = 6,
+ text = ''
+ },
+ -- undo entire deletion
+ {
+ range = {
+ ['start'] = {
+ character = 4,
+ line = 1
+ },
+ ['end'] = {
+ character = 9,
+ line = 1
+ }
+ },
+ rangeLength = 5,
+ text = "_fdsa\nhello world\n1234 asdf"
+ },
+ -- redo entire deletion
+ {
+ range = {
+ ['start'] = {
+ character = 4,
+ line = 1
+ },
+ ['end'] = {
+ character = 9,
+ line = 3
+ }
+ },
+ rangeLength = 27,
+ text = ' asdf'
+ },
+ }
+ local original_lines = {
+ "\\begin{document}",
+ "test_fdsa",
+ "hello world",
+ "1234 asdf",
+ "\\end{document}"
+ }
+ test_edit(original_lines, {"jf_vejjbhhdu<C-R>"}, expected_text_changes, 'utf-16', '\n')
+ end)
end)
describe('multi-operation edits', function()
@@ -297,6 +492,80 @@ describe('incremental synchronization', function()
}
test_edit({"🔥"}, {"x"}, expected_text_changes, 'utf-16', '\n')
end)
+ it('replacing a multibyte character with matching prefix', function()
+ local expected_text_changes = {
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 1
+ },
+ ['end'] = {
+ character = 1,
+ line = 1
+ }
+ },
+ rangeLength = 1,
+ text = '⟩'
+ }
+ }
+ -- ⟨ is e29fa8, ⟩ is e29fa9
+ local original_lines = {
+ "\\begin{document}",
+ "⟨",
+ "\\end{document}",
+ }
+ test_edit(original_lines, {"jr⟩"}, expected_text_changes, 'utf-16', '\n')
+ end)
+ it('replacing a multibyte character with matching suffix', function()
+ local expected_text_changes = {
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 1
+ },
+ ['end'] = {
+ character = 1,
+ line = 1
+ }
+ },
+ rangeLength = 1,
+ text = 'ḟ'
+ }
+ }
+ -- ฟ is e0b89f, ḟ is e1b89f
+ local original_lines = {
+ "\\begin{document}",
+ "ฟ",
+ "\\end{document}",
+ }
+ test_edit(original_lines, {"jrḟ"}, expected_text_changes, 'utf-16', '\n')
+ end)
+ it('inserting before a multibyte character', function()
+ local expected_text_changes = {
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 1
+ },
+ ['end'] = {
+ character = 0,
+ line = 1
+ }
+ },
+ rangeLength = 0,
+ text = ' '
+ }
+ }
+ local original_lines = {
+ "\\begin{document}",
+ "→",
+ "\\end{document}",
+ }
+ test_edit(original_lines, {"ji "}, expected_text_changes, 'utf-16', '\n')
+ end)
it('deleting a multibyte character from a long line', function()
local expected_text_changes = {
{
diff --git a/test/functional/plugin/lsp_spec.lua b/test/functional/plugin/lsp_spec.lua
index b12d4227d5..eab520948f 100644
--- a/test/functional/plugin/lsp_spec.lua
+++ b/test/functional/plugin/lsp_spec.lua
@@ -73,8 +73,11 @@ local function fake_lsp_server_setup(test_name, timeout_ms, options)
on_init = function(client, result)
TEST_RPC_CLIENT = client
vim.rpcrequest(1, "init", result)
- client.config.flags.allow_incremental_sync = options.allow_incremental_sync or false
end;
+ flags = {
+ allow_incremental_sync = options.allow_incremental_sync or false;
+ debounce_text_changes = options.debounce_text_changes or 0;
+ };
on_exit = function(...)
vim.rpcnotify(1, "exit", ...)
end;
@@ -301,6 +304,43 @@ describe('LSP', function()
}
end)
+ it('should detach buffer in response to nvim_buf_detach', function()
+ local expected_handlers = {
+ {NIL, {}, {method="shutdown", client_id=1}};
+ {NIL, {}, {method="finish", client_id=1}};
+ }
+ local client
+ test_rpc_server {
+ test_name = "basic_finish";
+ on_setup = function()
+ exec_lua [[
+ BUFFER = vim.api.nvim_create_buf(false, true)
+ ]]
+ eq(true, exec_lua("return lsp.buf_attach_client(BUFFER, TEST_RPC_CLIENT_ID)"))
+ eq(true, exec_lua("return lsp.buf_is_attached(BUFFER, TEST_RPC_CLIENT_ID)"))
+ exec_lua [[
+ vim.api.nvim_command(BUFFER.."bwipeout")
+ ]]
+ end;
+ on_init = function(_client)
+ client = _client
+ client.notify('finish')
+ end;
+ on_exit = function(code, signal)
+ eq(0, code, "exit code", fake_lsp_logfile)
+ eq(0, signal, "exit signal", fake_lsp_logfile)
+ end;
+ on_handler = function(err, result, ctx)
+ eq(table.remove(expected_handlers), {err, result, ctx}, "expected handler")
+ if ctx.method == 'finish' then
+ exec_lua("return lsp.buf_detach_client(BUFFER, TEST_RPC_CLIENT_ID)")
+ eq(false, exec_lua("return lsp.buf_is_attached(BUFFER, TEST_RPC_CLIENT_ID)"))
+ client.stop()
+ end
+ end;
+ }
+ end)
+
it('client should return settings via workspace/configuration handler', function()
local expected_handlers = {
{NIL, {}, {method="shutdown", client_id=1}};
@@ -889,7 +929,60 @@ describe('LSP', function()
local client
test_rpc_server {
test_name = "basic_check_buffer_open_and_change_incremental";
- options = { allow_incremental_sync = true };
+ options = {
+ allow_incremental_sync = true,
+ };
+ on_setup = function()
+ exec_lua [[
+ BUFFER = vim.api.nvim_create_buf(false, true)
+ vim.api.nvim_buf_set_lines(BUFFER, 0, -1, false, {
+ "testing";
+ "123";
+ })
+ ]]
+ end;
+ on_init = function(_client)
+ client = _client
+ local sync_kind = exec_lua("return require'vim.lsp.protocol'.TextDocumentSyncKind.Incremental")
+ eq(sync_kind, client.resolved_capabilities().text_document_did_change)
+ eq(true, client.resolved_capabilities().text_document_open_close)
+ exec_lua [[
+ assert(lsp.buf_attach_client(BUFFER, TEST_RPC_CLIENT_ID))
+ ]]
+ end;
+ on_exit = function(code, signal)
+ eq(0, code, "exit code", fake_lsp_logfile)
+ eq(0, signal, "exit signal", fake_lsp_logfile)
+ end;
+ on_handler = function(err, result, ctx)
+ if ctx.method == 'start' then
+ exec_lua [[
+ vim.api.nvim_buf_set_lines(BUFFER, 1, 2, false, {
+ "123boop";
+ })
+ ]]
+ client.notify('finish')
+ end
+ eq(table.remove(expected_handlers), {err, result, ctx}, "expected handler")
+ if ctx.method == 'finish' then
+ client.stop()
+ end
+ end;
+ }
+ end)
+ it('should check the body and didChange incremental with debounce', function()
+ local expected_handlers = {
+ {NIL, {}, {method="shutdown", client_id=1}};
+ {NIL, {}, {method="finish", client_id=1}};
+ {NIL, {}, {method="start", client_id=1}};
+ }
+ local client
+ test_rpc_server {
+ test_name = "basic_check_buffer_open_and_change_incremental";
+ options = {
+ allow_incremental_sync = true,
+ debounce_text_changes = 5
+ };
on_setup = function()
exec_lua [[
BUFFER = vim.api.nvim_create_buf(false, true)
@@ -1198,7 +1291,7 @@ describe('LSP', function()
make_edit(2, 0, 2, 2, {"3"});
make_edit(3, 2, 3, 4, {""});
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'123First line of text';
'2econd line of text';
@@ -1218,7 +1311,7 @@ describe('LSP', function()
make_edit(3, #'', 3, #"Fourth", {"another line of text", "before this"});
make_edit(3, #'Fourth', 3, #"Fourth line of text", {"!"});
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'';
'123';
@@ -1242,7 +1335,7 @@ describe('LSP', function()
make_edit(3, #"Fourth", 3, #'', {"another line of text", "before this"});
make_edit(3, #"Fourth line of text", 3, #'Fourth', {"!"});
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'';
'123';
@@ -1259,7 +1352,7 @@ describe('LSP', function()
local edits = {
make_edit(4, 3, 4, 4, {"ä"});
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'First line of text';
'Second line of text';
@@ -1272,7 +1365,7 @@ describe('LSP', function()
local edits = {
make_edit(5, 0, 5, 0, "foobar");
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'First line of text';
'Second line of text';
@@ -1282,6 +1375,20 @@ describe('LSP', function()
'foobar';
}, buf_lines(1))
end)
+ it('applies multiple text edits at the end of the document', function()
+ local edits = {
+ make_edit(4, 0, 5, 0, "");
+ make_edit(5, 0, 5, 0, "foobar");
+ }
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
+ eq({
+ 'First line of text';
+ 'Second line of text';
+ 'Third line of text';
+ 'Fourth line of text';
+ 'foobar';
+ }, buf_lines(1))
+ end)
describe('cursor position', function()
it('don\'t fix the cursor if the range contains the cursor', function()
@@ -1289,7 +1396,7 @@ describe('LSP', function()
local edits = {
make_edit(1, 0, 1, 19, 'Second line of text')
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'First line of text';
'Second line of text';
@@ -1306,7 +1413,7 @@ describe('LSP', function()
make_edit(1, 0, 1, 6, ''),
make_edit(1, 6, 1, 19, '')
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'First line of text';
'';
@@ -1323,7 +1430,7 @@ describe('LSP', function()
make_edit(1, 0, 1, 6, ''),
make_edit(0, 18, 5, 0, '')
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'First line of text';
}, buf_lines(1))
@@ -1335,7 +1442,7 @@ describe('LSP', function()
local edits = {
make_edit(1, 0, 2, 0, '')
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'First line of text';
'Third line of text';
@@ -1350,7 +1457,7 @@ describe('LSP', function()
local edits = {
make_edit(1, 7, 1, 11, '')
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'First line of text';
'Second of text';
@@ -1366,7 +1473,7 @@ describe('LSP', function()
local edits = {
make_edit(0, 11, 1, 12, '')
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({
'First line of text';
'Third line of text';
@@ -1382,21 +1489,21 @@ describe('LSP', function()
local edits = {
make_edit(0, 0, 5, 0, {"All replaced"});
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({'All replaced'}, buf_lines(1))
end)
it('applies edits when the end line is 2 larger than vim\'s', function()
local edits = {
make_edit(0, 0, 6, 0, {"All replaced"});
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({'All replaced'}, buf_lines(1))
end)
it('applies edits with a column offset', function()
local edits = {
make_edit(0, 0, 5, 2, {"All replaced"});
}
- exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1)
+ exec_lua('vim.lsp.util.apply_text_edits(...)', edits, 1, "utf-16")
eq({'All replaced'}, buf_lines(1))
end)
end)
@@ -1424,7 +1531,7 @@ describe('LSP', function()
]]
end)
it('correctly goes ahead with the edit if all is normal', function()
- exec_lua('vim.lsp.util.apply_text_document_edit(...)', text_document_edit(5))
+ exec_lua("vim.lsp.util.apply_text_document_edit(..., nil, 'utf-16')", text_document_edit(5))
eq({
'First ↥ 🤦 🦄 line of text';
'2nd line of 语text';
@@ -1436,7 +1543,7 @@ describe('LSP', function()
local bufnr = select(1, ...)
local text_edit = select(2, ...)
vim.lsp.util.buf_versions[bufnr] = 10
- vim.lsp.util.apply_text_document_edit(text_edit)
+ vim.lsp.util.apply_text_document_edit(text_edit, nil, 'utf-16')
]], target_bufnr, text_document_edit(0))
eq({
'First ↥ 🤦 🦄 line of text';
@@ -1449,7 +1556,7 @@ describe('LSP', function()
local args = {...}
local versionedBuf = args[2]
vim.lsp.util.buf_versions[versionedBuf.bufnr] = versionedBuf.currentVersion
- vim.lsp.util.apply_text_document_edit(args[1])
+ vim.lsp.util.apply_text_document_edit(args[1], nil, 'utf-16')
]], edit, versionedBuf)
end
@@ -1475,17 +1582,36 @@ describe('LSP', function()
describe('workspace_apply_edit', function()
it('workspace/applyEdit returns ApplyWorkspaceEditResponse', function()
- local expected = {
- applied = true;
- failureReason = nil;
+ local expected_handlers = {
+ {NIL, {}, {method="test", client_id=1}};
+ }
+ test_rpc_server {
+ test_name = "basic_init";
+ on_init = function(client, _)
+ client.stop()
+ end;
+ -- If the program timed out, then code will be nil.
+ on_exit = function(code, signal)
+ eq(0, code, "exit code", fake_lsp_logfile)
+ eq(0, signal, "exit signal", fake_lsp_logfile)
+ end;
+ -- Note that NIL must be used here.
+ -- on_handler(err, method, result, client_id)
+ on_handler = function(...)
+ local expected = {
+ applied = true;
+ failureReason = nil;
+ }
+ eq(expected, exec_lua [[
+ local apply_edit = {
+ label = nil;
+ edit = {};
+ }
+ return vim.lsp.handlers['workspace/applyEdit'](nil, apply_edit, {client_id = TEST_RPC_CLIENT_ID})
+ ]])
+ eq(table.remove(expected_handlers), {...})
+ end;
}
- eq(expected, exec_lua [[
- local apply_edit = {
- label = nil;
- edit = {};
- }
- return vim.lsp.handlers['workspace/applyEdit'](nil, apply_edit)
- ]])
end)
end)
@@ -1559,7 +1685,7 @@ describe('LSP', function()
local workspace_edits = args[1]
local target_bufnr = args[2]
- vim.lsp.util.apply_workspace_edit(workspace_edits)
+ vim.lsp.util.apply_workspace_edit(workspace_edits, 'utf-16')
return vim.api.nvim_buf_get_lines(target_bufnr, 0, -1, false)
]], make_workspace_edit(edits), target_bufnr))
@@ -1581,7 +1707,7 @@ describe('LSP', function()
local workspace_edits = args[1]
local target_bufnr = args[2]
- vim.lsp.util.apply_workspace_edit(workspace_edits)
+ vim.lsp.util.apply_workspace_edit(workspace_edits, 'utf-16')
return vim.api.nvim_buf_get_lines(target_bufnr, 0, -1, false)
]], make_workspace_edit(edits), target_bufnr))
@@ -1598,7 +1724,7 @@ describe('LSP', function()
},
}
}
- exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit)
+ exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16')
eq(true, exec_lua('return vim.loop.fs_stat(...) ~= nil', tmpfile))
end)
it('createFile does not touch file if it exists and ignoreIfExists is set', function()
@@ -1616,7 +1742,7 @@ describe('LSP', function()
},
}
}
- exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit)
+ exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16')
eq(true, exec_lua('return vim.loop.fs_stat(...) ~= nil', tmpfile))
eq('Dummy content', read_file(tmpfile))
end)
@@ -1636,7 +1762,7 @@ describe('LSP', function()
},
}
}
- exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit)
+ exec_lua('vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16')
eq(true, exec_lua('return vim.loop.fs_stat(...) ~= nil', tmpfile))
eq('', read_file(tmpfile))
end)
@@ -1657,7 +1783,7 @@ describe('LSP', function()
}
}
}
- eq(true, pcall(exec_lua, 'vim.lsp.util.apply_workspace_edit(...)', edit))
+ eq(true, pcall(exec_lua, 'vim.lsp.util.apply_workspace_edit(...)', edit, 'utf-16'))
eq(false, exec_lua('return vim.loop.fs_stat(...) ~= nil', tmpfile))
eq(false, exec_lua('return vim.api.nvim_buf_is_loaded(vim.fn.bufadd(...))', tmpfile))
end)
@@ -1818,7 +1944,7 @@ describe('LSP', function()
}
},
}
- return vim.lsp.util.locations_to_items(locations)
+ return vim.lsp.util.locations_to_items(locations, 'utf-16')
]]
eq(expected, actual)
end)
@@ -1848,7 +1974,7 @@ describe('LSP', function()
}
},
}
- return vim.lsp.util.locations_to_items(locations)
+ return vim.lsp.util.locations_to_items(locations, 'utf-16')
]]
eq(expected, actual)
end)
@@ -2152,7 +2278,7 @@ describe('LSP', function()
end
local jump = function(msg)
- eq(true, exec_lua('return vim.lsp.util.jump_to_location(...)', msg))
+ eq(true, exec_lua('return vim.lsp.util.jump_to_location(...)', msg, "utf-16"))
eq(target_bufnr, exec_lua[[return vim.fn.bufnr('%')]])
return {
line = exec_lua[[return vim.fn.line('.')]],
@@ -2226,6 +2352,27 @@ describe('LSP', function()
end)
end)
+ describe('lsp.util.convert_signature_help_to_markdown_lines', function()
+ it('can handle negative activeSignature', function()
+ local result = exec_lua[[
+ local signature_help = {
+ activeParameter = 0,
+ activeSignature = -1,
+ signatures = {
+ {
+ documentation = "",
+ label = "TestEntity.TestEntity()",
+ parameters = {}
+ },
+ }
+ }
+ return vim.lsp.util.convert_signature_help_to_markdown_lines(signature_help, 'cs', {','})
+ ]]
+ local expected = {'```cs', 'TestEntity.TestEntity()', '```', ''}
+ eq(expected, result)
+ end)
+ end)
+
describe('lsp.util.get_effective_tabstop', function()
local function test_tabstop(tabsize, softtabstop)
exec_lua(string.format([[
diff --git a/test/functional/terminal/buffer_spec.lua b/test/functional/terminal/buffer_spec.lua
index f25cfa2039..beb43e0271 100644
--- a/test/functional/terminal/buffer_spec.lua
+++ b/test/functional/terminal/buffer_spec.lua
@@ -292,10 +292,9 @@ describe(':terminal buffer', function()
command('quit')
end)
- it('does not segfault when pasting empty buffer #13955', function()
- feed_command('terminal')
+ it('does not segfault when pasting empty register #13955', function()
feed('<c-\\><c-n>')
- feed_command('put a') -- buffer a is empty
+ feed_command('put a') -- register a is empty
helpers.assert_alive()
end)
end)
@@ -350,7 +349,7 @@ describe('on_lines does not emit out-of-bounds line indexes when', function()
end)
it('creating a terminal buffer #16394', function()
- feed_command([[autocmd TermOpen * ++once call v:lua.register_callback(expand("<abuf>"))]])
+ feed_command('autocmd TermOpen * ++once call v:lua.register_callback(str2nr(expand("<abuf>")))')
feed_command('terminal')
sleep(500)
eq('', exec_lua([[return _G.cb_error]]))
diff --git a/test/functional/terminal/channel_spec.lua b/test/functional/terminal/channel_spec.lua
index 7d37dcccc8..7223f5ba61 100644
--- a/test/functional/terminal/channel_spec.lua
+++ b/test/functional/terminal/channel_spec.lua
@@ -2,7 +2,7 @@ local helpers = require('test.functional.helpers')(after_each)
local clear = helpers.clear
local eq = helpers.eq
local command = helpers.command
-local exc_exec = helpers.exc_exec
+local pcall_err = helpers.pcall_err
local feed = helpers.feed
local sleep = helpers.sleep
local poke_eventloop = helpers.poke_eventloop
@@ -13,24 +13,22 @@ describe('associated channel is closed and later freed for terminal', function()
it('opened by nvim_open_term() and deleted by :bdelete!', function()
command([[let id = nvim_open_term(0, {})]])
-- channel hasn't been freed yet
- eq("Vim(call):Can't send data to closed stream", exc_exec([[bdelete! | call chansend(id, 'test')]]))
- -- process free_channel_event
- poke_eventloop()
- -- channel has been freed
- eq("Vim(call):E900: Invalid channel id", exc_exec([[call chansend(id, 'test')]]))
+ eq("Vim(call):Can't send data to closed stream", pcall_err(command, [[bdelete! | call chansend(id, 'test')]]))
+ -- channel has been freed after one main loop iteration
+ eq("Vim(call):E900: Invalid channel id", pcall_err(command, [[call chansend(id, 'test')]]))
end)
it('opened by termopen(), exited, and deleted by pressing a key', function()
command([[let id = termopen('echo')]])
sleep(500)
-- process has exited
- eq("Vim(call):Can't send data to closed stream", exc_exec([[call chansend(id, 'test')]]))
+ eq("Vim(call):Can't send data to closed stream", pcall_err(command, [[call chansend(id, 'test')]]))
-- delete terminal
feed('i<CR>')
- -- process term_delayed_free and free_channel_event
+ -- need to first process input
poke_eventloop()
- -- channel has been freed
- eq("Vim(call):E900: Invalid channel id", exc_exec([[call chansend(id, 'test')]]))
+ -- channel has been freed after another main loop iteration
+ eq("Vim(call):E900: Invalid channel id", pcall_err(command, [[call chansend(id, 'test')]]))
end)
-- This indirectly covers #16264
@@ -38,12 +36,10 @@ describe('associated channel is closed and later freed for terminal', function()
command([[let id = termopen('echo')]])
sleep(500)
-- process has exited
- eq("Vim(call):Can't send data to closed stream", exc_exec([[call chansend(id, 'test')]]))
+ eq("Vim(call):Can't send data to closed stream", pcall_err(command, [[call chansend(id, 'test')]]))
-- channel hasn't been freed yet
- eq("Vim(call):Can't send data to closed stream", exc_exec([[bdelete | call chansend(id, 'test')]]))
- -- process term_delayed_free and free_channel_event
- poke_eventloop()
- -- channel has been freed
- eq("Vim(call):E900: Invalid channel id", exc_exec([[call chansend(id, 'test')]]))
+ eq("Vim(call):Can't send data to closed stream", pcall_err(command, [[bdelete | call chansend(id, 'test')]]))
+ -- channel has been freed after one main loop iteration
+ eq("Vim(call):E900: Invalid channel id", pcall_err(command, [[call chansend(id, 'test')]]))
end)
end)
diff --git a/test/functional/terminal/mouse_spec.lua b/test/functional/terminal/mouse_spec.lua
index 3d8441b93c..6e2c851df7 100644
--- a/test/functional/terminal/mouse_spec.lua
+++ b/test/functional/terminal/mouse_spec.lua
@@ -1,7 +1,7 @@
local helpers = require('test.functional.helpers')(after_each)
local thelpers = require('test.functional.terminal.helpers')
local clear, eq, eval = helpers.clear, helpers.eq, helpers.eval
-local feed, nvim = helpers.feed, helpers.nvim
+local feed, nvim, command = helpers.feed, helpers.nvim, helpers.command
local feed_data = thelpers.feed_data
describe(':terminal mouse', function()
@@ -10,9 +10,9 @@ describe(':terminal mouse', function()
before_each(function()
clear()
nvim('set_option', 'statusline', '==========')
- nvim('command', 'highlight StatusLine cterm=NONE')
- nvim('command', 'highlight StatusLineNC cterm=NONE')
- nvim('command', 'highlight VertSplit cterm=NONE')
+ command('highlight StatusLine cterm=NONE')
+ command('highlight StatusLineNC cterm=NONE')
+ command('highlight VertSplit cterm=NONE')
screen = thelpers.screen_setup()
local lines = {}
for i = 1, 30 do
@@ -38,6 +38,26 @@ describe(':terminal mouse', function()
eq('nt', eval('mode(1)'))
end)
+ it('will exit focus and trigger Normal mode mapping on mouse click', function()
+ command('let g:got_leftmouse = 0')
+ command('nnoremap <LeftMouse> <Cmd>let g:got_leftmouse = 1<CR>')
+ eq('t', eval('mode(1)'))
+ eq(0, eval('g:got_leftmouse'))
+ feed('<LeftMouse>')
+ eq('nt', eval('mode(1)'))
+ eq(1, eval('g:got_leftmouse'))
+ end)
+
+ it('will exit focus and trigger Normal mode mapping on mouse click with modifier', function()
+ command('let g:got_ctrl_leftmouse = 0')
+ command('nnoremap <C-LeftMouse> <Cmd>let g:got_ctrl_leftmouse = 1<CR>')
+ eq('t', eval('mode(1)'))
+ eq(0, eval('g:got_ctrl_leftmouse'))
+ feed('<C-LeftMouse>')
+ eq('nt', eval('mode(1)'))
+ eq(1, eval('g:got_ctrl_leftmouse'))
+ end)
+
it('will exit focus on <C-\\> + mouse-scroll', function()
eq('t', eval('mode(1)'))
feed('<C-\\>')
@@ -45,6 +65,12 @@ describe(':terminal mouse', function()
eq('nt', eval('mode(1)'))
end)
+ it('does not leave terminal mode on left-release', function()
+ if helpers.pending_win32(pending) then return end
+ feed('<LeftRelease>')
+ eq('t', eval('mode(1)'))
+ end)
+
describe('with mouse events enabled by the program', function()
before_each(function()
thelpers.enable_mouse()
@@ -60,7 +86,7 @@ describe(':terminal mouse', function()
]])
end)
- it('will forward mouse clicks to the program', function()
+ it('will forward mouse press, drag and release to the program', function()
if helpers.pending_win32(pending) then return end
feed('<LeftMouse><1,2>')
screen:expect([[
@@ -72,6 +98,36 @@ describe(':terminal mouse', function()
"#{1: } |
{3:-- TERMINAL --} |
]])
+ feed('<LeftDrag><2,2>')
+ screen:expect([[
+ line27 |
+ line28 |
+ line29 |
+ line30 |
+ mouse enabled |
+ @##{1: } |
+ {3:-- TERMINAL --} |
+ ]])
+ feed('<LeftDrag><3,2>')
+ screen:expect([[
+ line27 |
+ line28 |
+ line29 |
+ line30 |
+ mouse enabled |
+ @$#{1: } |
+ {3:-- TERMINAL --} |
+ ]])
+ feed('<LeftRelease><3,2>')
+ screen:expect([[
+ line27 |
+ line28 |
+ line29 |
+ line30 |
+ mouse enabled |
+ #$#{1: } |
+ {3:-- TERMINAL --} |
+ ]])
end)
it('will forward mouse scroll to the program', function()
@@ -88,9 +144,63 @@ describe(':terminal mouse', function()
]])
end)
+ it('dragging and scrolling do not interfere with each other', function()
+ if helpers.pending_win32(pending) then return end
+ feed('<LeftMouse><1,2>')
+ screen:expect([[
+ line27 |
+ line28 |
+ line29 |
+ line30 |
+ mouse enabled |
+ "#{1: } |
+ {3:-- TERMINAL --} |
+ ]])
+ feed('<ScrollWheelUp><1,2>')
+ screen:expect([[
+ line27 |
+ line28 |
+ line29 |
+ line30 |
+ mouse enabled |
+ `"#{1: } |
+ {3:-- TERMINAL --} |
+ ]])
+ feed('<LeftDrag><2,2>')
+ screen:expect([[
+ line27 |
+ line28 |
+ line29 |
+ line30 |
+ mouse enabled |
+ @##{1: } |
+ {3:-- TERMINAL --} |
+ ]])
+ feed('<ScrollWheelUp><2,2>')
+ screen:expect([[
+ line27 |
+ line28 |
+ line29 |
+ line30 |
+ mouse enabled |
+ `##{1: } |
+ {3:-- TERMINAL --} |
+ ]])
+ feed('<LeftRelease><2,2>')
+ screen:expect([[
+ line27 |
+ line28 |
+ line29 |
+ line30 |
+ mouse enabled |
+ ###{1: } |
+ {3:-- TERMINAL --} |
+ ]])
+ end)
+
it('will forward mouse clicks to the program with the correct even if set nu', function()
if helpers.pending_win32(pending) then return end
- nvim('command', 'set number')
+ command('set number')
-- When the display area such as a number is clicked, it returns to the
-- normal mode.
feed('<LeftMouse><3,0>')
diff --git a/test/functional/terminal/tui_spec.lua b/test/functional/terminal/tui_spec.lua
index 7113cc1b49..faf44fa01d 100644
--- a/test/functional/terminal/tui_spec.lua
+++ b/test/functional/terminal/tui_spec.lua
@@ -582,16 +582,16 @@ describe('TUI', function()
it("paste: 'nomodifiable' buffer", function()
child_session:request('nvim_command', 'set nomodifiable')
child_session:request('nvim_exec_lua', [[
- -- Stack traces for this test are non-deterministic, so disable them
- _G.debug.traceback = function(msg) return msg end
+ -- Truncate the error message to hide the line number
+ _G.debug.traceback = function(msg) return msg:sub(-49) end
]], {})
feed_data('\027[200~fail 1\nfail 2\n\027[201~')
screen:expect{grid=[[
|
{4:~ }|
{5: }|
- {8:paste: Error executing lua: vim.lua:243: Vim:E21: }|
- {8:Cannot make changes, 'modifiable' is off} |
+ {8:paste: Error executing lua: Vim:E21: Cannot make c}|
+ {8:hanges, 'modifiable' is off} |
{10:Press ENTER or type command to continue}{1: } |
{3:-- TERMINAL --} |
]]}
diff --git a/test/functional/treesitter/parser_spec.lua b/test/functional/treesitter/parser_spec.lua
index 911fa017ab..44a7f00d8b 100644
--- a/test/functional/treesitter/parser_spec.lua
+++ b/test/functional/treesitter/parser_spec.lua
@@ -167,6 +167,27 @@ void ui_refresh(void)
eq('variable', ret)
end)
+ it("supports caching queries", function()
+ local long_query = query:rep(100)
+ local first_run = exec_lua ([[
+ local before = vim.loop.hrtime()
+ cquery = vim.treesitter.parse_query("c", ...)
+ local after = vim.loop.hrtime()
+ return after - before
+ ]], long_query)
+
+ local subsequent_runs = exec_lua ([[
+ local before = vim.loop.hrtime()
+ for i=1,100,1 do
+ cquery = vim.treesitter.parse_query("c", ...)
+ end
+ local after = vim.loop.hrtime()
+ return after - before
+ ]], long_query)
+
+ assert.True(1000 * subsequent_runs < first_run)
+ end)
+
it('support query and iter by capture', function()
insert(test_text)
diff --git a/test/functional/ui/bufhl_spec.lua b/test/functional/ui/bufhl_spec.lua
index 16ed3b9486..7716414e87 100644
--- a/test/functional/ui/bufhl_spec.lua
+++ b/test/functional/ui/bufhl_spec.lua
@@ -755,12 +755,24 @@ describe('Buffer highlighting', function()
-- TODO: only a virtual text from the same ns curretly overrides
-- an existing virtual text. We might add a prioritation system.
set_virtual_text(id1, 0, s1, {})
- eq({{1, 0, 0, { priority = 0, virt_text = s1}}}, get_extmarks(id1, {0,0}, {0, -1}, {details=true}))
+ eq({{1, 0, 0, {
+ priority = 0,
+ virt_text = s1,
+ -- other details
+ virt_text_pos = 'eol',
+ virt_text_hide = false,
+ }}}, get_extmarks(id1, {0,0}, {0, -1}, {details=true}))
-- TODO: is this really valid? shouldn't the max be line_count()-1?
local lastline = line_count()
set_virtual_text(id1, line_count(), s2, {})
- eq({{3, lastline, 0, { priority = 0, virt_text = s2}}}, get_extmarks(id1, {lastline,0}, {lastline, -1}, {details=true}))
+ eq({{3, lastline, 0, {
+ priority = 0,
+ virt_text = s2,
+ -- other details
+ virt_text_pos = 'eol',
+ virt_text_hide = false,
+ }}}, get_extmarks(id1, {lastline,0}, {lastline, -1}, {details=true}))
eq({}, get_extmarks(id1, {lastline+9000,0}, {lastline+9000, -1}, {}))
end)
diff --git a/test/functional/ui/input_spec.lua b/test/functional/ui/input_spec.lua
index ea8968a653..11718a6e18 100644
--- a/test/functional/ui/input_spec.lua
+++ b/test/functional/ui/input_spec.lua
@@ -114,11 +114,30 @@ describe('mappings', function()
end)
end)
-describe('input utf sequences that contain CSI/K_SPECIAL', function()
+describe('input utf sequences that contain K_SPECIAL (0x80)', function()
it('ok', function()
feed('i…<esc>')
expect('…')
end)
+
+ it('can be mapped', function()
+ command('inoremap … E280A6')
+ feed('i…<esc>')
+ expect('E280A6')
+ end)
+end)
+
+describe('input utf sequences that contain CSI (0x9B)', function()
+ it('ok', function()
+ feed('iě<esc>')
+ expect('ě')
+ end)
+
+ it('can be mapped', function()
+ command('inoremap ě C49B')
+ feed('iě<esc>')
+ expect('C49B')
+ end)
end)
describe('input non-printable chars', function()
diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua
index aeba049557..d7f43ca18c 100644
--- a/test/functional/ui/popupmenu_spec.lua
+++ b/test/functional/ui/popupmenu_spec.lua
@@ -10,6 +10,7 @@ local funcs = helpers.funcs
local get_pathsep = helpers.get_pathsep
local eq = helpers.eq
local pcall_err = helpers.pcall_err
+local exec_lua = helpers.exec_lua
describe('ui/ext_popupmenu', function()
local screen
@@ -369,6 +370,62 @@ describe('ui/ext_popupmenu', function()
{1:~ }|
{2:-- INSERT --} |
]])
+
+ command('iunmap <f1>')
+ command('iunmap <f2>')
+ command('iunmap <f3>')
+ exec_lua([[
+ vim.keymap.set('i', '<f1>', function() vim.api.nvim_select_popupmenu_item(2, true, false, {}) end)
+ vim.keymap.set('i', '<f2>', function() vim.api.nvim_select_popupmenu_item(-1, false, false, {}) end)
+ vim.keymap.set('i', '<f3>', function() vim.api.nvim_select_popupmenu_item(1, false, true, {}) end)
+ ]])
+ feed('<C-r>=TestComplete()<CR>')
+ screen:expect([[
+ |
+ foo^ |
+ {6:fo x the foo }{1: }|
+ {7:bar }{1: }|
+ {7:spam }{1: }|
+ {1:~ }|
+ {1:~ }|
+ {2:-- INSERT --} |
+ ]])
+
+ feed('<f1>')
+ screen:expect([[
+ |
+ spam^ |
+ {7:fo x the foo }{1: }|
+ {7:bar }{1: }|
+ {6:spam }{1: }|
+ {1:~ }|
+ {1:~ }|
+ {2:-- INSERT --} |
+ ]])
+
+ feed('<f2>')
+ screen:expect([[
+ |
+ spam^ |
+ {7:fo x the foo }{1: }|
+ {7:bar }{1: }|
+ {7:spam }{1: }|
+ {1:~ }|
+ {1:~ }|
+ {2:-- INSERT --} |
+ ]])
+
+ feed('<f3>')
+ screen:expect([[
+ |
+ bar^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {2:-- INSERT --} |
+ ]])
end)
local function source_complete_month()
@@ -2213,4 +2270,134 @@ describe('builtin popupmenu', function()
feed('<c-y>')
assert_alive()
end)
+
+ it('truncates double-width character correctly when there is no scrollbar', function()
+ screen:try_resize(32,8)
+ command('set completeopt+=menuone,noselect')
+ feed('i' .. string.rep(' ', 13))
+ funcs.complete(14, {'哦哦哦哦哦哦哦哦哦哦'})
+ screen:expect([[
+ ^ |
+ {1:~ }{n: 哦哦哦哦哦哦哦哦哦>}|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {2:-- INSERT --} |
+ ]])
+ end)
+
+ it('truncates double-width character correctly when there is scrollbar', function()
+ screen:try_resize(32,8)
+ command('set completeopt+=noselect')
+ command('set pumheight=4')
+ feed('i' .. string.rep(' ', 12))
+ local items = {}
+ for _ = 1, 8 do
+ table.insert(items, {word = '哦哦哦哦哦哦哦哦哦哦', equal = 1, dup = 1})
+ end
+ funcs.complete(13, items)
+ screen:expect([[
+ ^ |
+ {1:~ }{n: 哦哦哦哦哦哦哦哦哦>}{c: }|
+ {1:~ }{n: 哦哦哦哦哦哦哦哦哦>}{c: }|
+ {1:~ }{n: 哦哦哦哦哦哦哦哦哦>}{s: }|
+ {1:~ }{n: 哦哦哦哦哦哦哦哦哦>}{s: }|
+ {1:~ }|
+ {1:~ }|
+ {2:-- INSERT --} |
+ ]])
+ end)
+end)
+
+describe('builtin popupmenu with ui/ext_multigrid', function()
+ local screen
+ before_each(function()
+ clear()
+ screen = Screen.new(32, 20)
+ screen:attach({ext_multigrid=true})
+ screen:set_default_attr_ids({
+ -- popup selected item / scrollbar track
+ ['s'] = {background = Screen.colors.WebGray},
+ -- popup non-selected item
+ ['n'] = {background = Screen.colors.LightMagenta},
+ -- popup scrollbar knob
+ ['c'] = {background = Screen.colors.Grey0},
+ [1] = {bold = true, foreground = Screen.colors.Blue},
+ [2] = {bold = true},
+ [3] = {reverse = true},
+ [4] = {bold = true, reverse = true},
+ [5] = {bold = true, foreground = Screen.colors.SeaGreen},
+ [6] = {foreground = Screen.colors.Grey100, background = Screen.colors.Red},
+ })
+ end)
+
+ it('truncates double-width character correctly when there is no scrollbar', function()
+ screen:try_resize(32,8)
+ command('set completeopt+=menuone,noselect')
+ feed('i' .. string.rep(' ', 13))
+ funcs.complete(14, {'哦哦哦哦哦哦哦哦哦哦'})
+ screen:expect({grid=[[
+ ## grid 1
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [3:--------------------------------]|
+ ## grid 2
+ ^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ ## grid 3
+ {2:-- INSERT --} |
+ ## grid 4
+ {n: 哦哦哦哦哦哦哦哦哦>}|
+ ]], float_pos={[4] = {{id = -1}, 'NW', 2, 1, 12, false, 100}}})
+ end)
+
+ it('truncates double-width character correctly when there is scrollbar', function()
+ screen:try_resize(32,8)
+ command('set completeopt+=noselect')
+ command('set pumheight=4')
+ feed('i' .. string.rep(' ', 12))
+ local items = {}
+ for _ = 1, 8 do
+ table.insert(items, {word = '哦哦哦哦哦哦哦哦哦哦', equal = 1, dup = 1})
+ end
+ funcs.complete(13, items)
+ screen:expect({grid=[[
+ ## grid 1
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [2:--------------------------------]|
+ [3:--------------------------------]|
+ ## grid 2
+ ^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ ## grid 3
+ {2:-- INSERT --} |
+ ## grid 4
+ {n: 哦哦哦哦哦哦哦哦哦>}{c: }|
+ {n: 哦哦哦哦哦哦哦哦哦>}{c: }|
+ {n: 哦哦哦哦哦哦哦哦哦>}{s: }|
+ {n: 哦哦哦哦哦哦哦哦哦>}{s: }|
+ ]], float_pos={[4] = {{id = -1}, 'NW', 2, 1, 11, false, 100}}})
+ end)
end)
diff --git a/test/functional/vimscript/screenpos_spec.lua b/test/functional/vimscript/screenpos_spec.lua
new file mode 100644
index 0000000000..75e5c02298
--- /dev/null
+++ b/test/functional/vimscript/screenpos_spec.lua
@@ -0,0 +1,51 @@
+local helpers = require('test.functional.helpers')(after_each)
+local clear, eq, meths = helpers.clear, helpers.eq, helpers.meths
+local command, funcs = helpers.command, helpers.funcs
+
+before_each(clear)
+
+describe('screenpos() function', function()
+ it('works in floating window with border', function()
+ local bufnr = meths.create_buf(false, true)
+ local opts = {
+ relative='editor',
+ height=8,
+ width=12,
+ row=6,
+ col=8,
+ anchor='NW',
+ style='minimal',
+ border='none',
+ focusable=1
+ }
+ local float = meths.open_win(bufnr, false, opts)
+ command('redraw')
+ local pos = funcs.screenpos(bufnr, 1, 1)
+ eq(7, pos.row)
+ eq(9, pos.col)
+
+ -- only left border
+ opts.border = {'', '', '', '', '', '', '', '|'}
+ meths.win_set_config(float, opts)
+ command('redraw')
+ pos = funcs.screenpos(bufnr, 1, 1)
+ eq(7, pos.row)
+ eq(10, pos.col)
+
+ -- only top border
+ opts.border = {'', '_', '', '', '', '', '', ''}
+ meths.win_set_config(float, opts)
+ command('redraw')
+ pos = funcs.screenpos(bufnr, 1, 1)
+ eq(8, pos.row)
+ eq(9, pos.col)
+
+ -- both left and top border
+ opts.border = 'single'
+ meths.win_set_config(float, opts)
+ command('redraw')
+ pos = funcs.screenpos(bufnr, 1, 1)
+ eq(8, pos.row)
+ eq(10, pos.col)
+ end)
+end)
diff --git a/test/unit/charset/vim_str2nr_spec.lua b/test/unit/charset/vim_str2nr_spec.lua
index 5fc3b83a13..caf330c378 100644
--- a/test/unit/charset/vim_str2nr_spec.lua
+++ b/test/unit/charset/vim_str2nr_spec.lua
@@ -463,7 +463,7 @@ describe('vim_str2nr()', function()
test_vim_str2nr("1'2'3'4", flags, {len = 7, num = 1234, unum = 1234, pre = 0}, 0)
-- counter-intuitive, but like Vim, strict=true should partially accept
- -- these: (' and - are not alpha-numeric)
+ -- these: (' and - are not alphanumeric)
test_vim_str2nr("7''331", flags, {len = 1, num = 7, unum = 7, pre = 0}, 0)
test_vim_str2nr("123'x4", flags, {len = 3, num = 123, unum = 123, pre = 0}, 0)
test_vim_str2nr("1337'", flags, {len = 4, num = 1337, unum = 1337, pre = 0}, 0)
diff --git a/test/unit/garray_spec.lua b/test/unit/garray_spec.lua
index 28df8a6e3f..5d41dd39ec 100644
--- a/test/unit/garray_spec.lua
+++ b/test/unit/garray_spec.lua
@@ -18,7 +18,7 @@ local growsize = 95
-- constructing a class wrapper around garray. It could for example associate
-- ga_clear_strings to the underlying garray cdata if the garray is a string
-- array. But for now I estimate that that kind of magic might make testing
--- less "transparant" (i.e.: the interface would become quite different as to
+-- less "transparent" (i.e.: the interface would become quite different as to
-- how one would use it from C.
-- accessors
diff --git a/test/unit/marktree_spec.lua b/test/unit/marktree_spec.lua
index 10d02d2eb4..3c96bc5f58 100644
--- a/test/unit/marktree_spec.lua
+++ b/test/unit/marktree_spec.lua
@@ -32,11 +32,11 @@ local function shadoworder(tree, shadow, iter, giveorder)
local mark = lib.marktree_itr_current(iter)
local id = tonumber(mark.id)
local spos = shadow[id]
- if (mark.row ~= spos[1] or mark.col ~= spos[2]) then
- error("invalid pos for "..id..":("..mark.row..", "..mark.col..") instead of ("..spos[1]..", "..spos[2]..")")
+ if (mark.pos.row ~= spos[1] or mark.pos.col ~= spos[2]) then
+ error("invalid pos for "..id..":("..mark.pos.row..", "..mark.pos.col..") instead of ("..spos[1]..", "..spos[2]..")")
end
- if mark.right_gravity ~= spos[3] then
- error("invalid gravity for "..id..":("..mark.row..", "..mark.col..")")
+ if lib.mt_right_test(mark) ~= spos[3] then
+ error("invalid gravity for "..id..":("..mark.pos.row..", "..mark.pos.col..")")
end
if count > 0 then
if not pos_leq(last, spos) then
@@ -87,7 +87,21 @@ local function dosplice(tree, shadow, start, old_extent, new_extent)
shadowsplice(shadow, start, old_extent, new_extent)
end
+local last_id = nil
+
+local function put(tree, row, col, gravitate)
+ last_id = last_id + 1
+ local my_id = last_id
+
+ lib.marktree_put_test(tree, my_id, row, col, gravitate);
+ return my_id
+end
+
describe('marktree', function()
+ before_each(function()
+ last_id = 0
+ end)
+
itp('works', function()
local tree = ffi.new("MarkTree[1]") -- zero initialized by luajit
local shadow = {}
@@ -97,7 +111,7 @@ describe('marktree', function()
for i = 1,100 do
for j = 1,100 do
local gravitate = (i%2) > 0
- local id = tonumber(lib.marktree_put(tree, j, i, gravitate, 0))
+ local id = put(tree, j, i, gravitate)
ok(id > 0)
eq(nil, shadow[id])
shadow[id] = {j,i,gravitate}
@@ -115,12 +129,12 @@ describe('marktree', function()
eq({}, id2pos)
for i,ipos in pairs(shadow) do
- local pos = lib.marktree_lookup(tree, i, iter)
- eq(ipos[1], pos.row)
- eq(ipos[2], pos.col)
+ local p = lib.marktree_lookup_ns(tree, -1, i, false, iter)
+ eq(ipos[1], p.pos.row)
+ eq(ipos[2], p.pos.col)
local k = lib.marktree_itr_current(iter)
- eq(ipos[1], k.row)
- eq(ipos[2], k.col, ipos[1])
+ eq(ipos[1], k.pos.row)
+ eq(ipos[2], k.pos.col, ipos[1])
lib.marktree_itr_next(tree, iter)
-- TODO(bfredl): use id2pos to check neighbour?
-- local k2 = lib.marktree_itr_current(iter)
@@ -130,8 +144,8 @@ describe('marktree', function()
lib.marktree_itr_get(tree, ipos[1], ipos[2], iter)
local k = lib.marktree_itr_current(iter)
eq(i, tonumber(k.id))
- eq(ipos[1], k.row)
- eq(ipos[2], k.col)
+ eq(ipos[1], k.pos.row)
+ eq(ipos[2], k.pos.col)
end
ok(lib.marktree_itr_first(tree, iter))
@@ -146,8 +160,8 @@ describe('marktree', function()
lib.marktree_itr_get(tree, i, 50+ci, iter)
local k = lib.marktree_itr_current(iter)
local id = tonumber(k.id)
- eq(shadow[id][1], k.row)
- eq(shadow[id][2], k.col)
+ eq(shadow[id][1], k.pos.row)
+ eq(shadow[id][2], k.pos.col)
lib.marktree_del_itr(tree, iter, false)
shadow[id] = nil
end
@@ -191,7 +205,7 @@ describe('marktree', function()
-- https://github.com/neovim/neovim/pull/14719
lib.marktree_clear(tree)
for i = 1,20 do
- lib.marktree_put(tree, i, i, false, 0)
+ put(tree, i, i, false)
end
lib.marktree_itr_get(tree, 10, 10, iter)
diff --git a/test/unit/os/env_spec.lua b/test/unit/os/env_spec.lua
index e7cb5e5d5e..a0e02b6624 100644
--- a/test/unit/os/env_spec.lua
+++ b/test/unit/os/env_spec.lua
@@ -191,7 +191,7 @@ describe('env.c', function()
if ffi.abi('64bit') then
-- couldn't use a bigger number because it gets converted to
- -- double somewere, should be big enough anyway
+ -- double somewhere, should be big enough anyway
-- maxuint64 = ffi.new 'size_t', 18446744073709551615
local maxuint64 = ffi.new('size_t', 18446744073709000000)
eq(NULL, cimp.os_getenvname_at_index(maxuint64))
diff --git a/test/unit/os/fs_spec.lua b/test/unit/os/fs_spec.lua
index 7fd71cb1ae..0bb33772cd 100644
--- a/test/unit/os/fs_spec.lua
+++ b/test/unit/os/fs_spec.lua
@@ -1029,7 +1029,7 @@ describe('fs.c', function()
itp('returns the correct blocksize of a file', function()
local path = 'unit-test-directory/test.file'
-- there is a bug in luafilesystem where
- -- `lfs.attributes path, 'blksize'` returns the worng value:
+ -- `lfs.attributes path, 'blksize'` returns the wrong value:
-- https://github.com/keplerproject/luafilesystem/pull/44
-- using this workaround for now:
local blksize = lfs.attributes(path).blksize
@@ -1038,7 +1038,7 @@ describe('fs.c', function()
if blksize then
eq(blksize, fs.os_fileinfo_blocksize(info))
else
- -- luafs dosn't support blksize on windows
+ -- luafs doesn't support blksize on windows
-- libuv on windows returns a constant value as blocksize
-- checking for this constant value should be enough
eq(2048, fs.os_fileinfo_blocksize(info))
diff --git a/third-party/CMakeLists.txt b/third-party/CMakeLists.txt
index c5adf36908..cdca7c7b9c 100644
--- a/third-party/CMakeLists.txt
+++ b/third-party/CMakeLists.txt
@@ -151,8 +151,8 @@ set(MSGPACK_URL https://github.com/msgpack/msgpack-c/releases/download/cpp-3.0.0
set(MSGPACK_SHA256 bfbb71b7c02f806393bc3cbc491b40523b89e64f83860c58e3e54af47de176e4)
# https://github.com/LuaJIT/LuaJIT/tree/v2.1
-set(LUAJIT_URL https://github.com/LuaJIT/LuaJIT/archive/b4b2dce9fc3ffaaaede39b36d06415311e2aa516.tar.gz)
-set(LUAJIT_SHA256 6c9e46877db2df16ca0fa76db4043ed30a1ae60c89d9ba2c3e4d35eb2360cd4d)
+set(LUAJIT_URL https://github.com/LuaJIT/LuaJIT/archive/1d20f33d2905db55fb7191076bbac10f570f9175.tar.gz)
+set(LUAJIT_SHA256 4b6e2fc726ed8bf51fe461d90db9fffbc5c894bbdc862a67d17a70190f1fb07f)
set(LUA_URL https://www.lua.org/ftp/lua-5.1.5.tar.gz)
set(LUA_SHA256 2640fc56a795f29d28ef15e13c34a47e223960b0240e8cb0a82d9b0738695333)
@@ -203,8 +203,8 @@ set(LIBICONV_SHA256 ccf536620a45458d26ba83887a983b96827001e92a13847b45e4925cc891
set(TREESITTER_C_URL https://github.com/tree-sitter/tree-sitter-c/archive/v0.20.1.tar.gz)
set(TREESITTER_C_SHA256 ffcc2ef0eded59ad1acec9aec4f9b0c7dd209fc1a85d85f8b0e81298e3dddcc2)
-set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/25f64e1eb66bb1ab3eccd4f0b7da543005f3ba79.tar.gz)
-set(TREESITTER_SHA256 4f43bad474df494d00a779157f1c437638987d0e7896f9c73492cfeef35366b5)
+set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.3.tar.gz)
+set(TREESITTER_SHA256 ab52fe93e0c658cff656b9d10d67cdd29084247052964eba13ed6f0e9fa3bd36)
if(USE_BUNDLED_UNIBILIUM)
include(BuildUnibilium)
diff --git a/third-party/cmake/BuildLuajit.cmake b/third-party/cmake/BuildLuajit.cmake
index c4e5112dce..e02d7fe609 100644
--- a/third-party/cmake/BuildLuajit.cmake
+++ b/third-party/cmake/BuildLuajit.cmake
@@ -124,7 +124,9 @@ elseif(MINGW)
COMMAND ${CMAKE_COMMAND} -E copy ${DEPS_BUILD_DIR}/src/luajit/src/libluajit.a ${DEPS_INSTALL_DIR}/lib
COMMAND ${CMAKE_COMMAND} -E make_directory ${DEPS_INSTALL_DIR}/include/luajit-2.1
COMMAND ${CMAKE_COMMAND} -DFROM_GLOB=${DEPS_BUILD_DIR}/src/luajit/src/*.h -DTO=${DEPS_INSTALL_DIR}/include/luajit-2.1 -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/CopyFilesGlob.cmake
- )
+ COMMAND ${CMAKE_COMMAND} -E make_directory ${DEPS_INSTALL_DIR}/bin/lua/jit
+ COMMAND ${CMAKE_COMMAND} -E copy_directory ${DEPS_BUILD_DIR}/src/luajit/src/jit ${DEPS_INSTALL_DIR}/bin/lua/jit
+ )
elseif(MSVC)
BuildLuaJit(
@@ -138,8 +140,10 @@ elseif(MSVC)
# Luv searches for luajit.lib
COMMAND ${CMAKE_COMMAND} -E copy ${DEPS_BUILD_DIR}/src/luajit/src/lua51.lib ${DEPS_INSTALL_DIR}/lib/luajit.lib
COMMAND ${CMAKE_COMMAND} -E make_directory ${DEPS_INSTALL_DIR}/include/luajit-2.1
- COMMAND ${CMAKE_COMMAND} -DFROM_GLOB=${DEPS_BUILD_DIR}/src/luajit/src/*.h -DTO=${DEPS_INSTALL_DIR}/include/luajit-2.1 -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/CopyFilesGlob.cmake)
-
+ COMMAND ${CMAKE_COMMAND} -DFROM_GLOB=${DEPS_BUILD_DIR}/src/luajit/src/*.h -DTO=${DEPS_INSTALL_DIR}/include/luajit-2.1 -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/CopyFilesGlob.cmake
+ COMMAND ${CMAKE_COMMAND} -E make_directory ${DEPS_INSTALL_DIR}/bin/lua/jit
+ COMMAND ${CMAKE_COMMAND} -E copy_directory ${DEPS_BUILD_DIR}/src/luajit/src/jit ${DEPS_INSTALL_DIR}/bin/lua/jit
+ )
else()
message(FATAL_ERROR "Trying to build luajit in an unsupported system ${CMAKE_SYSTEM_NAME}/${CMAKE_C_COMPILER_ID}")
endif()