aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.builds/freebsd.yml14
-rw-r--r--.builds/openbsd.yml3
-rw-r--r--.clang-format28
-rw-r--r--.github/scripts/reviews.js9
-rw-r--r--.github/workflows/ci.yml74
-rwxr-xr-x.github/workflows/env.sh4
-rw-r--r--.github/workflows/notes.md42
-rw-r--r--.github/workflows/release.yml36
-rw-r--r--.gitignore1
-rw-r--r--CMakeLists.txt21
-rw-r--r--LICENSE.txt (renamed from LICENSE)0
-rw-r--r--README.md2
-rwxr-xr-xci/before_cache.sh4
-rw-r--r--ci/build.ps145
-rw-r--r--ci/common/suite.sh39
-rw-r--r--ci/common/test.sh29
-rwxr-xr-xci/run_lint.sh39
-rwxr-xr-xci/run_tests.sh42
-rw-r--r--contrib/flake.lock12
-rw-r--r--packaging/CMakeLists.txt78
-rw-r--r--packaging/logo.icnsbin0 -> 637562 bytes
-rw-r--r--packaging/logo.icobin0 -> 3518 bytes
-rw-r--r--packaging/logo.svg1
-rw-r--r--runtime/autoload/dist/ft.vim6
-rw-r--r--runtime/autoload/health/provider.vim24
-rw-r--r--runtime/autoload/provider/pythonx.vim4
-rw-r--r--runtime/compiler/jest.vim8
-rw-r--r--runtime/compiler/sml.vim8
-rw-r--r--runtime/doc/api.txt230
-rw-r--r--runtime/doc/arabic.txt2
-rw-r--r--runtime/doc/autocmd.txt22
-rw-r--r--runtime/doc/builtin.txt176
-rw-r--r--runtime/doc/change.txt14
-rw-r--r--runtime/doc/channel.txt4
-rw-r--r--runtime/doc/cmdline.txt4
-rw-r--r--runtime/doc/develop.txt2
-rw-r--r--runtime/doc/diagnostic.txt20
-rw-r--r--runtime/doc/diff.txt12
-rw-r--r--runtime/doc/editing.txt16
-rw-r--r--runtime/doc/eval.txt238
-rw-r--r--runtime/doc/filetype.txt3
-rw-r--r--runtime/doc/fold.txt2
-rw-r--r--runtime/doc/ft_raku.txt24
-rw-r--r--runtime/doc/ft_rust.txt4
-rw-r--r--runtime/doc/ft_sql.txt12
-rw-r--r--runtime/doc/if_pyth.txt2
-rw-r--r--runtime/doc/index.txt4
-rw-r--r--runtime/doc/insert.txt11
-rw-r--r--runtime/doc/lsp.txt84
-rw-r--r--runtime/doc/lua.txt84
-rw-r--r--runtime/doc/map.txt10
-rw-r--r--runtime/doc/motion.txt2
-rw-r--r--runtime/doc/options.txt56
-rw-r--r--runtime/doc/pattern.txt13
-rw-r--r--runtime/doc/pi_netrw.txt6
-rw-r--r--runtime/doc/print.txt6
-rw-r--r--runtime/doc/quickfix.txt60
-rw-r--r--runtime/doc/quickref.txt1
-rw-r--r--runtime/doc/remote.txt131
-rw-r--r--runtime/doc/repeat.txt22
-rw-r--r--runtime/doc/sign.txt2
-rw-r--r--runtime/doc/spell.txt4
-rw-r--r--runtime/doc/starting.txt2
-rw-r--r--runtime/doc/syntax.txt42
-rw-r--r--runtime/doc/tabpage.txt35
-rw-r--r--runtime/doc/tagsrch.txt2
-rw-r--r--runtime/doc/term.txt2
-rw-r--r--runtime/doc/tips.txt28
-rw-r--r--runtime/doc/treesitter.txt19
-rw-r--r--runtime/doc/uganda.txt11
-rw-r--r--runtime/doc/ui.txt36
-rw-r--r--runtime/doc/undo.txt4
-rw-r--r--runtime/doc/usr_04.txt8
-rw-r--r--runtime/doc/usr_05.txt2
-rw-r--r--runtime/doc/usr_07.txt4
-rw-r--r--runtime/doc/usr_08.txt2
-rw-r--r--runtime/doc/usr_10.txt4
-rw-r--r--runtime/doc/various.txt13
-rw-r--r--runtime/doc/vim_diff.txt8
-rw-r--r--runtime/doc/windows.txt16
-rw-r--r--runtime/filetype.lua33
-rw-r--r--runtime/filetype.vim7
-rw-r--r--runtime/ftplugin/ant.vim6
-rw-r--r--runtime/ftplugin/aspvbs.vim6
-rw-r--r--runtime/ftplugin/config.vim6
-rw-r--r--runtime/ftplugin/csc.vim6
-rw-r--r--runtime/ftplugin/csh.vim2
-rw-r--r--runtime/ftplugin/dtd.vim6
-rw-r--r--runtime/ftplugin/html.vim6
-rw-r--r--runtime/ftplugin/java.vim6
-rw-r--r--runtime/ftplugin/jsp.vim6
-rw-r--r--runtime/ftplugin/pascal.vim2
-rw-r--r--runtime/ftplugin/php.vim6
-rw-r--r--runtime/ftplugin/sgml.vim6
-rw-r--r--runtime/ftplugin/sh.vim6
-rw-r--r--runtime/ftplugin/svg.vim6
-rw-r--r--runtime/ftplugin/tcsh.vim2
-rw-r--r--runtime/ftplugin/xhtml.vim6
-rw-r--r--runtime/ftplugin/xml.vim2
-rw-r--r--runtime/ftplugin/xsd.vim6
-rw-r--r--runtime/ftplugin/xslt.vim6
-rw-r--r--runtime/indent/vim.vim20
-rw-r--r--runtime/lua/vim/_editor.lua (renamed from src/nvim/lua/vim.lua)286
-rw-r--r--runtime/lua/vim/_init_packages.lua83
-rw-r--r--runtime/lua/vim/diagnostic.lua5
-rw-r--r--runtime/lua/vim/filetype.lua6
-rw-r--r--runtime/lua/vim/highlight.lua105
-rw-r--r--runtime/lua/vim/keymap.lua10
-rw-r--r--runtime/lua/vim/lsp.lua2
-rw-r--r--runtime/lua/vim/lsp/diagnostic.lua6
-rw-r--r--runtime/lua/vim/lsp/handlers.lua4
-rw-r--r--runtime/lua/vim/lsp/sync.lua21
-rw-r--r--runtime/lua/vim/lsp/util.lua6
-rw-r--r--runtime/lua/vim/shared.lua10
-rw-r--r--runtime/menu.vim6
-rw-r--r--runtime/spell/cleanadd.vim32
-rw-r--r--runtime/syntax/structurizr.vim9
-rw-r--r--runtime/syntax/vim.vim20
-rwxr-xr-xscripts/gen_vimdoc.py89
-rwxr-xr-xscripts/stripdecls.py140
-rwxr-xr-xscripts/uncrustify.sh11
-rwxr-xr-xscripts/vim-patch.sh20
-rw-r--r--src/cjson/lua_cjson.c22
-rwxr-xr-xsrc/clint.py6
-rw-r--r--src/mpack/lmpack.c2
-rwxr-xr-x[-rw-r--r--]src/nvim/CMakeLists.txt31
-rw-r--r--src/nvim/api/autocmd.c776
-rw-r--r--src/nvim/api/autocmd.h11
-rw-r--r--src/nvim/api/buffer.c138
-rw-r--r--src/nvim/api/deprecated.c7
-rw-r--r--src/nvim/api/extmark.c57
-rw-r--r--src/nvim/api/keysets.lua38
-rw-r--r--src/nvim/api/private/converter.c19
-rw-r--r--src/nvim/api/private/dispatch.c28
-rw-r--r--src/nvim/api/private/helpers.c143
-rw-r--r--src/nvim/api/private/helpers.h19
-rw-r--r--src/nvim/api/tabpage.c6
-rw-r--r--src/nvim/api/ui_events.in.h4
-rw-r--r--src/nvim/api/vim.c90
-rw-r--r--src/nvim/api/vimscript.c7
-rw-r--r--src/nvim/api/win_config.c2
-rw-r--r--src/nvim/api/window.c3
-rw-r--r--src/nvim/aucmd.c123
-rw-r--r--src/nvim/aucmd.h11
-rw-r--r--src/nvim/autocmd.c1460
-rw-r--r--src/nvim/autocmd.h44
-rw-r--r--src/nvim/buffer.c579
-rw-r--r--src/nvim/buffer_defs.h19
-rw-r--r--src/nvim/change.c89
-rw-r--r--src/nvim/channel.c16
-rw-r--r--src/nvim/channel.h1
-rw-r--r--src/nvim/charset.c66
-rw-r--r--src/nvim/context.c3
-rw-r--r--src/nvim/cursor.c176
-rw-r--r--src/nvim/cursor_shape.c14
-rw-r--r--src/nvim/debugger.c32
-rw-r--r--src/nvim/decoration.c226
-rw-r--r--src/nvim/decoration.h35
-rw-r--r--src/nvim/decoration_provider.c231
-rw-r--r--src/nvim/decoration_provider.h26
-rw-r--r--src/nvim/diff.c169
-rw-r--r--src/nvim/digraph.c48
-rw-r--r--src/nvim/edit.c10
-rw-r--r--src/nvim/eval.c898
-rw-r--r--src/nvim/eval/funcs.c1103
-rw-r--r--src/nvim/eval/typval.c16
-rw-r--r--src/nvim/eval/typval.h3
-rw-r--r--src/nvim/eval/userfunc.c9
-rw-r--r--src/nvim/event/rstream.c2
-rw-r--r--src/nvim/event/socket.c13
-rw-r--r--src/nvim/ex_cmds.c209
-rw-r--r--src/nvim/ex_cmds2.c150
-rw-r--r--src/nvim/ex_cmds_defs.h30
-rw-r--r--src/nvim/ex_docmd.c74
-rw-r--r--src/nvim/ex_docmd.h2
-rw-r--r--src/nvim/ex_eval.c319
-rw-r--r--src/nvim/ex_getln.c12
-rw-r--r--src/nvim/ex_session.c4
-rw-r--r--src/nvim/extmark.c13
-rw-r--r--src/nvim/extmark.h2
-rw-r--r--src/nvim/fileio.c13
-rw-r--r--src/nvim/fold.c402
-rw-r--r--src/nvim/generators/c_grammar.lua1
-rwxr-xr-x[-rw-r--r--]src/nvim/generators/gen_api_ui_events.lua74
-rw-r--r--src/nvim/generators/gen_char_blob.lua20
-rw-r--r--src/nvim/getchar.c72
-rw-r--r--src/nvim/globals.h28
-rw-r--r--src/nvim/hardcopy.c46
-rw-r--r--src/nvim/hardcopy.h3
-rw-r--r--src/nvim/highlight.c53
-rw-r--r--src/nvim/highlight_defs.h10
-rw-r--r--src/nvim/indent.c13
-rw-r--r--src/nvim/input.c2
-rw-r--r--src/nvim/lua/converter.c63
-rw-r--r--src/nvim/lua/executor.c611
-rw-r--r--src/nvim/lua/executor.h25
-rw-r--r--src/nvim/lua/spell.c8
-rw-r--r--src/nvim/lua/stdlib.c90
-rw-r--r--src/nvim/lua/xdiff.c1
-rw-r--r--src/nvim/main.c157
-rw-r--r--src/nvim/main.h2
-rw-r--r--src/nvim/map.c3
-rw-r--r--src/nvim/map.h4
-rw-r--r--src/nvim/mark.c2
-rw-r--r--src/nvim/marktree.c8
-rw-r--r--src/nvim/marktree.h9
-rw-r--r--src/nvim/mbyte.c6
-rw-r--r--src/nvim/memline.c4
-rw-r--r--src/nvim/memory.c2
-rw-r--r--src/nvim/message.c323
-rw-r--r--src/nvim/mouse.c16
-rw-r--r--src/nvim/msgpack_rpc/channel.c3
-rw-r--r--src/nvim/normal.c19
-rw-r--r--src/nvim/ops.c104
-rw-r--r--src/nvim/option.c83
-rw-r--r--src/nvim/os/env.c4
-rw-r--r--src/nvim/os/fs.c34
-rw-r--r--src/nvim/os/os_defs.h2
-rw-r--r--src/nvim/os/pty_process_unix.c23
-rw-r--r--src/nvim/os/pty_process_win.c7
-rw-r--r--src/nvim/os/shell.c6
-rw-r--r--src/nvim/path.c3
-rw-r--r--src/nvim/popupmnu.c7
-rw-r--r--src/nvim/quickfix.c182
-rw-r--r--src/nvim/rbuffer.h14
-rw-r--r--src/nvim/regexp.c5524
-rw-r--r--src/nvim/regexp.h1
-rw-r--r--src/nvim/regexp_bt.c4955
-rw-r--r--src/nvim/runtime.c58
-rw-r--r--src/nvim/screen.c634
-rw-r--r--src/nvim/screen.h18
-rw-r--r--src/nvim/search.c10
-rw-r--r--src/nvim/shada.c4
-rw-r--r--src/nvim/sign.c18
-rw-r--r--src/nvim/sign_defs.h1
-rw-r--r--src/nvim/spell.c2
-rw-r--r--src/nvim/strings.c2
-rw-r--r--src/nvim/syntax.c17
-rw-r--r--src/nvim/syntax_defs.h16
-rw-r--r--src/nvim/tag.h10
-rw-r--r--src/nvim/terminal.c10
-rw-r--r--src/nvim/testdir/check.vim8
-rwxr-xr-xsrc/nvim/testdir/runnvim.sh10
-rw-r--r--src/nvim/testdir/test_alot.vim38
-rw-r--r--src/nvim/testdir/test_autochdir.vim71
-rw-r--r--src/nvim/testdir/test_autocmd.vim6
-rw-r--r--src/nvim/testdir/test_breakindent.vim2
-rw-r--r--src/nvim/testdir/test_cindent.vim9
-rw-r--r--src/nvim/testdir/test_cmdline.vim12
-rw-r--r--src/nvim/testdir/test_delete.vim114
-rw-r--r--src/nvim/testdir/test_diffmode.vim26
-rw-r--r--src/nvim/testdir/test_digraph.vim4
-rw-r--r--src/nvim/testdir/test_edit.vim2
-rw-r--r--src/nvim/testdir/test_exit.vim22
-rw-r--r--src/nvim/testdir/test_file_perm.vim30
-rw-r--r--src/nvim/testdir/test_filetype.vim42
-rw-r--r--src/nvim/testdir/test_functions.vim73
-rw-r--r--src/nvim/testdir/test_highlight.vim4
-rw-r--r--src/nvim/testdir/test_mapping.vim108
-rw-r--r--src/nvim/testdir/test_mksession.vim5
-rw-r--r--src/nvim/testdir/test_normal.vim8
-rw-r--r--src/nvim/testdir/test_profile.vim31
-rw-r--r--src/nvim/testdir/test_quickfix.vim147
-rw-r--r--src/nvim/testdir/test_regexp_latin.vim16
-rw-r--r--src/nvim/testdir/test_regexp_utf8.vim12
-rw-r--r--src/nvim/testdir/test_registers.vim163
-rw-r--r--src/nvim/testdir/test_searchpos.vim30
-rw-r--r--src/nvim/testdir/test_set.vim29
-rw-r--r--src/nvim/testdir/test_sort.vim1
-rw-r--r--src/nvim/testdir/test_stat.vim2
-rw-r--r--src/nvim/testdir/test_suspend.vim4
-rw-r--r--src/nvim/testdir/test_system.vim26
-rw-r--r--src/nvim/testdir/test_tabline.vim11
-rw-r--r--src/nvim/testdir/test_tabpage.vim71
-rw-r--r--src/nvim/testdir/test_usercommands.vim20
-rw-r--r--src/nvim/testdir/test_vimscript.vim5
-rw-r--r--src/nvim/tui/input.c30
-rw-r--r--src/nvim/tui/tui.c39
-rw-r--r--src/nvim/ui.c23
-rw-r--r--src/nvim/ui_client.c215
-rw-r--r--src/nvim/ui_client.h13
-rw-r--r--src/nvim/undo_defs.h6
-rw-r--r--src/nvim/vim.h4
-rw-r--r--src/nvim/viml/parser/expressions.c4
-rw-r--r--src/nvim/viml/parser/parser.h6
-rw-r--r--src/nvim/window.c413
-rw-r--r--src/nvim/window.h37
-rw-r--r--test/functional/api/autocmd_spec.lua920
-rw-r--r--test/functional/api/buffer_spec.lua35
-rw-r--r--test/functional/api/buffer_updates_spec.lua1
-rw-r--r--test/functional/api/command_spec.lua66
-rw-r--r--test/functional/api/highlight_spec.lua30
-rw-r--r--test/functional/api/keymap_spec.lua31
-rw-r--r--test/functional/api/vim_spec.lua445
-rw-r--r--test/functional/api/window_spec.lua44
-rw-r--r--test/functional/autocmd/autocmd_oldtest_spec.lua86
-rw-r--r--test/functional/autocmd/autocmd_spec.lua167
-rw-r--r--test/functional/autocmd/cursormoved_spec.lua1
-rw-r--r--test/functional/autocmd/show_spec.lua35
-rw-r--r--test/functional/autocmd/termxx_spec.lua4
-rw-r--r--test/functional/core/channels_spec.lua21
-rw-r--r--test/functional/core/job_spec.lua1
-rw-r--r--test/functional/core/remote_spec.lua142
-rw-r--r--test/functional/core/startup_spec.lua4
-rw-r--r--test/functional/editor/completion_spec.lua19
-rw-r--r--test/functional/editor/put_spec.lua4
-rw-r--r--test/functional/ex_cmds/map_spec.lua221
-rw-r--r--test/functional/ex_cmds/mksession_spec.lua1
-rw-r--r--test/functional/ex_cmds/verbose_spec.lua168
-rw-r--r--test/functional/legacy/autochdir_spec.lua94
-rw-r--r--test/functional/legacy/delete_spec.lua43
-rw-r--r--test/functional/legacy/file_perm_spec.lua43
-rw-r--r--test/functional/legacy/searchpos_spec.lua35
-rw-r--r--test/functional/legacy/set_spec.lua30
-rw-r--r--test/functional/lua/api_spec.lua7
-rw-r--r--test/functional/lua/command_line_completion_spec.lua8
-rw-r--r--test/functional/lua/thread_spec.lua408
-rw-r--r--test/functional/lua/vim_spec.lua134
-rw-r--r--test/functional/options/autochdir_spec.lua31
-rw-r--r--test/functional/plugin/lsp/diagnostic_spec.lua1
-rw-r--r--test/functional/plugin/lsp/incremental_sync_spec.lua48
-rw-r--r--test/functional/plugin/shada_spec.lua8
-rw-r--r--test/functional/provider/clipboard_spec.lua16
-rw-r--r--test/functional/provider/python3_spec.lua8
-rw-r--r--test/functional/terminal/buffer_spec.lua1
-rw-r--r--test/functional/terminal/channel_spec.lua87
-rw-r--r--test/functional/terminal/cursor_spec.lua3
-rw-r--r--test/functional/terminal/edit_spec.lua1
-rw-r--r--test/functional/terminal/ex_terminal_spec.lua7
-rw-r--r--test/functional/terminal/helpers.lua2
-rw-r--r--test/functional/terminal/highlight_spec.lua16
-rw-r--r--test/functional/terminal/scrollback_spec.lua2
-rw-r--r--test/functional/terminal/tui_spec.lua14
-rw-r--r--test/functional/terminal/window_spec.lua1
-rw-r--r--test/functional/ui/cmdline_highlight_spec.lua13
-rw-r--r--test/functional/ui/cursor_spec.lua4
-rw-r--r--test/functional/ui/decorations_spec.lua369
-rw-r--r--test/functional/ui/diff_spec.lua26
-rw-r--r--test/functional/ui/global_statusline_spec.lua233
-rw-r--r--test/functional/ui/highlight_spec.lua60
-rw-r--r--test/functional/ui/hlstate_spec.lua4
-rw-r--r--test/functional/ui/messages_spec.lua1
-rw-r--r--test/functional/ui/output_spec.lua1
-rw-r--r--test/functional/ui/popupmenu_spec.lua2
-rw-r--r--test/functional/ui/screen.lua19
-rw-r--r--test/functional/ui/sign_spec.lua8
-rw-r--r--test/helpers.lua10
-rw-r--r--test/unit/strings_spec.lua12
-rw-r--r--test/unit/viml/expressions/parser_spec.lua1
-rw-r--r--third-party/CMakeLists.txt12
-rw-r--r--third-party/cmake/BuildGettext.cmake1
-rw-r--r--third-party/cmake/BuildGperf.cmake1
-rw-r--r--third-party/cmake/BuildLibiconv.cmake1
-rw-r--r--third-party/cmake/BuildLibtermkey.cmake1
-rw-r--r--third-party/cmake/BuildLibuv.cmake5
-rw-r--r--third-party/cmake/BuildLibvterm.cmake1
-rw-r--r--third-party/cmake/BuildLuv.cmake1
-rw-r--r--third-party/cmake/BuildMsgpack.cmake1
-rw-r--r--third-party/cmake/BuildTreesitter.cmake1
-rw-r--r--third-party/cmake/BuildTreesitterParsers.cmake2
-rw-r--r--third-party/cmake/BuildUnibilium.cmake1
-rw-r--r--third-party/patches/libuv-disable-typedef-MinGW.patch19
362 files changed, 19384 insertions, 11483 deletions
diff --git a/.builds/freebsd.yml b/.builds/freebsd.yml
index d5809c42cf..2d06b1e685 100644
--- a/.builds/freebsd.yml
+++ b/.builds/freebsd.yml
@@ -1,11 +1,10 @@
-image: freebsd/12.x
+image: freebsd/latest
packages:
- cmake
- gmake
- ninja
- libtool
-- sha
- automake
- pkgconf
- unzip
@@ -13,6 +12,7 @@ packages:
- gettext
- python
- libffi
+- gdb
sources:
- https://github.com/neovim/neovim
@@ -35,10 +35,6 @@ tasks:
- unittest: |
cd neovim
gmake unittest
-
-# Unfortunately, oldtest is tanking hard on sourcehut's FreeBSD instance
-# and not producing any logs as a result. So don't do this task for now.
-# Ref: https://github.com/neovim/neovim/pull/11477#discussion_r352095005.
-# - test-oldtest: |
-# cd neovim
-# gmake oldtest
+- oldtest: |
+ cd neovim
+ gmake oldtest
diff --git a/.builds/openbsd.yml b/.builds/openbsd.yml
index 422fa366b6..0aaa003820 100644
--- a/.builds/openbsd.yml
+++ b/.builds/openbsd.yml
@@ -1,6 +1,6 @@
# sourcehut CI: https://builds.sr.ht/~jmk/neovim
-image: openbsd/6.9
+image: openbsd/latest
packages:
- autoconf-2.71
@@ -12,6 +12,7 @@ packages:
- libtool
- ninja-1.10.2p0
- unzip-6.0p14
+- gdb
sources:
- https://github.com/neovim/neovim
diff --git a/.clang-format b/.clang-format
index c86f5a3ddf..d5e328f461 100644
--- a/.clang-format
+++ b/.clang-format
@@ -2,10 +2,10 @@ BasedOnStyle: Google
Language: Cpp
ColumnLimit: 100
IndentWidth: 2
-TabWidth: 2
+TabWidth: 8
UseTab: Never
-IndentCaseLabels: true
-BreakBeforeBraces: Linux
+IndentCaseLabels: false
+BreakBeforeBraces: Custom
AlignEscapedNewlinesLeft: false
AllowShortFunctionsOnASingleLine: false
AlignTrailingComments: true
@@ -17,4 +17,24 @@ AllowShortLoopsOnASingleLine: false
BinPackParameters: false
BreakBeforeBinaryOperators: true
BreakBeforeTernaryOperators: true
-ContinuationIndentWidth: 4
+ContinuationIndentWidth: 2
+AlwaysBreakAfterDefinitionReturnType: None
+AlwaysBreakAfterReturnType: None
+AlwaysBreakBeforeMultilineStrings: No
+AlwaysBreakTemplateDeclarations: No
+AlignEscapedNewlines: DontAlign
+BinPackArguments: false
+BraceWrapping:
+ AfterClass: false
+ AfterControlStatement: false
+ AfterEnum: false
+ AfterFunction: true
+ AfterObjCDeclaration: false
+ AfterStruct: false
+ AfterUnion: false
+ BeforeCatch: false
+ BeforeElse: false
+ IndentBraces: false
+PointerAlignment: Right
+SortIncludes: false
+Cpp11BracedListStyle: false
diff --git a/.github/scripts/reviews.js b/.github/scripts/reviews.js
index 25ef08be36..e227b62c8c 100644
--- a/.github/scripts/reviews.js
+++ b/.github/scripts/reviews.js
@@ -13,6 +13,10 @@ module.exports = async ({github, context}) => {
reviewers.add("muniter")
}
+ if (labels.includes('build')) {
+ reviewers.add("jamessan")
+ }
+
if (labels.includes('ci')) {
reviewers.add("jamessan")
}
@@ -29,6 +33,10 @@ module.exports = async ({github, context}) => {
reviewers.add("lewis6991")
}
+ if (labels.includes('dependencies')) {
+ reviewers.add("jamessan")
+ }
+
if (labels.includes('distribution')) {
reviewers.add("jamessan")
}
@@ -70,7 +78,6 @@ module.exports = async ({github, context}) => {
}
if (labels.includes('vim-patch')) {
- reviewers.add("janlazo")
reviewers.add("seandewar")
reviewers.add("zeertzjq")
}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 34b73e8ef4..ea3185d2a1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -9,6 +9,8 @@ on:
branches:
- 'master'
- 'release-[0-9]+.[0-9]+'
+ paths-ignore:
+ - 'runtime/doc/*'
# Cancel any in-progress CI runs for a PR if it is updated
concurrency:
@@ -17,8 +19,14 @@ concurrency:
jobs:
lint:
+ # This job tests two things: it lints the code but also builds neovim using
+ # system dependencies instead of bundled dependencies. This is to make sure
+ # we are able to build neovim without pigeonholing ourselves into specifics
+ # of the bundled dependencies.
+
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
+ timeout-minutes: 10
env:
CC: gcc
steps:
@@ -29,23 +37,54 @@ jobs:
- name: Install apt packages
run: |
+ sudo add-apt-repository ppa:neovim-ppa/stable
sudo apt-get update
- sudo apt-get install -y autoconf automake build-essential ccache cmake gettext gperf libtool-bin locales ninja-build pkg-config flake8
-
- - name: Cache dependencies
+ sudo apt-get install -y \
+ autoconf \
+ automake \
+ build-essential \
+ ccache \
+ cmake \
+ flake8 \
+ gettext \
+ gperf \
+ libluajit-5.1-dev \
+ libmsgpack-dev \
+ libtermkey-dev \
+ libtool-bin \
+ libtree-sitter-dev \
+ libunibilium-dev \
+ libuv1-dev \
+ libvterm-dev \
+ locales \
+ lua-busted \
+ lua-check \
+ lua-filesystem \
+ lua-inspect \
+ lua-lpeg \
+ lua-luv-dev \
+ lua-nvim \
+ luajit \
+ ninja-build \
+ pkg-config
+
+ - name: Cache artifacts
uses: actions/cache@v2
with:
path: |
${{ env.CACHE_NVIM_DEPS_DIR }}
~/.ccache
- key: lint-${{ hashFiles('cmake/*', 'third-party/**', '**/CMakeLists.txt') }}-${{ github.base_ref }}
+ key: lint-${{ hashFiles('cmake/*', '**/CMakeLists.txt', '!third-party/**CMakeLists.txt') }}-${{ github.base_ref }}
- name: Build third-party
run: ./ci/before_script.sh
+ - name: Build nvim
+ run: ./ci/run_tests.sh build_nvim
+
- if: "!cancelled()"
- name: clint
- run: ./ci/run_lint.sh clint
+ name: clint-full
+ run: ./ci/run_lint.sh clint-full
- if: "!cancelled()"
name: lualint
@@ -60,14 +99,13 @@ jobs:
run: ./ci/run_lint.sh shlint
- if: "!cancelled()"
- name: single-includes
- run: ./ci/run_lint.sh single-includes
+ name: check-single-includes
+ run: ./ci/run_lint.sh check-single-includes
- name: Cache dependencies
- if: ${{ success() }}
run: ./ci/before_cache.sh
- unixish:
+ posix:
name: ${{ matrix.runner }} ${{ matrix.flavor }} (cc=${{ matrix.cc }})
strategy:
fail-fast: false
@@ -87,6 +125,12 @@ jobs:
- cc: clang
runner: macos-11.0
os: osx
+
+ # The functionaltest-lua test two things simultaneously:
+ # 1. Check that the tests pass with PUC Lua instead of LuaJIT.
+ # 2. Use as oldest/minimum versions of dependencies/build tools we
+ # still explicitly support so we don't accidentally rely on
+ # features that is only available on later versions.
- flavor: functionaltest-lua
cc: gcc
runner: ubuntu-20.04
@@ -139,8 +183,8 @@ jobs:
- name: Install brew packages
if: matrix.os == 'osx'
run: |
- brew update >/dev/null
- brew install automake ccache perl cpanminus ninja
+ brew update --quiet
+ brew install automake ccache cpanminus ninja
- name: Setup interpreter packages
run: ./ci/install.sh
@@ -157,7 +201,7 @@ jobs:
run: ./ci/before_script.sh
- name: Build
- run: ./ci/run_tests.sh build
+ run: ./ci/run_tests.sh build_nvim
- if: matrix.flavor != 'tsan' && matrix.flavor != 'functionaltest-lua' && !cancelled()
name: Unittests
@@ -176,11 +220,11 @@ jobs:
run: ./ci/run_tests.sh install_nvim
- name: Cache dependencies
- if: ${{ success() }}
run: ./ci/before_cache.sh
windows:
- runs-on: windows-2016
+ runs-on: windows-2019
+ timeout-minutes: 45
if: github.event.pull_request.draft == false
env:
DEPS_BUILD_DIR: ${{ format('{0}/nvim-deps', github.workspace) }}
diff --git a/.github/workflows/env.sh b/.github/workflows/env.sh
index 0964995605..bd170f92fb 100755
--- a/.github/workflows/env.sh
+++ b/.github/workflows/env.sh
@@ -46,7 +46,11 @@ CLANG_SANITIZER=TSAN
EOF
;;
lint)
+# Re-enable once system deps are available
+# BUILD_FLAGS="$BUILD_FLAGS -DLIBLUV_LIBRARY:FILEPATH=/usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/lua/5.1/luv.so -DLIBLUV_INCLUDE_DIR:PATH=/usr/include/lua5.1"
+ DEPS_CMAKE_FLAGS="$DEPS_CMAKE_FLAGS -DUSE_BUNDLED_LUV=ON"
cat <<EOF >> "$GITHUB_ENV"
+USE_BUNDLED=OFF
CI_TARGET=lint
EOF
;;
diff --git a/.github/workflows/notes.md b/.github/workflows/notes.md
index 9928d472b3..7181972696 100644
--- a/.github/workflows/notes.md
+++ b/.github/workflows/notes.md
@@ -6,8 +6,26 @@ ${NVIM_VERSION}
### Windows
-1. Extract **nvim-win64.zip**
-2. Run `nvim-qt.exe`
+#### Zip
+
+1. Download **nvim-win64.zip**
+2. Extract the zip.
+3. Run `nvim-qt.exe`
+
+#### MSI
+
+1. Download **nvim-win64.msi**
+2. Run the MSI
+3. Add the Neovim location to your path.
+ - Default location is `C:\Program Files\Neovim`
+4. Search and run `nvim-qt.exe` or run `nvim.exe` on your CLI of choice.
+
+#### NSIS
+
+1. Download **nvim-win64.exe**
+2. Run the installer.
+ - Ensure that the option to add the installation location to your path is checked if it's your first installation.
+3. Search and run `nvim-qt.exe` or run `nvim.exe` on your CLI of choice.
### macOS
@@ -17,6 +35,19 @@ ${NVIM_VERSION}
### Linux (x64)
+#### Tarball
+
+1. Download **nvim-linux64.tar.gz**
+2. Extract: `tar xzvf nvim-linux64.tar.gz`
+3. Run `./nvim-linux64/bin/nvim`
+
+#### Debian Package
+
+1. Download **nvim-linux64.deb**
+2. Install the package using `sudo apt install ./nvim-linux64.deb`
+3. Run `nvim`
+
+#### AppImage
1. Download **nvim.appimage**
2. Run `chmod u+x nvim.appimage && ./nvim.appimage`
- If your system does not have FUSE you can [extract the appimage](https://github.com/AppImage/AppImageKit/wiki/FUSE#type-2-appimage):
@@ -32,9 +63,12 @@ ${NVIM_VERSION}
## SHA256 Checksums
```
-${SHA_LINUX_64}
+${SHA_LINUX_64_TAR}
+${SHA_LINUX_64_DEB}
${SHA_APP_IMAGE}
${SHA_APP_IMAGE_ZSYNC}
${SHA_MACOS}
-${SHA_WIN_64}
+${SHA_WIN_64_ZIP}
+${SHA_WIN_64_MSI}
+${SHA_WIN_64_EXE}
```
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index b72c2ab71d..8e0b13d59c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -39,12 +39,17 @@ jobs:
printf '::set-output name=version::%s\n' "$(./build/bin/nvim --version | head -n 3 | sed -z 's/\n/%0A/g')"
printf '::set-output name=release::%s\n' "$(./build/bin/nvim --version | head -n 1)"
make DESTDIR="$GITHUB_WORKSPACE/build/release/nvim-linux64" install
- cd "$GITHUB_WORKSPACE/build/release"
- tar cfz nvim-linux64.tar.gz nvim-linux64
+ cd "$GITHUB_WORKSPACE/build/"
+ cpack -C $NVIM_BUILD_TYPE
- uses: actions/upload-artifact@v2
with:
name: nvim-linux64
- path: build/release/nvim-linux64.tar.gz
+ path: build/nvim-linux64.tar.gz
+ retention-days: 1
+ - uses: actions/upload-artifact@v2
+ with:
+ name: nvim-linux64
+ path: build/nvim-linux64.deb
retention-days: 1
appimage:
@@ -80,7 +85,7 @@ jobs:
fetch-depth: 0
- name: Install brew packages
run: |
- brew update >/dev/null
+ brew update --quiet
brew install automake ninja
- if: github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && github.event.inputs.tag_name != 'nightly')
run: printf 'NVIM_BUILD_TYPE=Release\n' >> $GITHUB_ENV
@@ -114,7 +119,7 @@ jobs:
retention-days: 1
windows:
- runs-on: windows-2016
+ runs-on: windows-2019
env:
DEPS_BUILD_DIR: ${{ format('{0}/nvim-deps', github.workspace) }}
DEPS_PREFIX: ${{ format('{0}/nvim-deps/usr', github.workspace) }}
@@ -131,12 +136,21 @@ jobs:
- run: powershell ci\build.ps1 -NoTests
env:
CONFIGURATION: ${{ matrix.config }}
- - run: move build\Neovim.zip build\${{ matrix.archive }}.zip
- uses: actions/upload-artifact@v2
with:
name: ${{ matrix.archive }}
path: build/${{ matrix.archive }}.zip
retention-days: 1
+ - uses: actions/upload-artifact@v2
+ with:
+ name: ${{ matrix.archive }}
+ path: build/${{ matrix.archive }}.msi
+ retention-days: 1
+ - uses: actions/upload-artifact@v2
+ with:
+ name: ${{ matrix.archive }}
+ path: build/${{ matrix.archive }}.exe
+ retention-days: 1
publish:
needs: [linux, appimage, macOS, windows]
@@ -187,7 +201,9 @@ jobs:
run: |
cd ./nvim-linux64
sha256sum nvim-linux64.tar.gz > nvim-linux64.tar.gz.sha256sum
- echo "SHA_LINUX_64=$(cat nvim-linux64.tar.gz.sha256sum)" >> $GITHUB_ENV
+ echo "SHA_LINUX_64_TAR=$(cat nvim-linux64.tar.gz.sha256sum)" >> $GITHUB_ENV
+ sha256sum nvim-linux64.deb > nvim-linux64.deb.sha256sum
+ echo "SHA_LINUX_64_DEB=$(cat nvim-linux64.deb.sha256sum)" >> $GITHUB_ENV
- name: Generate App Image SHA256 checksums
run: |
cd ./appimage
@@ -207,7 +223,11 @@ jobs:
run: |
cd ./nvim-win64
sha256sum nvim-win64.zip > nvim-win64.zip.sha256sum
- echo "SHA_WIN_64=$(cat nvim-win64.zip.sha256sum)" >> $GITHUB_ENV
+ echo "SHA_WIN_64_ZIP=$(cat nvim-win64.zip.sha256sum)" >> $GITHUB_ENV
+ sha256sum nvim-win64.msi > nvim-win64.msi.sha256sum
+ echo "SHA_WIN_64_MSI=$(cat nvim-win64.msi.sha256sum)" >> $GITHUB_ENV
+ sha256sum nvim-win64.exe > nvim-win64.exe.sha256sum
+ echo "SHA_WIN_64_EXE=$(cat nvim-win64.exe.sha256sum)" >> $GITHUB_ENV
- name: Publish release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.gitignore b/.gitignore
index 0988a51cd9..11479346c7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,6 +15,7 @@ compile_commands.json
/.clangd/
/.cache/clangd/
/.ccls-cache/
+/.clang-tidy
.DS_Store
*.mo
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e0f05e1205..767bd797bc 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -12,6 +12,9 @@ endif()
if(POLICY CMP0060)
cmake_policy(SET CMP0060 NEW)
endif()
+if(POLICY CMP0075)
+ cmake_policy(SET CMP0075 NEW)
+endif()
# Point CMake at any custom modules we may ship
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake")
@@ -387,7 +390,7 @@ include_directories(SYSTEM ${LIBUV_INCLUDE_DIRS})
find_package(Msgpack 1.0.0 REQUIRED)
include_directories(SYSTEM ${MSGPACK_INCLUDE_DIRS})
-find_package(LibLUV 1.30.0 REQUIRED)
+find_package(LibLUV 1.43.0 REQUIRED)
include_directories(SYSTEM ${LIBLUV_INCLUDE_DIRS})
find_package(TreeSitter REQUIRED)
@@ -736,17 +739,6 @@ else()
COMMENT "lualint: LUACHECK_PRG not defined")
endif()
-set(CPACK_PACKAGE_NAME "Neovim")
-set(CPACK_PACKAGE_VENDOR "neovim.io")
-set(CPACK_PACKAGE_VERSION ${NVIM_VERSION_MEDIUM})
-set(CPACK_PACKAGE_INSTALL_DIRECTORY "Neovim")
-# Set toplevel directory/installer name as Neovim
-set(CPACK_PACKAGE_FILE_NAME "Neovim")
-set(CPACK_TOPLEVEL_TAG "Neovim")
-set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE")
-set(CPACK_NSIS_MODIFY_PATH ON)
-set(CPACK_NSIS_ENABLE_UNINSTALL_BEFORE_INSTALL ON)
-include(CPack)
#add uninstall target
if(NOT TARGET uninstall)
@@ -758,3 +750,8 @@ if(NOT TARGET uninstall)
add_custom_target(uninstall
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/UninstallHelper.cmake)
endif()
+
+
+if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
+ add_subdirectory(packaging)
+endif()
diff --git a/LICENSE b/LICENSE.txt
index c1b8286c4b..c1b8286c4b 100644
--- a/LICENSE
+++ b/LICENSE.txt
diff --git a/README.md b/README.md
index 8342c27fd7..4ec5cf2be3 100644
--- a/README.md
+++ b/README.md
@@ -119,7 +119,7 @@ Apache 2.0 license, except for contributions copied from Vim (identified by the
[Managed packages]: https://github.com/neovim/neovim/wiki/Installing-Neovim#install-from-package
[Debian]: https://packages.debian.org/testing/neovim
[Ubuntu]: http://packages.ubuntu.com/search?keywords=neovim
-[Fedora]: https://apps.fedoraproject.org/packages/neovim
+[Fedora]: https://packages.fedoraproject.org/pkgs/neovim/neovim/
[Arch Linux]: https://www.archlinux.org/packages/?q=neovim
[Void Linux]: https://voidlinux.org/packages/?arch=x86_64&q=neovim
[Gentoo]: https://packages.gentoo.org/packages/app-editors/neovim
diff --git a/ci/before_cache.sh b/ci/before_cache.sh
index c86109168e..bec6c37bbe 100755
--- a/ci/before_cache.sh
+++ b/ci/before_cache.sh
@@ -7,6 +7,8 @@ CI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${CI_DIR}/common/build.sh"
source "${CI_DIR}/common/suite.sh"
+mkdir -p "${HOME}/.cache"
+
echo "before_cache.sh: cache size"
du -chd 1 "${HOME}/.cache" | sort -rh | head -20
@@ -16,7 +18,7 @@ ccache -s 2>/dev/null || true
find "${HOME}/.ccache" -name stats -delete
# Update the third-party dependency cache only if the build was successful.
-if ended_successfully; then
+if ended_successfully && [ -d "${DEPS_BUILD_DIR}" ]; then
# Do not cache downloads. They should not be needed with up-to-date deps.
rm -rf "${DEPS_BUILD_DIR}/build/downloads"
rm -rf "${CACHE_NVIM_DEPS_DIR}"
diff --git a/ci/build.ps1 b/ci/build.ps1
index ef5ba3bf2d..c7c3b3d470 100644
--- a/ci/build.ps1
+++ b/ci/build.ps1
@@ -77,11 +77,16 @@ if ($compiler -eq 'MINGW') {
}
elseif ($compiler -eq 'MSVC') {
$cmakeGeneratorArgs = '/verbosity:normal'
- if ($bits -eq 32) {
- $cmakeGenerator = 'Visual Studio 15 2017'
- }
- elseif ($bits -eq 64) {
- $cmakeGenerator = 'Visual Studio 15 2017 Win64'
+ $cmakeGenerator = 'Visual Studio 16 2019'
+}
+
+if ($compiler -eq 'MSVC') {
+ $installationPath = vswhere.exe -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
+ if ($installationPath -and (test-path "$installationPath\Common7\Tools\vsdevcmd.bat")) {
+ & "${env:COMSPEC}" /s /c "`"$installationPath\Common7\Tools\vsdevcmd.bat`" -arch=x${bits} -no_logo && set" | foreach-object {
+ $name, $value = $_ -split '=', 2
+ set-content env:\"$name" $value
+ }
}
}
@@ -99,24 +104,35 @@ if (-not $NoTests) {
npm.cmd link neovim
}
-if ($compiler -eq 'MSVC') {
- # Required for LuaRocks (https://github.com/luarocks/luarocks/issues/1039#issuecomment-507296940).
- $env:VCINSTALLDIR = "C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Tools/MSVC/14.16.27023/"
-}
-
function convertToCmakeArgs($vars) {
return $vars.GetEnumerator() | foreach { "-D$($_.Key)=$($_.Value)" }
}
cd $env:DEPS_BUILD_DIR
-cmake -G $cmakeGenerator $(convertToCmakeArgs($depsCmakeVars)) "$buildDir/third-party/" ; exitIfFailed
+if ($compiler -eq 'MSVC') {
+ if ($bits -eq 32) {
+ cmake -G $cmakeGenerator -A Win32 $(convertToCmakeArgs($depsCmakeVars)) "$buildDir/third-party/" ; exitIfFailed
+ } else {
+ cmake -G $cmakeGenerator -A x64 $(convertToCmakeArgs($depsCmakeVars)) "$buildDir/third-party/" ; exitIfFailed
+ }
+} else {
+ cmake -G $cmakeGenerator $(convertToCmakeArgs($depsCmakeVars)) "$buildDir/third-party/" ; exitIfFailed
+}
cmake --build . --config $cmakeBuildType -- $cmakeGeneratorArgs ; exitIfFailed
cd $buildDir
# Build Neovim
mkdir build
cd build
-cmake -G $cmakeGenerator $(convertToCmakeArgs($nvimCmakeVars)) .. ; exitIfFailed
+if ($compiler -eq 'MSVC') {
+ if ($bits -eq 32) {
+ cmake -G $cmakeGenerator -A Win32 $(convertToCmakeArgs($nvimCmakeVars)) .. ; exitIfFailed
+ } else {
+ cmake -G $cmakeGenerator -A x64 $(convertToCmakeArgs($nvimCmakeVars)) .. ; exitIfFailed
+ }
+} else {
+ cmake -G $cmakeGenerator $(convertToCmakeArgs($nvimCmakeVars)) .. ; exitIfFailed
+}
cmake --build . --config $cmakeBuildType -- $cmakeGeneratorArgs ; exitIfFailed
.\bin\nvim --version ; exitIfFailed
@@ -167,7 +183,4 @@ if (Test-Path -Path $env:ChocolateyInstall\bin\cpack.exe) {
}
# Build artifacts
-cpack -G ZIP -C RelWithDebInfo
-if ($env:APPVEYOR_REPO_TAG_NAME -ne $null) {
- cpack -G NSIS -C RelWithDebInfo
-}
+cpack -C $cmakeBuildType
diff --git a/ci/common/suite.sh b/ci/common/suite.sh
index 5110e22ec2..0320ac15c3 100644
--- a/ci/common/suite.sh
+++ b/ci/common/suite.sh
@@ -1,9 +1,3 @@
-# HACK: get newline for use in strings given that "\n" and $'' do not work.
-NL="$(printf '\nE')"
-NL="${NL%E}"
-
-FAIL_SUMMARY=""
-
# Test success marker. If END_MARKER file exists, we know that all tests
# finished. If FAIL_SUMMARY_FILE exists we know that some tests failed, this
# file will contain information about failed tests. Build is considered
@@ -11,32 +5,13 @@ FAIL_SUMMARY=""
END_MARKER="$BUILD_DIR/.tests_finished"
FAIL_SUMMARY_FILE="$BUILD_DIR/.test_errors"
-enter_suite() {
- FAILED=0
- rm -f "${END_MARKER}"
- local suite_name="$1"
- export NVIM_TEST_CURRENT_SUITE="${NVIM_TEST_CURRENT_SUITE}/$suite_name"
-}
-
-exit_suite() {
- if test $FAILED -ne 0 ; then
- echo "Suite ${NVIM_TEST_CURRENT_SUITE} failed, summary:"
- echo "${FAIL_SUMMARY}"
- fi
- export NVIM_TEST_CURRENT_SUITE="${NVIM_TEST_CURRENT_SUITE%/*}"
- FAILED=0
-}
-
fail() {
local test_name="$1"
- local fail_char="$2"
- local message="$3"
+ local message="$2"
- : ${fail_char:=F}
: ${message:=Test $test_name failed}
- local full_msg="$fail_char $NVIM_TEST_CURRENT_SUITE|$test_name :: $message"
- FAIL_SUMMARY="${FAIL_SUMMARY}${NL}${full_msg}"
+ local full_msg="$test_name :: $message"
echo "${full_msg}" >> "${FAIL_SUMMARY_FILE}"
echo "Failed: $full_msg"
FAILED=1
@@ -64,13 +39,3 @@ end_tests() {
touch "${END_MARKER}"
ended_successfully
}
-
-run_suite() {
- local command="$1"
- local suite_name="$2"
-
- enter_suite "$suite_name"
- eval "$command" || fail "$suite_name"
- exit_suite
-}
-
diff --git a/ci/common/test.sh b/ci/common/test.sh
index f211a2e7aa..7db39a0e5f 100644
--- a/ci/common/test.sh
+++ b/ci/common/test.sh
@@ -51,7 +51,7 @@ check_core_dumps() {
fi
done
if test "$app" != quiet ; then
- fail 'cores' E 'Core dumps found'
+ fail 'cores' 'Core dumps found'
fi
}
@@ -72,7 +72,7 @@ check_logs() {
rm "${log}"
done
if test -n "${err}" ; then
- fail 'logs' E 'Runtime errors detected.'
+ fail 'logs' 'Runtime errors detected.'
fi
}
@@ -86,19 +86,19 @@ check_sanitizer() {
fi
}
-run_unittests() {(
+unittests() {(
ulimit -c unlimited || true
if ! build_make unittest ; then
- fail 'unittests' F 'Unit tests failed'
+ fail 'unittests' 'Unit tests failed'
fi
submit_coverage unittest
check_core_dumps "$(command -v luajit)"
)}
-run_functionaltests() {(
+functionaltests() {(
ulimit -c unlimited || true
if ! build_make ${FUNCTIONALTEST}; then
- fail 'functionaltests' F 'Functional tests failed'
+ fail 'functionaltests' 'Functional tests failed'
fi
submit_coverage functionaltest
check_sanitizer "${LOG_DIR}"
@@ -106,11 +106,11 @@ run_functionaltests() {(
check_core_dumps
)}
-run_oldtests() {(
+oldtests() {(
ulimit -c unlimited || true
if ! make oldtest; then
reset
- fail 'oldtests' F 'Legacy tests failed'
+ fail 'oldtests' 'Legacy tests failed'
fi
submit_coverage oldtest
check_sanitizer "${LOG_DIR}"
@@ -129,26 +129,25 @@ check_runtime_files() {(
# Prefer failing the build over using more robust construct because files
# with IFS are not welcome.
if ! test -e "$file" ; then
- fail "$test_name" E \
- "It appears that $file is only a part of the file name"
+ fail "$test_name" "It appears that $file is only a part of the file name"
fi
if ! test "$tst" "$INSTALL_PREFIX/share/nvim/runtime/$file" ; then
- fail "$test_name" F "$(printf "$message" "$file")"
+ fail "$test_name" "$(printf "$message" "$file")"
fi
done
)}
install_nvim() {(
if ! build_make install ; then
- fail 'install' E 'make install failed'
- exit_suite
+ fail 'install' 'make install failed'
+ exit 1
fi
"${INSTALL_PREFIX}/bin/nvim" --version
if ! "${INSTALL_PREFIX}/bin/nvim" -u NONE -e -c ':help' -c ':qall' ; then
echo "Running ':help' in the installed nvim failed."
echo "Maybe the helptags have not been generated properly."
- fail 'help' F 'Failed running :help'
+ fail 'help' 'Failed running :help'
fi
# Check that all runtime files were installed
@@ -169,6 +168,6 @@ install_nvim() {(
local genvimsynf=syntax/vim/generated.vim
local gpat='syn keyword vimFuncName .*eval'
if ! grep -q "$gpat" "${INSTALL_PREFIX}/share/nvim/runtime/$genvimsynf" ; then
- fail 'funcnames' F "It appears that $genvimsynf does not contain $gpat."
+ fail 'funcnames' "It appears that $genvimsynf does not contain $gpat."
fi
)}
diff --git a/ci/run_lint.sh b/ci/run_lint.sh
index 2fea7a40c0..3a524b4ed6 100755
--- a/ci/run_lint.sh
+++ b/ci/run_lint.sh
@@ -8,34 +8,17 @@ CI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${CI_DIR}/common/build.sh"
source "${CI_DIR}/common/suite.sh"
-if [[ "$GITHUB_ACTIONS" != "true" ]]; then
- run_suite 'make clint-full' 'clint'
- run_suite 'make lualint' 'lualint'
- run_suite 'make pylint' 'pylint'
- run_suite 'make shlint' 'shlint'
- run_suite 'make check-single-includes' 'single-includes'
+rm -f "$END_MARKER"
- end_tests
+# Run all tests if no input argument is given
+if (($# == 0)); then
+ tests=('clint-full' 'lualint' 'pylint' 'shlint' 'check-single-includes')
else
- case "$1" in
- clint)
- run_suite 'make clint-full' 'clint'
- ;;
- lualint)
- run_suite 'make lualint' 'lualint'
- ;;
- pylint)
- run_suite 'make pylint' 'pylint'
- ;;
- shlint)
- run_suite 'make shlint' 'shlint'
- ;;
- single-includes)
- run_suite 'make check-single-includes' 'single-includes'
- ;;
- *)
- :;;
- esac
-
- end_tests
+ tests=("$@")
fi
+
+for i in "${tests[@]}"; do
+ make "$i" || fail "$i"
+done
+
+end_tests
diff --git a/ci/run_tests.sh b/ci/run_tests.sh
index ae85246ab6..23460b682e 100755
--- a/ci/run_tests.sh
+++ b/ci/run_tests.sh
@@ -8,42 +8,28 @@ source "${CI_DIR}/common/build.sh"
source "${CI_DIR}/common/test.sh"
source "${CI_DIR}/common/suite.sh"
+rm -f "$END_MARKER"
-if [[ "$GITHUB_ACTIONS" != "true" ]]; then
- run_suite 'build_nvim' 'build'
+# Run all tests (with some caveats) if no input argument is given
+if (($# == 0)); then
+ tests=('build_nvim')
if test "$CLANG_SANITIZER" != "TSAN"; then
# Additional threads are only created when the builtin UI starts, which
# doesn't happen in the unit/functional tests
if test "${FUNCTIONALTEST}" != "functionaltest-lua"; then
- run_suite run_unittests unittests
+ tests+=('unittests')
fi
- run_suite run_functionaltests functionaltests
+ tests+=('functionaltests')
fi
- run_suite run_oldtests oldtests
- run_suite install_nvim install_nvim
- end_tests
+ tests+=('oldtests' 'install_nvim')
else
- case "$1" in
- build)
- run_suite 'build_nvim' 'build'
- ;;
- unittests)
- run_suite 'run_unittests' 'unittests'
- ;;
- functionaltests)
- run_suite 'run_functionaltests' 'functionaltests'
- ;;
- oldtests)
- run_suite 'run_oldtests' 'oldtests'
- ;;
- install_nvim)
- run_suite 'install_nvim' 'install_nvim'
- ;;
- *)
- :;;
- esac
-
- end_tests
+ tests=("$@")
fi
+
+for i in "${tests[@]}"; do
+ eval "$i" || fail "$i"
+done
+
+end_tests
diff --git a/contrib/flake.lock b/contrib/flake.lock
index c4d7f120ba..b72e1f8d5f 100644
--- a/contrib/flake.lock
+++ b/contrib/flake.lock
@@ -2,11 +2,11 @@
"nodes": {
"flake-utils": {
"locked": {
- "lastModified": 1629481132,
- "narHash": "sha256-JHgasjPR0/J1J3DRm4KxM4zTyAj4IOJY8vIl75v/kPI=",
+ "lastModified": 1644229661,
+ "narHash": "sha256-1YdnJAsNy69bpcjuoKdOYQX0YxZBiCYZo4Twxerqv7k=",
"owner": "numtide",
"repo": "flake-utils",
- "rev": "997f7efcb746a9c140ce1f13c72263189225f482",
+ "rev": "3cecb5b042f7f209c56ffd8371b2711a290ec797",
"type": "github"
},
"original": {
@@ -17,11 +17,11 @@
},
"nixpkgs": {
"locked": {
- "lastModified": 1630074300,
- "narHash": "sha256-BFM7OiXRs0RvSUZd6NCGAKWVPn3VodgYQ4TUQXxbMBU=",
+ "lastModified": 1646254136,
+ "narHash": "sha256-8nQx02tTzgYO21BP/dy5BCRopE8OwE8Drsw98j+Qoaw=",
"owner": "nixos",
"repo": "nixpkgs",
- "rev": "21c937f8cb1e6adcfeb36dfd6c90d9d9bfab1d28",
+ "rev": "3e072546ea98db00c2364b81491b893673267827",
"type": "github"
},
"original": {
diff --git a/packaging/CMakeLists.txt b/packaging/CMakeLists.txt
new file mode 100644
index 0000000000..6ae744c2cd
--- /dev/null
+++ b/packaging/CMakeLists.txt
@@ -0,0 +1,78 @@
+set(CPACK_PACKAGE_NAME "Neovim")
+set(CPACK_PACKAGE_VENDOR "neovim.io")
+set(CPACK_PACKAGE_FILE_NAME "nvim")
+
+# From the GitHub About section
+set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Vim-fork focused on extensibility and usability.")
+
+set(CPACK_PACKAGE_INSTALL_DIRECTORY ${CPACK_PACKAGE_NAME})
+
+# Pull the versions defined with the top level CMakeLists.txt
+set(CPACK_PACKAGE_VERSION_MAJOR ${NVIM_VERSION_MAJOR})
+set(CPACK_PACKAGE_VERSION_MINOR ${NVIM_VERSION_MINOR})
+set(CPACK_PACKAGE_VERSION_PATCH ${NVIM_VERSION_PATCH})
+
+# CPACK_VERBATIM_VARIABLES ensures that the variables prefixed with *CPACK_*
+# are correctly passed to the cpack program.
+# This should always be set to true.
+set(CPACK_VERBATIM_VARIABLES TRUE)
+
+set(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE.txt")
+set(CPACK_RESOURCE_FILE_README ${PROJECT_SOURCE_DIR}/README.md)
+
+
+if(WIN32)
+ set(CPACK_PACKAGE_FILE_NAME "nvim-win64")
+ set(CPACK_GENERATOR ZIP WIX NSIS)
+
+ # WIX
+ # CPACK_WIX_UPGRADE_GUID should be set, but should never change.
+ # CPACK_WIX_PRODUCT_GUID should not be set (leave as default to auto-generate).
+
+ # The following guid is just a randomly generated guid that's been pasted here.
+ # It has no special meaning other than to supply it to WIX.
+ set(CPACK_WIX_UPGRADE_GUID "207A1A70-7B0C-418A-A153-CA6883E38F4D")
+ set(CPACK_WIX_PRODUCT_ICON ${CMAKE_CURRENT_LIST_DIR}/logo.ico)
+
+ # NSIS
+ # install icon
+ set(CPACK_NSIS_MUI_ICON ${CMAKE_CURRENT_LIST_DIR}/logo.ico)
+
+ # uninstall icon
+ set(CPACK_NSIS_MUI_UNIICON ${CMAKE_CURRENT_LIST_DIR}/logo.ico)
+
+ # icon that appears when you search in Add/Remove programs
+ set(CPACK_NSIS_INSTALLED_ICON_NAME ${CMAKE_CURRENT_LIST_DIR}/logo.ico)
+
+ # name that appears in the list in Add/Remove programs
+ set(CPACK_NSIS_DISPLAY_NAME "Neovim")
+
+ # name used in various installer UI locations, such as the title
+ set(CPACK_NSIS_PACKAGE_NAME "Neovim")
+
+ # Allow the user to modify their path to include neovim during
+ # the installation process.
+ set(CPACK_NSIS_MODIFY_PATH TRUE)
+elseif(APPLE)
+ set(CPACK_PACKAGE_FILE_NAME "nvim-macos")
+ set(CPACK_GENERATOR TGZ)
+ set(CPACK_PACKAGE_ICON ${CMAKE_CURRENT_LIST_DIR}/logo.icns)
+elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
+ set(CPACK_PACKAGE_FILE_NAME "nvim-linux64")
+ set(CPACK_GENERATOR TGZ DEB)
+ set(CPACK_DEBIAN_PACKAGE_NAME "Neovim") # required
+ set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Neovim.io") # required
+
+ # Automatically compute required shared lib dependencies.
+ # Unfortunately, you "just need to know" that this has a hidden
+ # dependency on dpkg-shlibdeps whilst using a debian based host.
+ set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS TRUE)
+else()
+ set(CPACK_GENERATOR TGZ)
+endif()
+
+# CPack variables are loaded in on the call to include(CPack). If you set
+# variables *after* the inclusion, they don't get updated within the CPack
+# config. Note that some CPack commands should still be run after it, such
+# as cpack_add_component().
+include(CPack)
diff --git a/packaging/logo.icns b/packaging/logo.icns
new file mode 100644
index 0000000000..a6377d9cdb
--- /dev/null
+++ b/packaging/logo.icns
Binary files differ
diff --git a/packaging/logo.ico b/packaging/logo.ico
new file mode 100644
index 0000000000..a4523501b9
--- /dev/null
+++ b/packaging/logo.ico
Binary files differ
diff --git a/packaging/logo.svg b/packaging/logo.svg
new file mode 100644
index 0000000000..e8aa8bd33e
--- /dev/null
+++ b/packaging/logo.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 54 65" fill="#fff" fill-rule="evenodd" stroke="#000" stroke-linecap="round" stroke-linejoin="round"><use xlink:href="#D" x=".5" y=".5"/><defs><linearGradient x1="50.00%" y1="0.00%" x2="50.00%" y2="100.00%" id="A"><stop stop-color="#16b0ed" stop-opacity=".8" offset="0%"/><stop stop-color="#0f59b2" stop-opacity=".837" offset="100%"/></linearGradient><linearGradient x1="50.00%" y1="0.00%" x2="50.00%" y2="100.00%" id="B"><stop stop-color="#7db643" offset="0%"/><stop stop-color="#367533" offset="100%"/></linearGradient><linearGradient x1="50.00%" y1="-0.00%" x2="50.00%" y2="100.01%" id="C"><stop stop-color="#88c649" stop-opacity=".8" offset="0%"/><stop stop-color="#439240" stop-opacity=".84" offset="100%"/></linearGradient></defs><symbol id="D" overflow="visible"><g stroke="none"><path d="M0 13.761L13.63 0v63.983L0 50.381z" fill="url(#A)"/><path d="M52.664 13.894L38.848.008l.281 63.976 13.63-13.602z" fill="url(#B)"/><path d="M13.621.011l35.435 54.07-9.916 9.915L3.686 10.046z" fill="url(#C)"/><path d="M13.633 25.092l-.019 2.13L2.676 11.069l1.013-1.032z" fill="#000" fill-opacity=".13"/></g></symbol></svg> \ No newline at end of file
diff --git a/runtime/autoload/dist/ft.vim b/runtime/autoload/dist/ft.vim
index aacecc521e..c52def1051 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: 2022 Jan 31
+" Last Change: 2022 Mar 05
" These functions are moved here from runtime/filetype.vim to make startup
" faster.
@@ -211,6 +211,10 @@ func dist#ft#EuphoriaCheck()
endfunc
func dist#ft#DtraceCheck()
+ if did_filetype()
+ " Filetype was already detected
+ return
+ endif
let lines = getline(1, min([line("$"), 100]))
if match(lines, '^module\>\|^import\>') > -1
" D files often start with a module and/or import statement.
diff --git a/runtime/autoload/health/provider.vim b/runtime/autoload/health/provider.vim
index 2f35179338..6022e05c22 100644
--- a/runtime/autoload/health/provider.vim
+++ b/runtime/autoload/health/provider.vim
@@ -301,7 +301,7 @@ function! s:check_python() abort
call health#report_info(printf('Using: g:%s = "%s"', host_prog_var, get(g:, host_prog_var)))
endif
- let [pyname, pythonx_errors] = provider#pythonx#Detect(3)
+ let [pyname, pythonx_warnings] = provider#pythonx#Detect(3)
if empty(pyname)
call health#report_warn('No Python executable found that can `import neovim`. '
@@ -311,8 +311,9 @@ function! s:check_python() abort
endif
" No Python executable could `import neovim`, or host_prog_var was used.
- if !empty(pythonx_errors)
- call health#report_error('Python provider error:', pythonx_errors)
+ if !empty(pythonx_warnings)
+ call health#report_warn(pythonx_warnings, ['See :help provider-python for more information.',
+ \ 'You may disable this provider (and warning) by adding `let g:loaded_python3_provider = 0` to your init.vim'])
elseif !empty(pyname) && empty(python_exe)
if !exists('g:'.host_prog_var)
@@ -573,7 +574,8 @@ function! s:check_ruby() abort
\ ['Run `gem install neovim` to ensure the neovim RubyGem is installed.',
\ 'Run `gem environment` to ensure the gem bin directory is in $PATH.',
\ 'If you are using rvm/rbenv/chruby, try "rehashing".',
- \ 'See :help g:ruby_host_prog for non-standard gem installations.'])
+ \ 'See :help g:ruby_host_prog for non-standard gem installations.',
+ \ 'You may disable this provider (and warning) by adding `let g:loaded_ruby_provider = 0` to your init.vim'])
return
endif
call health#report_info('Host: '. host)
@@ -634,7 +636,8 @@ function! s:check_node() abort
if empty(host)
call health#report_warn('Missing "neovim" npm (or yarn) package.',
\ ['Run in shell: npm install -g neovim',
- \ 'Run in shell (if you use yarn): yarn global add neovim'])
+ \ 'Run in shell (if you use yarn): yarn global add neovim',
+ \ 'You may disable this provider (and warning) by adding `let g:loaded_node_provider = 0` to your init.vim'])
return
endif
call health#report_info('Nvim node.js host: '. host)
@@ -683,14 +686,15 @@ function! s:check_perl() abort
return
endif
- let [perl_exec, perl_errors] = provider#perl#Detect()
+ let [perl_exec, perl_warnings] = provider#perl#Detect()
if empty(perl_exec)
- if !empty(perl_errors)
- call health#report_error('perl provider error:', perl_errors)
- else
+ if !empty(perl_warnings)
+ call health#report_warn(perl_warnings, ['See :help provider-perl for more information.',
+ \ 'You may disable this provider (and warning) by adding `let g:loaded_node_provider = 0` to your init.vim'])
+ else
call health#report_warn('No usable perl executable found')
endif
- return
+ return
endif
call health#report_info('perl executable: '. perl_exec)
diff --git a/runtime/autoload/provider/pythonx.vim b/runtime/autoload/provider/pythonx.vim
index 5b299b322c..048f898e62 100644
--- a/runtime/autoload/provider/pythonx.vim
+++ b/runtime/autoload/provider/pythonx.vim
@@ -56,7 +56,7 @@ function! provider#pythonx#DetectByModule(module, major_version) abort
endfor
" No suitable Python executable found.
- return ['', 'provider/pythonx: Could not load Python '.a:major_version.":\n".join(errors, "\n")]
+ return ['', 'Could not load Python '.a:major_version.":\n".join(errors, "\n")]
endfunction
" Returns array: [prog_exitcode, prog_version]
@@ -99,7 +99,7 @@ function! provider#pythonx#CheckForModule(prog, module, major_version) abort
endif
if prog_exitcode == 2
- return [0, prog_path.' does not have the "' . a:module . '" module. :help provider-python']
+ return [0, prog_path.' does not have the "' . a:module . '" module.']
elseif prog_exitcode == 127
" This can happen with pyenv's shims.
return [0, prog_path . ' does not exist: ' . prog_version]
diff --git a/runtime/compiler/jest.vim b/runtime/compiler/jest.vim
index fee70b7c55..a4bb549de1 100644
--- a/runtime/compiler/jest.vim
+++ b/runtime/compiler/jest.vim
@@ -1,7 +1,7 @@
" Vim compiler file
" Compiler: Jest
" Maintainer: Doug Kearns <dougkearns@gmail.com>
-" Last Change: 2018 May 15
+" Last Change: 2021 Nov 20
if exists("current_compiler")
finish
@@ -15,12 +15,14 @@ endif
let s:cpo_save = &cpo
set cpo&vim
-" CompilerSet makeprg=npx\ jest\ --no-colors
+" CompilerSet makeprg=npx\ --no-install\ jest\ --no-colors
CompilerSet makeprg=jest\ --no-colors
-CompilerSet errorformat=%E\ \ ●\ %m,
+CompilerSet errorformat=%-A\ \ ●\ Console,
+ \%E\ \ ●\ %m,
\%Z\ %\\{4}%.%#Error:\ %f:\ %m\ (%l:%c):%\\=,
\%Z\ %\\{6}at\ %\\S%#\ (%f:%l:%c),
+ \%Z\ %\\{6}at\ %\\S%#\ %f:%l:%c,
\%+C\ %\\{4}%\\w%.%#,
\%+C\ %\\{4}%[-+]%.%#,
\%-C%.%#,
diff --git a/runtime/compiler/sml.vim b/runtime/compiler/sml.vim
index c7e1b1bf16..a0b13b6c8a 100644
--- a/runtime/compiler/sml.vim
+++ b/runtime/compiler/sml.vim
@@ -1,7 +1,7 @@
" Vim compiler file
" Compiler: SML/NJ Compiler
" Maintainer: Doug Kearns <dougkearns@gmail.com>
-" Last Change: 2020 Feb 10
+" Last Change: 2022 Feb 09
if exists("current_compiler")
finish
@@ -16,10 +16,10 @@ let s:cpo_save = &cpo
set cpo&vim
CompilerSet makeprg=sml
-CompilerSet errorformat=%f:%l.%c-%\\d%\\+.%\\d%\\+\ %trror:\ %m,
+CompilerSet errorformat=%f:%l.%c-%e.%k\ %trror:\ %m,
\%f:%l.%c\ %trror:\ %m,
- \%trror:\ %m
- \%f:%l.%c-%\\d%\\+.%\\d%\\+\ %tarning:\ %m,
+ \%trror:\ %m,
+ \%f:%l.%c-%e.%k\ %tarning:\ %m,
\%f:%l.%c\ %tarning:\ %m,
\%tarning:\ %m,
\%-G%.%#
diff --git a/runtime/doc/api.txt b/runtime/doc/api.txt
index 1e1534c31f..4af13a3bbf 100644
--- a/runtime/doc/api.txt
+++ b/runtime/doc/api.txt
@@ -594,7 +594,8 @@ nvim__id_float({flt}) *nvim__id_float()*
its argument.
nvim__inspect_cell({grid}, {row}, {col}) *nvim__inspect_cell()*
- TODO: Documentation
+ NB: if your UI doesn't use hlstate, this will not return
+ hlstate first time.
nvim__runtime_inspect() *nvim__runtime_inspect()*
TODO: Documentation
@@ -651,6 +652,9 @@ nvim_add_user_command({name}, {command}, {*opts})
that contains the following keys:
• args: (string) The args passed to the
command, if any |<args>|
+ • fargs: (table) The args split by unescaped
+ whitespace (when more than one argument is
+ allowed), if any |<f-args>|
• bang: (boolean) "true" if the command was
executed with a ! modifier |<bang>|
• line1: (number) The starting line of the
@@ -706,7 +710,7 @@ nvim_call_atomic({calls}) *nvim_call_atomic()*
be returned.
nvim_chan_send({chan}, {data}) *nvim_chan_send()*
- Send data to channel `id` . For a job, it writes it to the
+ 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 terminal output.
@@ -846,7 +850,7 @@ nvim_exec_lua({code}, {args}) *nvim_exec_lua()*
inside the chunk. The chunk can return a value.
Only statements are executed. To evaluate an expression,
- prefix it with `return` : return my_function(...)
+ prefix it with `return`: return my_function(...)
Parameters: ~
{code} Lua code to execute
@@ -1129,13 +1133,13 @@ nvim_get_option_value({name}, {*opts}) *nvim_get_option_value()*
Option value
nvim_get_proc({pid}) *nvim_get_proc()*
- Gets info describing process `pid` .
+ Gets info describing process `pid`.
Return: ~
Map of process properties, or NIL if process not found.
nvim_get_proc_children({pid}) *nvim_get_proc_children()*
- Gets the immediate children of process `pid` .
+ Gets the immediate children of process `pid`.
Return: ~
Array of child process ids, empty if process not found.
@@ -1244,8 +1248,8 @@ nvim_input_mouse({button}, {action}, {modifier}, {grid}, {row}, {col})
nvim_list_bufs() *nvim_list_bufs()*
Gets the current list of buffer handles
- Includes unlisted (unloaded/deleted) buffers, like `:ls!` .
- Use |nvim_buf_is_loaded()| to check if a buffer is loaded.
+ Includes unlisted (unloaded/deleted) buffers, like `:ls!`. Use
+ |nvim_buf_is_loaded()| to check if a buffer is loaded.
Return: ~
List of buffer handles
@@ -1354,7 +1358,7 @@ nvim_paste({data}, {crlf}, {phase}) *nvim_paste()*
Errors ('nomodifiable', `vim.paste()` failure, …) are
reflected in `err` but do not affect the return value (which
- is strictly decided by `vim.paste()` ). On error, subsequent
+ is strictly decided by `vim.paste()`). On error, subsequent
calls are ignored ("drained") until the next paste is
initiated (phase 1 or -1).
@@ -1431,7 +1435,7 @@ nvim_select_popupmenu_item({item}, {insert}, {finish}, {opts})
{insert} Whether the selection should be inserted in the
buffer.
{finish} Finish the completion and dismiss the popupmenu.
- Implies `insert` .
+ Implies `insert`.
{opts} Optional parameters. Reserved for future use.
*nvim_set_client_info()*
@@ -1541,23 +1545,24 @@ nvim_set_current_win({window}) *nvim_set_current_win()*
{window} Window handle
nvim_set_hl({ns_id}, {name}, {*val}) *nvim_set_hl()*
- Set a highlight group.
-
- Parameters: ~
- {ns_id} number of namespace for this highlight. Use value
- 0 to set a highlight group in the global (
- `:highlight` ) namespace.
- {name} highlight group name, like ErrorMsg
- {val} highlight definition map, like
- |nvim_get_hl_by_name|. in addition the following
- keys are also recognized: `default` : don't
- override existing definition, like `hi default`
- `ctermfg` : sets foreground of cterm color
- `ctermbg` : sets background of cterm color
- `cterm` : cterm attribute map. sets attributed
- for cterm colors. similer to `hi cterm` Note: by
- default cterm attributes are same as attributes
- of gui color
+ Sets a highlight group.
+
+ Parameters: ~
+ {ns_id} Namespace id for this highlight
+ |nvim_create_namespace()|. Use 0 to set a
+ highlight group globally |:highlight|.
+ {name} Highlight group name, e.g. "ErrorMsg"
+ {val} Highlight definition map, like |synIDattr()|. In
+ addition, the following keys are recognized:
+ • default: Don't override existing definition
+ |:hi-default|
+ • ctermfg: Sets foreground of cterm color
+ |highlight-ctermfg|
+ • ctermbg: Sets background of cterm color
+ |highlight-ctermbg|
+ • cterm: cterm attribute map, like
+ |highlight-args|. Note: Attributes default to
+ those set for `gui` if not set.
nvim_set_keymap({mode}, {lhs}, {rhs}, {*opts}) *nvim_set_keymap()*
Sets a global |mapping| for the given mode.
@@ -1626,7 +1631,7 @@ nvim_set_vvar({name}, {value}) *nvim_set_vvar()*
{value} Variable value
nvim_strwidth({text}) *nvim_strwidth()*
- Calculates the number of display cells occupied by `text` .
+ Calculates the number of display cells occupied by `text`.
<Tab> counts as one cell.
Parameters: ~
@@ -1878,9 +1883,10 @@ nvim_buf_attach({buffer}, {send_buffer}, {opts}) *nvim_buf_attach()*
{buffer} Buffer handle, or 0 for current buffer
{send_buffer} True if the initial notification should
contain the whole buffer: first
- notification will be `nvim_buf_lines_event`
- . Else the first notification will be
- `nvim_buf_changedtick_event` . Not for Lua
+ notification will be
+ `nvim_buf_lines_event`. Else the first
+ notification will be
+ `nvim_buf_changedtick_event`. Not for Lua
callbacks.
{opts} Optional parameters.
• on_lines: Lua callback invoked on change.
@@ -1936,7 +1942,7 @@ nvim_buf_attach({buffer}, {send_buffer}, {opts}) *nvim_buf_attach()*
• utf_sizes: include UTF-32 and UTF-16 size
of the replaced region, as args to
- `on_lines` .
+ `on_lines`.
• preview: also attach to command preview
(i.e. 'inccommand') events.
@@ -2152,6 +2158,29 @@ nvim_buf_get_option({buffer}, {name}) *nvim_buf_get_option()*
Return: ~
Option value
+ *nvim_buf_get_text()*
+nvim_buf_get_text({buffer}, {start_row}, {start_col}, {end_row}, {end_col},
+ {opts})
+ Gets a range from the buffer.
+
+ This differs from |nvim_buf_get_lines()| in that it allows
+ retrieving only portions of a line.
+
+ Indexing is zero-based. Column indices are end-exclusive.
+
+ Prefer |nvim_buf_get_lines()| when retrieving entire lines.
+
+ Parameters: ~
+ {buffer} Buffer handle, or 0 for current buffer
+ {start_row} First line index
+ {start_col} Starting byte offset of first line
+ {end_row} Last line index
+ {end_col} Ending byte offset of last line (exclusive)
+ {opts} Optional parameters. Currently unused.
+
+ Return: ~
+ Array of lines, or empty array for unloaded buffer.
+
nvim_buf_get_var({buffer}, {name}) *nvim_buf_get_var()*
Gets a buffer-scoped (b:) variable.
@@ -2328,7 +2357,7 @@ nvim_buf_add_highlight({buffer}, {ns_id}, {hl_group}, {line}, {col_start},
namespace. All highlights in the same namespace can then be
cleared with single call to |nvim_buf_clear_namespace()|. If
the highlight never will be deleted by an API call, pass
- `ns_id = -1` .
+ `ns_id = -1`.
As a shorthand, `ns_id = 0` can be used to create a new
namespace for the highlight, the allocated id is then
@@ -2408,8 +2437,8 @@ nvim_buf_get_extmarks({buffer}, {ns_id}, {start}, {end}, {opts})
nvim_buf_get_extmarks(0, my_ns, [0,0], [-1,-1], {})
<
- If `end` is less than `start` , traversal works backwards.
- (Useful with `limit` , to get the first marks prior to a given
+ If `end` is less than `start`, traversal works backwards.
+ (Useful with `limit`, to get the first marks prior to a given
position.)
Example:
@@ -2756,7 +2785,7 @@ nvim_win_hide({window}) *nvim_win_hide()*
|:hide| with a |window-ID|).
Like |:hide| the buffer becomes hidden unless another window
- is editing it, or 'bufhidden' is `unload` , `delete` or `wipe`
+ is editing it, or 'bufhidden' is `unload`, `delete` or `wipe`
as opposed to |:close| or |nvim_win_close|, which will close
the buffer.
@@ -3004,7 +3033,7 @@ nvim_win_set_config({window}, {*config}) *nvim_win_set_config()*
layouts).
When reconfiguring a floating window, absent option keys will
- not be changed. `row` / `col` and `relative` must be
+ not be changed. `row`/`col` and `relative` must be
reconfigured together.
Parameters: ~
@@ -3083,6 +3112,135 @@ nvim_tabpage_set_var({tabpage}, {name}, {value})
==============================================================================
+Autocmd Functions *api-autocmd*
+
+nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()*
+ Create or get an augroup.
+
+ To get an existing augroup ID, do: >
+ local id = vim.api.nvim_create_augroup(name, {
+ clear = false
+ })
+<
+
+ Parameters: ~
+ {name} String: The name of the augroup to create
+ {opts} Parameters
+ • clear (bool): Whether to clear existing commands
+ or not. Defaults to true. See |autocmd-groups|
+
+ Return: ~
+ opaque value to use with nvim_del_augroup_by_id
+
+nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()*
+ Create an autocmd.
+
+ Examples:
+ • event: "pat1,pat2,pat3",
+ • event: "pat1"
+ • event: { "pat1" }
+ • event: { "pat1", "pat2", "pat3" }
+
+ Parameters: ~
+ {event} The event or events to register this autocmd
+ Required keys: event: string | ArrayOf(string)
+
+ Parameters: ~
+ {opts} Optional Parameters:
+ • callback: (string|function)
+ • (string): The name of the viml function to
+ execute when triggering this autocmd
+ • (function): The lua function to execute when
+ triggering this autocmd
+ • NOTE: Cannot be used with {command}
+
+ • command: (string) command
+ • vimscript command
+ • NOTE: Cannot be used with {callback} Eg.
+ command = "let g:value_set = v:true"
+
+ • pattern: (string|table)
+ • pattern or patterns to match against
+ • defaults to "*".
+ • NOTE: Cannot be used with {buffer}
+
+ • buffer: (bufnr)
+ • create a |autocmd-buflocal| autocmd.
+ • NOTE: Cannot be used with {pattern}
+
+ • group: (string|int) The augroup name or id
+ • once: (boolean) - See |autocmd-once|
+ • nested: (boolean) - See |autocmd-nested|
+ • desc: (string) - Description of the autocmd
+
+ Return: ~
+ opaque value to use with nvim_del_autocmd
+
+nvim_del_augroup_by_id({id}) *nvim_del_augroup_by_id()*
+ Delete an augroup by {id}. {id} can only be returned when
+ augroup was created with |nvim_create_augroup|.
+
+ NOTE: behavior differs from augroup-delete.
+
+ When deleting an augroup, autocmds contained by this augroup
+ will also be deleted and cleared. This augroup will no longer
+ exist
+
+nvim_del_augroup_by_name({name}) *nvim_del_augroup_by_name()*
+ Delete an augroup by {name}.
+
+ NOTE: behavior differs from augroup-delete.
+
+ When deleting an augroup, autocmds contained by this augroup
+ will also be deleted and cleared. This augroup will no longer
+ exist
+
+nvim_del_autocmd({id}) *nvim_del_autocmd()*
+ Delete an autocmd by {id}. Autocmds only return IDs when
+ created via the API. Will not error if called and no autocmds
+ match the {id}.
+
+ Parameters: ~
+ {id} Integer The ID returned by nvim_create_autocmd
+
+nvim_do_autocmd({event}, {*opts}) *nvim_do_autocmd()*
+ Do one autocmd.
+
+ Parameters: ~
+ {event} The event or events to execute
+ {opts} Optional Parameters:
+ • buffer (number) - buffer number
+ • NOTE: Cannot be used with {pattern}
+
+ • pattern (string|table) - optional, defaults to
+ "*".
+ • NOTE: Cannot be used with {buffer}
+
+ • group (string|int) - autocmd group name or id
+ • modeline (boolean) - Default true, see
+ |<nomodeline>|
+
+nvim_get_autocmds({*opts}) *nvim_get_autocmds()*
+ Get autocmds that match the requirements passed to {opts}.
+
+ Parameters: ~
+ {opts} Optional Parameters:
+ • event : Name or list of name of events to match
+ against
+ • group (string|int): Name or id of group to match
+ against
+ • pattern: Pattern or list of patterns to match
+ against. Cannot be used with {buffer}
+ • buffer: Buffer number or list of buffer numbers
+ for buffer local autocommands
+ |autocmd-buflocal|. Cannot be used with
+ {pattern}
+
+ Return: ~
+ A list of autocmds that match
+
+
+==============================================================================
UI Functions *api-ui*
nvim_ui_attach({width}, {height}, {options}) *nvim_ui_attach()*
diff --git a/runtime/doc/arabic.txt b/runtime/doc/arabic.txt
index 5d3bf7a761..0df861111c 100644
--- a/runtime/doc/arabic.txt
+++ b/runtime/doc/arabic.txt
@@ -175,7 +175,7 @@ o Enable Arabic settings [short-cut]
vertical separator like "l" or "𝖨" may be used. It may also be
hidden by changing its color to the foreground color: >
:set fillchars=vert:l
- :hi VertSplit ctermbg=White
+ :hi WinSeparator ctermbg=White
< Note that this is a workaround, not a proper solution.
If, on the other hand, you'd like to be verbose and explicit and
diff --git a/runtime/doc/autocmd.txt b/runtime/doc/autocmd.txt
index dbe70b84cf..ab0b0cd07c 100644
--- a/runtime/doc/autocmd.txt
+++ b/runtime/doc/autocmd.txt
@@ -674,15 +674,19 @@ FuncUndefined When a user function is used but it isn't
alternative is to use an autoloaded function.
See |autoload-functions|.
*UIEnter*
-UIEnter After a UI connects via |nvim_ui_attach()|,
- after VimEnter. Can be used for GUI-specific
- configuration.
+UIEnter After a UI connects via |nvim_ui_attach()|, or
+ after builtin TUI is started, after |VimEnter|.
Sets these |v:event| keys:
- chan
+ chan: 0 for builtin TUI
+ 1 for |--embed|
+ |channel-id| of the UI otherwise
*UILeave*
-UILeave After a UI disconnects from Nvim.
+UILeave After a UI disconnects from Nvim, or after
+ builtin TUI is stopped, after |VimLeave|.
Sets these |v:event| keys:
- chan
+ chan: 0 for builtin TUI
+ 1 for |--embed|
+ |channel-id| of the UI otherwise
*InsertChange*
InsertChange When typing <Insert> while in Insert or
Replace mode. The |v:insertmode| variable
@@ -1075,7 +1079,7 @@ WinLeave Before leaving a window. If the window to be
executes the BufLeave autocommands before the
WinLeave autocommands (but not for ":new").
Not used for ":qa" or ":q" when exiting Vim.
- After WinClosed.
+ Before WinClosed.
*WinNew*
WinNew When a new window was created. Not done for
the first window, when Vim has just started.
@@ -1406,7 +1410,7 @@ Examples for reading and writing compressed files: >
: autocmd BufReadPre,FileReadPre *.gz set bin
: autocmd BufReadPost,FileReadPost *.gz '[,']!gunzip
: autocmd BufReadPost,FileReadPost *.gz set nobin
- : autocmd BufReadPost,FileReadPost *.gz execute ":doautocmd BufReadPost " . expand("%:r")
+ : autocmd BufReadPost,FileReadPost *.gz execute ":doautocmd BufReadPost " .. expand("%:r")
: autocmd BufWritePost,FileWritePost *.gz !mv <afile> <afile>:r
: autocmd BufWritePost,FileWritePost *.gz !gzip <afile>:r
@@ -1505,7 +1509,7 @@ To insert the current date and time in a *.html file when writing it: >
: else
: let l = line("$")
: endif
- : exe "1," . l . "g/Last modified: /s/Last modified: .*/Last modified: " .
+ : exe "1," .. l .. "g/Last modified: /s/Last modified: .*/Last modified: " ..
: \ strftime("%Y %b %d")
:endfun
diff --git a/runtime/doc/builtin.txt b/runtime/doc/builtin.txt
index 35a232c0c2..9eec23b7b7 100644
--- a/runtime/doc/builtin.txt
+++ b/runtime/doc/builtin.txt
@@ -693,7 +693,7 @@ argv([{nr} [, {winid}]])
:let i = 0
:while i < argc()
: let f = escape(fnameescape(argv(i)), '.')
- : exe 'amenu Arg.' . f . ' :e ' . f . '<CR>'
+ : exe 'amenu Arg.' .. f .. ' :e ' .. f .. '<CR>'
: let i = i + 1
:endwhile
< Without the {nr} argument, or when {nr} is -1, a |List| with
@@ -895,7 +895,7 @@ bufwinid({buf}) *bufwinid()*
see |bufname()| above. If buffer {buf} doesn't exist or
there is no such window, -1 is returned. Example: >
- echo "A window containing buffer 1 is " . (bufwinid(1))
+ echo "A window containing buffer 1 is " .. (bufwinid(1))
<
Only deals with the current tab page.
@@ -908,7 +908,7 @@ bufwinnr({buf}) *bufwinnr()*
If buffer {buf} doesn't exist or there is no such window, -1
is returned. Example: >
- echo "A window containing buffer 1 is " . (bufwinnr(1))
+ echo "A window containing buffer 1 is " .. (bufwinnr(1))
< The number can be used with |CTRL-W_w| and ":wincmd w"
|:wincmd|.
@@ -955,7 +955,7 @@ byteidx({expr}, {nr}) *byteidx()*
byteidxcomp({expr}, {nr}) *byteidxcomp()*
Like byteidx(), except that a composing character is counted
as a separate character. Example: >
- let s = 'e' . nr2char(0x301)
+ let s = 'e' .. nr2char(0x301)
echo byteidx(s, 1)
echo byteidxcomp(s, 1)
echo byteidxcomp(s, 2)
@@ -1152,7 +1152,7 @@ col({expr}) The result is a Number, which is the byte index of the column
col(".") column of cursor
col("$") length of cursor line plus one
col("'t") column of mark t
- col("'" . markname) column of mark markname
+ col("'" .. markname) column of mark markname
< The first column is 1. 0 is returned for an error.
For an uppercase mark the column may actually be in another
buffer.
@@ -1161,7 +1161,7 @@ col({expr}) The result is a Number, which is the byte index of the column
line. This can be used to obtain the column in Insert mode: >
:imap <F2> <C-O>:let save_ve = &ve<CR>
\<C-O>:set ve=all<CR>
- \<C-O>:echo col(".") . "\n" <Bar>
+ \<C-O>:echo col(".") .. "\n" <Bar>
\let &ve = save_ve<CR>
< Can also be used as a |method|: >
@@ -1284,7 +1284,7 @@ complete_info([{what}]) *complete_info()*
<
*confirm()*
confirm({msg} [, {choices} [, {default} [, {type}]]])
- Confirm() offers the user a dialog, from which a choice can be
+ confirm() offers the user a dialog, from which a choice can be
made. It returns the number of the choice. For the first
choice this is 1.
@@ -1807,6 +1807,7 @@ exists({expr}) The result is a Number, which is |TRUE| if {expr} is
exists("$HOSTNAME")
exists("*strftime")
exists("*s:MyFunc")
+ exists("*MyFunc")
exists("bufcount")
exists(":Make")
exists("#CursorHold")
@@ -1898,12 +1899,12 @@ expand({string} [, {nosuf} [, {list}]]) *expand()*
:e extension only
Example: >
- :let &tags = expand("%:p:h") . "/tags"
+ :let &tags = expand("%:p:h") .. "/tags"
< Note that when expanding a string that starts with '%', '#' or
'<', any following text is ignored. This does NOT work: >
:let doesntwork = expand("%:h.bak")
< Use this: >
- :let doeswork = expand("%:h") . ".bak"
+ :let doeswork = expand("%:h") .. ".bak"
< Also note that expanding "<cfile>" and others only returns the
referenced file name without further expansion. If "<cfile>"
is "~/.cshrc", you need to do another expand() to have the
@@ -2239,7 +2240,7 @@ fnameescape({string}) *fnameescape()*
and |:write|). And a "-" by itself (special after |:cd|).
Example: >
:let fname = '+some str%nge|name'
- :exe "edit " . fnameescape(fname)
+ :exe "edit " .. fnameescape(fname)
< results in executing: >
edit \+some\ str\%nge\|name
<
@@ -2394,7 +2395,7 @@ function({name} [, {arglist}] [, {dict}])
< The Dictionary is only useful when calling a "dict" function.
In that case the {dict} is passed in as "self". Example: >
function Callback() dict
- echo "called for " . self.name
+ echo "called for " .. self.name
endfunction
...
let context = {"name": "example"}
@@ -2577,7 +2578,7 @@ getbufvar({buf}, {varname} [, {def}]) *getbufvar()*
string is returned, there is no error message.
Examples: >
:let bufmodified = getbufvar(1, "&mod")
- :echo "todo myvar = " . getbufvar("todo", "myvar")
+ :echo "todo myvar = " .. getbufvar("todo", "myvar")
< Can also be used as a |method|: >
GetBufnr()->getbufvar(varname)
@@ -2638,9 +2639,9 @@ getchar([expr]) *getchar()*
This example positions the mouse as it would normally happen: >
let c = getchar()
if c == "\<LeftMouse>" && v:mouse_win > 0
- exe v:mouse_win . "wincmd w"
+ exe v:mouse_win .. "wincmd w"
exe v:mouse_lnum
- exe "normal " . v:mouse_col . "|"
+ exe "normal " .. v:mouse_col .. "|"
endif
<
There is no prompt, you will somehow have to make clear to the
@@ -3038,10 +3039,16 @@ getloclist({nr} [, {what}]) *getloclist()*
If the optional {what} dictionary argument is supplied, then
returns the items listed in {what} as a dictionary. Refer to
|getqflist()| for the supported items in {what}.
- If {what} contains 'filewinid', then returns the id of the
- window used to display files from the location list. This
- field is applicable only when called from a location list
- window. See |location-list-file-window| for more details.
+
+ In addition to the items supported by |getqflist()| in {what},
+ the following item is supported by |getloclist()|:
+
+ filewinid id of the window used to display files
+ from the location list. This field is
+ applicable only when called from a
+ location list window. See
+ |location-list-file-window| for more
+ details.
Returns a |Dictionary| with default values if there is no
location list for the window {nr}.
@@ -3217,6 +3224,9 @@ getqflist([{what}]) *getqflist()*
nr get information for this quickfix list; zero
means the current quickfix list and "$" means
the last quickfix list
+ qfbufnr number of the buffer displayed in the quickfix
+ window. Returns 0 if the quickfix buffer is
+ not present. See |quickfix-buffer|.
size number of entries in the quickfix list
title get the list title |quickfix-title|
winid get the quickfix |window-ID|
@@ -3245,6 +3255,8 @@ getqflist([{what}]) *getqflist()*
items quickfix list entries. If not present, set to
an empty list.
nr quickfix list number. If not present, set to 0
+ qfbufnr number of the buffer displayed in the quickfix
+ window. If not present, set to 0.
size number of entries in the quickfix list. If not
present, set to 0.
title quickfix list title text. If not present, set
@@ -3373,7 +3385,7 @@ gettabwinvar({tabnr}, {winnr}, {varname} [, {def}]) *gettabwinvar()*
empty string is returned, there is no error message.
Examples: >
:let list_is_on = gettabwinvar(1, 2, '&list')
- :echo "myvar = " . gettabwinvar(3, 1, 'myvar')
+ :echo "myvar = " .. gettabwinvar(3, 1, 'myvar')
<
To obtain all window-local variables use: >
gettabwinvar({tabnr}, {winnr}, '&')
@@ -3488,7 +3500,7 @@ getwinvar({winnr}, {varname} [, {def}]) *getwinvar()*
Like |gettabwinvar()| for the current tabpage.
Examples: >
:let list_is_on = getwinvar(2, '&list')
- :echo "myvar = " . getwinvar(1, 'myvar')
+ :echo "myvar = " .. getwinvar(1, 'myvar')
< Can also be used as a |method|: >
GetWinnr()->getwinvar(varname)
@@ -3757,7 +3769,7 @@ histdel({history} [, {item}]) *histdel()*
The following three are equivalent: >
:call histdel("search", histnr("search"))
:call histdel("search", -1)
- :call histdel("search", '^'.histget("search", -1).'$')
+ :call histdel("search", '^' .. histget("search", -1) .. '$')
<
To delete the last search pattern and use the last-but-one for
the "n" command and 'hlsearch': >
@@ -3776,7 +3788,7 @@ histget({history} [, {index}]) *histget()*
Examples:
Redo the second last search from history. >
- :execute '/' . histget("search", -2)
+ :execute '/' .. histget("search", -2)
< Define an Ex command ":H {num}" that supports re-execution of
the {num}th entry from the output of |:history|. >
@@ -3940,11 +3952,11 @@ input({opts})
let lvl = 0
while i < len(a:cmdline)
if a:cmdline[i] is# '('
- call add(ret, [i, i + 1, 'RBP' . ((lvl % g:rainbow_levels) + 1)])
+ call add(ret, [i, i + 1, 'RBP' .. ((lvl % g:rainbow_levels) + 1)])
let lvl += 1
elseif a:cmdline[i] is# ')'
let lvl -= 1
- call add(ret, [i, i + 1, 'RBP' . ((lvl % g:rainbow_levels) + 1)])
+ call add(ret, [i, i + 1, 'RBP' .. ((lvl % g:rainbow_levels) + 1)])
endif
let i += 1
endwhile
@@ -3974,7 +3986,7 @@ input({opts})
|:execute| or |:normal|.
Example with a mapping: >
- :nmap \x :call GetFoo()<CR>:exe "/" . Foo<CR>
+ :nmap \x :call GetFoo()<CR>:exe "/" .. Foo<CR>
:function GetFoo()
: call inputsave()
: let g:Foo = input("enter search pattern: ")
@@ -4133,7 +4145,7 @@ items({dict}) *items()*
order. Also see |keys()| and |values()|.
Example: >
for [key, value] in items(mydict)
- echo key . ': ' . value
+ echo key .. ': ' .. value
endfor
< Can also be used as a |method|: >
@@ -4269,7 +4281,7 @@ join({list} [, {sep}]) *join()*
{sep} is omitted a single space is used.
Note that {sep} is not added at the end. You might want to
add it there too: >
- let lines = join(mylist, "\n") . "\n"
+ let lines = join(mylist, "\n") .. "\n"
< String items are used as-is. |Lists| and |Dictionaries| are
converted into a string like with |string()|.
The opposite function is |split()|.
@@ -4418,7 +4430,7 @@ line({expr} [, {winid}]) *line()*
line(".") line number of the cursor
line(".", winid) idem, in window "winid"
line("'t") line number of mark t
- line("'" . marker) line number of mark marker
+ line("'" .. marker) line number of mark marker
<
To jump to the last known position when opening a file see
|last-position-jump|.
@@ -4519,7 +4531,7 @@ map({expr1}, {expr2}) *map()*
the current item. For a |Blob| |v:key| has the index of the
current byte.
Example: >
- :call map(mylist, '"> " . v:val . " <"')
+ :call map(mylist, '"> " .. v:val .. " <"')
< This puts "> " before and " <" after each item in "mylist".
Note that {expr2} is the result of an expression and is then
@@ -4533,19 +4545,19 @@ map({expr1}, {expr2}) *map()*
The function must return the new value of the item. Example
that changes each value by "key-value": >
func KeyValue(key, val)
- return a:key . '-' . a:val
+ return a:key .. '-' .. a:val
endfunc
call map(myDict, function('KeyValue'))
< It is shorter when using a |lambda|: >
- call map(myDict, {key, val -> key . '-' . val})
+ call map(myDict, {key, val -> key .. '-' .. val})
< If you do not use "val" you can leave it out: >
- call map(myDict, {key -> 'item: ' . key})
+ call map(myDict, {key -> 'item: ' .. key})
< If you do not use "key" you can use a short name: >
- call map(myDict, {_, val -> 'item: ' . val})
+ call map(myDict, {_, val -> 'item: ' .. val})
<
The operation is done in-place. If you want a |List| or
|Dictionary| to remain unmodified make a copy first: >
- :let tlist = map(copy(mylist), ' v:val . "\t"')
+ :let tlist = map(copy(mylist), ' v:val .. "\t"')
< Returns {expr1}, the |List|, |Blob| or |Dictionary| that was
filtered. When an error is encountered while evaluating
@@ -4611,7 +4623,7 @@ maparg({name} [, {mode} [, {abbr} [, {dict}]]]) *maparg()*
then the global mappings.
This function can be used to map a key even when it's already
mapped, and have it do the original mapping too. Sketch: >
- exe 'nnoremap <Tab> ==' . maparg('<Tab>', 'n')
+ exe 'nnoremap <Tab> ==' .. maparg('<Tab>', 'n')
< Can also be used as a |method|: >
GetKey()->maparg('n')
@@ -4899,7 +4911,7 @@ matchfuzzy({list}, {str} [, {dict}]) *matchfuzzy()*
empty list is returned. If length of {str} is greater than
256, then returns an empty list.
- Refer to |fuzzy-match| for more information about fuzzy
+ Refer to |fuzzy-matching| for more information about fuzzy
matching strings.
Example: >
@@ -5084,7 +5096,7 @@ mkdir({name} [, {path} [, {prot}]])
{prot} is applied for all parts of {name}. Thus if you create
/tmp/foo/bar then /tmp/foo will be created with 0o700. Example: >
- :call mkdir($HOME . "/tmp/foo/bar", "p", 0o700)
+ :call mkdir($HOME .. "/tmp/foo/bar", "p", 0o700)
< This function is not available in the |sandbox|.
@@ -5584,7 +5596,7 @@ prompt_setcallback({buf}, {expr}) *prompt_setcallback()*
stopinsert
close
else
- call append(line('$') - 1, 'Entered: "' . a:text . '"')
+ call append(line('$') - 1, 'Entered: "' .. a:text .. '"')
" Reset 'modified' to allow the buffer to be closed.
set nomodified
endif
@@ -5731,7 +5743,7 @@ readdir({directory} [, {expr}])
function! s:tree(dir)
return {a:dir : map(readdir(a:dir),
\ {_, x -> isdirectory(x) ?
- \ {x : s:tree(a:dir . '/' . x)} : x})}
+ \ {x : s:tree(a:dir .. '/' .. x)} : x})}
endfunction
echo s:tree(".")
<
@@ -5863,16 +5875,22 @@ reltimestr({time}) *reltimestr()*
<
*remote_expr()* *E449*
remote_expr({server}, {string} [, {idvar} [, {timeout}]])
- Send the {string} to {server}. The string is sent as an
- expression and the result is returned after evaluation.
- The result must be a String or a |List|. A |List| is turned
- into a String by joining the items with a line break in
- between (not at the end), like with join(expr, "\n").
+ Send the {string} to {server}. The {server} argument is a
+ string, also see |{server}|.
+
+ The string is sent as an expression and the result is returned
+ after evaluation. The result must be a String or a |List|. A
+ |List| is turned into a String by joining the items with a
+ line break in between (not at the end), like with join(expr,
+ "\n").
+
If {idvar} is present and not empty, it is taken as the name
of a variable and a {serverid} for later use with
|remote_read()| is stored there.
+
If {timeout} is given the read times out after this many
seconds. Otherwise a timeout of 600 seconds is used.
+
See also |clientserver| |RemoteReply|.
This function is not available in the |sandbox|.
Note: Any errors will cause a local error message to be issued
@@ -5890,7 +5908,7 @@ remote_expr({server}, {string} [, {idvar} [, {timeout}]])
remote_foreground({server}) *remote_foreground()*
Move the Vim server with the name {server} to the foreground.
- The {server} argument is a string.
+ The {server} argument is a string, also see |{server}|.
This works like: >
remote_expr({server}, "foreground()")
< Except that on Win32 systems the client does the work, to work
@@ -5913,7 +5931,7 @@ remote_peek({serverid} [, {retvar}]) *remote_peek()*
This function is not available in the |sandbox|.
Examples: >
:let repl = ""
- :echo "PEEK: ".remote_peek(id, "repl").": ".repl
+ :echo "PEEK: " .. remote_peek(id, "repl") .. ": " .. repl
remote_read({serverid}, [{timeout}]) *remote_read()*
Return the oldest available reply from {serverid} and consume
@@ -5926,24 +5944,29 @@ remote_read({serverid}, [{timeout}]) *remote_read()*
<
*remote_send()* *E241*
remote_send({server}, {string} [, {idvar}])
- Send the {string} to {server}. The string is sent as input
- keys and the function returns immediately. At the Vim server
- the keys are not mapped |:map|.
+ Send the {string} to {server}. The {server} argument is a
+ string, also see |{server}|.
+
+ The string is sent as input keys and the function returns
+ immediately. At the Vim server the keys are not mapped
+ |:map|.
+
If {idvar} is present, it is taken as the name of a variable
and a {serverid} for later use with remote_read() is stored
there.
+
See also |clientserver| |RemoteReply|.
This function is not available in the |sandbox|.
Note: Any errors will be reported in the server and may mess
up the display.
Examples: >
- :echo remote_send("gvim", ":DropAndReply ".file, "serverid").
+ :echo remote_send("gvim", ":DropAndReply " .. file, "serverid") ..
\ remote_read(serverid)
:autocmd NONE RemoteReply *
\ echo remote_read(expand("<amatch>"))
- :echo remote_send("gvim", ":sleep 10 | echo ".
+ :echo remote_send("gvim", ":sleep 10 | echo " ..
\ 'server2client(expand("<client>"), "HELLO")<CR>')
<
*remote_startserver()* *E941* *E942*
@@ -5960,7 +5983,7 @@ remove({list}, {idx} [, {end}]) *remove()*
points to an item before {idx} this is an error.
See |list-index| for possible values of {idx} and {end}.
Example: >
- :echo "last item: " . remove(mylist, -1)
+ :echo "last item: " .. remove(mylist, -1)
:call remove(mylist, 0, 9)
<
Use |delete()| to remove a file.
@@ -5976,13 +5999,13 @@ remove({blob}, {idx} [, {end}])
byte as {end} a |Blob| with one byte is returned. When {end}
points to a byte before {idx} this is an error.
Example: >
- :echo "last byte: " . remove(myblob, -1)
+ :echo "last byte: " .. remove(myblob, -1)
:call remove(mylist, 0, 9)
remove({dict}, {key})
Remove the entry from {dict} with key {key} and return it.
Example: >
- :echo "removed " . remove(dict, "one")
+ :echo "removed " .. remove(dict, "one")
< If there is no {key} in {dict} this is an error.
rename({from}, {to}) *rename()*
@@ -6123,7 +6146,7 @@ screencol() *screencol()*
column inside the command line, which is 1 when the command is
executed. To get the cursor position in the file use one of
the following mappings: >
- nnoremap <expr> GG ":echom ".screencol()."\n"
+ nnoremap <expr> GG ":echom " .. screencol() .. "\n"
nnoremap <silent> GG :echom screencol()<CR>
noremap GG <Cmd>echom screencol()<Cr>
<
@@ -6244,7 +6267,7 @@ search({pattern} [, {flags} [, {stopline} [, {timeout} [, {skip}]]]])
Example (goes over all files in the argument list): >
:let n = 1
:while n <= argc() " loop over all files in arglist
- : exe "argument " . n
+ : exe "argument " .. n
: " start at the last char in the file and wrap for the
: " first search to find match at start of file
: normal G$
@@ -6328,11 +6351,11 @@ searchcount([{options}]) *searchcount()*
return printf(' /%s [%d/%d]', @/,
\ result.current, result.total)
endfunction
- let &statusline .= '%{LastSearchCount()}'
+ let &statusline ..= '%{LastSearchCount()}'
" Or if you want to show the count only when
" 'hlsearch' was on
- " let &statusline .=
+ " let &statusline ..=
" \ '%{v:hlsearch ? LastSearchCount() : ""}'
<
You can also update the search count, which can be useful in a
@@ -6868,12 +6891,14 @@ setqflist({list} [, {action} [, {what}]]) *setqflist()*
filename name of a file; only used when "bufnr" is not
present or it is invalid.
module name of a module; if given it will be used in
- quickfix error window instead of the filename
+ quickfix error window instead of the filename.
lnum line number in the file
+ end_lnum end of lines, if the item spans multiple lines
pattern search pattern used to locate the error
col column number
vcol when non-zero: "col" is visual column
when zero: "col" is byte index
+ end_col end column, if the item spans multiple columns
nr error number
text description of the error
type single-character error type, 'E', 'W', etc.
@@ -7134,10 +7159,10 @@ shellescape({string} [, {special}]) *shellescape()*
inside single quotes.
Example of use with a |:!| command: >
- :exe '!dir ' . shellescape(expand('<cfile>'), 1)
+ :exe '!dir ' .. shellescape(expand('<cfile>'), 1)
< This results in a directory listing for the file under the
cursor. Example of use with |system()|: >
- :call system("chmod +w -- " . shellescape(expand("%")))
+ :call system("chmod +w -- " .. shellescape(expand("%")))
< See also |::S|.
Can also be used as a |method|: >
@@ -7829,7 +7854,7 @@ substitute({string}, {pat}, {sub}, {flags}) *substitute()*
When {sub} starts with "\=", the remainder is interpreted as
an expression. See |sub-replace-expression|. Example: >
:echo substitute(s, '%\(\x\x\)',
- \ '\=nr2char("0x" . submatch(1))', 'g')
+ \ '\=nr2char("0x" .. submatch(1))', 'g')
< When {sub} is a Funcref that function is called, with one
optional argument. Example: >
@@ -7837,7 +7862,7 @@ substitute({string}, {pat}, {sub}, {flags}) *substitute()*
< The optional argument is a list which contains the whole
matched string and up to nine submatches, like what
|submatch()| returns. Example: >
- :echo substitute(s, '%\(\x\x\)', {m -> '0x' . m[1]}, 'g')
+ :echo substitute(s, '%\(\x\x\)', {m -> '0x' .. m[1]}, 'g')
< Can also be used as a |method|: >
GetString()->substitute(pat, sub, flags)
@@ -7925,8 +7950,11 @@ synIDattr({synID}, {what} [, {mode}]) *synIDattr()*
"inverse" "1" if inverse (= reverse)
"standout" "1" if standout
"underline" "1" if underlined
+ "underlineline" "1" if double underlined
"undercurl" "1" if undercurled
- "strikethrough" "1" if struckthrough
+ "underdot" "1" if dotted underlined
+ "underdash" "1" if dashed underlined
+ "strikethrough" "1" if struckthrough
Example (echoes the color of the syntax item under the
cursor): >
@@ -8075,15 +8103,15 @@ tabpagebuflist([{arg}]) *tabpagebuflist()*
tabpagenr([{arg}]) *tabpagenr()*
The result is a Number, which is the number of the current
tab page. The first tab page has number 1.
+
The optional argument {arg} supports the following values:
$ the number of the last tab page (the tab page
count).
- # the number of the last accessed tab page (where
- |g<Tab>| goes to). If there is no previous
- tab page, 0 is returned.
+ # the number of the last accessed tab page
+ (where |g<Tab>| goes to). If there is no
+ previous tab page, 0 is returned.
The number can be used with the |:tab| command.
-
tabpagewinnr({tabarg} [, {arg}]) *tabpagewinnr()*
Like |winnr()| but for tab page {tabarg}.
{tabarg} specifies the number of tab page to be used.
@@ -8155,7 +8183,7 @@ tempname() *tempname()* *temp-file-name*
The result is a String, which is the name of a file that
doesn't exist. It can be used for a temporary file. Example: >
:let tmpfile = tempname()
- :exe "redir > " . tmpfile
+ :exe "redir > " .. tmpfile
< For Unix, the file will be in a private directory |tempfile|.
For MS-Windows forward slashes are used when the 'shellslash'
option is set or when 'shellcmdflag' starts with '-'.
@@ -8331,7 +8359,7 @@ trim({text} [, {mask} [, {dir}]]) *trim()*
Examples: >
echo trim(" some text ")
< returns "some text" >
- echo trim(" \r\t\t\r RESERVE \t\n\x0B\xA0") . "_TAIL"
+ echo trim(" \r\t\t\r RESERVE \t\n\x0B\xA0") .. "_TAIL"
< returns "RESERVE_TAIL" >
echo trim("rm<Xrm<>X>rrm", "rm<>")
< returns "Xrm<>X" (characters in the middle are not removed) >
@@ -8509,7 +8537,7 @@ visualmode([{expr}]) *visualmode()*
character-wise, line-wise, or block-wise Visual mode
respectively.
Example: >
- :exe "normal " . visualmode()
+ :exe "normal " .. visualmode()
< This enters the same Visual mode as before. It is also useful
in scripts if you wish to act differently depending on the
Visual mode that was used.
@@ -8696,7 +8724,7 @@ winbufnr({nr}) The result is a Number, which is the number of the buffer
window is returned.
When window {nr} doesn't exist, -1 is returned.
Example: >
- :echo "The file in the current window is " . bufname(winbufnr(0))
+ :echo "The file in the current window is " .. bufname(winbufnr(0))
<
Can also be used as a |method|: >
FindWindow()->winbufnr()->bufname()
@@ -8721,7 +8749,7 @@ winheight({nr}) *winheight()*
An existing window always has a height of zero or more.
This excludes any window toolbar line.
Examples: >
- :echo "The current window has " . winheight(0) . " lines."
+ :echo "The current window has " .. winheight(0) .. " lines."
< Can also be used as a |method|: >
GetWinid()->winheight()
@@ -8858,7 +8886,7 @@ winwidth({nr}) *winwidth()*
returned. When window {nr} doesn't exist, -1 is returned.
An existing window always has a width of zero or more.
Examples: >
- :echo "The current window has " . winwidth(0) . " columns."
+ :echo "The current window has " .. winwidth(0) .. " columns."
:if winwidth(0) <= 50
: 50 wincmd |
:endif
diff --git a/runtime/doc/change.txt b/runtime/doc/change.txt
index b4d3304880..86e19c5ec5 100644
--- a/runtime/doc/change.txt
+++ b/runtime/doc/change.txt
@@ -355,14 +355,14 @@ CTRL-A Add [count] to the number or alphabetic character at
*v_CTRL-A*
{Visual}CTRL-A Add [count] to the number or alphabetic character in
- the highlighted text. {not in Vi}
+ the highlighted text.
*v_g_CTRL-A*
{Visual}g CTRL-A Add [count] to the number or alphabetic character in
the highlighted text. If several lines are
highlighted, each one will be incremented by an
additional [count] (so effectively creating a
- [count] incrementing sequence). {not in Vi}
+ [count] incrementing sequence).
For Example, if you have this list of numbers:
1. ~
1. ~
@@ -381,14 +381,14 @@ CTRL-X Subtract [count] from the number or alphabetic
*v_CTRL-X*
{Visual}CTRL-X Subtract [count] from the number or alphabetic
- character in the highlighted text. {not in Vi}
+ character in the highlighted text.
*v_g_CTRL-X*
{Visual}g CTRL-X Subtract [count] from the number or alphabetic
character in the highlighted text. If several lines
are highlighted, each value will be decremented by an
additional [count] (so effectively creating a [count]
- decrementing sequence). {not in Vi}
+ decrementing sequence).
The CTRL-A and CTRL-X commands work for (signed) decimal numbers, unsigned
binary/octal/hexadecimal numbers and alphabetic characters.
@@ -906,7 +906,7 @@ Consider using a character like "@" or ":". There is no problem if the result
of the expression contains the separation character.
Examples: >
- :s@\n@\="\r" . expand("$HOME") . "\r"@
+ :s@\n@\="\r" .. expand("$HOME") .. "\r"@
This replaces an end-of-line with a new line containing the value of $HOME. >
s/E/\="\<Char-0x20ac>"/g
@@ -1018,7 +1018,7 @@ inside of strings can change! Also see 'softtabstop' option. >
in [range] (default: current line |cmdline-ranges|),
[into register x].
- *p* *put* *E353*
+ *p* *put* *E353* *E1240*
["x]p Put the text [from register x] after the cursor
[count] times.
@@ -1065,7 +1065,7 @@ inside of strings can change! Also see 'softtabstop' option. >
the command. You need to escape the '|' and '"'
characters to prevent them from terminating the
command. Example: >
- :put ='path' . \",/test\"
+ :put ='path' .. \",/test\"
< If there is no expression after '=', Vim uses the
previous expression. You can see it with ":dis =".
diff --git a/runtime/doc/channel.txt b/runtime/doc/channel.txt
index e14427494d..d4bed7a5f2 100644
--- a/runtime/doc/channel.txt
+++ b/runtime/doc/channel.txt
@@ -229,12 +229,12 @@ prompt. >
call chansend(g:shell_job, [a:text, ''])
endfunc
- " Function handling output from the shell: Added above the prompt.
+ " Function handling output from the shell: Add it above the prompt.
func GotOutput(channel, msg, name)
call append(line("$") - 1, a:msg)
endfunc
- " Function handling the shell exit: close the window.
+ " Function handling the shell exits: close the window.
func JobExit(job, status, event)
quit!
endfunc
diff --git a/runtime/doc/cmdline.txt b/runtime/doc/cmdline.txt
index f2f6ebb2c9..9fa2034718 100644
--- a/runtime/doc/cmdline.txt
+++ b/runtime/doc/cmdline.txt
@@ -207,7 +207,7 @@ CTRL-\ e {expr} *c_CTRL-\_e*
Example: >
:cmap <F7> <C-\>eAppendSome()<CR>
:func AppendSome()
- :let cmd = getcmdline() . " Some()"
+ :let cmd = getcmdline() .. " Some()"
:" place the cursor on the )
:call setcmdpos(strlen(cmd))
:return cmd
@@ -679,7 +679,7 @@ If more line specifiers are given than required for the command, the first
one(s) will be ignored.
Line numbers may be specified with: *:range* *{address}*
- {number} an absolute line number
+ {number} an absolute line number *E1247*
. the current line *:.*
$ the last line in the file *:$*
% equal to 1,$ (the entire file) *:%*
diff --git a/runtime/doc/develop.txt b/runtime/doc/develop.txt
index 178b0dc62b..cc146fcf6e 100644
--- a/runtime/doc/develop.txt
+++ b/runtime/doc/develop.txt
@@ -204,7 +204,7 @@ Docstring format:
- Use `<pre>` for code samples.
Example: the help for |vim.paste()| is generated from a docstring decorating
-vim.paste in src/nvim/lua/vim.lua like this: >
+vim.paste in runtime/lua/vim/_editor.lua like this: >
--- Paste handler, invoked by |nvim_paste()| when a conforming UI
--- (such as the |TUI|) pastes text into the editor.
diff --git a/runtime/doc/diagnostic.txt b/runtime/doc/diagnostic.txt
index 19db3158be..32936a7ee6 100644
--- a/runtime/doc/diagnostic.txt
+++ b/runtime/doc/diagnostic.txt
@@ -39,16 +39,18 @@ modify the diagnostics for a buffer (e.g. |vim.diagnostic.set()|) then it
requires a namespace.
*diagnostic-structure*
-A diagnostic is a Lua table with the following keys:
+A diagnostic is a Lua table with the following keys. Required keys are
+indicated with (*):
bufnr: Buffer number
- lnum: The starting line of the diagnostic
+ lnum(*): The starting line of the diagnostic
end_lnum: The final line of the diagnostic
- col: The starting column of the diagnostic
+ col(*): The starting column of the diagnostic
end_col: The final column of the diagnostic
severity: The severity of the diagnostic |vim.diagnostic.severity|
- message: The diagnostic text
+ message(*): The diagnostic text
source: The source of the diagnostic
+ code: The diagnostic code
user_data: Arbitrary data plugins or users can add
Diagnostics use the same indexing as the rest of the Nvim API (i.e. 0-based
@@ -72,7 +74,7 @@ Functions that take a severity as an optional parameter (e.g.
2. A table with a "min" or "max" key (or both): >
- vim.diagnostic.get(0, { severity = {min=vim.diagnostic.severity.WARN})
+ vim.diagnostic.get(0, { severity = {min=vim.diagnostic.severity.WARN} })
The latter form allows users to specify a range of severities.
@@ -326,11 +328,11 @@ config({opts}, {namespace}) *vim.diagnostic.config()*
Note:
Each of the configuration options below accepts one of the
following:
- • `false` : Disable this feature
- • `true` : Enable this feature, use default settings.
- • `table` : Enable this feature with overrides. Use an
+ • `false`: Disable this feature
+ • `true`: Enable this feature, use default settings.
+ • `table`: Enable this feature with overrides. Use an
empty table to use default values.
- • `function` : Function with signature (namespace, bufnr)
+ • `function`: Function with signature (namespace, bufnr)
that returns any of the above.
Parameters: ~
diff --git a/runtime/doc/diff.txt b/runtime/doc/diff.txt
index abe99102ee..9c5792dd43 100644
--- a/runtime/doc/diff.txt
+++ b/runtime/doc/diff.txt
@@ -371,13 +371,13 @@ Example (this does almost the same as 'diffexpr' being empty): >
function MyDiff()
let opt = ""
if &diffopt =~ "icase"
- let opt = opt . "-i "
+ let opt = opt .. "-i "
endif
if &diffopt =~ "iwhite"
- let opt = opt . "-b "
+ let opt = opt .. "-b "
endif
- silent execute "!diff -a --binary " . opt . v:fname_in . " " . v:fname_new .
- \ " > " . v:fname_out
+ silent execute "!diff -a --binary " .. opt .. v:fname_in .. " " .. v:fname_new ..
+ \ " > " .. v:fname_out
redraw!
endfunction
@@ -427,8 +427,8 @@ Example (this does the same as 'patchexpr' being empty): >
set patchexpr=MyPatch()
function MyPatch()
- :call system("patch -o " . v:fname_out . " " . v:fname_in .
- \ " < " . v:fname_diff)
+ :call system("patch -o " .. v:fname_out .. " " .. v:fname_in ..
+ \ " < " .. v:fname_diff)
endfunction
Make sure that using the "patch" program doesn't have unwanted side effects.
diff --git a/runtime/doc/editing.txt b/runtime/doc/editing.txt
index 8ddc661c0e..1cc8c21462 100644
--- a/runtime/doc/editing.txt
+++ b/runtime/doc/editing.txt
@@ -196,7 +196,7 @@ If you want to keep the changed buffer without saving it, switch on the
Edit {file} always. Discard any changes to the
current buffer.
Also see |++opt| and |+cmd|.
-
+ *:edit_#* *:e#*
:e[dit] [++opt] [+cmd] #[count]
Edit the [count]th buffer (as shown by |:files|).
This command does the same as [count] CTRL-^. But ":e
@@ -356,7 +356,7 @@ as a wildcard when "[" is in the 'isfname' option. A simple way to avoid this
is to use "path\[[]abc]", this matches the file "path\[abc]".
*starstar-wildcard*
-Expanding "**" is possible on Unix, Win32, Mac OS/X and a few other systems.
+Expanding "**" is possible on Unix, Win32, macOS and a few other systems.
This allows searching a directory tree. This goes up to 100 directories deep.
Note there are some commands where this works slightly differently, see
|file-searching|.
@@ -411,9 +411,9 @@ does apply like to other wildcards.
Environment variables in the expression are expanded when evaluating the
expression, thus this works: >
- :e `=$HOME . '/.vimrc'`
+ :e `=$HOME .. '/.vimrc'`
This does not work, $HOME is inside a string and used literally: >
- :e `='$HOME' . '/.vimrc'`
+ :e `='$HOME' .. '/.vimrc'`
If the expression returns a string then names are to be separated with line
breaks. When the result is a |List| then each item is used as a name. Line
@@ -1495,7 +1495,7 @@ which version of the file you want to keep.
The accuracy of the time check depends on the filesystem. On Unix it is
usually sub-second. With old file sytems and on MS-Windows it is normally one
-second. Use has('nanotime') check if sub-second time stamp checks are
+second. Use `has('nanotime')` to check if sub-second time stamp checks are
available.
There is one situation where you get the message while there is nothing wrong:
@@ -1575,10 +1575,8 @@ There are three different types of searching:
/u/user_x/include
< Note: If your 'path' setting includes a non-existing directory, Vim will
- skip the non-existing directory, but continues searching in the parent of
- the non-existing directory if upwards searching is used. E.g. when
- searching "../include" and that doesn't exist, and upward searching is
- used, also searches in "..".
+ skip the non-existing directory, and also does not search in the parent of
+ the non-existing directory if upwards searching is used.
3) Combined up/downward search:
If Vim's current path is /u/user_x/work/release and you do >
diff --git a/runtime/doc/eval.txt b/runtime/doc/eval.txt
index fc422f13e5..ca2334500c 100644
--- a/runtime/doc/eval.txt
+++ b/runtime/doc/eval.txt
@@ -402,7 +402,7 @@ It is also possible to put remaining items in a List variable: >
:for [i, j; rest] in listlist
: call Doit(i, j)
: if !empty(rest)
- : echo "remainder: " . string(rest)
+ : echo "remainder: " .. string(rest)
: endif
:endfor
@@ -430,11 +430,11 @@ Functions that are useful with a List: >
:let list = split("a b c") " create list from items in a string
:let string = join(list, ', ') " create string from list items
:let s = string(list) " String representation of list
- :call map(list, '">> " . v:val') " prepend ">> " to each item
+ :call map(list, '">> " .. v:val') " prepend ">> " to each item
Don't forget that a combination of features can make things simple. For
example, to add up all the numbers in a list: >
- :exe 'let sum = ' . join(nrlist, '+')
+ :exe 'let sum = ' .. join(nrlist, '+')
1.4 Dictionaries ~
@@ -496,7 +496,7 @@ turn the Dictionary into a List and pass it to |:for|.
Most often you want to loop over the keys, using the |keys()| function: >
:for key in keys(mydict)
- : echo key . ': ' . mydict[key]
+ : echo key .. ': ' .. mydict[key]
:endfor
The List of keys is unsorted. You may want to sort them first: >
@@ -504,13 +504,13 @@ The List of keys is unsorted. You may want to sort them first: >
To loop over the values use the |values()| function: >
:for v in values(mydict)
- : echo "value: " . v
+ : echo "value: " .. v
:endfor
If you want both the key and the value use the |items()| function. It returns
a List in which each item is a List with two items, the key and the value: >
:for [key, value] in items(mydict)
- : echo key . ': ' . value
+ : echo key .. ': ' .. value
:endfor
@@ -605,7 +605,7 @@ Functions that can be used with a Dictionary: >
:let small = min(dict) " minimum value in dict
:let xs = count(dict, 'x') " count nr of times 'x' appears in dict
:let s = string(dict) " String representation of dict
- :call map(dict, '">> " . v:val') " prepend ">> " to each item
+ :call map(dict, '">> " .. v:val') " prepend ">> " to each item
1.5 Blobs ~
@@ -840,7 +840,7 @@ Example: >
All expressions within one level are parsed from left to right.
-expr1 *expr1* *trinary* *E109*
+expr1 *expr1* *ternary* *E109*
-----
expr2 ? expr1 : expr1
@@ -1362,7 +1362,7 @@ option *expr-option* *E112* *E113*
&l:option local option value
Examples: >
- echo "tabstop is " . &tabstop
+ echo "tabstop is " .. &tabstop
if &insertmode
Any option name can be used here. See |options|. When using the local value
@@ -1637,7 +1637,7 @@ maintain a counter: >
echo "script executed for the first time"
else
let s:counter = s:counter + 1
- echo "script executed " . s:counter . " times now"
+ echo "script executed " .. s:counter .. " times now"
endif
Note that this means that filetype plugins don't get a different set of script
@@ -1651,6 +1651,7 @@ Some variables can be set by the user, but the type cannot be changed.
*v:argv* *argv-variable*
v:argv The command line arguments Vim was invoked with. This is a
list of strings. The first item is the Vim command.
+ See |v:progpath| for the command with full path.
*v:beval_col* *beval_col-variable*
v:beval_col The number of the column, over which the mouse pointer is.
@@ -1736,7 +1737,7 @@ v:completed_item
*v:count* *count-variable*
v:count The count given for the last Normal mode command. Can be used
to get the count before a mapping. Read-only. Example: >
- :map _x :<C-U>echo "the count is " . v:count<CR>
+ :map _x :<C-U>echo "the count is " .. v:count<CR>
< Note: The <C-U> is required to remove the line range that you
get when typing ':' after a count.
When there are two counts, as in "3d2w", they are multiplied,
@@ -2027,6 +2028,9 @@ v:null Special value used to put "null" in JSON and NIL in msgpack.
used as a String (e.g. in |expr5| with string concatenation
operator) and to zero when used as a Number (e.g. in |expr5|
or |expr7| when used with numeric operators). Read-only.
+ In some places `v:null` can be used for a List, Dict, etc.
+ that is not set. That is slightly different than an empty
+ List, Dict, etc.
*v:numbermax* *numbermax-variable*
v:numbermax Maximum value of a number.
@@ -2531,9 +2535,9 @@ Example: >
: echohl Title
: echo a:title
: echohl None
- : echo a:0 . " items:"
+ : echo a:0 .. " items:"
: for s in a:000
- : echon ' ' . s
+ : echon ' ' .. s
: endfor
:endfunction
@@ -2572,7 +2576,7 @@ This function can then be called with: >
this works:
*function-range-example* >
:function Mynumber(arg)
- : echo line(".") . " " . a:arg
+ : echo line(".") .. " " .. a:arg
:endfunction
:1,5call Mynumber(getline("."))
<
@@ -2583,7 +2587,7 @@ This function can then be called with: >
Example of a function that handles the range itself: >
:function Cont() range
- : execute (a:firstline + 1) . "," . a:lastline . 's/^/\t\\ '
+ : execute (a:firstline + 1) .. "," .. a:lastline .. 's/^/\t\\ '
:endfunction
:4,8call Cont()
<
@@ -2745,7 +2749,7 @@ This does NOT work: >
This cannot be used to add an item to a |List|.
This cannot be used to set a byte in a String. You
can do that like this: >
- :let var = var[0:2] . 'X' . var[4:]
+ :let var = var[0:2] .. 'X' .. var[4:]
< When {var-name} is a |Blob| then {idx} can be the
length of the blob, in which case one byte is
appended.
@@ -2807,7 +2811,7 @@ This does NOT work: >
is just like using the |:set| command: both the local
value and the global value are changed.
Example: >
- :let &path = &path . ',/usr/local/include'
+ :let &path = &path .. ',/usr/local/include'
:let &{option-name} .= {expr1}
For a string option: Append {expr1} to the value.
@@ -3062,14 +3066,17 @@ text...
opposite of |:lockvar|.
:if {expr1} *:if* *:end* *:endif* *:en* *E171* *E579* *E580*
-:en[dif] Execute the commands until the next matching ":else"
- or ":endif" if {expr1} evaluates to non-zero.
+:en[dif] Execute the commands until the next matching `:else`
+ or `:endif` if {expr1} evaluates to non-zero.
+ Although the short forms work, it is recommended to
+ always use `:endif` to avoid confusion and to make
+ auto-indenting work properly.
From Vim version 4.5 until 5.0, every Ex command in
- between the ":if" and ":endif" is ignored. These two
+ between the `:if` and `:endif` is ignored. These two
commands were just to allow for future expansions in a
backward compatible way. Nesting was allowed. Note
- that any ":else" or ":elseif" was ignored, the "else"
+ that any `:else` or `:elseif` was ignored, the `else`
part was not executed either.
You can use this to remain compatible with older
@@ -3078,32 +3085,32 @@ text...
: version-5-specific-commands
:endif
< The commands still need to be parsed to find the
- "endif". Sometimes an older Vim has a problem with a
- new command. For example, ":silent" is recognized as
- a ":substitute" command. In that case ":execute" can
+ `endif`. Sometimes an older Vim has a problem with a
+ new command. For example, `:silent` is recognized as
+ a `:substitute` command. In that case `:execute` can
avoid problems: >
:if version >= 600
: execute "silent 1,$delete"
:endif
<
- NOTE: The ":append" and ":insert" commands don't work
- properly in between ":if" and ":endif".
+ NOTE: The `:append` and `:insert` commands don't work
+ properly in between `:if` and `:endif`.
*:else* *:el* *E581* *E583*
-:el[se] Execute the commands until the next matching ":else"
- or ":endif" if they previously were not being
+:el[se] Execute the commands until the next matching `:else`
+ or `:endif` if they previously were not being
executed.
*:elseif* *:elsei* *E582* *E584*
-:elsei[f] {expr1} Short for ":else" ":if", with the addition that there
- is no extra ":endif".
+:elsei[f] {expr1} Short for `:else` `:if`, with the addition that there
+ is no extra `:endif`.
:wh[ile] {expr1} *:while* *:endwhile* *:wh* *:endw*
*E170* *E585* *E588* *E733*
-:endw[hile] Repeat the commands between ":while" and ":endwhile",
+:endw[hile] Repeat the commands between `:while` and `:endwhile`,
as long as {expr1} evaluates to non-zero.
When an error is detected from a command inside the
- loop, execution continues after the "endwhile".
+ loop, execution continues after the `endwhile`.
Example: >
:let lnum = 1
:while lnum <= line("$")
@@ -3111,16 +3118,16 @@ text...
:let lnum = lnum + 1
:endwhile
<
- NOTE: The ":append" and ":insert" commands don't work
- properly inside a ":while" and ":for" loop.
+ NOTE: The `:append` and `:insert` commands don't work
+ properly inside a `:while` and `:for` loop.
:for {var} in {object} *:for* *E690* *E732*
:endfo[r] *:endfo* *:endfor*
- Repeat the commands between ":for" and ":endfor" for
+ Repeat the commands between `:for` and `:endfor` for
each item in {object}. {object} can be a |List| or
a |Blob|. Variable {var} is set to the value of each
item. When an error is detected for a command inside
- the loop, execution continues after the "endfor".
+ the loop, execution continues after the `endfor`.
Changing {object} inside the loop affects what items
are used. Make a copy if this is unwanted: >
:for item in copy(mylist)
@@ -3144,7 +3151,7 @@ text...
:for [{var1}, {var2}, ...] in {listlist}
:endfo[r]
- Like ":for" above, but each item in {listlist} must be
+ Like `:for` above, but each item in {listlist} must be
a list, of which each item is assigned to {var1},
{var2}, etc. Example: >
:for [lnum, col] in [[1, 3], [2, 5], [3, 8]]
@@ -3152,38 +3159,39 @@ text...
:endfor
<
*:continue* *:con* *E586*
-:con[tinue] When used inside a ":while" or ":for" loop, jumps back
+:con[tinue] When used inside a `:while` or `:for` loop, jumps back
to the start of the loop.
- If it is used after a |:try| inside the loop but
- before the matching |:finally| (if present), the
- commands following the ":finally" up to the matching
- |:endtry| are executed first. This process applies to
- all nested ":try"s inside the loop. The outermost
- ":endtry" then jumps back to the start of the loop.
+
+ If it is used after a `:try` inside the loop but
+ before the matching `:finally` (if present), the
+ commands following the `:finally` up to the matching
+ `:endtry` are executed first. This process applies to
+ all nested `:try`s inside the loop. The outermost
+ `:endtry` then jumps back to the start of the loop.
*:break* *:brea* *E587*
-:brea[k] When used inside a ":while" or ":for" loop, skips to
- the command after the matching ":endwhile" or
- ":endfor".
- If it is used after a |:try| inside the loop but
- before the matching |:finally| (if present), the
- commands following the ":finally" up to the matching
- |:endtry| are executed first. This process applies to
- all nested ":try"s inside the loop. The outermost
- ":endtry" then jumps to the command after the loop.
+:brea[k] When used inside a `:while` or `:for` loop, skips to
+ the command after the matching `:endwhile` or
+ `:endfor`.
+ If it is used after a `:try` inside the loop but
+ before the matching `:finally` (if present), the
+ commands following the `:finally` up to the matching
+ `:endtry` are executed first. This process applies to
+ all nested `:try`s inside the loop. The outermost
+ `:endtry` then jumps to the command after the loop.
:try *:try* *:endt* *:endtry* *E600* *E601* *E602*
:endt[ry] Change the error handling for the commands between
- ":try" and ":endtry" including everything being
- executed across ":source" commands, function calls,
+ `:try` and `:endtry` including everything being
+ executed across `:source` commands, function calls,
or autocommand invocations.
When an error or interrupt is detected and there is
- a |:finally| command following, execution continues
- after the ":finally". Otherwise, or when the
- ":endtry" is reached thereafter, the next
- (dynamically) surrounding ":try" is checked for
- a corresponding ":finally" etc. Then the script
+ a `:finally` command following, execution continues
+ after the `:finally`. Otherwise, or when the
+ `:endtry` is reached thereafter, the next
+ (dynamically) surrounding `:try` is checked for
+ a corresponding `:finally` etc. Then the script
processing is terminated. Whether a function
definition has an "abort" argument does not matter.
Example: >
@@ -3191,9 +3199,9 @@ text...
echomsg "not reached"
<
Moreover, an error or interrupt (dynamically) inside
- ":try" and ":endtry" is converted to an exception. It
- can be caught as if it were thrown by a |:throw|
- command (see |:catch|). In this case, the script
+ `:try` and `:endtry` is converted to an exception. It
+ can be caught as if it were thrown by a `:throw`
+ command (see `:catch`). In this case, the script
processing is not terminated.
The value "Vim:Interrupt" is used for an interrupt
@@ -3209,22 +3217,22 @@ text...
try | edit | catch /^Vim(edit):E\d\+/ | echo "error" | endtry
<
*:cat* *:catch* *E603* *E604* *E605*
-:cat[ch] /{pattern}/ The following commands until the next |:catch|,
- |:finally|, or |:endtry| that belongs to the same
- |:try| as the ":catch" are executed when an exception
+:cat[ch] /{pattern}/ The following commands until the next `:catch`,
+ `:finally`, or `:endtry` that belongs to the same
+ `:try` as the `:catch` are executed when an exception
matching {pattern} is being thrown and has not yet
- been caught by a previous ":catch". Otherwise, these
+ been caught by a previous `:catch`. Otherwise, these
commands are skipped.
When {pattern} is omitted all errors are caught.
Examples: >
- :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
- :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
- :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
- :catch /^Vim(write):/ " catch all errors in :write
- :catch /^Vim\%((\a\+)\)\=:E123/ " catch error E123
- :catch /my-exception/ " catch user exception
- :catch /.*/ " catch everything
- :catch " same as /.*/
+ :catch /^Vim:Interrupt$/ " catch interrupts (CTRL-C)
+ :catch /^Vim\%((\a\+)\)\=:E/ " catch all Vim errors
+ :catch /^Vim\%((\a\+)\)\=:/ " catch errors and interrupts
+ :catch /^Vim(write):/ " catch all errors in :write
+ :catch /^Vim\%((\a\+)\)\=:E123:/ " catch error E123
+ :catch /my-exception/ " catch user exception
+ :catch /.*/ " catch everything
+ :catch " same as /.*/
<
Another character can be used instead of / around the
{pattern}, so long as it does not have a special
@@ -3237,27 +3245,27 @@ text...
locales.
*:fina* *:finally* *E606* *E607*
-:fina[lly] The following commands until the matching |:endtry|
+:fina[lly] The following commands until the matching `:endtry`
are executed whenever the part between the matching
- |:try| and the ":finally" is left: either by falling
- through to the ":finally" or by a |:continue|,
- |:break|, |:finish|, or |:return|, or by an error or
- interrupt or exception (see |:throw|).
+ `:try` and the `:finally` is left: either by falling
+ through to the `:finally` or by a `:continue`,
+ `:break`, `:finish`, or `:return`, or by an error or
+ interrupt or exception (see `:throw`).
*:th* *:throw* *E608*
:th[row] {expr1} The {expr1} is evaluated and thrown as an exception.
- If the ":throw" is used after a |:try| but before the
- first corresponding |:catch|, commands are skipped
- until the first ":catch" matching {expr1} is reached.
- If there is no such ":catch" or if the ":throw" is
- used after a ":catch" but before the |:finally|, the
- commands following the ":finally" (if present) up to
- the matching |:endtry| are executed. If the ":throw"
- is after the ":finally", commands up to the ":endtry"
- are skipped. At the ":endtry", this process applies
- again for the next dynamically surrounding ":try"
+ If the `:throw` is used after a `:try` but before the
+ first corresponding `:catch`, commands are skipped
+ until the first `:catch` matching {expr1} is reached.
+ If there is no such `:catch` or if the `:throw` is
+ used after a `:catch` but before the `:finally`, the
+ commands following the `:finally` (if present) up to
+ the matching `:endtry` are executed. If the `:throw`
+ is after the `:finally`, commands up to the `:endtry`
+ are skipped. At the `:endtry`, this process applies
+ again for the next dynamically surrounding `:try`
(which may be found in a calling function or sourcing
- script), until a matching ":catch" has been found.
+ script), until a matching `:catch` has been found.
If the exception is not caught, the command processing
is terminated.
Example: >
@@ -3272,7 +3280,7 @@ text...
Also see |:comment|.
Use "\n" to start a new line. Use "\r" to move the
cursor to the first column.
- Uses the highlighting set by the |:echohl| command.
+ Uses the highlighting set by the `:echohl` command.
Cannot be followed by a comment.
Example: >
:echo "the value of 'shell' is" &shell
@@ -3281,9 +3289,9 @@ text...
And since Vim mostly postpones redrawing until it's
finished with a sequence of commands this happens
quite often. To avoid that a command from before the
- ":echo" causes a redraw afterwards (redraws are often
+ `:echo` causes a redraw afterwards (redraws are often
postponed until you type something), force a redraw
- with the |:redraw| command. Example: >
+ with the `:redraw` command. Example: >
:new | redraw | echo "there is a new window"
< *:echo-self-refer*
When printing nested containers echo prints second
@@ -3302,13 +3310,13 @@ text...
*:echon*
:echon {expr1} .. Echoes each {expr1}, without anything added. Also see
|:comment|.
- Uses the highlighting set by the |:echohl| command.
+ Uses the highlighting set by the `:echohl` command.
Cannot be followed by a comment.
Example: >
:echon "the value of 'shell' is " &shell
<
- Note the difference between using ":echo", which is a
- Vim command, and ":!echo", which is an external shell
+ Note the difference between using `:echo`, which is a
+ Vim command, and `:!echo`, which is an external shell
command: >
:!echo % --> filename
< The arguments of ":!" are expanded, see |:_%|. >
@@ -3324,8 +3332,8 @@ text...
*:echoh* *:echohl*
:echoh[l] {name} Use the highlight group {name} for the following
- |:echo|, |:echon| and |:echomsg| commands. Also used
- for the |input()| prompt. Example: >
+ `:echo`, `:echon` and `:echomsg` commands. Also used
+ for the `input()` prompt. Example: >
:echohl WarningMsg | echo "Don't panic!" | echohl None
< Don't forget to set the group back to "None",
otherwise all following echo's will be highlighted.
@@ -3334,14 +3342,14 @@ text...
:echom[sg] {expr1} .. Echo the expression(s) as a true message, saving the
message in the |message-history|.
Spaces are placed between the arguments as with the
- |:echo| command. But unprintable characters are
+ `:echo` command. But unprintable characters are
displayed, not interpreted.
- The parsing works slightly different from |:echo|,
- more like |:execute|. All the expressions are first
+ The parsing works slightly different from `:echo`,
+ more like `:execute`. All the expressions are first
evaluated and concatenated before echoing anything.
If expressions does not evaluate to a Number or
String, string() is used to turn it into a string.
- Uses the highlighting set by the |:echohl| command.
+ Uses the highlighting set by the `:echohl` command.
Example: >
:echomsg "It's a Zizzer Zazzer Zuzz, as you can plainly see."
< See |:echo-redraw| to avoid the message disappearing
@@ -3351,12 +3359,12 @@ text...
message in the |message-history|. When used in a
script or function the line number will be added.
Spaces are placed between the arguments as with the
- |:echomsg| command. When used inside a try conditional,
+ `:echomsg` command. When used inside a try conditional,
the message is raised as an error exception instead
(see |try-echoerr|).
Example: >
:echoerr "This script just failed!"
-< If you just want a highlighted message use |:echohl|.
+< If you just want a highlighted message use `:echohl`.
And to get a beep: >
:exe "normal \<Esc>"
<
@@ -3661,7 +3669,7 @@ exception most recently caught as long it is not finished.
:function! Caught()
: if v:exception != ""
- : echo 'Caught "' . v:exception . '" in ' . v:throwpoint
+ : echo 'Caught "' .. v:exception .. '" in ' .. v:throwpoint
: else
: echo 'Nothing caught'
: endif
@@ -4064,8 +4072,8 @@ a script in order to catch unexpected things.
:catch /^Vim:Interrupt$/
: echo "Script interrupted"
:catch /.*/
- : echo "Internal error (" . v:exception . ")"
- : echo " - occurred at " . v:throwpoint
+ : echo "Internal error (" .. v:exception .. ")"
+ : echo " - occurred at " .. v:throwpoint
:endtry
:" end of script
@@ -4261,7 +4269,7 @@ parentheses can be cut out from |v:exception| with the ":substitute" command.
:function! CheckRange(a, func)
: if a:a < 0
- : throw "EXCEPT:MATHERR:RANGE(" . a:func . ")"
+ : throw "EXCEPT:MATHERR:RANGE(" .. a:func .. ")"
: endif
:endfunction
:
@@ -4288,7 +4296,7 @@ parentheses can be cut out from |v:exception| with the ":substitute" command.
: try
: execute "write" fnameescape(a:file)
: catch /^Vim(write):/
- : throw "EXCEPT:IO(" . getcwd() . ", " . a:file . "):WRITEERR"
+ : throw "EXCEPT:IO(" .. getcwd() .. ", " .. a:file .. "):WRITEERR"
: endtry
:endfunction
:
@@ -4307,9 +4315,9 @@ parentheses can be cut out from |v:exception| with the ":substitute" command.
: let dir = substitute(v:exception, '.*(\(.\+\),\s*.\+).*', '\1', "")
: let file = substitute(v:exception, '.*(.\+,\s*\(.\+\)).*', '\1', "")
: if file !~ '^/'
- : let file = dir . "/" . file
+ : let file = dir .. "/" .. file
: endif
- : echo 'I/O error for "' . file . '"'
+ : echo 'I/O error for "' .. file .. '"'
:
:catch /^EXCEPT/
: echo "Unspecified error"
@@ -4377,7 +4385,7 @@ clauses, however, is executed.
: echo "inner finally"
: endtry
:catch
- : echo 'outer catch-all caught "' . v:exception . '"'
+ : echo 'outer catch-all caught "' .. v:exception .. '"'
: finally
: echo "outer finally"
:endtry
@@ -4439,7 +4447,7 @@ Printing in Binary ~
: let n = a:nr
: let r = ""
: while n
- : let r = '01'[n % 2] . r
+ : let r = '01'[n % 2] .. r
: let n = n / 2
: endwhile
: return r
@@ -4450,7 +4458,7 @@ Printing in Binary ~
:func String2Bin(str)
: let out = ''
: for ix in range(strlen(a:str))
- : let out = out . '-' . Nr2Bin(char2nr(a:str[ix]))
+ : let out = out .. '-' .. Nr2Bin(char2nr(a:str[ix]))
: endfor
: return out[1:]
:endfunc
diff --git a/runtime/doc/filetype.txt b/runtime/doc/filetype.txt
index 5486c87af9..bd3acfcac7 100644
--- a/runtime/doc/filetype.txt
+++ b/runtime/doc/filetype.txt
@@ -140,7 +140,8 @@ variables can be used to overrule the filetype used for certain extensions:
*.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|
+ *.frm g:filetype_frm |ft-form-syntax|
+ *.fs g:filetype_fs |ft-forth-syntax|
*.i g:filetype_i |ft-progress-syntax|
*.inc g:filetype_inc
*.m g:filetype_m |ft-mathematica-syntax|
diff --git a/runtime/doc/fold.txt b/runtime/doc/fold.txt
index 8bc47a3b10..9e3d78faff 100644
--- a/runtime/doc/fold.txt
+++ b/runtime/doc/fold.txt
@@ -497,7 +497,7 @@ Note the use of backslashes to avoid some characters to be interpreted by the
:function MyFoldText()
: let line = getline(v:foldstart)
: let sub = substitute(line, '/\*\|\*/\|{{{\d\=', '', 'g')
- : return v:folddashes . sub
+ : return v:folddashes .. sub
:endfunction
Evaluating 'foldtext' is done in the |sandbox|. The current window is set to
diff --git a/runtime/doc/ft_raku.txt b/runtime/doc/ft_raku.txt
index 00b140ee9c..3d1179ed4e 100644
--- a/runtime/doc/ft_raku.txt
+++ b/runtime/doc/ft_raku.txt
@@ -47,20 +47,20 @@ Numbers, subscripts and superscripts are available with 's' and 'S':
But some don't come defined by default. Those are digraph definitions you can
add in your ~/.vimrc file. >
- exec 'digraph \\ '.char2nr('∖')
- exec 'digraph \< '.char2nr('≼')
- exec 'digraph \> '.char2nr('≽')
- exec 'digraph (L '.char2nr('⊈')
- exec 'digraph )L '.char2nr('⊉')
- exec 'digraph (/ '.char2nr('⊄')
- exec 'digraph )/ '.char2nr('⊅')
- exec 'digraph )/ '.char2nr('⊅')
- exec 'digraph U+ '.char2nr('⊎')
- exec 'digraph 0- '.char2nr('⊖')
+ exec 'digraph \\ ' .. char2nr('∖')
+ exec 'digraph \< ' .. char2nr('≼')
+ exec 'digraph \> ' .. char2nr('≽')
+ exec 'digraph (L ' .. char2nr('⊈')
+ exec 'digraph )L ' .. char2nr('⊉')
+ exec 'digraph (/ ' .. char2nr('⊄')
+ exec 'digraph )/ ' .. char2nr('⊅')
+ exec 'digraph )/ ' .. char2nr('⊅')
+ exec 'digraph U+ ' .. char2nr('⊎')
+ exec 'digraph 0- ' .. char2nr('⊖')
" Euler's constant
- exec 'digraph ne '.char2nr('𝑒')
+ exec 'digraph ne ' .. char2nr('𝑒')
" Raku's atomic operations marker
- exec 'digraph @@ '.char2nr('⚛')
+ exec 'digraph @@ ' .. char2nr('⚛')
Alternatively, you can write Insert mode abbreviations that convert ASCII-
based operators into their single-character Unicode equivalent. >
diff --git a/runtime/doc/ft_rust.txt b/runtime/doc/ft_rust.txt
index ff2e0ca56f..5c8782ec7a 100644
--- a/runtime/doc/ft_rust.txt
+++ b/runtime/doc/ft_rust.txt
@@ -26,7 +26,7 @@ behavior of the plugin.
g:rustc_path~
Set this option to the path to rustc for use in the |:RustRun| and
|:RustExpand| commands. If unset, "rustc" will be located in $PATH: >
- let g:rustc_path = $HOME."/bin/rustc"
+ let g:rustc_path = $HOME .. "/bin/rustc"
<
*g:rustc_makeprg_no_percent*
@@ -87,7 +87,7 @@ g:rust_bang_comment_leader~
g:ftplugin_rust_source_path~
Set this option to a path that should be prepended to 'path' for Rust
source files: >
- let g:ftplugin_rust_source_path = $HOME.'/dev/rust'
+ let g:ftplugin_rust_source_path = $HOME .. '/dev/rust'
<
*g:rustfmt_command*
diff --git a/runtime/doc/ft_sql.txt b/runtime/doc/ft_sql.txt
index 53a99a9e1d..fccbbce17f 100644
--- a/runtime/doc/ft_sql.txt
+++ b/runtime/doc/ft_sql.txt
@@ -109,8 +109,8 @@ must be configurable. The filetype plugin attempts to define many of the
standard objects, plus many additional ones. In order to make this as
flexible as possible, you can override the list of objects from within your
|vimrc| with the following: >
- let g:ftplugin_sql_objects = 'function,procedure,event,table,trigger' .
- \ ',schema,service,publication,database,datatype,domain' .
+ let g:ftplugin_sql_objects = 'function,procedure,event,table,trigger' ..
+ \ ',schema,service,publication,database,datatype,domain' ..
\ ',index,subscription,synchronization,view,variable'
The following |Normal| mode and |Visual| mode maps have been created which use
@@ -131,10 +131,10 @@ Repeatedly pressing ]} will cycle through each of these create statements: >
create index i1 on t1 (c1);
The default setting for g:ftplugin_sql_objects is: >
- let g:ftplugin_sql_objects = 'function,procedure,event,' .
- \ '\\(existing\\\\|global\\s\\+temporary\\s\\+\\)\\\{,1}' .
- \ 'table,trigger' .
- \ ',schema,service,publication,database,datatype,domain' .
+ let g:ftplugin_sql_objects = 'function,procedure,event,' ..
+ \ '\\(existing\\\\|global\\s\\+temporary\\s\\+\\)\\\{,1}' ..
+ \ 'table,trigger' ..
+ \ ',schema,service,publication,database,datatype,domain' ..
\ ',index,subscription,synchronization,view,variable'
The above will also handle these cases: >
diff --git a/runtime/doc/if_pyth.txt b/runtime/doc/if_pyth.txt
index afdf039aa8..9b434e61d7 100644
--- a/runtime/doc/if_pyth.txt
+++ b/runtime/doc/if_pyth.txt
@@ -658,7 +658,7 @@ To see what version of Python is being used: >
*has-pythonx*
To check if `pyx*` functions and commands are available: >
if has('pythonx')
- echo 'pyx* commands are available. (Python ' . &pyx . ')'
+ echo 'pyx* commands are available. (Python ' .. &pyx .. ')'
endif
==============================================================================
diff --git a/runtime/doc/index.txt b/runtime/doc/index.txt
index e3bc3d5437..572b4e3f93 100644
--- a/runtime/doc/index.txt
+++ b/runtime/doc/index.txt
@@ -353,6 +353,7 @@ tag char note action in Normal mode ~
register x]
|Y| ["x]Y yank N lines [into register x]; synonym for
"yy"
+ Note: Mapped to "y$" by default. |default-mappings|
|ZZ| ZZ write if buffer changed and close window
|ZQ| ZQ close window without writing
|[| [{char} square bracket command (see |[| below)
@@ -430,6 +431,7 @@ tag char note action in Normal mode ~
|<C-LeftMouse>| <C-LeftMouse> ":ta" to the keyword at the mouse click
|<C-Right>| <C-Right> 1 same as "w"
|<C-RightMouse>| <C-RightMouse> same as "CTRL-T"
+|<C-Tab>| <C-Tab> same as "g<Tab>"
|<Del>| ["x]<Del> 2 same as "x"
|N<Del>| {count}<Del> remove the last digit from {count}
|<Down>| <Down> 1 same as "j"
@@ -576,7 +578,7 @@ tag command action in Normal mode ~
following the file name.
|CTRL-W_gt| CTRL-W g t same as `gt`: go to next tab page
|CTRL-W_gT| CTRL-W g T same as `gT`: go to previous tab page
-|CTRL-W_g<Tab>| CTRL-W g <Tab> same as `g<Tab>` : go to last accessed tab
+|CTRL-W_g<Tab>| CTRL-W g <Tab> same as |g<Tab>|: go to last accessed tab
page
|CTRL-W_h| CTRL-W h go to Nth left window (stop at first window)
|CTRL-W_i| CTRL-W i split window and jump to declaration of
diff --git a/runtime/doc/insert.txt b/runtime/doc/insert.txt
index ae2b9c4418..d9aecfe4fd 100644
--- a/runtime/doc/insert.txt
+++ b/runtime/doc/insert.txt
@@ -269,8 +269,8 @@ start allow backspacing over the start position of insert; CTRL-W and
When 'backspace' is empty, Vi compatible backspacing is used. You cannot
backspace over autoindent, before column 1 or before where insert started.
-For backwards compatibility the values "0", "1" and "2" are also allowed, see
-|'backspace'|.
+For backwards compatibility the values "0", "1", "2" and "3" are also allowed,
+see |'backspace'|.
If the 'backspace' option does contain "eol" and the cursor is in column 1
when one of the three keys is used, the current line is joined with the
@@ -798,6 +798,7 @@ CTRL-X CTRL-K Search the files given with the 'dictionary' option
the 'dictionary' option is empty.
For suggestions where to find a list of words, see the
'dictionary' option.
+ 'ignorecase', 'smartcase' and 'infercase' apply.
CTRL-K or
CTRL-N Search forward for next matching keyword. This
@@ -864,7 +865,7 @@ Groß): >
else
let res = []
let h = ''
- for l in split(system('aiksaurus '.shellescape(a:base)), '\n')
+ for l in split(system('aiksaurus ' .. shellescape(a:base)), '\n')
if l[:3] == '=== '
let h = substitute(l[4:], ' =*$', '', '')
elseif l[0] =~ '\a'
@@ -1199,7 +1200,7 @@ An example that completes the names of the months: >
" find months matching with "a:base"
let res = []
for m in split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec")
- if m =~ '^' . a:base
+ if m =~ '^' .. a:base
call add(res, m)
endif
endfor
@@ -1221,7 +1222,7 @@ The same, but now pretending searching for matches is slow: >
else
" find months matching with "a:base"
for m in split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec")
- if m =~ '^' . a:base
+ if m =~ '^' .. a:base
call complete_add(m)
endif
sleep 300m " simulate searching for next match
diff --git a/runtime/doc/lsp.txt b/runtime/doc/lsp.txt
index d717759444..a9ebcd27ae 100644
--- a/runtime/doc/lsp.txt
+++ b/runtime/doc/lsp.txt
@@ -355,8 +355,8 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method
*lsp-handler-resolution*
Handlers can be set by:
-- Setting a field in |vim.lsp.handlers|. *vim.lsp.handlers*
- |vim.lsp.handlers| is a global table that contains the default mapping of
+- Setting a field in vim.lsp.handlers. *vim.lsp.handlers*
+ vim.lsp.handlers is a global table that contains the default mapping of
|lsp-method| names to |lsp-handlers|.
To override the handler for the `"textDocument/definition"` method: >
@@ -563,7 +563,7 @@ buf_request_all({bufnr}, {method}, {params}, {callback})
Return: ~
(function) A function that will cancel all requests which
- is the same as the one returned from `buf_request` .
+ is the same as the one returned from `buf_request`.
*vim.lsp.buf_request_sync()*
buf_request_sync({bufnr}, {method}, {params}, {timeout_ms})
@@ -600,9 +600,9 @@ client() *vim.lsp.client*
{handler} is not specified, If one is not found there,
then an error will occur. Returns: {status},
{[client_id]}. {status} is a boolean indicating if the
- notification was successful. If it is `false` , then it
+ notification was successful. If it is `false`, then it
will always be `false` (the client has shutdown). If
- {status} is `true` , the function returns {request_id} as
+ {status} is `true`, the function returns {request_id} as
the second result. You can use this with
`client.cancel_request(request_id)` to cancel the request.
• request_sync(method, params, timeout_ms, bufnr) Sends a
@@ -612,13 +612,13 @@ client() *vim.lsp.client*
`err` and `result` come from the |lsp-handler|. On
timeout, cancel or error, returns `(nil, err)` where `err`
is a string describing the failure reason. If the request
- was unsuccessful returns `nil` .
+ was unsuccessful returns `nil`.
• notify(method, params) Sends a notification to an LSP
server. Returns: a boolean to indicate if the notification
was successful. If it is false, then it will always be
false (the client has shutdown).
• cancel_request(id) Cancels a request with a given request
- id. Returns: same as `notify()` .
+ id. Returns: same as `notify()`.
• stop([force]) Stops a client, optionally with force. By
default, it will just ask the server to shutdown without
force. If you request to stop a client which has
@@ -639,14 +639,14 @@ client() *vim.lsp.client*
interaction with the client. See |vim.lsp.rpc.start()|.
• {offset_encoding} (string): The encoding used for
communicating with the server. You can modify this in the
- `config` 's `on_init` method before text is sent to the
+ `config`'s `on_init` method before text is sent to the
server.
• {handlers} (table): The handlers used by the client as
described in |lsp-handler|.
• {requests} (table): The current pending requests in flight
to the server. Entries are key-value pairs with the key
being the request ID while the value is a table with
- `type` , `bufnr` , and `method` key-value pairs. `type` is
+ `type`, `bufnr`, and `method` key-value pairs. `type` is
either "pending" for an active request, or "cancel" for a
cancel request.
• {config} (table): copy of the table that was passed by the
@@ -655,7 +655,7 @@ client() *vim.lsp.client*
sent on `initialize` describing the server's capabilities.
• {resolved_capabilities} (table): Normalized table of
capabilities that we have detected based on the initialize
- response from the server in `server_capabilities` .
+ response from the server in `server_capabilities`.
client_is_stopped({client_id}) *vim.lsp.client_is_stopped()*
Checks whether a client is stopped.
@@ -775,7 +775,7 @@ start_client({config}) *vim.lsp.start_client()*
initiates the LSP client.
{cmd_cwd} (string, default=|getcwd()|)
Directory to launch the `cmd`
- process. Not related to `root_dir` .
+ process. Not related to `root_dir`.
{cmd_env} (table) Environment flags to pass to
the LSP on spawn. Can be specified
using keys like a map or as a list
@@ -800,15 +800,15 @@ start_client({config}) *vim.lsp.start_client()*
its result.
• Note: To send an empty dictionary
use
- `{[vim.type_idx]=vim.types.dictionary}`
- , else it will be encoded as an
+ `{[vim.type_idx]=vim.types.dictionary}`,
+ else it will be encoded as an
array.
{handlers} Map of language server method names
to |lsp-handler|
{settings} Map with language server specific
settings. These are returned to the
language server if requested via
- `workspace/configuration` . Keys are
+ `workspace/configuration`. Keys are
case-sensitive.
{commands} table Table that maps string of
clientside commands to user-defined
@@ -821,7 +821,7 @@ start_client({config}) *vim.lsp.start_client()*
action, code lenses, ...) triggers
the command.
{init_options} Values to pass in the initialization
- request as `initializationOptions` .
+ request as `initializationOptions`.
See `initialize` in the LSP spec.
{name} (string, default=client-id) Name in
log messages.
@@ -976,7 +976,7 @@ code_action({context}) *vim.lsp.buf.code_action()*
• only: (string|nil) LSP `CodeActionKind` used
to filter the code actions. Most language
servers support values like `refactor` or
- `quickfix` .
+ `quickfix`.
See also: ~
https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_codeAction
@@ -1007,7 +1007,7 @@ definition() *vim.lsp.buf.definition()*
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` ,
+ triggered by a key mapping or by events such as `CursorHold`,
e.g.:
>
autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight()
@@ -1124,7 +1124,7 @@ range_code_action({context}, {start_pos}, {end_pos})
• only: (string|nil) LSP `CodeActionKind`
used to filter the code actions. Most
language servers support values like
- `refactor` or `quickfix` .
+ `refactor` or `quickfix`.
{start_pos} ({number, number}, optional) mark-indexed
position. Defaults to the start of the last
visual selection.
@@ -1246,8 +1246,8 @@ display({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.display()*
Display the lenses using virtual text
Parameters: ~
- {lenses} table of lenses to display ( `CodeLens[] |
- null` )
+ {lenses} table of lenses to display (`CodeLens[] |
+ null`)
{bufnr} number
{client_id} number
@@ -1259,7 +1259,7 @@ get({bufnr}) *vim.lsp.codelens.get()*
current buffer.
Return: ~
- table ( `CodeLens[]` )
+ table (`CodeLens[]`)
*vim.lsp.codelens.on_codelens()*
on_codelens({err}, {result}, {ctx}, {_})
@@ -1281,8 +1281,8 @@ save({lenses}, {bufnr}, {client_id}) *vim.lsp.codelens.save()*
Store lenses for a specific buffer and client
Parameters: ~
- {lenses} table of lenses to store ( `CodeLens[] |
- null` )
+ {lenses} table of lenses to store (`CodeLens[] |
+ null`)
{bufnr} number
{client_id} number
@@ -1333,7 +1333,7 @@ Lua module: vim.lsp.util *lsp-util*
*vim.lsp.util.apply_text_document_edit()*
apply_text_document_edit({text_document_edit}, {index}, {offset_encoding})
- Applies a `TextDocumentEdit` , which is a list of changes to a
+ Applies a `TextDocumentEdit`, which is a list of changes to a
single document.
Parameters: ~
@@ -1360,7 +1360,7 @@ apply_text_edits({text_edits}, {bufnr}, {offset_encoding})
*vim.lsp.util.apply_workspace_edit()*
apply_workspace_edit({workspace_edit}, {offset_encoding})
- Applies a `WorkspaceEdit` .
+ Applies a `WorkspaceEdit`.
Parameters: ~
{workspace_edit} table `WorkspaceEdit`
@@ -1408,13 +1408,13 @@ convert_input_to_markdown_lines({input}, {contents})
Converts any of `MarkedString` | `MarkedString[]` |
`MarkupContent` into a list of lines containing valid
markdown. Useful to populate the hover window for
- `textDocument/hover` , for parsing the result of
- `textDocument/signatureHelp` , and potentially others.
+ `textDocument/hover`, for parsing the result of
+ `textDocument/signatureHelp`, and potentially others.
Parameters: ~
- {input} ( `MarkedString` | `MarkedString[]` |
- `MarkupContent` )
- {contents} (table, optional, default `{}` ) List of
+ {input} (`MarkedString` | `MarkedString[]` |
+ `MarkupContent`)
+ {contents} (table, optional, default `{}`) List of
strings to extend with converted lines
Return: ~
@@ -1475,7 +1475,7 @@ jump_to_location({location}, {offset_encoding})
Jumps to a location.
Parameters: ~
- {location} table ( `Location` | `LocationLink` )
+ {location} table (`Location`|`LocationLink`)
{offset_encoding} string utf-8|utf-16|utf-32 (required)
Return: ~
@@ -1491,8 +1491,8 @@ locations_to_items({locations}, {offset_encoding})
|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
@@ -1526,7 +1526,7 @@ make_floating_popup_options({width}, {height}, {opts})
• border (string or table) override `border`
• focusable (string or table) override
`focusable`
- • zindex (string or table) override `zindex` ,
+ • zindex (string or table) override `zindex`,
defaults to 50
Return: ~
@@ -1566,7 +1566,7 @@ make_given_range_params({start_pos}, {end_pos}, {bufnr}, {offset_encoding})
Return: ~
{ textDocument = { uri = `current_file_uri` }, range = {
- start = `start_position` , end = `end_position` } }
+ start = `start_position`, end = `end_position` } }
*vim.lsp.util.make_position_params()*
make_position_params({window}, {offset_encoding})
@@ -1590,9 +1590,9 @@ make_position_params({window}, {offset_encoding})
make_range_params({window}, {offset_encoding})
Using the current position in the current buffer, creates an
object that can be used as a building block for several LSP
- requests, such as `textDocument/codeAction` ,
- `textDocument/colorPresentation` ,
- `textDocument/rangeFormatting` .
+ requests, such as `textDocument/codeAction`,
+ `textDocument/colorPresentation`,
+ `textDocument/rangeFormatting`.
Parameters: ~
{window} (optional, number): window handle or 0
@@ -1603,7 +1603,7 @@ make_range_params({window}, {offset_encoding})
Return: ~
{ textDocument = { uri = `current_file_uri` }, range = {
- start = `current_position` , end = `current_position` } }
+ start = `current_position`, end = `current_position` } }
*vim.lsp.util.make_text_document_params()*
make_text_document_params({bufnr})
@@ -1657,8 +1657,8 @@ open_floating_preview({contents}, {syntax}, {opts})
closes the floating window
• focusable: (boolean, default true) Make
float focusable
- • focus: (boolean, default true) If `true` ,
- and if {focusable} is also `true` , focus an
+ • focus: (boolean, default true) If `true`,
+ and if {focusable} is also `true`, focus an
existing floating window with the same
{focus_id}
@@ -1757,7 +1757,7 @@ text_document_completion_list_to_complete_items({result}, {prefix})
Parameters: ~
{result} The result of a `textDocument/completion` call,
e.g. from |vim.lsp.buf.completion()|, which may
- be one of `CompletionItem[]` , `CompletionList`
+ be one of `CompletionItem[]`, `CompletionList`
or `null`
{prefix} (string) the prefix to filter the completion
items
diff --git a/runtime/doc/lua.txt b/runtime/doc/lua.txt
index 1a2d845281..93386ddfe9 100644
--- a/runtime/doc/lua.txt
+++ b/runtime/doc/lua.txt
@@ -568,6 +568,26 @@ Example: TCP echo-server *tcp-server*
end)
print('TCP echo-server listening on port: '..server:getsockname().port)
+
+Multithreading *lua-loop-threading*
+
+Plugins can perform work in separate (os-level) threads using the threading
+APIs in luv, for instance `vim.loop.new_thread`. Note that every thread
+gets its own separate lua interpreter state, with no access to lua globals
+in the main thread. Neither can the state of the editor (buffers, windows,
+etc) be directly accessed from threads.
+
+A subset of the `vim.*` API is available in threads. This includes:
+
+- `vim.loop` with a separate event loop per thread.
+- `vim.mpack` and `vim.json` (useful for serializing messages between threads)
+- `require` in threads can use lua packages from the global |lua-package-path|
+- `print()` and `vim.inspect`
+- `vim.diff`
+- most utility functions in `vim.*` for working with pure lua values
+ like `vim.split`, `vim.tbl_*`, `vim.list_*`, and so on.
+- `vim.is_thread()` returns true from a non-main thread.
+
------------------------------------------------------------------------------
VIM.HIGHLIGHT *lua-highlight*
@@ -595,13 +615,33 @@ vim.highlight.on_yank({opts}) *vim.highlight.on_yank()*
- {on_visual} highlight when yanking visual selection (default `true`)
- {event} event structure (default |v:event|)
-vim.highlight.range({bufnr}, {ns}, {higroup}, {start}, {finish}, {rtype}, {inclusive})
+vim.highlight.range({bufnr}, {ns}, {hlgroup}, {start}, {finish}, {opts})
*vim.highlight.range()*
- Highlights the range between {start} and {finish} (tuples of {line,col})
- in buffer {bufnr} with the highlight group {higroup} using the namespace
- {ns}. Optional arguments are the type of range (characterwise, linewise,
- or blockwise, see |setreg|; default to characterwise) and whether the
- range is inclusive (default false).
+
+ Apply highlight group to range of text.
+
+ Parameters: ~
+ {bufnr} buffer number
+ {ns} namespace for highlights
+ {hlgroup} highlight group name
+ {start} starting position (tuple {line,col})
+ {finish} finish position (tuple {line,col})
+ {opts} optional parameters:
+ • `regtype`: type of range (characterwise, linewise,
+ or blockwise, see |setreg|), default `'v'`
+ • `inclusive`: range includes end position, default
+ `false`
+ • `priority`: priority of highlight, default
+ `vim.highlight.user` (see below)
+
+vim.highlight.priorities *vim.highlight.priorities*
+
+ Table with default priorities used for highlighting:
+ • `syntax`: `50`, used for standard syntax highlighting
+ • `treesitter`: `100`, used for tree-sitter-based highlighting
+ • `diagnostics`: `150`, used for code analysis such as diagnostics
+ • `user`: `200`, used for user-triggered highlights such as LSP
+ document symbols or `on_yank` autocommands
------------------------------------------------------------------------------
VIM.REGEX *lua-regex*
@@ -1043,7 +1083,7 @@ from within Lua.
`vim.opt.wildignore = '*.o,*.a,__pycache__'`
However, vim.opt also supports a more elegent way of setting
- list-style options, but using lua tables:
+ list-style options by using lua tables:
`vim.opt.wildignore = { '*.o', '*.a', '__pycache__' }`
To replicate the behavior of |:set+=|, use: >
@@ -1378,7 +1418,7 @@ deep_equal({a}, {b}) *vim.deep_equal()*
{b} second value
Return: ~
- `true` if values are equals, else `false` .
+ `true` if values are equals, else `false`.
deepcopy({orig}) *vim.deepcopy()*
Returns a deep copy of the given object. Non-table objects are
@@ -1395,7 +1435,7 @@ deepcopy({orig}) *vim.deepcopy()*
New table of copied keys and (nested) values.
endswith({s}, {suffix}) *vim.endswith()*
- Tests if `s` ends with `suffix` .
+ Tests if `s` ends with `suffix`.
Parameters: ~
{s} (string) a string
@@ -1499,7 +1539,7 @@ split({s}, {sep}, {kwargs}) *vim.split()*
|vim.gsplit()|
startswith({s}, {prefix}) *vim.startswith()*
- Tests if `s` starts with `prefix` .
+ Tests if `s` starts with `prefix`.
Parameters: ~
{s} (string) a string
@@ -1516,7 +1556,7 @@ tbl_add_reverse_lookup({o}) *vim.tbl_add_reverse_lookup()*
{o} table The table to add the reverse to.
tbl_contains({t}, {value}) *vim.tbl_contains()*
- Checks if a list-like (vector) table contains `value` .
+ Checks if a list-like (vector) table contains `value`.
Parameters: ~
{t} Table to check
@@ -1526,7 +1566,7 @@ tbl_contains({t}, {value}) *vim.tbl_contains()*
true if `t` contains `value`
tbl_count({t}) *vim.tbl_count()*
- Counts the number of non-nil values in table `t` .
+ Counts the number of non-nil values in table `t`.
>
vim.tbl_count({ a=1, b=2 }) => 2
@@ -1611,7 +1651,7 @@ tbl_islist({t}) *vim.tbl_islist()*
{t} Table
Return: ~
- `true` if array-like table, else `false` .
+ `true` if array-like table, else `false`.
tbl_keys({t}) *vim.tbl_keys()*
Return a list of all keys used in a table. However, the order
@@ -1773,7 +1813,7 @@ input({opts}, {on_confirm}) *vim.ui.input()*
Parameters: ~
{opts} table Additional options. See |input()|
• prompt (string|nil) Text of the prompt.
- Defaults to `Input:` .
+ Defaults to `Input:`.
• default (string|nil) Default reply to the
input
• completion (string|nil) Specifies type of
@@ -1816,16 +1856,16 @@ select({items}, {opts}, {on_choice}) *vim.ui.select()*
Defaults to `Select one of:`
• format_item (function item -> text)
Function to format an individual item from
- `items` . Defaults to `tostring` .
+ `items`. Defaults to `tostring`.
• kind (string|nil) Arbitrary hint string
indicating the item shape. Plugins
reimplementing `vim.ui.select` may wish to
use this to infer the structure or
- semantics of `items` , or the context in
+ semantics of `items`, or the context in
which select() was called.
{on_choice} function ((item|nil, idx|nil) -> ()) Called
once the user made a choice. `idx` is the
- 1-based index of `item` within `item` . `nil`
+ 1-based index of `item` within `item`. `nil`
if the user aborted the dialog.
@@ -1950,9 +1990,9 @@ set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
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: >
+ 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)
<
@@ -1974,9 +2014,7 @@ set({mode}, {lhs}, {rhs}, {opts}) *vim.keymap.set()*
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.
+ |nvim_set_keymap()|. Default `false`.
See also: ~
|nvim_set_keymap()|
diff --git a/runtime/doc/map.txt b/runtime/doc/map.txt
index 358e944261..b874d6dc61 100644
--- a/runtime/doc/map.txt
+++ b/runtime/doc/map.txt
@@ -65,6 +65,8 @@ modes.
where the map command applies. Disallow mapping of
{rhs}, to avoid nested and recursive mappings. Often
used to redefine a command.
+ Note: When <Plug> appears in the {rhs} this part is
+ always applied even if remapping is disallowed.
:unm[ap] {lhs} |mapmode-nvo| *:unm* *:unmap*
@@ -285,7 +287,7 @@ Here is an example that inserts a list number that increases: >
func ListItem()
let g:counter += 1
- return g:counter . '. '
+ return g:counter .. '. '
endfunc
func ListReset()
@@ -1489,12 +1491,12 @@ The valid escape sequences are
Examples: >
command! -nargs=+ -complete=file MyEdit
\ for f in expand(<q-args>, 0, 1) |
- \ exe '<mods> split ' . f |
+ \ exe '<mods> split ' .. f |
\ endfor
function! SpecialEdit(files, mods)
for f in expand(a:files, 0, 1)
- exe a:mods . ' split ' . f
+ exe a:mods .. ' split ' .. f
endfor
endfunction
command! -nargs=+ -complete=file Sedit
@@ -1570,7 +1572,7 @@ This will invoke: >
: let i = 0
: while i < argc()
: if filereadable(argv(i))
- : execute "e " . argv(i)
+ : execute "e " .. argv(i)
: execute a:command
: endif
: let i = i + 1
diff --git a/runtime/doc/motion.txt b/runtime/doc/motion.txt
index c473244827..20033bd76a 100644
--- a/runtime/doc/motion.txt
+++ b/runtime/doc/motion.txt
@@ -993,7 +993,7 @@ These commands are not marks themselves, but jump to a mark:
:let lnum = line(".")
:keepjumps normal gg
:call SetLastChange()
- :keepjumps exe "normal " . lnum . "G"
+ :keepjumps exe "normal " .. lnum .. "G"
<
Note that ":keepjumps" must be used for every command.
When invoking a function the commands in that function
diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt
index 6e2bc228d0..b2bbf5ddad 100644
--- a/runtime/doc/options.txt
+++ b/runtime/doc/options.txt
@@ -897,7 +897,7 @@ A jump table for the options with a short description can be found at |Q_op|.
If you like to keep a lot of backups, you could use a BufWritePre
autocommand to change 'backupext' just before writing the file to
include a timestamp. >
- :au BufWritePre * let &bex = '-' . strftime("%Y%b%d%X") . '~'
+ :au BufWritePre * let &bex = '-' .. strftime("%Y%b%d%X") .. '~'
< Use 'backupdir' to put the backup in a different directory.
*'backupskip'* *'bsk'*
@@ -920,7 +920,7 @@ A jump table for the options with a short description can be found at |Q_op|.
Note that environment variables are not expanded. If you want to use
$HOME you must expand it explicitly, e.g.: >
- :let backupskip = escape(expand('$HOME'), '\') . '/tmp/*'
+ :let backupskip = escape(expand('$HOME'), '\') .. '/tmp/*'
< Note that the default also makes sure that "crontab -e" works (when a
backup would be made by renaming the original file crontab won't see
@@ -1185,7 +1185,7 @@ A jump table for the options with a short description can be found at |Q_op|.
If the default value taken from $CDPATH is not what you want, include
a modified version of the following command in your vimrc file to
override it: >
- :let &cdpath = ',' . substitute(substitute($CDPATH, '[, ]', '\\\0', 'g'), ':', ',', 'g')
+ :let &cdpath = ',' .. substitute(substitute($CDPATH, '[, ]', '\\\0', 'g'), ':', ',', 'g')
< This option cannot be set from a |modeline| or in the |sandbox|, for
security reasons.
(parts of 'cdpath' can be passed to the shell to expand file names).
@@ -1232,8 +1232,8 @@ A jump table for the options with a short description can be found at |Q_op|.
set charconvert=CharConvert()
fun CharConvert()
system("recode "
- \ . v:charconvert_from . ".." . v:charconvert_to
- \ . " <" . v:fname_in . " >" v:fname_out)
+ \ .. v:charconvert_from .. ".." .. v:charconvert_to
+ \ .. " <" .. v:fname_in .. " >" .. v:fname_out)
return v:shell_error
endfun
< The related Vim variables are:
@@ -2441,7 +2441,14 @@ A jump table for the options with a short description can be found at |Q_op|.
item default Used for ~
stl:c ' ' or '^' statusline of the current window
stlnc:c ' ' or '=' statusline of the non-current windows
+ horiz:c '─' or '-' horizontal separators |:split|
+ horizup:c '┴' or '-' upwards facing horizontal separator
+ horizdown:c '┬' or '-' downwards facing horizontal separator
vert:c '│' or '|' vertical separators |:vsplit|
+ vertleft:c '┤' or '|' left facing vertical separator
+ vertright:c '├' or '|' right facing vertical separator
+ verthoriz:c '┼' or '+' overlapping vertical and horizontal
+ separator
fold:c '·' or '-' filling 'foldtext'
foldopen:c '-' mark the beginning of a fold
foldclose:c '+' show a closed fold
@@ -2454,8 +2461,13 @@ A jump table for the options with a short description can be found at |Q_op|.
"stlnc" the space will be used when there is highlighting, '^' or '='
otherwise.
- If 'ambiwidth' is "double" then "vert", "foldsep" and "fold" default to
- single-byte alternatives.
+ Note that "horiz", "horizup", "horizdown", "vertleft", "vertright" and
+ "verthoriz" are only used when 'laststatus' is 3, since only vertical
+ window separators are used otherwise.
+
+ If 'ambiwidth' is "double" then "horiz", "horizup", "horizdown",
+ "vert", "vertleft", "vertright", "verthoriz", "foldsep" and "fold"
+ default to single-byte alternatives.
Example: >
:set fillchars=stl:^,stlnc:=,vert:│,fold:·,diff:-
@@ -2469,7 +2481,13 @@ A jump table for the options with a short description can be found at |Q_op|.
item highlight group ~
stl:c StatusLine |hl-StatusLine|
stlnc:c StatusLineNC |hl-StatusLineNC|
- vert:c VertSplit |hl-VertSplit|
+ horiz:c WinSeparator |hl-WinSeparator|
+ horizup:c WinSeparator |hl-WinSeparator|
+ horizdown:c WinSeparator |hl-WinSeparator|
+ vert:c WinSeparator |hl-WinSeparator|
+ vertleft:c WinSeparator |hl-WinSeparator|
+ vertright:c WinSeparator |hl-WinSeparator|
+ verthoriz:c WinSeparator |hl-WinSeparator|
fold:c Folded |hl-Folded|
diff:c DiffDelete |hl-DiffDelete|
eob:c EndOfBuffer |hl-EndOfBuffer|
@@ -3040,7 +3058,7 @@ A jump table for the options with a short description can be found at |Q_op|.
*'guitablabel'* *'gtl'*
'guitablabel' 'gtl' string (default empty)
global
- When nonempty describes the text to use in a label of the GUI tab
+ When non-empty describes the text to use in a label of the GUI tab
pages line. When empty and when the result is empty Vim will use a
default label. See |setting-guitablabel| for more info.
@@ -3057,7 +3075,7 @@ A jump table for the options with a short description can be found at |Q_op|.
*'guitabtooltip'* *'gtt'*
'guitabtooltip' 'gtt' string (default empty)
global
- When nonempty describes the text to use in a tooltip for the GUI tab
+ When non-empty describes the text to use in a tooltip for the GUI tab
pages line. When empty Vim will use a default tooltip.
This option is otherwise just like 'guitablabel' above.
You can include a line break. Simplest method is to use |:let|: >
@@ -3620,7 +3638,7 @@ A jump table for the options with a short description can be found at |Q_op|.
global
Language to use for menu translation. Tells which file is loaded
from the "lang" directory in 'runtimepath': >
- "lang/menu_" . &langmenu . ".vim"
+ "lang/menu_" .. &langmenu .. ".vim"
< (without the spaces). For example, to always use the Dutch menus, no
matter what $LANG is set to: >
:set langmenu=nl_NL.ISO_8859-1
@@ -3652,6 +3670,8 @@ A jump table for the options with a short description can be found at |Q_op|.
0: never
1: only if there are at least two windows
2: always
+ 3: have a global statusline at the bottom instead of one for
+ each window
The screen looks nicer with a status line if you have several
windows, but it takes another screen line. |status-line|
@@ -4522,7 +4542,7 @@ A jump table for the options with a short description can be found at |Q_op|.
< To use an environment variable, you probably need to replace the
separator. Here is an example to append $INCL, in which directory
names are separated with a semi-colon: >
- :let &path = &path . "," . substitute($INCL, ';', ',', 'g')
+ :let &path = &path .. "," .. substitute($INCL, ';', ',', 'g')
< Replace the ';' with a ':' or whatever separator is used. Note that
this doesn't work when $INCL contains a comma or white space.
@@ -5906,7 +5926,7 @@ A jump table for the options with a short description can be found at |Q_op|.
*'statusline'* *'stl'* *E540* *E542*
'statusline' 'stl' string (default empty)
global or local to window |global-local|
- When nonempty, this option determines the content of the status line.
+ When non-empty, this option determines the content of the status line.
Also see |status-line|.
The option consists of printf style '%' items interspersed with
@@ -5929,7 +5949,7 @@ A jump table for the options with a short description can be found at |Q_op|.
empty to avoid further errors. Otherwise screen updating would loop.
Note that the only effect of 'ruler' when this option is set (and
- 'laststatus' is 2) is controlling the output of |CTRL-G|.
+ 'laststatus' is 2 or 3) is controlling the output of |CTRL-G|.
field meaning ~
- Left justify the item. The default is right justified
@@ -6222,7 +6242,7 @@ A jump table for the options with a short description can be found at |Q_op|.
*'tabline'* *'tal'*
'tabline' 'tal' string (default empty)
global
- When nonempty, this option determines the content of the tab pages
+ When non-empty, this option determines the content of the tab pages
line at the top of the Vim window. When empty Vim will use a default
tab pages line. See |setting-tabline| for more info.
@@ -6570,7 +6590,7 @@ A jump table for the options with a short description can be found at |Q_op|.
This option cannot be set in a modeline when 'modelineexpr' is off.
Example: >
- :auto BufEnter * let &titlestring = hostname() . "/" . expand("%:p")
+ :auto BufEnter * let &titlestring = hostname() .. "/" .. expand("%:p")
:set title titlestring=%<%F%=%l/%L-%P titlelen=70
< The value of 'titlelen' is used to align items in the middle or right
of the available space.
@@ -6716,8 +6736,8 @@ A jump table for the options with a short description can be found at |Q_op|.
global
When bigger than zero, Vim will give messages about what it is doing.
Currently, these messages are given:
- >= 1 When the shada file is read or written.
- >= 2 When a file is ":source"'ed.
+ >= 1 Lua assignments to options,keymaps etc.
+ >= 2 When a file is ":source"'ed and when the shada file is read or written..
>= 3 UI info, terminal capabilities
>= 4 Shell commands.
>= 5 Every searched tags file and include file.
diff --git a/runtime/doc/pattern.txt b/runtime/doc/pattern.txt
index 42005b0d78..680b853dab 100644
--- a/runtime/doc/pattern.txt
+++ b/runtime/doc/pattern.txt
@@ -153,9 +153,10 @@ index, on which the cursor is. This can look like this: >
Note: the count does not take offset into account.
When no match is found you get the error: *E486* Pattern not found
-Note that for the |:global| command this behaves like a normal message, for Vi
-compatibility. For the |:s| command the "e" flag can be used to avoid the
-error message |:s_flags|.
+Note that for the `:global` command, you get a normal message "Pattern not
+found", for Vi compatibility.
+For the |:s| command the "e" flag can be used to avoid the error message
+|:s_flags|.
*search-offset* *{offset}*
These commands search for the specified pattern. With "/" and "?" an
@@ -923,7 +924,7 @@ $ At end of pattern or in front of "\|", "\)" or "\n" ('magic' on):
update the matches. This means Syntax highlighting quickly becomes
wrong.
Example, to highlight the line where the cursor currently is: >
- :exe '/\%' . line(".") . 'l.*'
+ :exe '/\%' .. line(".") .. 'l.*'
< When 'hlsearch' is set and you move the cursor around and make changes
this will clearly show when the match is updated or not.
@@ -939,7 +940,7 @@ $ At end of pattern or in front of "\|", "\)" or "\n" ('magic' on):
update the matches. This means Syntax highlighting quickly becomes
wrong.
Example, to highlight the column where the cursor currently is: >
- :exe '/\%' . col(".") . 'c'
+ :exe '/\%' .. col(".") .. 'c'
< When 'hlsearch' is set and you move the cursor around and make changes
this will clearly show when the match is updated or not.
Example for matching a single byte in column 44: >
@@ -1422,7 +1423,7 @@ Finally, these constructs are unique to Perl:
":2match" for another plugin.
==============================================================================
-11. Fuzzy matching *fuzzy-match*
+11. Fuzzy matching *fuzzy-matching*
Fuzzy matching refers to matching strings using a non-exact search string.
Fuzzy matching will match a string, if all the characters in the search string
diff --git a/runtime/doc/pi_netrw.txt b/runtime/doc/pi_netrw.txt
index 3ac61be6f2..8257152b11 100644
--- a/runtime/doc/pi_netrw.txt
+++ b/runtime/doc/pi_netrw.txt
@@ -968,7 +968,7 @@ itself:
fun! NetReadFixup(method, line1, line2)
if method == 3 " ftp (no <.netrc>)
let fourblanklines= line2 - 3
- silent fourblanklines.",".line2."g/^\s*/d"
+ silent fourblanklines .. "," .. line2 .. "g/^\s*/d"
endif
endfunction
endif
@@ -1975,7 +1975,7 @@ To use this function, simply assign its output to |g:netrw_list_hide| option. >
Example: let g:netrw_list_hide= netrw_gitignore#Hide('my_gitignore_file')
Function can take additional files with git-ignore patterns.
- Example: g:netrw_list_hide= netrw_gitignore#Hide() . '.*\.swp$'
+ Example: let g:netrw_list_hide= netrw_gitignore#Hide() .. '.*\.swp$'
Combining 'netrw_gitignore#Hide' with custom patterns.
<
@@ -2824,7 +2824,7 @@ your browsing preferences. (see also: |netrw-settings|)
Examples:
let g:netrw_list_hide= '.*\.swp$'
- let g:netrw_list_hide= netrw_gitignore#Hide().'.*\.swp$'
+ let g:netrw_list_hide= netrw_gitignore#Hide() .. '.*\.swp$'
default: ""
*g:netrw_localcopycmd* ="cp" Linux/Unix/MacOS/Cygwin
diff --git a/runtime/doc/print.txt b/runtime/doc/print.txt
index f54d0429a6..924fab175e 100644
--- a/runtime/doc/print.txt
+++ b/runtime/doc/print.txt
@@ -127,21 +127,21 @@ file: >
system(['lpr']
+ (empty(&printdevice)?[]:['-P', &printdevice])
+ [v:fname_in])
- . delete(v:fname_in)
+ .. delete(v:fname_in)
+ v:shell_error
On MS-Dos and MS-Windows machines the default is to copy the file to the
currently specified printdevice: >
system(['copy', v:fname_in, empty(&printdevice)?'LPT1':&printdevice])
- . delete(v:fname_in)
+ .. delete(v:fname_in)
If you change this option, using a function is an easy way to avoid having to
escape all the spaces. Example: >
:set printexpr=PrintFile(v:fname_in)
:function PrintFile(fname)
- : call system("ghostview " . a:fname)
+ : call system("ghostview " .. a:fname)
: call delete(a:fname)
: return v:shell_error
:endfunc
diff --git a/runtime/doc/quickfix.txt b/runtime/doc/quickfix.txt
index 5b68da8be9..8e91b101cd 100644
--- a/runtime/doc/quickfix.txt
+++ b/runtime/doc/quickfix.txt
@@ -341,7 +341,7 @@ processing a quickfix or location list command, it will be aborted.
cursor position will not be changed. See |:cexpr| for
more information.
Example: >
- :g/mypattern/caddexpr expand("%") . ":" . line(".") . ":" . getline(".")
+ :g/mypattern/caddexpr expand("%") .. ":" .. line(".") .. ":" .. getline(".")
<
*:lad* *:addd* *:laddexpr*
:lad[dexpr] {expr} Same as ":caddexpr", except the location list for the
@@ -497,7 +497,6 @@ EXECUTE A COMMAND IN ALL THE BUFFERS IN QUICKFIX OR LOCATION LIST:
autocommand event is disabled by adding it to
'eventignore'. This considerably speeds up editing
each buffer.
- {not in Vi}
Also see |:bufdo|, |:tabdo|, |:argdo|, |:windo|,
|:ldo|, |:cfdo| and |:lfdo|.
@@ -510,7 +509,6 @@ EXECUTE A COMMAND IN ALL THE BUFFERS IN QUICKFIX OR LOCATION LIST:
:{cmd}
etc.
< Otherwise it works the same as `:cdo`.
- {not in Vi}
*:ldo*
:ld[o][!] {cmd} Execute {cmd} in each valid entry in the location list
@@ -523,7 +521,6 @@ EXECUTE A COMMAND IN ALL THE BUFFERS IN QUICKFIX OR LOCATION LIST:
etc.
< Only valid entries in the location list are used.
Otherwise it works the same as `:cdo`.
- {not in Vi}
*:lfdo*
:lfdo[!] {cmd} Execute {cmd} in each file in the location list for
@@ -535,7 +532,6 @@ EXECUTE A COMMAND IN ALL THE BUFFERS IN QUICKFIX OR LOCATION LIST:
:{cmd}
etc.
< Otherwise it works the same as `:ldo`.
- {not in Vi}
FILTERING A QUICKFIX OR LOCATION LIST:
*cfilter-plugin* *:Cfilter* *:Lfilter*
@@ -575,6 +571,7 @@ location list.
second quickfix window. If [height] is given the
existing window will be resized to it.
+ *quickfix-buffer*
The window will contain a special buffer, with
'buftype' equal to "quickfix". Don't change this!
The window will have the w:quickfix_title variable set
@@ -583,7 +580,11 @@ location list.
status line if the value of 'statusline' is adjusted
properly. Whenever this buffer is modified by a
quickfix command or function, the |b:changedtick|
- variable is incremented.
+ variable is incremented. You can get the number of
+ this buffer using the getqflist() and getloclist()
+ functions by passing the 'qfbufnr' item. For a
+ location list, this buffer is wiped out when the
+ location list is removed.
*:lop* *:lopen*
:lop[en] [height] Open a window to show the location list for the
@@ -641,6 +642,27 @@ quickfix window. If there already is a window for that file, it is used
instead. If the buffer in the used window has changed, and the error is in
another file, jumping to the error will fail. You will first have to make
sure the window contains a buffer which can be abandoned.
+
+When you select a file from the quickfix window, the following steps are used
+to find a window to edit the file:
+
+1. If a window displaying the selected file is present in the current tabpage
+ (starting with the window before the quickfix window), then that window is
+ used.
+2. If the above step fails and if 'switchbuf' contains "usetab" and a window
+ displaying the selected file is present in any one of the tabpages
+ (starting with the first tabpage) then that window is used.
+3. If the above step fails then a window in the current tabpage displaying a
+ buffer with 'buftype' not set (starting with the window before the quickfix
+ window) is used.
+4. If the above step fails and if 'switchbuf' contains "uselast", then the
+ previously accessed window is used.
+5. If the above step fails then the window before the quickfix window is used.
+ If there is no previous window, then the window after the quickfix window
+ is used.
+6. If the above step fails, then a new horizontally split window above the
+ quickfix window is used.
+
*CTRL-W_<Enter>* *CTRL-W_<CR>*
You can use CTRL-W <Enter> to open a new window and jump to the error there.
@@ -650,7 +672,7 @@ FileType event (also see |qf.vim|). Then the BufReadPost event is triggered,
using "quickfix" for the buffer name. This can be used to perform some action
on the listed errors. Example: >
au BufReadPost quickfix setlocal modifiable
- \ | silent exe 'g/^/s//\=line(".")." "/'
+ \ | silent exe 'g/^/s//\=line(".") .. " "/'
\ | setlocal nomodifiable
This prepends the line number to each line. Note the use of "\=" in the
substitute string of the ":s" command, which is used to evaluate an
@@ -679,13 +701,15 @@ this window, the displayed location list is used.
When you select a file from the location list window, the following steps are
used to find a window to edit the file:
-1. If a window with the location list displayed in the location list window is
- present, then the file is opened in that window.
-2. If the above step fails and if the file is already opened in another
- window, then that window is used.
-3. If the above step fails then an existing window showing a buffer with
- 'buftype' not set is used.
-4. If the above step fails, then the file is edited in a new window.
+1. If a non-quickfix window associated with the location list is present in
+ the current tabpage, then that window is used.
+2. If the above step fails and if the file is already opened in another window
+ in the current tabpage, then that window is used.
+3. If the above step fails and 'switchbuf' contains "usetab" and if the file
+ is opened in a window in any one of the tabpages, then that window is used.
+4. If the above step fails then a window in the current tabpage showing a
+ buffer with 'buftype' not set is used.
+5. If the above step fails, then the file is edited in a new window.
In all of the above cases, if the location list for the selected window is not
yet set, then it is set to the location list displayed in the location list
@@ -749,12 +773,18 @@ using these functions are below:
" get the quickfix list window id
:echo getqflist({'winid' : 0}).winid
+ " get the quickfix list window buffer number
+ :echo getqflist({'qfbufnr' : 0}).qfbufnr
+
" get the context of the current location list
:echo getloclist(0, {'context' : 0}).context
" get the location list window id of the third window
:echo getloclist(3, {'winid' : 0}).winid
+ " get the location list window buffer number of the third window
+ :echo getloclist(3, {'qfbufnr' : 0}).qfbufnr
+
" get the file window id of a location list window (winnr: 4)
:echo getloclist(4, {'filewinid' : 0}).filewinid
<
@@ -1018,7 +1048,7 @@ commands can be combined to create a NewGrep command: >
matching is used to find matching lines. In this
case, {pattern} is treated as a literal string
instead of a regular expression. See
- |fuzzy-match| for more information about fuzzy
+ |fuzzy-matching| for more information about fuzzy
matching strings.
|QuickFixCmdPre| and |QuickFixCmdPost| are triggered.
diff --git a/runtime/doc/quickref.txt b/runtime/doc/quickref.txt
index af8301f1a0..e36eb2359f 100644
--- a/runtime/doc/quickref.txt
+++ b/runtime/doc/quickref.txt
@@ -356,6 +356,7 @@ In Insert or Command-line mode:
|v_y| {visual}y yank the highlighted text into a register
|yy| N yy yank N lines into a register
|Y| N Y yank N lines into a register
+ Note: Mapped to "y$" by default. |default-mappings|
|p| N p put a register after the cursor position (N times)
|P| N P put a register before the cursor position (N times)
|]p| N ]p like p, but adjust indent to current line
diff --git a/runtime/doc/remote.txt b/runtime/doc/remote.txt
new file mode 100644
index 0000000000..0c1e3438de
--- /dev/null
+++ b/runtime/doc/remote.txt
@@ -0,0 +1,131 @@
+*remote.txt* Nvim
+
+
+ VIM REFERENCE MANUAL by Bram Moolenaar
+
+
+Vim client-server communication *client-server*
+
+ Type |gO| to see the table of contents.
+
+==============================================================================
+1. Common functionality *clientserver*
+
+Nvim's |RPC| functionality allows clients to programmatically control Nvim. Nvim
+itself takes command-line arguments that cause it to become a client to another
+Nvim running as a server. These arguments match those provided by Vim's
+clientserver option.
+
+The following command line arguments are available:
+
+ argument meaning ~
+
+ --remote [+{cmd}] {file} ... *--remote*
+ Open the file list in a remote Vim. When
+ there is no Vim server, execute locally.
+ Vim allows one init command: +{cmd}.
+ This must be an Ex command that can be
+ followed by "|". It's not yet supported by
+ Nvim.
+ The rest of the command line is taken as the
+ file list. Thus any non-file arguments must
+ come before this.
+ You cannot edit stdin this way |--|.
+ The remote Vim is raised. If you don't want
+ this use >
+ nvim --remote-send "<C-\><C-N>:n filename<CR>"
+<
+ --remote-silent [+{cmd}] {file} ... *--remote-silent*
+ As above, but don't complain if there is no
+ server and the file is edited locally.
+ *--remote-tab*
+ --remote-tab Like --remote but open each file in a new
+ tabpage.
+ *--remote-tab-silent*
+ --remote-tab-silent Like --remote-silent but open each file in a
+ new tabpage.
+ *--remote-send*
+ --remote-send {keys} Send {keys} to server and exit. The {keys}
+ are not mapped. Special key names are
+ recognized, e.g., "<CR>" results in a CR
+ character.
+ *--remote-expr*
+ --remote-expr {expr} Evaluate {expr} in server and print the result
+ on stdout.
+ *--server*
+ --server {addr} Connect to the named pipe or socket at the
+ given address for executing remote commands.
+ See |--listen| for specifying an address when
+ starting a server.
+
+Examples ~
+
+Start an Nvim server listening on a named pipe at '~/.cache/nvim/server.pipe': >
+ nvim --listen ~/.cache/nvim/server.pipe
+
+Edit "file.txt" in an Nvim server listening at '~/.cache/nvim/server.pipe': >
+ nvim --server ~/.cache/nvim/server.pipe --remote file.txt
+
+This doesn't work, all arguments after --remote will be used as file names: >
+ nvim --remote --server ~/.cache/nvim/server.pipe file.txt
+
+Tell the remote server to write all files and exit: >
+ nvim --server ~/.cache/nvim/server.pipe --remote-send '<C-\><C-N>:wqa<CR>'
+
+
+REMOTE EDITING
+
+The --remote argument will cause a |:drop| command to be constructed from the
+rest of the command line and sent as described above.
+Note that the --remote and --remote-wait arguments will consume the rest of
+the command line. I.e. all remaining arguments will be regarded as filenames.
+You can not put options there!
+
+
+==============================================================================
+2. Missing functionality *E5600* *clientserver-missing*
+
+Vim supports additional functionality in clientserver that's not yet
+implemented in Nvim. In particular, none of the "wait" variants are supported
+yet. The following command line arguments are not yet available:
+
+ argument meaning ~
+
+ --remote-wait [+{cmd}] {file} ... *--remote-wait*
+ Not yet supported by Nvim.
+ As --remote, but wait for files to complete
+ (unload) in remote Vim.
+ --remote-wait-silent [+{cmd}] {file} ... *--remote-wait-silent*
+ Not yet supported by Nvim.
+ As --remote-wait, but don't complain if there
+ is no server.
+ *--remote-tab-wait*
+ --remote-tab-wait Not yet supported by Nvim.
+ Like --remote-wait but open each file in a new
+ tabpage.
+ *--remote-tab-wait-silent*
+ --remote-tab-wait-silent Not yet supported by Nvim.
+ Like --remote-wait-silent but open each file
+ in a new tabpage.
+ *--servername*
+ --servername {name} Not yet supported by Nvim.
+ Become the server {name}. When used together
+ with one of the --remote commands: connect to
+ server {name} instead of the default (see
+ below). The name used will be uppercase.
+
+ *--serverlist*
+ --serverlist Not yet supported by Nvim.
+ Output a list of server names.
+
+
+
+
+SERVER NAME *client-server-name*
+
+By default Vim will try to register the name under which it was invoked (gvim,
+egvim ...). This can be overridden with the --servername argument. Nvim
+either listens on a named pipe or a socket and does not yet support this
+--servername functionality.
+
+ vim:tw=78:sw=4:ts=8:noet:ft=help:norl:
diff --git a/runtime/doc/repeat.txt b/runtime/doc/repeat.txt
index a022049766..994f97bba0 100644
--- a/runtime/doc/repeat.txt
+++ b/runtime/doc/repeat.txt
@@ -161,6 +161,11 @@ Q Repeat the last recorded register [count] times.
result of evaluating the expression is executed as an
Ex command.
Mappings are not recognized in these commands.
+ When the |line-continuation| character (\) is present
+ at the beginning of a line in a linewise register,
+ then it is combined with the previous line. This is
+ useful for yanking and executing parts of a Vim
+ script.
*:@:*
:[addr]@: Repeat last command-line. First set cursor at line
@@ -253,21 +258,22 @@ For writing a Vim script, see chapter 41 of the user manual |usr_41.txt|.
below "plugin", just like with plugins in
'runtimepath'.
- If the filetype detection was not enabled yet (this
+ If the filetype detection was already enabled (this
is usually done with a "syntax enable" or "filetype
- on" command in your .vimrc file), this will also look
+ on" command in your |init.vim|, or automatically during
+ |initialization|), and the package was found in
+ "pack/*/opt/{name}", this command will also look
for "{name}/ftdetect/*.vim" files.
When the optional ! is added no plugin files or
ftdetect scripts are loaded, only the matching
directories are added to 'runtimepath'. This is
- useful in your .vimrc. The plugins will then be
- loaded during initialization, see |load-plugins| (note
+ useful in your |init.vim|. The plugins will then be
+ loaded during |initialization|, see |load-plugins| (note
that the loading order will be reversed, because each
- directory is inserted before others).
- Note that for ftdetect scripts to be loaded
- you will need to write `filetype plugin indent on`
- AFTER all `packadd!` commands.
+ directory is inserted before others). In this case, the
+ ftdetect scripts will be loaded during |initialization|,
+ before the |load-plugins| step.
Also see |pack-add|.
diff --git a/runtime/doc/sign.txt b/runtime/doc/sign.txt
index 5cfa06c33c..a2a5645baa 100644
--- a/runtime/doc/sign.txt
+++ b/runtime/doc/sign.txt
@@ -87,7 +87,7 @@ the delete is undone the sign does not move back.
Here is an example that places a sign "piet", displayed with the text ">>", in
line 23 of the current file: >
:sign define piet text=>> texthl=Search
- :exe ":sign place 2 line=23 name=piet file=" . expand("%:p")
+ :exe ":sign place 2 line=23 name=piet file=" .. expand("%:p")
And here is the command to delete it again: >
:sign unplace 2
diff --git a/runtime/doc/spell.txt b/runtime/doc/spell.txt
index 03c00c8495..bc45b0e511 100644
--- a/runtime/doc/spell.txt
+++ b/runtime/doc/spell.txt
@@ -120,8 +120,8 @@ zuG Undo |zW| and |zG|, remove the word from the internal
rare as this is a fairly uncommon command and all
intuitive commands for this are already taken. If you
want you can add mappings with e.g.: >
- nnoremap z? :exe ':spellrare ' . expand('<cWORD>')<CR>
- nnoremap z/ :exe ':spellrare! ' . expand('<cWORD>')<CR>
+ nnoremap z? :exe ':spellrare ' .. expand('<cWORD>')<CR>
+ nnoremap z/ :exe ':spellrare! ' .. expand('<cWORD>')<CR>
< |:spellundo|, |zuw|, or |zuW| can be used to undo this.
:spellr[rare]! {word} Add {word} as a rare word to the internal word
diff --git a/runtime/doc/starting.txt b/runtime/doc/starting.txt
index 978142a1e0..1d3fa6c2ca 100644
--- a/runtime/doc/starting.txt
+++ b/runtime/doc/starting.txt
@@ -800,7 +800,7 @@ resulting file, when executed with a ":source" command:
After restoring the Session, the full filename of your current Session is
available in the internal variable |v:this_session|.
An example mapping: >
- :nmap <F2> :wa<Bar>exe "mksession! " . v:this_session<CR>:so ~/sessions/
+ :nmap <F2> :wa<Bar>exe "mksession! " .. v:this_session<CR>:so ~/sessions/
This saves the current Session, and starts off the command to load another.
A session includes all tab pages, unless "tabpages" was removed from
diff --git a/runtime/doc/syntax.txt b/runtime/doc/syntax.txt
index 319a715e40..0ff31e81ab 100644
--- a/runtime/doc/syntax.txt
+++ b/runtime/doc/syntax.txt
@@ -188,7 +188,8 @@ A syntax group name doesn't specify any color or attributes itself.
The name for a highlight or syntax group must consist of ASCII letters, digits
and the underscore. As a regexp: "[a-zA-Z0-9_]*". However, Vim does not give
-an error when using other characters.
+an error when using other characters. The maxium length of a group name is
+about 200 bytes. *E1249*
To be able to allow each user to pick their favorite set of colors, there must
be preferred names for highlight groups that are common for many languages.
@@ -616,7 +617,7 @@ evaluate to get a unique string to append to each ID used in a given document,
so that the full IDs will be unique even when combined with other content in a
larger HTML document. Example, to append _ and the buffer number to each ID: >
- :let g:html_id_expr = '"_".bufnr("%")'
+ :let g:html_id_expr = '"_" .. bufnr("%")'
<
To append a string "_mystring" to the end of each ID: >
@@ -1500,6 +1501,14 @@ The enhanced mode also takes advantage of additional color features for a dark
gvim display. Here, statements are colored LightYellow instead of Yellow, and
conditionals are LightBlue for better distinction.
+Both Visual Basic and FORM use the extension ".frm". 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 found, filetype will be "vb", otherwise "form".
+
+If the automatic detection doesn't work for you or you only edit, for
+example, FORM files, use this in your startup vimrc: >
+ :let filetype_frm = "form"
+
FORTH *forth.vim* *ft-forth-syntax*
@@ -3550,8 +3559,8 @@ Do you want to draw with the mouse? Try the following: >
:function! GetPixel()
: let c = getline(".")[col(".") - 1]
: echo c
- : exe "noremap <LeftMouse> <LeftMouse>r".c
- : exe "noremap <LeftDrag> <LeftMouse>r".c
+ : exe "noremap <LeftMouse> <LeftMouse>r" .. c
+ : exe "noremap <LeftDrag> <LeftMouse>r" .. c
:endfunction
:noremap <RightMouse> <LeftMouse>:call GetPixel()<CR>
:set guicursor=n:hor20 " to see the color beneath the cursor
@@ -4388,7 +4397,7 @@ Leading context *:syn-lc* *:syn-leading* *:syn-context*
Note: This is an obsolete feature, only included for backwards compatibility
with previous Vim versions. It's now recommended to use the |/\@<=| construct
-in the pattern.
+in the pattern. You can also often use |/\zs|.
The "lc" offset specifies leading context -- a part of the pattern that must
be present, but is not considered part of the match. An offset of "lc=n" will
@@ -4875,7 +4884,8 @@ the same syntax file on all UIs.
1. TUI highlight arguments
- *bold* *underline* *undercurl*
+ *bold* *underline* *underlineline*
+ *undercurl* *underdot* *underdash*
*inverse* *italic* *standout*
*nocombine* *strikethrough*
cterm={attr-list} *attr-list* *highlight-cterm* *E418*
@@ -4883,7 +4893,10 @@ cterm={attr-list} *attr-list* *highlight-cterm* *E418*
following items (in any order):
bold
underline
+ underlineline double underline
undercurl curly underline
+ underdot dotted underline
+ underdash dashed underline
strikethrough
reverse
inverse same as reverse
@@ -4894,8 +4907,9 @@ cterm={attr-list} *attr-list* *highlight-cterm* *E418*
Note that "bold" can be used here and by using a bold font. They
have the same effect.
- "undercurl" falls back to "underline" in a terminal that does not
- support it. The color is set using |highlight-guisp|.
+ "underlineline", "undercurl", "underdot", and "underdash" fall back
+ to "underline" in a terminal that does not support them. The color is
+ set using |highlight-guisp|.
start={term-list} *highlight-start* *E422*
stop={term-list} *term-list* *highlight-stop*
@@ -5028,8 +5042,8 @@ guifg={color-name} *highlight-guifg*
guibg={color-name} *highlight-guibg*
guisp={color-name} *highlight-guisp*
These give the foreground (guifg), background (guibg) and special
- (guisp) color to use in the GUI. "guisp" is used for undercurl
- and underline.
+ (guisp) color to use in the GUI. "guisp" is used for various
+ underlines.
There are a few special names:
NONE no color (transparent)
bg use normal background color
@@ -5105,8 +5119,8 @@ TermCursor cursor in a focused terminal
TermCursorNC cursor in an unfocused terminal
*hl-ErrorMsg*
ErrorMsg error messages on the command line
- *hl-VertSplit*
-VertSplit the column separating vertically split windows
+ *hl-WinSeparator*
+WinSeparator separators between window splits
*hl-Folded*
Folded line used for closed folds
*hl-FoldColumn*
@@ -5363,9 +5377,9 @@ types.vim: *.[ch]
And put these lines in your vimrc: >
" load the types.vim highlighting file, if it exists
- autocmd BufRead,BufNewFile *.[ch] let fname = expand('<afile>:p:h') . '/types.vim'
+ autocmd BufRead,BufNewFile *.[ch] let fname = expand('<afile>:p:h') .. '/types.vim'
autocmd BufRead,BufNewFile *.[ch] if filereadable(fname)
- autocmd BufRead,BufNewFile *.[ch] exe 'so ' . fname
+ autocmd BufRead,BufNewFile *.[ch] exe 'so ' .. fname
autocmd BufRead,BufNewFile *.[ch] endif
==============================================================================
diff --git a/runtime/doc/tabpage.txt b/runtime/doc/tabpage.txt
index 7f91fda9f4..f06a6bcc34 100644
--- a/runtime/doc/tabpage.txt
+++ b/runtime/doc/tabpage.txt
@@ -133,7 +133,10 @@ something else.
:tabclose + " close the next tab page
:tabclose 3 " close the third tab page
:tabclose $ " close the last tab page
-<
+ :tabclose # " close the last accessed tab page
+
+When a tab is closed the next tab page will become the current one.
+
*:tabo* *:tabonly*
:tabo[nly][!] Close all other tab pages.
When the 'hidden' option is set, all buffers in closed windows
@@ -159,6 +162,8 @@ something else.
" one
:tabonly 1 " close all tab pages except the first one
:tabonly $ " close all tab pages except the last one
+ :tabonly # " close all tab pages except the last
+ " accessed one
SWITCHING TO ANOTHER TAB PAGE:
@@ -181,6 +186,7 @@ gt *i_CTRL-<PageDown>* *i_<C-PageDown>*
:+2tabnext " go to the two next tab page
:1tabnext " go to the first tab page
:$tabnext " go to the last tab page
+ :tabnext # " go to the last accessed tab page
:tabnext $ " as above
:tabnext - " go to the previous tab page
:tabnext -1 " as above
@@ -190,10 +196,6 @@ gt *i_CTRL-<PageDown>* *i_<C-PageDown>*
{count}<C-PageDown>
{count}gt Go to tab page {count}. The first tab page has number one.
-CTRL-<Tab> *CTRL-<Tab>*
-CTRL-W g<Tab> *g<Tab>* *CTRL-W_g<Tab>*
-g<Tab> Go to previous (last accessed) tab page.
-
:tabp[revious] *:tabp* *:tabprevious* *gT* *:tabN*
:tabN[ext] *:tabNext* *CTRL-<PageUp>*
<C-PageUp> *<C-PageUp>* *i_CTRL-<PageUp>* *i_<C-PageUp>*
@@ -213,6 +215,9 @@ gT Go to the previous tab page. Wraps around from the first one
*:tabl* *:tablast*
:tabl[ast] Go to the last tab page.
+<C-Tab> *CTRL-<Tab>* *<C-Tab>*
+CTRL-W g<Tab> *g<Tab>* *CTRL-W_g<Tab>*
+g<Tab> Go to the last accessed tab page.
Other commands:
*:tabs*
@@ -245,6 +250,8 @@ REORDERING TAB PAGES:
:tabmove " move the tab page to the last
:$tabmove " as above
:tabmove $ " as above
+ :tabmove # " move the tab page after the last accessed
+ " tab page
:tabm[ove] +[N]
:tabm[ove] -[N]
@@ -366,24 +373,24 @@ pages and define labels for them. Then get the label for each tab page. >
for i in range(tabpagenr('$'))
" select the highlighting
if i + 1 == tabpagenr()
- let s .= '%#TabLineSel#'
+ let s ..= '%#TabLineSel#'
else
- let s .= '%#TabLine#'
+ let s ..= '%#TabLine#'
endif
" set the tab page number (for mouse clicks)
- let s .= '%' . (i + 1) . 'T'
+ let s ..= '%' .. (i + 1) .. 'T'
" the label is made by MyTabLabel()
- let s .= ' %{MyTabLabel(' . (i + 1) . ')} '
+ let s ..= ' %{MyTabLabel(' .. (i + 1) .. ')} '
endfor
" after the last tab fill with TabLineFill and reset tab page nr
- let s .= '%#TabLineFill#%T'
+ let s ..= '%#TabLineFill#%T'
" right-align the label to close the current tab page
if tabpagenr('$') > 1
- let s .= '%=%#TabLine#%999Xclose'
+ let s ..= '%=%#TabLine#%999Xclose'
endif
return s
@@ -446,14 +453,14 @@ windows in the tab page and a '+' if there is a modified buffer: >
" Append the number of windows in the tab page if more than one
let wincount = tabpagewinnr(v:lnum, '$')
if wincount > 1
- let label .= wincount
+ let label ..= wincount
endif
if label != ''
- let label .= ' '
+ let label ..= ' '
endif
" Append the buffer name
- return label . bufname(bufnrlist[tabpagewinnr(v:lnum) - 1])
+ return label .. bufname(bufnrlist[tabpagewinnr(v:lnum) - 1])
endfunction
set guitablabel=%{GuiTabLabel()}
diff --git a/runtime/doc/tagsrch.txt b/runtime/doc/tagsrch.txt
index 4d938c4a23..5a0d16d6b8 100644
--- a/runtime/doc/tagsrch.txt
+++ b/runtime/doc/tagsrch.txt
@@ -705,7 +705,7 @@ matches the pattern "^# *define" it is not considered to be a comment.
If you want to list matches, and then select one to jump to, you could use a
mapping to do that for you. Here is an example: >
- :map <F4> [I:let nr = input("Which one: ")<Bar>exe "normal " . nr ."[\t"<CR>
+ :map <F4> [I:let nr = input("Which one: ")<Bar>exe "normal " .. nr .. "[\t"<CR>
<
*[i*
[i Display the first line that contains the keyword
diff --git a/runtime/doc/term.txt b/runtime/doc/term.txt
index 62e13285f5..f9b2271756 100644
--- a/runtime/doc/term.txt
+++ b/runtime/doc/term.txt
@@ -321,7 +321,7 @@ an #if/#else/#endif block, the selection becomes linewise.
For MS-Windows and xterm the time for double clicking can be set with the
'mousetime' option. For the other systems this time is defined outside of Vim.
An example, for using a double click to jump to the tag under the cursor: >
- :map <2-LeftMouse> :exe "tag ". expand("<cword>")<CR>
+ :map <2-LeftMouse> :exe "tag " .. expand("<cword>")<CR>
Dragging the mouse with a double click (button-down, button-up, button-down
and then drag) will result in whole words to be selected. This continues
diff --git a/runtime/doc/tips.txt b/runtime/doc/tips.txt
index b77c7d9a6d..d913b53c6b 100644
--- a/runtime/doc/tips.txt
+++ b/runtime/doc/tips.txt
@@ -84,14 +84,14 @@ What you need:
create it with the shell command "mkid file1 file2 ..".
Put this in your |init.vim|: >
- map _u :call ID_search()<Bar>execute "/\\<" . g:word . "\\>"<CR>
- map _n :n<Bar>execute "/\\<" . g:word . "\\>"<CR>
+ map _u :call ID_search()<Bar>execute "/\\<" .. g:word .. "\\>"<CR>
+ map _n :n<Bar>execute "/\\<" .. g:word .. "\\>"<CR>
function! ID_search()
let g:word = expand("<cword>")
- let x = system("lid --key=none ". g:word)
+ let x = system("lid --key=none " .. g:word)
let x = substitute(x, "\n", " ", "g")
- execute "next " . x
+ execute "next " .. x
endfun
To use it, place the cursor on a word, type "_u" and vim will load the file
@@ -285,13 +285,13 @@ This mapping will format any bullet list. It requires that there is an empty
line above and below each list entry. The expression commands are used to
be able to give comments to the parts of the mapping. >
- :let m = ":map _f :set ai<CR>" " need 'autoindent' set
- :let m = m . "{O<Esc>" " add empty line above item
- :let m = m . "}{)^W" " move to text after bullet
- :let m = m . "i <CR> <Esc>" " add space for indent
- :let m = m . "gq}" " format text after the bullet
- :let m = m . "{dd" " remove the empty line
- :let m = m . "5lDJ" " put text after bullet
+ :let m = ":map _f :set ai<CR>" " need 'autoindent' set
+ :let m ..= "{O<Esc>" " add empty line above item
+ :let m ..= "}{)^W" " move to text after bullet
+ :let m ..= "i <CR> <Esc>" " add space for indent
+ :let m ..= "gq}" " format text after the bullet
+ :let m ..= "{dd" " remove the empty line
+ :let m ..= "5lDJ" " put text after bullet
:execute m |" define the mapping
(<> notation |<>|. Note that this is all typed literally. ^W is "^" "W", not
@@ -429,15 +429,15 @@ A slightly more advanced version is used in the |matchparen| plugin.
let c = '\['
let c2 = '\]'
endif
- let s_skip ='synIDattr(synID(line("."), col("."), 0), "name") ' .
+ let s_skip ='synIDattr(synID(line("."), col("."), 0), "name") ' ..
\ '=~? "string\\|comment"'
execute 'if' s_skip '| let s_skip = 0 | endif'
let [m_lnum, m_col] = searchpairpos(c, '', c2, s_flags, s_skip)
if m_lnum > 0 && m_lnum >= line('w0') && m_lnum <= line('w$')
- exe 'match Search /\(\%' . c_lnum . 'l\%' . c_col .
- \ 'c\)\|\(\%' . m_lnum . 'l\%' . m_col . 'c\)/'
+ exe 'match Search /\(\%' .. c_lnum .. 'l\%' .. c_col ..
+ \ 'c\)\|\(\%' .. m_lnum .. 'l\%' .. m_col .. 'c\)/'
let s:paren_hl_on = 1
endif
endfunction
diff --git a/runtime/doc/treesitter.txt b/runtime/doc/treesitter.txt
index dbd8ec6fef..a9d9f81849 100644
--- a/runtime/doc/treesitter.txt
+++ b/runtime/doc/treesitter.txt
@@ -207,14 +207,14 @@ Here is a list of built-in predicates :
`eq?` *ts-predicate-eq?*
This predicate will check text correspondence between nodes or
- strings : >
+ 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 provided vim regex matches the text
- corresponding to a node : >
+ corresponding to a node: >
((identifier) @constant (#match? @constant "^[A-Z_]+$"))
< Note: the `^` and `$` anchors will respectively match the
start and end of the node's text.
@@ -225,17 +225,18 @@ Here is a list of built-in predicates :
`contains?` *ts-predicate-contains?*
Will check if any of the following arguments appears in the
- text corresponding to the node : >
+ text corresponding to the node: >
((identifier) @foo (#contains? @foo "foo"))
((identifier) @foo-bar (#contains @foo-bar "foo" "bar"))
<
`any-of?` *ts-predicate-any-of?*
- Will check if the text is the same as any of the following.
+ Will check if the text is the same as any of the following
+ arguments: >
+ ((identifier) @foo (#any-of? @foo "foo" "bar"))
+<
This is the recommended way to check if the node matches one
of many keywords for example, as it has been optimized for
this.
- arguments : >
- ((identifier) @foo (#any-of? @foo "foo" "bar"))
<
*lua-treesitter-not-predicate*
Each predicate has a `not-` prefixed predicate that is just the negation of
@@ -467,7 +468,7 @@ parse_query({lang}, {query}) *parse_query()*
Exposes `info` and `captures` with additional context about {query}.
• `captures` contains the list of unique capture names defined
- in {query}. - `info.captures` also points to `captures` .
+ in {query}. -`info.captures` also points to `captures`.
• `info.patterns` contains information about predicates.
Parameters: ~
@@ -527,8 +528,8 @@ Query:iter_matches({self}, {node}, {source}, {start}, {stop})
a table mapping capture indices to nodes, and metadata from
any directives processing the match. If the query has more
than one pattern the capture table might be sparse, and e.g.
- `pairs()` method should be used over `ipairs` . Here an
- example iterating over all captures in every match:
+ `pairs()` method should be used over `ipairs`. Here an example
+ iterating over all captures in every match:
>
for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do
diff --git a/runtime/doc/uganda.txt b/runtime/doc/uganda.txt
index 79519da51e..23dfa082a0 100644
--- a/runtime/doc/uganda.txt
+++ b/runtime/doc/uganda.txt
@@ -129,11 +129,12 @@ Kibaale Children's Centre *kcc* *Kibaale* *charity*
Kibaale Children's Centre (KCC) is located in Kibaale, a small town in the
south of Uganda, near Tanzania, in East Africa. The area is known as Rakai
District. The population is mostly farmers. Although people are poor, there
-is enough food. But this district is suffering from AIDS more than any other
-part of the world. Some say that it started there. Estimations are that 10
-to 30% of the Ugandans are infected with HIV. Because parents die, there are
-many orphans. In this district about 60,000 children have lost one or both
-parents, out of a population of 350,000. And this is still continuing.
+usually is enough food. But this district is suffering from AIDS more than
+any other part of the world. Some say that it started there. Estimations are
+that in the past 10 to 30% of the Ugandans are infected with HIV. Because
+parents die, there are many orphans. In this district about 60,000 children
+have lost one or both parents, out of a population of 350,000. Although AIDS
+is now mostly under control, the problems are still continuing.
The children need a lot of help. The KCC is working hard to provide the needy
with food, medical care and education. Food and medical care to keep them
diff --git a/runtime/doc/ui.txt b/runtime/doc/ui.txt
index e7be14e732..c5e3b60079 100644
--- a/runtime/doc/ui.txt
+++ b/runtime/doc/ui.txt
@@ -283,19 +283,24 @@ numerical highlight ids to the actual attributes.
attributes specified by the `rgb_attr` and `cterm_attr` dicts, with the
following (all optional) keys.
- `foreground`: foreground color.
- `background`: background color.
- `special`: color to use for underline and undercurl, when present.
- `reverse`: reverse video. Foreground and background colors are
- switched.
- `italic`: italic text.
- `bold`: bold text.
- `strikethrough`: struckthrough text.
- `underline`: underlined text. The line has `special` color.
- `undercurl`: undercurled text. The curl has `special` color.
- `blend`: Blend level (0-100). Could be used by UIs to support
- blending floating windows to the background or to
- signal a transparent cursor.
+ `foreground`: foreground color.
+ `background`: background color.
+ `special`: color to use for various underlines, when
+ present.
+ `reverse`: reverse video. Foreground and background colors
+ are switched.
+ `italic`: italic text.
+ `bold`: bold text.
+ `strikethrough`: struckthrough text.
+ `underline`: underlined text. The line has `special` color.
+ `underlineline`: double underlined text. The lines have `special`
+ color.
+ `undercurl`: undercurled text. The curl has `special` color.
+ `underdot`: underdotted text. The dots have `special` color.
+ `underdash`: underdashed text. The dashes have `special` color.
+ `blend`: Blend level (0-100). Could be used by UIs to
+ support blending floating windows to the
+ background or to signal a transparent cursor.
For absent color keys the default color should be used. Don't store
the default value in the table, rather a sentinel value, so that
@@ -444,14 +449,17 @@ is not active. New UIs should implement |ui-linegrid| instead.
`foreground`: foreground color.
`background`: background color.
- `special`: color to use for underline and undercurl, when present.
+ `special`: color to use for various underlines, when present.
`reverse`: reverse video. Foreground and background colors are
switched.
`italic`: italic text.
`bold`: bold text.
`strikethrough`: struckthrough text.
`underline`: underlined text. The line has `special` color.
+ `underlineline`: double underlined text. The lines have `special` color.
`undercurl`: undercurled text. The curl has `special` color.
+ `underdot`: underdotted text. The dots have `special` color.
+ `underdash`: underdashed text. The dashes have `special` color.
["put", text]
The (utf-8 encoded) string `text` is put at the cursor position
diff --git a/runtime/doc/undo.txt b/runtime/doc/undo.txt
index b11d7581ed..a853aea995 100644
--- a/runtime/doc/undo.txt
+++ b/runtime/doc/undo.txt
@@ -272,12 +272,12 @@ history file. E.g.: >
au BufReadPost * call ReadUndo()
au BufWritePost * call WriteUndo()
func ReadUndo()
- if filereadable(expand('%:h'). '/UNDO/' . expand('%:t'))
+ if filereadable(expand('%:h') .. '/UNDO/' .. expand('%:t'))
rundo %:h/UNDO/%:t
endif
endfunc
func WriteUndo()
- let dirname = expand('%:h') . '/UNDO'
+ let dirname = expand('%:h') .. '/UNDO'
if !isdirectory(dirname)
call mkdir(dirname)
endif
diff --git a/runtime/doc/usr_04.txt b/runtime/doc/usr_04.txt
index b2dd617542..c7c900274b 100644
--- a/runtime/doc/usr_04.txt
+++ b/runtime/doc/usr_04.txt
@@ -349,15 +349,17 @@ Notice that "yw" includes the white space after a word. If you don't want
this, use "ye".
The "yy" command yanks a whole line, just like "dd" deletes a whole line.
-Unexpectedly, while "D" deletes from the cursor to the end of the line, "Y"
-works like "yy", it yanks the whole line. Watch out for this inconsistency!
-Use "y$" to yank to the end of the line.
a text line yy a text line a text line
line 2 line 2 p line 2
last line last line a text line
last line
+"Y" was originally equivalent to "yank the entire line", as opposed to "D"
+which is "delete to end of the line". "Y" has thus been remapped to mean
+"yank to end of the line" to make it consistent with the behavior of "D".
+Mappings will be covered in later chapters.
+
==============================================================================
*04.7* Using the clipboard
diff --git a/runtime/doc/usr_05.txt b/runtime/doc/usr_05.txt
index f93a221e43..b1ef563e43 100644
--- a/runtime/doc/usr_05.txt
+++ b/runtime/doc/usr_05.txt
@@ -131,7 +131,7 @@ it worked before Vim 5.0. Otherwise the "Q" command starts Ex mode, but you
will not need it.
>
- vnoremap _g y:exe "grep /" . escape(@", '\\/') . "/ *.c *.h"<CR>
+ vnoremap _g y:exe "grep /" .. escape(@", '\\/') .. "/ *.c *.h"<CR>
This mapping yanks the visually selected text and searches for it in C files.
This is a complicated mapping. You can see that mappings can be used to do
diff --git a/runtime/doc/usr_07.txt b/runtime/doc/usr_07.txt
index 649be8d7ce..ebf5c3d7b8 100644
--- a/runtime/doc/usr_07.txt
+++ b/runtime/doc/usr_07.txt
@@ -336,7 +336,7 @@ there. >
Of course you can use many other commands to yank the text. For example, to
select whole lines start Visual mode with "V". Or use CTRL-V to select a
-rectangular block. Or use "Y" to yank a single line, "yaw" to yank-a-word,
+rectangular block. Or use "yy" to yank a single line, "yaw" to yank-a-word,
etc.
The "p" command puts the text after the cursor. Use "P" to put the text
before the cursor. Notice that Vim remembers if you yanked a whole line or a
@@ -359,7 +359,7 @@ the text should be placed in the f register. This must come just before the
yank command.
Now yank three whole lines to the l register (l for line): >
- "l3Y
+ "l3yy
The count could be before the "l just as well. To yank a block of text to the
b (for block) register: >
diff --git a/runtime/doc/usr_08.txt b/runtime/doc/usr_08.txt
index 8ccaa73006..1d20913a14 100644
--- a/runtime/doc/usr_08.txt
+++ b/runtime/doc/usr_08.txt
@@ -482,6 +482,8 @@ statusline:
0 never
1 only when there are split windows (the default)
2 always
+ 3 have a global statusline at the bottom instead of one for each
+ window
Many commands that edit another file have a variant that splits the window.
For Command-line commands this is done by prepending an "s". For example:
diff --git a/runtime/doc/usr_10.txt b/runtime/doc/usr_10.txt
index 5365f90314..8844671e01 100644
--- a/runtime/doc/usr_10.txt
+++ b/runtime/doc/usr_10.txt
@@ -132,11 +132,11 @@ This works both with recording and with yank and delete commands. For
example, you want to collect a sequence of lines into the a register. Yank
the first line with: >
- "aY
+ "ayy
Now move to the second line, and type: >
- "AY
+ "Ayy
Repeat this command for all lines. The a register now contains all those
lines, in the order you yanked them.
diff --git a/runtime/doc/various.txt b/runtime/doc/various.txt
index 38869f8e94..75ee0fdfdf 100644
--- a/runtime/doc/various.txt
+++ b/runtime/doc/various.txt
@@ -275,7 +275,7 @@ g8 Print the hex values of the bytes used in the
Special characters are not escaped, use quotes or
|shellescape()|: >
:!ls "%"
- :exe "!ls " . shellescape(expand("%"))
+ :exe "!ls " .. shellescape(expand("%"))
<
Newline character ends {cmd} unless a backslash
precedes the newline. What follows is interpreted as
@@ -432,7 +432,7 @@ g8 Print the hex values of the bytes used in the
used. In this example |:silent| is used to avoid the
message about reading the file and |:unsilent| to be
able to list the first line of each file. >
- :silent argdo unsilent echo expand('%') . ": " . getline(1)
+ :silent argdo unsilent echo expand('%') .. ": " .. getline(1)
<
*:verb* *:verbose*
@@ -461,10 +461,11 @@ g8 Print the hex values of the bytes used in the
*:verbose-cmd*
When 'verbose' is non-zero, listing the value of a Vim option or a key map or
an abbreviation or a user-defined function or a command or a highlight group
-or an autocommand will also display where it was last defined. If it was
-defined manually then there will be no "Last set" message. When it was
-defined while executing a function, user command or autocommand, the script in
-which it was defined is reported.
+or an autocommand will also display where it was last defined. If they were
+defined in Lua they will only be located if 'verbose' is set. So Start
+nvim with -V1 arg to see them. If it was defined manually then there
+will be no "Last set" message. When it was defined while executing a function,
+user command or autocommand, the script in which it was defined is reported.
*K*
[count]K Runs the program given by 'keywordprg' to lookup the
diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt
index 5ea6a9c5dd..9ca5faf112 100644
--- a/runtime/doc/vim_diff.txt
+++ b/runtime/doc/vim_diff.txt
@@ -84,7 +84,7 @@ Nvim creates the following default mappings at |startup|. You can disable any
of these in your config by simply removing the mapping, e.g. ":unmap Y".
>
nnoremap Y y$
- nnoremap <C-L> <Cmd>nohlsearch<Bar>diffupdate<CR><C-L>
+ nnoremap <C-L> <Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR>
inoremap <C-U> <C-G>u<C-U>
inoremap <C-W> <C-G>u<C-W>
<
@@ -211,6 +211,7 @@ Highlight groups:
|hl-Substitute|
|hl-TermCursor|
|hl-TermCursorNC|
+ |hl-WinSeparator| highlights window separators
|hl-Whitespace| highlights 'listchars' whitespace
Input/Mappings:
@@ -227,9 +228,11 @@ Options:
'cpoptions' flags: |cpo-_|
'display' flags: "msgsep" minimizes scrolling when showing messages
'guicursor' works in the terminal
- 'fillchars' flags: "msgsep" (see 'display')
+ 'fillchars' flags: "msgsep" (see 'display'), "horiz", "horizup",
+ "horizdown", "vertleft", "vertright", "verthoriz"
'foldcolumn' supports up to 9 dynamic/fixed columns
'inccommand' shows interactive results for |:substitute|-like commands
+ 'laststatus' global statusline support
'pumblend' pseudo-transparent popupmenu
'scrollback'
'signcolumn' supports up to 9 dynamic/fixed columns
@@ -348,6 +351,7 @@ Highlight groups:
|hl-ColorColumn|, |hl-CursorColumn| are lower priority than most other
groups
|hl-CursorLine| is low-priority unless foreground color is set
+ *hl-VertSplit* superseded by |hl-WinSeparator|
Macro/|recording| behavior
Replay of a macro recorded during :lmap produces the same actions as when it
diff --git a/runtime/doc/windows.txt b/runtime/doc/windows.txt
index 5b91321c40..cd5425336f 100644
--- a/runtime/doc/windows.txt
+++ b/runtime/doc/windows.txt
@@ -104,6 +104,8 @@ when the last window also has a status line:
'laststatus' = 0 never a status line
'laststatus' = 1 status line if there is more than one window
'laststatus' = 2 always a status line
+ 'laststatus' = 3 have a global statusline at the bottom instead
+ of one for each window
You can change the contents of the status line with the 'statusline' option.
This option can be local to the window, so that you can have a different
@@ -447,7 +449,7 @@ These commands can also be executed with ":wincmd":
the |CursorHold| autocommand event). Or when a Normal mode
command is inconvenient.
The count can also be a window number. Example: >
- :exe nr . "wincmd w"
+ :exe nr .. "wincmd w"
< This goes to window "nr".
==============================================================================
@@ -909,12 +911,12 @@ CTRL-W g } *CTRL-W_g}*
cursor. This is less clever than using |:ptag|, but you don't
need a tags file and it will also find matches in system
include files. Example: >
- :au! CursorHold *.[ch] ++nested exe "silent! psearch " . expand("<cword>")
+ :au! CursorHold *.[ch] ++nested exe "silent! psearch " .. expand("<cword>")
< Warning: This can be slow.
Example *CursorHold-example* >
- :au! CursorHold *.[ch] ++nested exe "silent! ptag " . expand("<cword>")
+ :au! CursorHold *.[ch] ++nested exe "silent! ptag " .. expand("<cword>")
This will cause a ":ptag" to be executed for the keyword under the cursor,
when the cursor hasn't moved for the time set with 'updatetime'. "++nested"
@@ -937,14 +939,14 @@ is no word under the cursor, and a few other things: >
:
: " Delete any existing highlight before showing another tag
: silent! wincmd P " jump to preview window
- : if &previewwindow " if we really get there...
+ : if &previewwindow " if we really get there...
: match none " delete existing highlight
: wincmd p " back to old window
: endif
:
: " Try displaying a matching tag for the word under the cursor
: try
- : exe "ptag " . w
+ : exe "ptag " .. w
: catch
: return
: endtry
@@ -956,10 +958,10 @@ is no word under the cursor, and a few other things: >
: endif
: call search("$", "b") " to end of previous line
: let w = substitute(w, '\\', '\\\\', "")
- : call search('\<\V' . w . '\>') " position cursor on match
+ : call search('\<\V' .. w .. '\>') " position cursor on match
: " Add a match highlight to the word at this position
: hi previewWord term=bold ctermbg=green guibg=green
- : exe 'match previewWord "\%' . line(".") . 'l\%' . col(".") . 'c\k*"'
+ : exe 'match previewWord "\%' .. line(".") .. 'l\%' .. col(".") .. 'c\k*"'
: wincmd p " back to old window
: endif
: endif
diff --git a/runtime/filetype.lua b/runtime/filetype.lua
index fcfc5701f0..8224b79534 100644
--- a/runtime/filetype.lua
+++ b/runtime/filetype.lua
@@ -7,19 +7,36 @@ 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>'))
+vim.api.nvim_create_augroup("filetypedetect", {clear = false})
+
+vim.api.nvim_create_autocmd({"BufRead", "BufNewFile"}, {
+ group = "filetypedetect",
+ callback = function()
+ vim.filetype.match(vim.fn.expand("<afile>"))
+ end,
+})
-" These *must* be sourced after the autocommand above is created
+-- These *must* be sourced after the autocommand above is created
+vim.cmd [[
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
+-- Set a marker so that the ftdetect scripts are not sourced a second time by filetype.vim
+vim.g.did_load_ftdetect = 1
-augroup END
-]]
+-- If filetype.vim is disabled, set up the autocmd to use scripts.vim
+if vim.g.did_load_filetypes then
+ vim.api.nvim_create_autocmd({"BufRead", "BufNewFile"}, {
+ group = "filetypedetect",
+ command = "if !did_filetype() && expand('<amatch>') !~ g:ft_ignore_pat | runtime! scripts.vim | endif",
+ })
+
+ vim.api.nvim_create_autocmd("StdinReadPost", {
+ group = "filetypedetect",
+ command = "if !did_filetype() | runtime! scripts.vim | endif",
+ })
+end
if not vim.g.ft_ignore_pat then
vim.g.ft_ignore_pat = "\\.\\(Z\\|gz\\|bz2\\|zip\\|tgz\\)$"
diff --git a/runtime/filetype.vim b/runtime/filetype.vim
index c7955d74ee..9df89674e3 100644
--- a/runtime/filetype.vim
+++ b/runtime/filetype.vim
@@ -480,6 +480,7 @@ au BufNewFile,BufRead */etc/dnsmasq.conf setf dnsmasq
au BufNewFile,BufRead *.desc setf desc
" the D language or dtrace
+au BufNewFile,BufRead */dtrace/*.d setf dtrace
au BufNewFile,BufRead *.d call dist#ft#DtraceCheck()
" Desktop files
@@ -663,7 +664,7 @@ au BufNewFile,BufRead *.fs call dist#ft#FTfs()
au BufNewFile,BufRead *.fsi,*.fsx setf fsharp
" GDB command files
-au BufNewFile,BufRead .gdbinit,gdbinit setf gdb
+au BufNewFile,BufRead .gdbinit,gdbinit,.gdbearlyinit,gdbearlyinit,*.gdb setf gdb
" GDMO
au BufNewFile,BufRead *.mo,*.gdmo setf gdmo
@@ -726,6 +727,10 @@ au BufNewFile,BufRead gnashrc,.gnashrc,gnashpluginrc,.gnashpluginrc setf gnash
au BufNewFile,BufRead gitolite.conf setf gitolite
au BufNewFile,BufRead {,.}gitolite.rc,example.gitolite.rc setf perl
+" Glimmer-flavored TypeScript and JavaScript
+au BufNewFile,BufRead *.gts setf typescript.glimmer
+au BufNewFile,BufRead *.gjs setf javascript.glimmer
+
" Gnuplot scripts
au BufNewFile,BufRead *.gpi,.gnuplot setf gnuplot
diff --git a/runtime/ftplugin/ant.vim b/runtime/ftplugin/ant.vim
index 5905858896..aee07ca4b9 100644
--- a/runtime/ftplugin/ant.vim
+++ b/runtime/ftplugin/ant.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: ant
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/aspvbs.vim b/runtime/ftplugin/aspvbs.vim
index 660dab4685..70a130d287 100644
--- a/runtime/ftplugin/aspvbs.vim
+++ b/runtime/ftplugin/aspvbs.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: aspvbs
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/config.vim b/runtime/ftplugin/config.vim
index 7fde42ebf5..73136cbc66 100644
--- a/runtime/ftplugin/config.vim
+++ b/runtime/ftplugin/config.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: config
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/csc.vim b/runtime/ftplugin/csc.vim
index 3a09c3bf8b..7b4126a503 100644
--- a/runtime/ftplugin/csc.vim
+++ b/runtime/ftplugin/csc.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: csc
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1
diff --git a/runtime/ftplugin/csh.vim b/runtime/ftplugin/csh.vim
index 929823219c..ca5da5a8b9 100644
--- a/runtime/ftplugin/csh.vim
+++ b/runtime/ftplugin/csh.vim
@@ -1,7 +1,7 @@
" Vim filetype plugin file
" Language: csh
" Maintainer: Doug Kearns <dougkearns@gmail.com>
-" Previous Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+" Previous Maintainer: Dan Sharp
" Contributor: Johannes Zellner <johannes@zellner.org>
" Last Change: 2021 Oct 15
diff --git a/runtime/ftplugin/dtd.vim b/runtime/ftplugin/dtd.vim
index 6c08f6691d..a046118c70 100644
--- a/runtime/ftplugin/dtd.vim
+++ b/runtime/ftplugin/dtd.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: dtd
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1
diff --git a/runtime/ftplugin/html.vim b/runtime/ftplugin/html.vim
index 7579080ea5..3179aa2e88 100644
--- a/runtime/ftplugin/html.vim
+++ b/runtime/ftplugin/html.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: html
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1
diff --git a/runtime/ftplugin/java.vim b/runtime/ftplugin/java.vim
index 292cb6b166..74c8e8d1c1 100644
--- a/runtime/ftplugin/java.vim
+++ b/runtime/ftplugin/java.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: Java
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Change: 2012 Mar 11
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1
diff --git a/runtime/ftplugin/jsp.vim b/runtime/ftplugin/jsp.vim
index fbba863b32..18136ccc24 100644
--- a/runtime/ftplugin/jsp.vim
+++ b/runtime/ftplugin/jsp.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: jsp
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/pascal.vim b/runtime/ftplugin/pascal.vim
index 2de92563ae..aba1e54f27 100644
--- a/runtime/ftplugin/pascal.vim
+++ b/runtime/ftplugin/pascal.vim
@@ -1,7 +1,7 @@
" Vim filetype plugin file
" Language: Pascal
" Maintainer: Doug Kearns <dougkearns@gmail.com>
-" Previous Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+" Previous Maintainer: Dan Sharp
" Last Change: 2021 Apr 23
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/php.vim b/runtime/ftplugin/php.vim
index a2f8b4d8d3..3ff0828ffe 100644
--- a/runtime/ftplugin/php.vim
+++ b/runtime/ftplugin/php.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: php
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/sgml.vim b/runtime/ftplugin/sgml.vim
index bf63efbf1f..ef52125c68 100644
--- a/runtime/ftplugin/sgml.vim
+++ b/runtime/ftplugin/sgml.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: sgml
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/sh.vim b/runtime/ftplugin/sh.vim
index 593fcec927..93a46f63e2 100644
--- a/runtime/ftplugin/sh.vim
+++ b/runtime/ftplugin/sh.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: sh
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
let b:did_ftplugin = 1
diff --git a/runtime/ftplugin/svg.vim b/runtime/ftplugin/svg.vim
index 8fff6ea32c..6f16b1a0f4 100644
--- a/runtime/ftplugin/svg.vim
+++ b/runtime/ftplugin/svg.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: svg
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/tcsh.vim b/runtime/ftplugin/tcsh.vim
index 33f1aabf68..85d3873b33 100644
--- a/runtime/ftplugin/tcsh.vim
+++ b/runtime/ftplugin/tcsh.vim
@@ -1,7 +1,7 @@
" Vim filetype plugin file
" Language: tcsh
" Maintainer: Doug Kearns <dougkearns@gmail.com>
-" Previous Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+" Previous Maintainer: Dan Sharp
" Last Change: 2021 Oct 15
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/xhtml.vim b/runtime/ftplugin/xhtml.vim
index 21ed3e1100..d2a1c0b566 100644
--- a/runtime/ftplugin/xhtml.vim
+++ b/runtime/ftplugin/xhtml.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: xhtml
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/xml.vim b/runtime/ftplugin/xml.vim
index 1d43521155..9aa188cecc 100644
--- a/runtime/ftplugin/xml.vim
+++ b/runtime/ftplugin/xml.vim
@@ -3,7 +3,7 @@
" Maintainer: Christian Brabandt <cb@256bit.org>
" Last Changed: Dec 07th, 2018
" Repository: https://github.com/chrisbra/vim-xml-ftplugin
-" Previous Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+" Previous Maintainer: Dan Sharp
" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/xsd.vim b/runtime/ftplugin/xsd.vim
index 6a4a193656..7d3efbb390 100644
--- a/runtime/ftplugin/xsd.vim
+++ b/runtime/ftplugin/xsd.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: xsd
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/ftplugin/xslt.vim b/runtime/ftplugin/xslt.vim
index 1a5ee62865..9d2def107b 100644
--- a/runtime/ftplugin/xslt.vim
+++ b/runtime/ftplugin/xslt.vim
@@ -1,8 +1,10 @@
" Vim filetype plugin file
" Language: xslt
-" Maintainer: Dan Sharp <dwsharp at users dot sourceforge dot net>
+"
+" This runtime file is looking for a new maintainer.
+"
+" Former maintainer: Dan Sharp
" Last Changed: 20 Jan 2009
-" URL: http://dwsharp.users.sourceforge.net/vim/ftplugin
if exists("b:did_ftplugin") | finish | endif
diff --git a/runtime/indent/vim.vim b/runtime/indent/vim.vim
index 7c03ff2873..cd2d4982d8 100644
--- a/runtime/indent/vim.vim
+++ b/runtime/indent/vim.vim
@@ -1,7 +1,7 @@
" Vim indent file
" Language: Vim script
" Maintainer: Bram Moolenaar <Bram@vim.org>
-" Last Change: 2021 Nov 27
+" Last Change: 2022 Mar 01
" Only load this indent file when no other was loaded.
if exists("b:did_indent")
@@ -10,7 +10,7 @@ endif
let b:did_indent = 1
setlocal indentexpr=GetVimIndent()
-setlocal indentkeys+==end,=},=else,=cat,=finall,=END,0\\,0=\"\\\
+setlocal indentkeys+==endif,=enddef,=endfu,=endfor,=endwh,=endtry,=},=else,=cat,=finall,=END,0\\,0=\"\\\
setlocal indentkeys-=0#
setlocal indentkeys-=:
@@ -103,10 +103,11 @@ function GetVimIndentIntern()
" A line starting with :au does not increment/decrement indent.
" A { may start a block or a dict. Assume that when a } follows it's a
" terminated dict.
+ " ":function" starts a block but "function(" doesn't.
if prev_text !~ '^\s*au\%[tocmd]' && prev_text !~ '^\s*{.*}'
- let i = match(prev_text, '\(^\||\)\s*\(export\s\+\)\?\({\|\(if\|wh\%[ile]\|for\|try\|cat\%[ch]\|fina\|finall\%[y]\|fu\%[nction]\|def\|el\%[seif]\)\>\)')
+ let i = match(prev_text, '\(^\||\)\s*\(export\s\+\)\?\({\|\(if\|wh\%[ile]\|for\|try\|cat\%[ch]\|fina\|finall\%[y]\|def\|el\%[seif]\)\>\|fu\%[nction][! ]\)')
if i >= 0
- let ind += shiftwidth()
+ let ind += shiftwidth()
if strpart(prev_text, i, 1) == '|' && has('syntax_items')
\ && synIDattr(synID(lnum, i, 1), "name") =~ '\(Comment\|String\|PatSep\)$'
let ind -= shiftwidth()
@@ -170,10 +171,15 @@ function GetVimIndentIntern()
let ind = ind + shiftwidth()
endif
- " Subtract a 'shiftwidth' on a :endif, :endwhile, :catch, :finally, :endtry,
- " :endfun, :else and :augroup END.
- if cur_text =~ '^\s*\(ene\@!\|cat\|finall\|el\|aug\%[roup]\s\+[eE][nN][dD]\)'
+ " Subtract a 'shiftwidth' on a :endif, :endwhile, :endfor, :catch, :finally,
+ " :endtry, :endfun, :enddef, :else and :augroup END.
+ " Although ":en" would be enough only match short command names as in
+ " 'indentkeys'.
+ if cur_text =~ '^\s*\(endif\|endwh\|endfor\|endtry\|endfu\|enddef\|cat\|finall\|else\|aug\%[roup]\s\+[eE][nN][dD]\)'
let ind = ind - shiftwidth()
+ if ind < 0
+ let ind = 0
+ endif
endif
return ind
diff --git a/src/nvim/lua/vim.lua b/runtime/lua/vim/_editor.lua
index f5993c3f55..d4db4850bd 100644
--- a/src/nvim/lua/vim.lua
+++ b/runtime/lua/vim/_editor.lua
@@ -3,9 +3,11 @@
-- Lua code lives in one of three places:
-- 1. runtime/lua/vim/ (the runtime): For "nice to have" features, e.g. the
-- `inspect` and `lpeg` modules.
--- 2. runtime/lua/vim/shared.lua: Code shared between Nvim and tests.
--- (This will go away if we migrate to nvim as the test-runner.)
--- 3. src/nvim/lua/: Compiled-into Nvim itself.
+-- 2. runtime/lua/vim/shared.lua: pure lua functions which always
+-- are available. Used in the test runner, as well as worker threads
+-- and processes launched from Nvim.
+-- 3. runtime/lua/vim/_editor.lua: Code which directly interacts with
+-- the Nvim editor state. Only available in the main thread.
--
-- Guideline: "If in doubt, put it in the runtime".
--
@@ -34,94 +36,20 @@
-- - https://github.com/bakpakin/Fennel (pretty print, repl)
-- - https://github.com/howl-editor/howl/tree/master/lib/howl/util
-local vim = vim
-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
- s = s:sub(1, -2) -- Strip trailing semicolon
- -- Find out path patterns. pathtrail should contain something like
- -- /?.so, \?.dll. This allows not to bother determining what correct
- -- suffixes are.
- local pathtrail = s:match('[/\\][^/\\]*%?.*$')
- if pathtrail and not pathtrails[pathtrail] then
- pathtrails[pathtrail] = true
- table.insert(vim._so_trails, pathtrail)
- end
-end
-
-function vim._load_package(name)
- local basename = name:gsub('%.', '/')
- local paths = {"lua/"..basename..".lua", "lua/"..basename.."/init.lua"}
- local found = vim.api.nvim__get_runtime(paths, false, {is_lua=true})
- if #found > 0 then
- local f, err = loadfile(found[1])
- return f or error(err)
- end
-
- local so_paths = {}
- for _,trail in ipairs(vim._so_trails) do
- local path = "lua"..trail:gsub('?', basename) -- so_trails contains a leading slash
- table.insert(so_paths, path)
- end
-
- found = vim.api.nvim__get_runtime(so_paths, false, {is_lua=true})
- if #found > 0 then
- -- Making function name in Lua 5.1 (see src/loadlib.c:mkfuncname) is
- -- a) strip prefix up to and including the first dash, if any
- -- b) replace all dots by underscores
- -- c) prepend "luaopen_"
- -- So "foo-bar.baz" should result in "luaopen_bar_baz"
- local dash = name:find("-", 1, true)
- local modname = dash and name:sub(dash + 1) or name
- local f, err = package.loadlib(found[1], "luaopen_"..modname:gsub("%.", "_"))
- return f or error(err)
- end
- return nil
-end
-
--- Insert vim._load_package after the preloader at position 2
-table.insert(package.loaders, 2, vim._load_package)
+local vim = assert(vim)
-- These are for loading runtime modules lazily since they aren't available in
-- the nvim binary as specified in executor.c
-setmetatable(vim, {
- __index = function(t, key)
- if key == 'treesitter' then
- t.treesitter = require('vim.treesitter')
- return t.treesitter
- elseif key == 'F' then
- t.F = require('vim.F')
- return t.F
- elseif require('vim.uri')[key] ~= nil then
- -- Expose all `vim.uri` functions on the `vim` module.
- t[key] = require('vim.uri')[key]
- return t[key]
- elseif key == 'lsp' then
- t.lsp = require('vim.lsp')
- return t.lsp
- elseif key == 'highlight' then
- t.highlight = require('vim.highlight')
- return t.highlight
- elseif key == 'diagnostic' then
- t.diagnostic = require('vim.diagnostic')
- return t.diagnostic
- 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
-})
+for k,v in pairs {
+ treesitter=true;
+ filetype = true;
+ F=true;
+ lsp=true;
+ highlight=true;
+ diagnostic=true;
+ keymap=true;
+ ui=true;
+} do vim._submodules[k] = v end
vim.log = {
levels = {
@@ -200,7 +128,7 @@ local function inspect(object, options) -- luacheck: no unused
end
do
- local tdots, tick, got_line1 = 0, 0, false
+ local tdots, tick, got_line1, undo_started, trailing_nl = 0, 0, false, false, false
--- Paste handler, invoked by |nvim_paste()| when a conforming UI
--- (such as the |TUI|) pastes text into the editor.
@@ -228,44 +156,80 @@ do
--- - 3: ends the paste (exactly once)
---@returns false if client should cancel the paste.
function vim.paste(lines, phase)
- local call = vim.api.nvim_call_function
local now = vim.loop.now()
- local mode = call('mode', {}):sub(1,1)
- if phase < 2 then -- Reset flags.
- tdots, tick, got_line1 = now, 0, false
- elseif mode ~= 'c' then
+ local is_first_chunk = phase < 2
+ local is_last_chunk = phase == -1 or phase == 3
+ if is_first_chunk then -- Reset flags.
+ tdots, tick, got_line1, undo_started, trailing_nl = now, 0, false, false, false
+ end
+ if #lines == 0 then
+ lines = {''}
+ end
+ if #lines == 1 and lines[1] == '' and not is_last_chunk then
+ -- An empty chunk can cause some edge cases in streamed pasting,
+ -- so don't do anything unless it is the last chunk.
+ return true
+ end
+ -- Note: mode doesn't always start with "c" in cmdline mode, so use getcmdtype() instead.
+ if vim.fn.getcmdtype() ~= '' then -- cmdline-mode: paste only 1 line.
+ if not got_line1 then
+ got_line1 = (#lines > 1)
+ vim.api.nvim_set_option('paste', true) -- For nvim_input().
+ -- Escape "<" and control characters
+ local line1 = lines[1]:gsub('<', '<lt>'):gsub('(%c)', '\022%1')
+ vim.api.nvim_input(line1)
+ vim.api.nvim_set_option('paste', false)
+ end
+ return true
+ end
+ local mode = vim.api.nvim_get_mode().mode
+ if undo_started then
vim.api.nvim_command('undojoin')
end
- if mode == 'c' and not got_line1 then -- cmdline-mode: paste only 1 line.
- got_line1 = (#lines > 1)
- vim.api.nvim_set_option('paste', true) -- For nvim_input().
- local line1 = lines[1]:gsub('<', '<lt>'):gsub('[\r\n\012\027]', ' ') -- Scrub.
- vim.api.nvim_input(line1)
- vim.api.nvim_set_option('paste', false)
- elseif mode ~= 'c' then
- if phase < 2 and mode:find('^[vV\22sS\19]') then
- vim.api.nvim_command([[exe "normal! \<Del>"]])
- vim.api.nvim_put(lines, 'c', false, true)
- elseif phase < 2 and not mode:find('^[iRt]') then
- vim.api.nvim_put(lines, 'c', true, true)
- -- XXX: Normal-mode: workaround bad cursor-placement after first chunk.
- vim.api.nvim_command('normal! a')
- elseif phase < 2 and mode == 'R' then
- local nchars = 0
- for _, line in ipairs(lines) do
- nchars = nchars + line:len()
+ if mode:find('^i') or mode:find('^n?t') then -- Insert mode or Terminal buffer
+ vim.api.nvim_put(lines, 'c', false, true)
+ elseif phase < 2 and mode:find('^R') and not mode:find('^Rv') then -- Replace mode
+ -- TODO: implement Replace mode streamed pasting
+ -- TODO: support Virtual Replace mode
+ local nchars = 0
+ for _, line in ipairs(lines) do
+ nchars = nchars + line:len()
+ end
+ local row, col = unpack(vim.api.nvim_win_get_cursor(0))
+ local bufline = vim.api.nvim_buf_get_lines(0, row-1, row, true)[1]
+ local firstline = lines[1]
+ firstline = bufline:sub(1, col)..firstline
+ lines[1] = firstline
+ lines[#lines] = lines[#lines]..bufline:sub(col + nchars + 1, bufline:len())
+ vim.api.nvim_buf_set_lines(0, row-1, row, false, lines)
+ elseif mode:find('^[nvV\22sS\19]') then -- Normal or Visual or Select mode
+ if mode:find('^n') then -- Normal mode
+ -- When there was a trailing new line in the previous chunk,
+ -- the cursor is on the first character of the next line,
+ -- so paste before the cursor instead of after it.
+ vim.api.nvim_put(lines, 'c', not trailing_nl, false)
+ else -- Visual or Select mode
+ vim.api.nvim_command([[exe "silent normal! \<Del>"]])
+ local del_start = vim.fn.getpos("'[")
+ local cursor_pos = vim.fn.getpos('.')
+ if mode:find('^[VS]') then -- linewise
+ if cursor_pos[2] < del_start[2] then -- replacing lines at eof
+ -- create a new line
+ vim.api.nvim_put({''}, 'l', true, true)
+ end
+ vim.api.nvim_put(lines, 'c', false, false)
+ else
+ -- paste after cursor when replacing text at eol, otherwise paste before cursor
+ vim.api.nvim_put(lines, 'c', cursor_pos[3] < del_start[3], false)
end
- local row, col = unpack(vim.api.nvim_win_get_cursor(0))
- local bufline = vim.api.nvim_buf_get_lines(0, row-1, row, true)[1]
- local firstline = lines[1]
- firstline = bufline:sub(1, col)..firstline
- lines[1] = firstline
- lines[#lines] = lines[#lines]..bufline:sub(col + nchars + 1, bufline:len())
- vim.api.nvim_buf_set_lines(0, row-1, row, false, lines)
- else
- vim.api.nvim_put(lines, 'c', false, true)
end
+ -- put cursor at the end of the text instead of one character after it
+ vim.fn.setpos('.', vim.fn.getpos("']"))
+ trailing_nl = lines[#lines] == ''
+ else -- Don't know what to do in other modes
+ return false
end
+ undo_started = true
if phase ~= -1 and (now - tdots >= 100) then
local dots = ('.'):rep(tick % 4)
tdots = now
@@ -274,7 +238,7 @@ do
-- message when there are zero dots.
vim.api.nvim_command(('echo "%s"'):format(dots))
end
- if phase == -1 or phase == 3 then
+ if is_last_chunk then
vim.api.nvim_command('redraw'..(tick > 1 and '|echo ""' or ''))
end
return true -- Paste will not continue if not returning `true`.
@@ -293,12 +257,6 @@ function vim.schedule_wrap(cb)
end)
end
---- <Docs described in |vim.empty_dict()| >
----@private
-function vim.empty_dict()
- return setmetatable({}, vim._empty_dict_mt)
-end
-
-- vim.fn.{func}(...)
vim.fn = setmetatable({}, {
__index = function(t, key)
@@ -597,6 +555,8 @@ function vim._expand_pat(pat, env)
local mt = getmetatable(final_env)
if mt and type(mt.__index) == "table" then
field = rawget(mt.__index, key)
+ elseif final_env == vim and vim._submodules[key] then
+ field = vim[key]
end
end
final_env = field
@@ -623,6 +583,9 @@ function vim._expand_pat(pat, env)
if mt and type(mt.__index) == "table" then
insert_keys(mt.__index)
end
+ if final_env == vim then
+ insert_keys(vim._submodules)
+ end
table.sort(keys)
@@ -709,4 +672,69 @@ function vim.pretty_print(...)
return ...
end
-return module
+function vim._cs_remote(rcid, server_addr, connect_error, args)
+ local function connection_failure_errmsg(consequence)
+ local explanation
+ if server_addr == '' then
+ explanation = "No server specified with --server"
+ else
+ explanation = "Failed to connect to '" .. server_addr .. "'"
+ if connect_error ~= "" then
+ explanation = explanation .. ": " .. connect_error
+ end
+ end
+ return "E247: " .. explanation .. ". " .. consequence
+ end
+
+ local f_silent = false
+ local f_tab = false
+
+ local subcmd = string.sub(args[1],10)
+ if subcmd == 'tab' then
+ f_tab = true
+ elseif subcmd == 'silent' then
+ f_silent = true
+ elseif subcmd == 'wait' or subcmd == 'wait-silent' or subcmd == 'tab-wait' or subcmd == 'tab-wait-silent' then
+ return { errmsg = 'E5600: Wait commands not yet implemented in nvim' }
+ elseif subcmd == 'tab-silent' then
+ f_tab = true
+ f_silent = true
+ elseif subcmd == 'send' then
+ if rcid == 0 then
+ return { errmsg = connection_failure_errmsg('Send failed.') }
+ end
+ vim.fn.rpcrequest(rcid, 'nvim_input', args[2])
+ return { should_exit = true, tabbed = false }
+ elseif subcmd == 'expr' then
+ if rcid == 0 then
+ return { errmsg = connection_failure_errmsg('Send expression failed.') }
+ end
+ print(vim.fn.rpcrequest(rcid, 'nvim_eval', args[2]))
+ return { should_exit = true, tabbed = false }
+ elseif subcmd ~= '' then
+ return { errmsg='Unknown option argument: ' .. args[1] }
+ end
+
+ if rcid == 0 then
+ if not f_silent then
+ vim.notify(connection_failure_errmsg("Editing locally"), vim.log.levels.WARN)
+ end
+ else
+ local command = {}
+ if f_tab then table.insert(command, 'tab') end
+ table.insert(command, 'drop')
+ for i = 2, #args do
+ table.insert(command, vim.fn.fnameescape(args[i]))
+ end
+ vim.fn.rpcrequest(rcid, 'nvim_command', table.concat(command, ' '))
+ end
+
+ return {
+ should_exit = rcid ~= 0,
+ tabbed = f_tab,
+ }
+end
+
+require('vim._meta')
+
+return vim
diff --git a/runtime/lua/vim/_init_packages.lua b/runtime/lua/vim/_init_packages.lua
new file mode 100644
index 0000000000..7d27741f1b
--- /dev/null
+++ b/runtime/lua/vim/_init_packages.lua
@@ -0,0 +1,83 @@
+-- prevents luacheck from making lints for setting things on vim
+local vim = assert(vim)
+
+local pathtrails = {}
+vim._so_trails = {}
+for s in (package.cpath..';'):gmatch('[^;]*;') do
+ s = s:sub(1, -2) -- Strip trailing semicolon
+ -- Find out path patterns. pathtrail should contain something like
+ -- /?.so, \?.dll. This allows not to bother determining what correct
+ -- suffixes are.
+ local pathtrail = s:match('[/\\][^/\\]*%?.*$')
+ if pathtrail and not pathtrails[pathtrail] then
+ pathtrails[pathtrail] = true
+ table.insert(vim._so_trails, pathtrail)
+ end
+end
+
+function vim._load_package(name)
+ local basename = name:gsub('%.', '/')
+ local paths = {"lua/"..basename..".lua", "lua/"..basename.."/init.lua"}
+ local found = vim.api.nvim__get_runtime(paths, false, {is_lua=true})
+ if #found > 0 then
+ local f, err = loadfile(found[1])
+ return f or error(err)
+ end
+
+ local so_paths = {}
+ for _,trail in ipairs(vim._so_trails) do
+ local path = "lua"..trail:gsub('?', basename) -- so_trails contains a leading slash
+ table.insert(so_paths, path)
+ end
+
+ found = vim.api.nvim__get_runtime(so_paths, false, {is_lua=true})
+ if #found > 0 then
+ -- Making function name in Lua 5.1 (see src/loadlib.c:mkfuncname) is
+ -- a) strip prefix up to and including the first dash, if any
+ -- b) replace all dots by underscores
+ -- c) prepend "luaopen_"
+ -- So "foo-bar.baz" should result in "luaopen_bar_baz"
+ local dash = name:find("-", 1, true)
+ local modname = dash and name:sub(dash + 1) or name
+ local f, err = package.loadlib(found[1], "luaopen_"..modname:gsub("%.", "_"))
+ return f or error(err)
+ end
+ return nil
+end
+
+-- Insert vim._load_package after the preloader at position 2
+table.insert(package.loaders, 2, vim._load_package)
+
+-- builtin functions which always should be available
+require'vim.shared'
+
+vim._submodules = {inspect=true}
+
+-- These are for loading runtime modules in the vim namespace lazily.
+setmetatable(vim, {
+ __index = function(t, key)
+ if vim._submodules[key] then
+ t[key] = require('vim.'..key)
+ return t[key]
+ elseif vim.startswith(key, 'uri_') then
+ local val = require('vim.uri')[key]
+ if val ~= nil then
+ -- Expose all `vim.uri` functions on the `vim` module.
+ t[key] = val
+ return t[key]
+ end
+ end
+ end
+})
+
+--- <Docs described in |vim.empty_dict()| >
+---@private
+--- TODO: should be in vim.shared when vim.shared always uses nvim-lua
+function vim.empty_dict()
+ return setmetatable({}, vim._empty_dict_mt)
+end
+
+-- only on main thread: functions for interacting with editor state
+if not vim.is_thread() then
+ require'vim._editor'
+end
diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua
index b4537c2882..fcb1e61764 100644
--- a/runtime/lua/vim/diagnostic.lua
+++ b/runtime/lua/vim/diagnostic.lua
@@ -447,7 +447,7 @@ local function set_list(loclist, opts)
vim.fn.setqflist({}, ' ', { title = title, items = items })
end
if open then
- vim.api.nvim_command(loclist and "lopen" or "copen")
+ vim.api.nvim_command(loclist and "lopen" or "botright copen")
end
end
@@ -920,7 +920,8 @@ M.handlers.underline = {
underline_ns,
higroup,
{ diagnostic.lnum, diagnostic.col },
- { diagnostic.end_lnum, diagnostic.end_col }
+ { diagnostic.end_lnum, diagnostic.end_col },
+ { priority = vim.highlight.priorities.diagnostics }
)
end
save_extmarks(underline_ns, bufnr)
diff --git a/runtime/lua/vim/filetype.lua b/runtime/lua/vim/filetype.lua
index c6bcdd965c..b356f5e3dc 100644
--- a/runtime/lua/vim/filetype.lua
+++ b/runtime/lua/vim/filetype.lua
@@ -225,6 +225,7 @@ local extension = {
fsi = "fsharp",
fsx = "fsharp",
fusion = "fusion",
+ gdb = "gdb",
gdmo = "gdmo",
mo = "gdmo",
tres = "gdresource",
@@ -247,6 +248,8 @@ local extension = {
gradle = "groovy",
groovy = "groovy",
gsp = "gsp",
+ gjs = "javascript.glimmer",
+ gts = "typescript.glimmer",
hack = "hack",
hackpartial = "hack",
haml = "haml",
@@ -917,6 +920,8 @@ local filename = {
mtab = "fstab",
[".gdbinit"] = "gdb",
gdbinit = "gdb",
+ [".gdbearlyinit"] = "gdb",
+ gdbearlyinit = "gdb",
["lltxxxxx.txt"] = "gedcom",
["TAG_EDITMSG"] = "gitcommit",
["MERGE_MSG"] = "gitcommit",
@@ -1176,6 +1181,7 @@ local pattern = {
[".*/etc/yum%.conf"] = "dosini",
[".*lvs"] = "dracula",
[".*lpe"] = "dracula",
+ [".*/dtrace/.*%.d"] = "dtrace",
[".*esmtprc"] = "esmtprc",
[".*Eterm/.*%.cfg"] = "eterm",
[".*%.git/modules/.*/config"] = "gitconfig",
diff --git a/runtime/lua/vim/highlight.lua b/runtime/lua/vim/highlight.lua
index 12faa0a6e1..4105ef0675 100644
--- a/runtime/lua/vim/highlight.lua
+++ b/runtime/lua/vim/highlight.lua
@@ -1,9 +1,16 @@
local api = vim.api
-local highlight = {}
+local M = {}
+
+M.priorities = {
+ syntax = 50,
+ treesitter = 100,
+ diagnostics = 150,
+ user = 200,
+}
---@private
-function highlight.create(higroup, hi_info, default)
+function M.create(higroup, hi_info, default)
local options = {}
-- TODO: Add validation
for k, v in pairs(hi_info) do
@@ -13,28 +20,33 @@ function highlight.create(higroup, hi_info, default)
end
---@private
-function highlight.link(higroup, link_to, force)
+function M.link(higroup, link_to, force)
vim.cmd(string.format([[highlight%s link %s %s]], force and "!" or " default", higroup, link_to))
end
-
--- Highlight range between two positions
---
---@param bufnr number of buffer to apply highlighting to
---@param ns namespace to add highlight to
---@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)
----@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
+---@param start first position (tuple {line,col})
+---@param finish second position (tuple {line,col})
+---@param opts table with options:
+-- - regtype type of range (:help setreg, default charwise)
+-- - inclusive boolean indicating whether the range is end-inclusive (default false)
+-- - priority number indicating priority of highlight (default priorities.user)
+function M.range(bufnr, ns, higroup, start, finish, opts)
+ opts = opts or {}
+ local regtype = opts.regtype or "v"
+ local inclusive = opts.inclusive or false
+ local priority = opts.priority or M.priorities.user
-- sanity check
- if start[2] < 0 or finish[1] < start[1] then return end
+ if start[2] < 0 or finish[1] < start[1] then
+ return
+ end
- local region = vim.region(bufnr, start, finish, rtype, inclusive)
+ local region = vim.region(bufnr, start, finish, regtype, inclusive)
for linenr, cols in pairs(region) do
local end_row
if cols[2] == -1 then
@@ -46,13 +58,12 @@ function highlight.range(bufnr, ns, higroup, start, finish, rtype, inclusive, pr
end_row = end_row,
end_col = cols[2],
priority = priority,
- strict = false
+ strict = false,
})
end
-
end
-local yank_ns = api.nvim_create_namespace('hlyank')
+local yank_ns = api.nvim_create_namespace("hlyank")
--- Highlight the yanked region
---
--- use from init.vim via
@@ -62,26 +73,40 @@ local yank_ns = api.nvim_create_namespace('hlyank')
--- customize conditions (here: do not highlight a visual selection) via
--- au TextYankPost * lua vim.highlight.on_yank {on_visual=false}
---
--- @param opts dictionary with options controlling the highlight:
+-- @param opts table with options controlling the highlight:
-- - higroup highlight group for yanked region (default "IncSearch")
-- - timeout time in ms before highlight is cleared (default 150)
-- - on_macro highlight when executing macro (default false)
-- - on_visual highlight when yanking visual selection (default true)
-- - event event structure (default vim.v.event)
-function highlight.on_yank(opts)
- vim.validate {
- opts = { opts,
- function(t) if t == nil then return true else return type(t) == 'table' end end,
- 'a table or nil to configure options (see `:h highlight.on_yank`)',
- }}
+function M.on_yank(opts)
+ vim.validate({
+ opts = {
+ opts,
+ function(t)
+ if t == nil then
+ return true
+ else
+ return type(t) == "table"
+ end
+ end,
+ "a table or nil to configure options (see `:h highlight.on_yank`)",
+ },
+ })
opts = opts or {}
local event = opts.event or vim.v.event
local on_macro = opts.on_macro or false
local on_visual = (opts.on_visual ~= false)
- if (not on_macro) and vim.fn.reg_executing() ~= '' then return end
- if event.operator ~= 'y' or event.regtype == '' then return end
- if (not on_visual) and event.visual then return end
+ if not on_macro and vim.fn.reg_executing() ~= "" then
+ return
+ end
+ if event.operator ~= "y" or event.regtype == "" then
+ return
+ end
+ if not on_visual and event.visual then
+ return
+ end
local higroup = opts.higroup or "IncSearch"
local timeout = opts.timeout or 150
@@ -92,19 +117,23 @@ function highlight.on_yank(opts)
local pos1 = vim.fn.getpos("'[")
local pos2 = vim.fn.getpos("']")
- 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, 200)
+ pos1 = { pos1[2] - 1, pos1[3] - 1 + pos1[4] }
+ pos2 = { pos2[2] - 1, pos2[3] - 1 + pos2[4] }
- vim.defer_fn(
- function()
- if api.nvim_buf_is_valid(bufnr) then
- api.nvim_buf_clear_namespace(bufnr, yank_ns, 0, -1)
- end
- end,
- timeout
+ M.range(
+ bufnr,
+ yank_ns,
+ higroup,
+ pos1,
+ pos2,
+ { regtype = event.regtype, inclusive = event.inclusive, priority = M.priorities.user }
)
+
+ vim.defer_fn(function()
+ if api.nvim_buf_is_valid(bufnr) then
+ api.nvim_buf_clear_namespace(bufnr, yank_ns, 0, -1)
+ end
+ end, timeout)
end
-return highlight
+return M
diff --git a/runtime/lua/vim/keymap.lua b/runtime/lua/vim/keymap.lua
index d53b790746..1be40b0081 100644
--- a/runtime/lua/vim/keymap.lua
+++ b/runtime/lua/vim/keymap.lua
@@ -25,8 +25,8 @@ local keymap = {}
--- 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:
+--- 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>
@@ -42,7 +42,7 @@ local keymap = {}
--- |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.
+--- Default `false`.
---@see |nvim_set_keymap()|
function keymap.set(mode, lhs, rhs, opts)
vim.validate {
@@ -66,8 +66,8 @@ function keymap.set(mode, lhs, rhs, opts)
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
+ -- default remap value is false
+ opts.noremap = true
else
-- remaps behavior is opposite of noremap option.
opts.noremap = not opts.remap
diff --git a/runtime/lua/vim/lsp.lua b/runtime/lua/vim/lsp.lua
index 8d11b4621c..105e7c4621 100644
--- a/runtime/lua/vim/lsp.lua
+++ b/runtime/lua/vim/lsp.lua
@@ -1689,7 +1689,7 @@ end
---
--- Currently only supports a single client. This can be set via
--- `setlocal formatexpr=v:lua.vim.lsp.formatexpr()` but will typically or in `on_attach`
---- via `vim.api.nvim_buf_set_option(bufnr, 'formatexpr', 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})')`.
+--- via ``vim.api.nvim_buf_set_option(bufnr, 'formatexpr', 'v:lua.vim.lsp.formatexpr(#{timeout_ms:250})')``.
---
---@param opts table options for customizing the formatting expression which takes the
--- following optional keys:
diff --git a/runtime/lua/vim/lsp/diagnostic.lua b/runtime/lua/vim/lsp/diagnostic.lua
index 68942ae11a..614d83f565 100644
--- a/runtime/lua/vim/lsp/diagnostic.lua
+++ b/runtime/lua/vim/lsp/diagnostic.lua
@@ -104,8 +104,10 @@ local function diagnostic_lsp_to_vim(diagnostics, bufnr, client_id)
severity = severity_lsp_to_vim(diagnostic.severity),
message = diagnostic.message,
source = diagnostic.source,
+ code = diagnostic.code,
user_data = {
lsp = {
+ -- usage of user_data.lsp.code is deprecated in favor of the top-level code field
code = diagnostic.code,
codeDescription = diagnostic.codeDescription,
tags = diagnostic.tags,
@@ -120,7 +122,8 @@ end
---@private
local function diagnostic_vim_to_lsp(diagnostics)
return vim.tbl_map(function(diagnostic)
- return vim.tbl_extend("error", {
+ return vim.tbl_extend("keep", {
+ -- "keep" the below fields over any duplicate fields in diagnostic.user_data.lsp
range = {
start = {
line = diagnostic.lnum,
@@ -134,6 +137,7 @@ local function diagnostic_vim_to_lsp(diagnostics)
severity = severity_vim_to_lsp(diagnostic.severity),
message = diagnostic.message,
source = diagnostic.source,
+ code = diagnostic.code,
}, diagnostic.user_data and (diagnostic.user_data.lsp or {}) or {})
end, diagnostics)
end
diff --git a/runtime/lua/vim/lsp/handlers.lua b/runtime/lua/vim/lsp/handlers.lua
index a997b887d9..f5aefd4402 100644
--- a/runtime/lua/vim/lsp/handlers.lua
+++ b/runtime/lua/vim/lsp/handlers.lua
@@ -336,7 +336,7 @@ local function location_handler(_, result, ctx, _)
title = 'LSP locations',
items = util.locations_to_items(result, client.offset_encoding)
})
- api.nvim_command("copen")
+ api.nvim_command("botright copen")
end
else
util.jump_to_location(result, client.offset_encoding)
@@ -430,7 +430,7 @@ local make_call_hierarchy_handler = function(direction)
end
end
vim.fn.setqflist({}, ' ', {title = 'LSP call hierarchy', items = items})
- api.nvim_command("copen")
+ api.nvim_command("botright copen")
end
end
diff --git a/runtime/lua/vim/lsp/sync.lua b/runtime/lua/vim/lsp/sync.lua
index 0f4e5b572b..9955fff3e2 100644
--- a/runtime/lua/vim/lsp/sync.lua
+++ b/runtime/lua/vim/lsp/sync.lua
@@ -131,13 +131,30 @@ end
---@param offset_encoding string utf-8|utf-16|utf-32|nil (fallback to utf-8)
---@returns table<int, int> line_idx, byte_idx, and char_idx of first change position
local function compute_start_range(prev_lines, curr_lines, firstline, lastline, new_lastline, offset_encoding)
+ local char_idx
+ local byte_idx
-- If firstline == lastline, no existing text is changed. All edit operations
-- occur on a new line pointed to by lastline. This occurs during insertion of
-- new lines(O), the new newline is inserted at the line indicated by
-- new_lastline.
+ if firstline == lastline then
+ local line_idx
+ local line = prev_lines[firstline - 1]
+ if line then
+ line_idx = firstline - 1
+ byte_idx = #line + 1
+ char_idx = compute_line_length(line, offset_encoding) + 1
+ else
+ line_idx = firstline
+ byte_idx = 1
+ char_idx = 1
+ end
+ return { line_idx = line_idx, byte_idx = byte_idx, char_idx = char_idx }
+ end
+
-- If firstline == new_lastline, the first change occurred on a line that was deleted.
-- In this case, the first byte change is also at the first byte of firstline
- if firstline == new_lastline or firstline == lastline then
+ if firstline == new_lastline then
return { line_idx = firstline, byte_idx = 1, char_idx = 1 }
end
@@ -158,8 +175,6 @@ local function compute_start_range(prev_lines, curr_lines, firstline, lastline,
end
-- Convert byte to codepoint if applicable
- local char_idx
- local byte_idx
if start_byte_idx == 1 or (#prev_line == 0 and start_byte_idx == 1)then
byte_idx = start_byte_idx
char_idx = 1
diff --git a/runtime/lua/vim/lsp/util.lua b/runtime/lua/vim/lsp/util.lua
index d22c00ae76..59ab3d7e1f 100644
--- a/runtime/lua/vim/lsp/util.lua
+++ b/runtime/lua/vim/lsp/util.lua
@@ -480,7 +480,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 (api.nvim_buf_get_option(bufnr, 'eol') or (api.nvim_buf_get_option(bufnr, 'fixeol') and not api.nvim_buf_get_option('binary')))
fix_eol = fix_eol and get_line(bufnr, max - 1) == ''
if fix_eol then
vim.api.nvim_buf_set_lines(bufnr, -2, -1, false, {})
@@ -1551,9 +1551,7 @@ do --[[ References ]]
document_highlight_kind[kind],
{ start_line, start_idx },
{ end_line, end_idx },
- nil,
- false,
- 40)
+ { priority = vim.highlight.priorities.user })
end
end
end
diff --git a/runtime/lua/vim/shared.lua b/runtime/lua/vim/shared.lua
index e170befa4c..3eb332279a 100644
--- a/runtime/lua/vim/shared.lua
+++ b/runtime/lua/vim/shared.lua
@@ -1,8 +1,10 @@
-- Functions shared by Nvim and its test-suite.
--
--- The singular purpose of this module is to share code with the Nvim
--- test-suite. If, in the future, Nvim itself is used to run the test-suite
--- instead of "vanilla Lua", these functions could move to src/nvim/lua/vim.lua
+-- These are "pure" lua functions not depending of the state of the editor.
+-- Thus they should always be available whenever nvim-related lua code is run,
+-- regardless if it is code in the editor itself, or in worker threads/processes,
+-- or the test suite. (Eventually the test suite will be run in a worker process,
+-- so this wouldn't be a separate case to consider)
local vim = vim or {}
@@ -329,7 +331,7 @@ end
--- Add the reverse lookup values to an existing table.
--- For example:
---- `tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A = 1 }`
+--- ``tbl_add_reverse_lookup { A = 1 } == { [1] = 'A', A = 1 }``
--
--Do note that it *modifies* the input.
---@param o table The table to add the reverse to.
diff --git a/runtime/menu.vim b/runtime/menu.vim
index 701dd33cdd..956b941971 100644
--- a/runtime/menu.vim
+++ b/runtime/menu.vim
@@ -569,9 +569,9 @@ func! s:XxdConv()
%!mc vim:xxd
else
call s:XxdFind()
- exe '%!' . g:xxdprogram
+ exe ':%!' . g:xxdprogram
endif
- if getline(1) =~ "^0000000:" " only if it worked
+ if getline(1) =~ "^00000000:" " only if it worked
set ft=xxd
endif
let &mod = mod
@@ -583,7 +583,7 @@ func! s:XxdBack()
%!mc vim:xxd -r
else
call s:XxdFind()
- exe '%!' . g:xxdprogram . ' -r'
+ exe ':%!' . g:xxdprogram . ' -r'
endif
set ft=
doautocmd filetypedetect BufReadPost
diff --git a/runtime/spell/cleanadd.vim b/runtime/spell/cleanadd.vim
new file mode 100644
index 0000000000..6dc0692186
--- /dev/null
+++ b/runtime/spell/cleanadd.vim
@@ -0,0 +1,32 @@
+" Vim script to clean the ll.xxxxx.add files of commented out entries
+" Author: Antonio Colombo, Bram Moolenaar
+" Last Update: 2008 Jun 3
+
+" Time in seconds after last time an ll.xxxxx.add file was updated
+" Default is one second.
+" If you invoke this script often set it to something bigger, e.g. 60 * 60
+" (one hour)
+if !exists("g:spell_clean_limit")
+ let g:spell_clean_limit = 1
+endif
+
+" Loop over all the runtime/spell/*.add files.
+" Delete all comment lines, except the ones starting with ##.
+for s:fname in split(globpath(&rtp, "spell/*.add"), "\n")
+ if filewritable(s:fname) && localtime() - getftime(s:fname) > g:spell_clean_limit
+ if exists('*fnameescape')
+ let s:f = fnameescape(s:fname)
+ else
+ let s:f = escape(s:fname, ' \|<')
+ endif
+ silent exe "tab split " . s:f
+ echo "Processing" s:f
+ silent! g/^#[^#]/d
+ silent update
+ close
+ unlet s:f
+ endif
+endfor
+unlet s:fname
+
+echo "Done"
diff --git a/runtime/syntax/structurizr.vim b/runtime/syntax/structurizr.vim
index 73629b1495..ab9e4ee609 100644
--- a/runtime/syntax/structurizr.vim
+++ b/runtime/syntax/structurizr.vim
@@ -1,7 +1,7 @@
" Vim syntax file
" Language: Structurizr DSL
" Maintainer: Bastian Venthur <venthur@debian.org>
-" Last Change: 2021-08-16
+" Last Change: 2022-02-15
" Remark: For a language reference, see
" https://github.com/structurizr/dsl
@@ -30,6 +30,7 @@ syn keyword skeyword deployment
syn keyword skeyword deploymentenvironment
syn keyword skeyword deploymentgroup
syn keyword skeyword deploymentnode
+syn keyword skeyword description
syn keyword skeyword dynamic
syn keyword skeyword element
syn keyword skeyword enterprise
@@ -37,7 +38,6 @@ syn keyword skeyword exclude
syn keyword skeyword filtered
syn keyword skeyword group
syn keyword skeyword healthcheck
-syn keyword skeyword impliedrelationships
syn keyword skeyword include
syn keyword skeyword infrastructurenode
syn keyword skeyword model
@@ -51,6 +51,7 @@ syn keyword skeyword styles
syn keyword skeyword systemcontext
syn keyword skeyword systemlandscape
syn keyword skeyword tags
+syn keyword skeyword technology
syn keyword skeyword terminology
syn keyword skeyword theme
syn keyword skeyword title
@@ -63,7 +64,11 @@ syn match skeyword "\!adrs\s\+"
syn match skeyword "\!constant\s\+"
syn match skeyword "\!docs\s\+"
syn match skeyword "\!identifiers\s\+"
+syn match skeyword "\!impliedrelationships\s\+"
syn match skeyword "\!include\s\+"
+syn match skeyword "\!plugin\s\+"
+syn match skeyword "\!ref\s\+"
+syn match skeyword "\!script\s\+"
syn region sstring oneline start='"' end='"'
diff --git a/runtime/syntax/vim.vim b/runtime/syntax/vim.vim
index 41993b65b0..0bc233fc2a 100644
--- a/runtime/syntax/vim.vim
+++ b/runtime/syntax/vim.vim
@@ -46,14 +46,14 @@ syn match vimTermOption contained "t_%i"
syn match vimTermOption contained "t_k;"
" unsupported settings: these are supported by vi but don't do anything in vim {{{2
-syn keyword vimErrSetting contained hardtabs ht w1200 w300 w9600
+syn keyword vimErrSetting contained hardtabs ht w1200 w300 w9600
"}}}2
syn case ignore
" Highlight commonly used Groupnames {{{2
-syn keyword vimGroup contained Comment Constant String Character Number Boolean Float Identifier Function Statement Conditional Repeat Label Operator Keyword Exception PreProc Include Define Macro PreCondit Type StorageClass Structure Typedef Special SpecialChar Tag Delimiter SpecialComment Debug Underlined Ignore Error Todo
+syn keyword vimGroup contained Comment Constant String Character Number Boolean Float Identifier Function Statement Conditional Repeat Label Operator Keyword Exception PreProc Include Define Macro PreCondit Type StorageClass Structure Typedef Special SpecialChar Tag Delimiter SpecialComment Debug Underlined Ignore Error Todo
" Default highlighting groups {{{2
-syn keyword vimHLGroup contained ColorColumn Cursor CursorColumn CursorIM CursorLine CursorLineFold CursorLineNr CursorLineSign DiffAdd DiffChange DiffDelete DiffText Directory EndOfBuffer ErrorMsg FoldColumn Folded IncSearch LineNr MatchParen Menu ModeMsg MoreMsg NonText Normal Pmenu PmenuSbar PmenuSel PmenuThumb Question QuickFixLine Scrollbar Search SignColumn SpecialKey SpellBad SpellCap SpellLocal SpellRare StatusLine StatusLineNC TabLine TabLineFill TabLineSel Title Tooltip VertSplit Visual WarningMsg WildMenu
+syn keyword vimHLGroup contained ColorColumn Cursor CursorColumn CursorIM CursorLine CursorLineFold CursorLineNr CursorLineSign DiffAdd DiffChange DiffDelete DiffText Directory EndOfBuffer ErrorMsg FoldColumn Folded IncSearch LineNr MatchParen Menu ModeMsg MoreMsg NonText Normal Pmenu PmenuSbar PmenuSel PmenuThumb Question QuickFixLine Scrollbar Search SignColumn SpecialKey SpellBad SpellCap SpellLocal SpellRare StatusLine StatusLineNC TabLine TabLineFill TabLineSel Title Tooltip VertSplit Visual WarningMsg WildMenu
syn match vimHLGroup contained "Conceal"
syn keyword vimOnlyHLGroup contained LineNrAbove LineNrBelow StatusLineTerm Terminal VisualNOS
syn keyword nvimHLGroup contained Substitute TermCursor TermCursorNC
@@ -88,10 +88,10 @@ if exists("g:vimsyn_folding") && g:vimsyn_folding =~# '[afhlmpPrt]'
else
com! -nargs=* VimFoldm <args>
endif
- if g:vimsyn_folding =~# 'p'
- com! -nargs=* VimFoldp <args> fold
- else
- com! -nargs=* VimFoldp <args>
+ if g:vimsyn_folding =~# 'p'
+ com! -nargs=* VimFoldp <args> fold
+ else
+ com! -nargs=* VimFoldp <args>
endif
if g:vimsyn_folding =~# 'P'
com! -nargs=* VimFoldP <args> fold
@@ -148,8 +148,8 @@ syn match vimNumber '-\d\+\%(\.\d\+\%([eE][+-]\=\d\+\)\=\)\=' skipwhite nextgro
syn match vimNumber '\<0[xX]\x\+' skipwhite nextgroup=vimGlobal,vimSubst,vimCommand,vimComment,vim9Comment
syn match vimNumber '\%(^\|\A\)\zs#\x\{6}' skipwhite nextgroup=vimGlobal,vimSubst,vimCommand,vimComment,vim9Comment
syn match vimNumber '\<0[zZ][a-zA-Z0-9.]\+' skipwhite nextgroup=vimGlobal,vimSubst,vimCommand,vimComment,vim9Comment
-syn match vimNumber '0[0-7]\+' skipwhite nextgroup=vimGlobal,vimSubst,vimCommand,vimComment,vim9Comment
-syn match vimNumber '0[bB][01]\+' skipwhite nextgroup=vimGlobal,vimSubst,vimCommand,vimComment,vim9Comment
+syn match vimNumber '0[0-7]\+' skipwhite nextgroup=vimGlobal,vimSubst,vimCommand,vimComment,vim9Comment
+syn match vimNumber '0[bB][01]\+' skipwhite nextgroup=vimGlobal,vimSubst,vimCommand,vimComment,vim9Comment
" All vimCommands are contained by vimIsCommand. {{{2
syn match vimCmdSep "[:|]\+" skipwhite nextgroup=vimAddress,vimAutoCmd,vimEcho,vimIsCommand,vimExtCmd,vimFilter,vimLet,vimMap,vimMark,vimSet,vimSyntax,vimUserCmd
@@ -574,7 +574,7 @@ syn match vimHiBang contained "!" skipwhite nextgroup=@vimHighlightCluster
syn match vimHiGroup contained "\i\+"
syn case ignore
-syn keyword vimHiAttrib contained none bold inverse italic nocombine reverse standout strikethrough underline undercurl
+syn keyword vimHiAttrib contained none bold inverse italic nocombine reverse standout strikethrough underline underlineline undercurl underdot underdash
syn keyword vimFgBgAttrib contained none bg background fg foreground
syn case match
syn match vimHiAttribList contained "\i\+" contains=vimHiAttrib
diff --git a/scripts/gen_vimdoc.py b/scripts/gen_vimdoc.py
index 36768953f9..7152f1005f 100755
--- a/scripts/gen_vimdoc.py
+++ b/scripts/gen_vimdoc.py
@@ -84,8 +84,6 @@ CONFIG = {
'api': {
'mode': 'c',
'filename': 'api.txt',
- # String used to find the start of the generated part of the doc.
- 'section_start_token': '*api-global*',
# Section ordering.
'section_order': [
'vim.c',
@@ -95,10 +93,11 @@ CONFIG = {
'window.c',
'win_config.c',
'tabpage.c',
+ 'autocmd.c',
'ui.c',
],
- # List of files/directories for doxygen to read, separated by blanks
- 'files': os.path.join(base_dir, 'src/nvim/api'),
+ # List of files/directories for doxygen to read, relative to `base_dir`
+ 'files': ['src/nvim/api'],
# file patterns used by doxygen
'file_patterns': '*.h *.c',
# Only function with this prefix are considered
@@ -121,31 +120,39 @@ CONFIG = {
'lua': {
'mode': 'lua',
'filename': 'lua.txt',
- 'section_start_token': '*lua-vim*',
'section_order': [
- 'vim.lua',
+ '_editor.lua',
'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'),
- ]),
+ 'files': [
+ 'runtime/lua/vim/_editor.lua',
+ 'runtime/lua/vim/shared.lua',
+ 'runtime/lua/vim/uri.lua',
+ 'runtime/lua/vim/ui.lua',
+ 'runtime/lua/vim/filetype.lua',
+ 'runtime/lua/vim/keymap.lua',
+ ],
'file_patterns': '*.lua',
'fn_name_prefix': '',
'section_name': {
'lsp.lua': 'core',
},
- 'section_fmt': lambda name: f'Lua module: {name.lower()}',
- 'helptag_fmt': lambda name: f'*lua-{name.lower()}*',
- 'fn_helptag_fmt': lambda fstem, name: f'*{fstem}.{name}()*',
+ 'section_fmt': lambda name: (
+ 'Lua module: vim'
+ if name.lower() == '_editor'
+ else f'Lua module: {name.lower()}'),
+ 'helptag_fmt': lambda name: (
+ '*lua-vim*'
+ if name.lower() == '_editor'
+ else f'*lua-{name.lower()}*'),
+ 'fn_helptag_fmt': lambda fstem, name: (
+ f'*vim.{name}()*'
+ if fstem.lower() == '_editor'
+ else f'*{fstem}.{name}()*'),
'module_override': {
# `shared` functions are exposed on the `vim` module.
'shared': 'vim',
@@ -161,7 +168,6 @@ CONFIG = {
'lsp': {
'mode': 'lua',
'filename': 'lsp.txt',
- 'section_start_token': '*lsp-core*',
'section_order': [
'lsp.lua',
'buf.lua',
@@ -175,10 +181,10 @@ CONFIG = {
'sync.lua',
'protocol.lua',
],
- 'files': ' '.join([
- os.path.join(base_dir, 'runtime/lua/vim/lsp'),
- os.path.join(base_dir, 'runtime/lua/vim/lsp.lua'),
- ]),
+ 'files': [
+ 'runtime/lua/vim/lsp',
+ 'runtime/lua/vim/lsp.lua',
+ ],
'file_patterns': '*.lua',
'fn_name_prefix': '',
'section_name': {'lsp.lua': 'lsp'},
@@ -204,11 +210,10 @@ CONFIG = {
'diagnostic': {
'mode': 'lua',
'filename': 'diagnostic.txt',
- 'section_start_token': '*diagnostic-api*',
'section_order': [
'diagnostic.lua',
],
- 'files': os.path.join(base_dir, 'runtime/lua/vim/diagnostic.lua'),
+ 'files': ['runtime/lua/vim/diagnostic.lua'],
'file_patterns': '*.lua',
'fn_name_prefix': '',
'section_name': {'diagnostic.lua': 'diagnostic'},
@@ -221,7 +226,6 @@ CONFIG = {
'treesitter': {
'mode': 'lua',
'filename': 'treesitter.txt',
- 'section_start_token': '*lua-treesitter-core*',
'section_order': [
'treesitter.lua',
'language.lua',
@@ -229,10 +233,10 @@ CONFIG = {
'highlighter.lua',
'languagetree.lua',
],
- 'files': ' '.join([
- os.path.join(base_dir, 'runtime/lua/vim/treesitter.lua'),
- os.path.join(base_dir, 'runtime/lua/vim/treesitter/'),
- ]),
+ 'files': [
+ 'runtime/lua/vim/treesitter.lua',
+ 'runtime/lua/vim/treesitter/',
+ ],
'file_patterns': '*.lua',
'fn_name_prefix': '',
'section_name': {},
@@ -339,14 +343,6 @@ def self_or_child(n):
return n.childNodes[0]
-def clean_text(text):
- """Cleans text.
-
- Only cleans superfluous whitespace at the moment.
- """
- return ' '.join(text.split()).strip()
-
-
def clean_lines(text):
"""Removes superfluous lines.
@@ -367,12 +363,12 @@ def get_text(n, preformatted=False):
if n.nodeName == 'computeroutput':
for node in n.childNodes:
text += get_text(node)
- return '`{}` '.format(text)
+ return '`{}`'.format(text)
for node in n.childNodes:
if node.nodeType == node.TEXT_NODE:
- text += node.data if preformatted else clean_text(node.data)
+ text += node.data
elif node.nodeType == node.ELEMENT_NODE:
- text += ' ' + get_text(node, preformatted)
+ text += get_text(node, preformatted)
return text
@@ -839,7 +835,9 @@ def extract_from_xml(filename, target, width):
'seealso': [],
}
if fmt_vimhelp:
- fn['desc_node'] = desc # HACK :(
+ # HACK :(
+ fn['desc_node'] = desc
+ fn['brief_desc_node'] = brief_desc
for m in paras:
if 'text' in m:
@@ -887,6 +885,8 @@ def fmt_doxygen_xml_as_vimhelp(filename, target):
# Generate Vim :help for parameters.
if fn['desc_node']:
doc = fmt_node_as_vimhelp(fn['desc_node'])
+ if not doc and fn['brief_desc_node']:
+ doc = fmt_node_as_vimhelp(fn['brief_desc_node'])
if not doc:
doc = 'TODO: Documentation'
@@ -996,7 +996,8 @@ def main(config, args):
stderr=(subprocess.STDOUT if debug else subprocess.DEVNULL))
p.communicate(
config.format(
- input=CONFIG[target]['files'],
+ input=' '.join(
+ [f'"{file}"' for file in CONFIG[target]['files']]),
output=output_dir,
filter=filter_cmd,
file_patterns=CONFIG[target]['file_patterns'])
@@ -1086,6 +1087,7 @@ def main(config, args):
raise RuntimeError(
'found new modules "{}"; update the "section_order" map'.format(
set(sections).difference(CONFIG[target]['section_order'])))
+ first_section_tag = sections[CONFIG[target]['section_order'][0]][1]
docs = ''
@@ -1111,7 +1113,8 @@ def main(config, args):
doc_file = os.path.join(base_dir, 'runtime', 'doc',
CONFIG[target]['filename'])
- delete_lines_below(doc_file, CONFIG[target]['section_start_token'])
+ if os.path.exists(doc_file):
+ delete_lines_below(doc_file, first_section_tag)
with open(doc_file, 'ab') as fp:
fp.write(docs.encode('utf8'))
diff --git a/scripts/stripdecls.py b/scripts/stripdecls.py
deleted file mode 100755
index b4ac34dcfe..0000000000
--- a/scripts/stripdecls.py
+++ /dev/null
@@ -1,140 +0,0 @@
-#!/usr/bin/python
-# vim: set fileencoding=utf-8:
-
-from __future__ import print_function, unicode_literals, division
-
-from clang.cindex import Index, CursorKind
-from collections import namedtuple, OrderedDict, defaultdict
-import sys
-import os
-
-
-DECL_KINDS = {
- CursorKind.FUNCTION_DECL,
-}
-
-
-Strip = namedtuple('Strip', 'start_line start_column end_line end_column')
-
-
-def main(progname, cfname, only_static, move_all):
- cfname = os.path.abspath(os.path.normpath(cfname))
-
- hfname1 = os.path.splitext(cfname)[0] + os.extsep + 'h'
- hfname2 = os.path.splitext(cfname)[0] + '_defs' + os.extsep + 'h'
-
- files_to_modify = (cfname, hfname1, hfname2)
-
- index = Index.create()
- src_dirname = os.path.join(os.path.dirname(__file__), '..', 'src')
- src_dirname = os.path.abspath(os.path.normpath(src_dirname))
- relname = os.path.join(src_dirname, 'nvim')
- unit = index.parse(cfname, args=('-I' + src_dirname,
- '-DUNIX',
- '-DEXITFREE',
- '-DFEAT_USR_CMDS',
- '-DFEAT_CMDL_COMPL',
- '-DFEAT_COMPL_FUNC',
- '-DPROTO',
- '-DUSE_MCH_ERRMSG'))
- cursor = unit.cursor
-
- tostrip = defaultdict(OrderedDict)
- definitions = set()
-
- for child in cursor.get_children():
- if not (child.location and child.location.file):
- continue
- fname = os.path.abspath(os.path.normpath(child.location.file.name))
- if fname not in files_to_modify:
- continue
- if child.kind not in DECL_KINDS:
- continue
- if only_static and next(child.get_tokens()).spelling == 'static':
- continue
-
- if child.is_definition() and fname == cfname:
- definitions.add(child.spelling)
- else:
- stripdict = tostrip[fname]
- assert(child.spelling not in stripdict)
- stripdict[child.spelling] = Strip(
- child.extent.start.line,
- child.extent.start.column,
- child.extent.end.line,
- child.extent.end.column,
- )
-
- for (fname, stripdict) in tostrip.items():
- if not move_all:
- for name in set(stripdict) - definitions:
- stripdict.pop(name)
-
- if not stripdict:
- continue
-
- if fname.endswith('.h'):
- is_h_file = True
- include_line = next(reversed(stripdict.values())).start_line + 1
- else:
- is_h_file = False
- include_line = next(iter(stripdict.values())).start_line
-
- lines = None
- generated_existed = os.path.exists(fname + '.generated.h')
- with open(fname, 'rb') as F:
- lines = list(F)
-
- stripped = []
-
- for name, position in reversed(stripdict.items()):
- sl = slice(position.start_line - 1, position.end_line)
- if is_h_file:
- include_line -= sl.stop - sl.start
- stripped += lines[sl]
- lines[sl] = ()
-
- if not generated_existed:
- lines[include_line:include_line] = [
- '#ifdef INCLUDE_GENERATED_DECLARATIONS\n',
- '# include "{0}.generated.h"\n'.format(
- os.path.relpath(fname, relname)),
- '#endif\n',
- ]
-
- with open(fname, 'wb') as F:
- F.writelines(lines)
-
-
-if __name__ == '__main__':
- progname = sys.argv[0]
- args = sys.argv[1:]
- if not args or '--help' in args:
- print('Usage:')
- print('')
- print(' {0} [--static [--all]] file.c...'.format(progname))
- print('')
- print('Stripts all declarations from file.c, file.h and file_defs.h.')
- print('If --static argument is given then only static declarations are')
- print('stripped. Declarations are stripped only if corresponding')
- print('definition is found unless --all argument was given.')
- print('')
- print('Note: it is assumed that static declarations starts with "static"')
- print(' keyword.')
- sys.exit(0 if args else 1)
-
- if args[0] == '--static':
- only_static = True
- args = args[1:]
- else:
- only_static = False
-
- if args[0] == '--all':
- move_all = True
- args = args[1:]
- else:
- move_all = False
-
- for cfname in args:
- print('Processing {0}'.format(cfname))
- main(progname, cfname, only_static, move_all)
diff --git a/scripts/uncrustify.sh b/scripts/uncrustify.sh
new file mode 100755
index 0000000000..ac5d542c29
--- /dev/null
+++ b/scripts/uncrustify.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+
+set -e
+
+# Check that you have uncrustify
+hash uncrustify
+
+COMMITISH="${1:-master}"
+for file in $(git diff --diff-filter=d --name-only $COMMITISH | grep '\.[ch]$'); do
+ uncrustify -c src/uncrustify.cfg -l C --replace --no-backup "$file"
+done
diff --git a/scripts/vim-patch.sh b/scripts/vim-patch.sh
index 67a2cc96fd..591c658e6b 100755
--- a/scripts/vim-patch.sh
+++ b/scripts/vim-patch.sh
@@ -36,7 +36,7 @@ usage() {
echo " can be a Vim version (8.0.xxx) or a Git hash."
echo " -P {vim-revision} Download, generate and apply a Vim patch."
echo " -g {vim-revision} Download a Vim patch."
- echo " -s Create a vim-patch pull request."
+ echo " -s [pr args] Create a vim-patch pull request."
echo " -r {pr-number} Review a vim-patch pull request."
echo " -V Clone the Vim source code to \$VIM_SOURCE_DIR."
echo
@@ -329,7 +329,8 @@ stage_patch() {
* Do this only for _related_ patches (otherwise it increases the
size of the pull request, making it harder to review)
- When you are done, try "%s -s" to create the pull request.
+ When you are done, try "%s -s" to create the pull request,
+ or "%s -s --draft" to create a draft pull request.
See the wiki for more information:
* https://github.com/neovim/neovim/wiki/Merging-patches-from-upstream-vim
@@ -338,13 +339,19 @@ stage_patch() {
}
gh_pr() {
- gh pr create --title "$1" --body "$2"
+ local pr_title
+ local pr_body
+ pr_title="$1"
+ pr_body="$2"
+ shift 2
+ gh pr create --title "${pr_title}" --body "${pr_body}" "$@"
}
git_hub_pr() {
local pr_message
pr_message="$(printf '%s\n\n%s\n' "$1" "$2")"
- git hub pull new -m "${pr_message}"
+ shift 2
+ git hub pull new -m "${pr_message}" "$@"
}
submit_pr() {
@@ -408,7 +415,7 @@ submit_pr() {
fi
echo "Creating pull request."
- if output="$($submit_fn "$pr_title" "$pr_body" 2>&1)"; then
+ if output="$($submit_fn "$pr_title" "$pr_body" "$@" 2>&1)"; then
msg_ok "$output"
else
msg_err "$output"
@@ -799,7 +806,8 @@ while getopts "hlLmMVp:P:g:r:s" opt; do
exit 0
;;
s)
- submit_pr
+ shift # remove opt
+ submit_pr "$@"
exit 0
;;
V)
diff --git a/src/cjson/lua_cjson.c b/src/cjson/lua_cjson.c
index cf9e82c38e..c243f93c05 100644
--- a/src/cjson/lua_cjson.c
+++ b/src/cjson/lua_cjson.c
@@ -776,7 +776,7 @@ static void json_append_data(lua_State *l, json_config_t *cfg,
if (has_metatable) {
- nlua_pushref(l, nlua_empty_dict_ref);
+ nlua_pushref(l, nlua_get_empty_dict_ref(l));
if (lua_rawequal(l, -2, -1)) {
as_empty_dict = true;
} else {
@@ -822,7 +822,7 @@ static void json_append_data(lua_State *l, json_config_t *cfg,
}
break;
case LUA_TUSERDATA:
- nlua_pushref(l, nlua_nil_ref);
+ nlua_pushref(l, nlua_get_nil_ref(l));
bool is_nil = lua_rawequal(l, -2, -1);
lua_pop(l, 1);
if (is_nil) {
@@ -1110,7 +1110,7 @@ static int json_is_invalid_number(json_parse_t *json)
/* Reject numbers starting with 0x, or leading zeros */
if (*p == '0') {
- int ch2 = *(p + 1);
+ char ch2 = *(p + 1);
if ((ch2 | 0x20) == 'x' || /* Hex */
('0' <= ch2 && ch2 <= '9')) /* Leading zero */
@@ -1285,7 +1285,7 @@ static void json_parse_object_context(lua_State *l, json_parse_t *json)
/* Handle empty objects */
if (token.type == T_OBJ_END) {
- nlua_pushref(l, nlua_empty_dict_ref); \
+ nlua_pushref(l, nlua_get_empty_dict_ref(l)); \
lua_setmetatable(l, -2); \
json_decode_ascend(json);
return;
@@ -1392,7 +1392,7 @@ static void json_process_value(lua_State *l, json_parse_t *json,
if (use_luanil) {
lua_pushnil(l);
} else {
- nlua_pushref(l, nlua_nil_ref);
+ nlua_pushref(l, nlua_get_nil_ref(l));
}
break;;
default:
@@ -1549,7 +1549,15 @@ int lua_cjson_new(lua_State *l)
};
/* Initialise number conversions */
- fpconv_init();
+ lua_getfield(l, LUA_REGISTRYINDEX, "nvim.thread");
+ bool is_thread = lua_toboolean(l, -1);
+ lua_pop(l, 1);
+
+ // Since fpconv_init does not need to be called multiple times and is not
+ // thread safe, it should only be called in the main thread.
+ if (!is_thread) {
+ fpconv_init();
+ }
/* Test if array metatables are in registry */
lua_pushlightuserdata(l, json_lightudata_mask(&json_empty_array));
@@ -1582,7 +1590,7 @@ int lua_cjson_new(lua_State *l)
compat_luaL_setfuncs(l, reg, 1);
/* Set cjson.null */
- nlua_pushref(l, nlua_nil_ref);
+ nlua_pushref(l, nlua_get_nil_ref(l));
lua_setfield(l, -2, "null");
/* Set cjson.empty_array_mt */
diff --git a/src/clint.py b/src/clint.py
index 4b7bf002e6..10f33d22e2 100755
--- a/src/clint.py
+++ b/src/clint.py
@@ -191,7 +191,6 @@ _ERROR_CATEGORIES = [
'readability/fn_size',
'readability/multiline_comment',
'readability/multiline_string',
- 'readability/nolint',
'readability/nul',
'readability/todo',
'readability/utf8',
@@ -298,9 +297,6 @@ def ParseNolintSuppressions(filename, raw_line, linenum, error):
if category in _ERROR_CATEGORIES:
_error_suppressions.setdefault(
category, set()).add(linenum)
- else:
- error(filename, linenum, 'readability/nolint', 5,
- 'Unknown NOLINT error category: %s' % category)
def ParseKnownErrorSuppressions(filename, raw_lines, linenum):
@@ -373,7 +369,7 @@ def Search(pattern, s):
return _regexp_compile_cache[pattern].search(s)
-class _IncludeState(dict):
+class _IncludeState(dict): # lgtm [py/missing-equals]
"""Tracks line numbers for includes, and the order in which includes appear.
diff --git a/src/mpack/lmpack.c b/src/mpack/lmpack.c
index 126f2f3824..53d7092a0c 100644
--- a/src/mpack/lmpack.c
+++ b/src/mpack/lmpack.c
@@ -246,7 +246,7 @@ static mpack_uint32_t lmpack_objlen(lua_State *L, int *is_array)
}
end:
- if ((size_t)-1 > (mpack_uint32_t)-1 && len > (mpack_uint32_t)-1)
+ if ((size_t)-1 > (mpack_uint32_t)-1 && len > (mpack_uint32_t)-1) // -V560
/* msgpack spec doesn't allow lengths > 32 bits */
len = (mpack_uint32_t)-1;
assert(top == lua_gettop(L));
diff --git a/src/nvim/CMakeLists.txt b/src/nvim/CMakeLists.txt
index dcc20194f0..8e17f94abc 100644..100755
--- a/src/nvim/CMakeLists.txt
+++ b/src/nvim/CMakeLists.txt
@@ -39,6 +39,7 @@ set(GENERATED_UI_EVENTS ${GENERATED_DIR}/ui_events.generated.h)
set(GENERATED_UI_EVENTS_CALL ${GENERATED_DIR}/ui_events_call.generated.h)
set(GENERATED_UI_EVENTS_REMOTE ${GENERATED_DIR}/ui_events_remote.generated.h)
set(GENERATED_UI_EVENTS_BRIDGE ${GENERATED_DIR}/ui_events_bridge.generated.h)
+set(GENERATED_UI_EVENTS_CLIENT ${GENERATED_DIR}/ui_events_client.generated.h)
set(GENERATED_UI_EVENTS_METADATA ${GENERATED_DIR}/api/private/ui_events_metadata.generated.h)
set(GENERATED_EX_CMDS_ENUM ${GENERATED_INCLUDES_DIR}/ex_cmds_enum.generated.h)
set(GENERATED_EX_CMDS_DEFS ${GENERATED_DIR}/ex_cmds_defs.generated.h)
@@ -57,12 +58,14 @@ set(UNICODE_TABLES_GENERATOR ${GENERATOR_DIR}/gen_unicode_tables.lua)
set(UNICODE_DIR ${PROJECT_SOURCE_DIR}/unicode)
set(GENERATED_UNICODE_TABLES ${GENERATED_DIR}/unicode_tables.generated.h)
set(VIM_MODULE_FILE ${GENERATED_DIR}/lua/vim_module.generated.h)
-set(LUA_VIM_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/src/nvim/lua/vim.lua)
+set(LUA_EDITOR_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/_editor.lua)
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(LUA_INIT_PACKAGES_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/_init_packages.lua)
+set(LUA_KEYMAP_MODULE_SOURCE ${PROJECT_SOURCE_DIR}/runtime/lua/vim/keymap.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")
@@ -133,6 +136,9 @@ foreach(sfile ${NVIM_SOURCES})
if(${f} MATCHES "^(regexp_nfa.c)$")
list(APPEND to_remove ${sfile})
endif()
+ if(${f} MATCHES "^(regexp_bt.c)$")
+ list(APPEND to_remove ${sfile})
+ endif()
if(WIN32 AND ${f} MATCHES "^(pty_process_unix.c)$")
list(APPEND to_remove ${sfile})
endif()
@@ -259,12 +265,14 @@ endif()
# NVIM_GENERATED_SOURCES: generated source files
# These lists must be mutually exclusive.
foreach(sfile ${NVIM_SOURCES}
+ "${CMAKE_CURRENT_LIST_DIR}/regexp_bt.c"
"${CMAKE_CURRENT_LIST_DIR}/regexp_nfa.c"
${GENERATED_API_DISPATCH}
"${GENERATED_UI_EVENTS_CALL}"
"${GENERATED_UI_EVENTS_REMOTE}"
"${GENERATED_UI_EVENTS_BRIDGE}"
"${GENERATED_KEYSETS}"
+ "${GENERATED_UI_EVENTS_CLIENT}"
)
get_filename_component(full_d ${sfile} PATH)
file(RELATIVE_PATH d "${CMAKE_CURRENT_LIST_DIR}" "${full_d}")
@@ -330,20 +338,25 @@ add_custom_command(
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
+ ${LUA_INIT_PACKAGES_MODULE_SOURCE} "vim._init_packages"
+ ${LUA_INSPECT_MODULE_SOURCE} "vim.inspect"
+ ${LUA_EDITOR_MODULE_SOURCE} "vim._editor"
+ ${LUA_SHARED_MODULE_SOURCE} "vim.shared"
+ ${LUA_F_MODULE_SOURCE} "vim.F"
+ ${LUA_META_MODULE_SOURCE} "vim._meta"
+ ${LUA_FILETYPE_MODULE_SOURCE} "vim.filetype"
+ ${LUA_KEYMAP_MODULE_SOURCE} "vim.keymap"
DEPENDS
${CHAR_BLOB_GENERATOR}
- ${LUA_VIM_MODULE_SOURCE}
+ ${LUA_INIT_PACKAGES_MODULE_SOURCE}
+ ${LUA_EDITOR_MODULE_SOURCE}
${LUA_SHARED_MODULE_SOURCE}
${LUA_INSPECT_MODULE_SOURCE}
${LUA_F_MODULE_SOURCE}
${LUA_META_MODULE_SOURCE}
${LUA_FILETYPE_MODULE_SOURCE}
+ ${LUA_LOAD_PACKAGE_MODULE_SOURCE}
+ ${LUA_KEYMAP_MODULE_SOURCE}
VERBATIM
)
@@ -357,6 +370,7 @@ add_custom_command(
${GENERATED_UI_EVENTS_REMOTE}
${GENERATED_UI_EVENTS_BRIDGE}
${GENERATED_UI_EVENTS_METADATA}
+ ${GENERATED_UI_EVENTS_CLIENT}
COMMAND ${LUA_PRG} ${API_UI_EVENTS_GENERATOR} ${CMAKE_CURRENT_LIST_DIR}
${CMAKE_CURRENT_LIST_DIR}/api/ui_events.in.h
${GENERATED_UI_EVENTS}
@@ -364,6 +378,7 @@ add_custom_command(
${GENERATED_UI_EVENTS_REMOTE}
${GENERATED_UI_EVENTS_BRIDGE}
${GENERATED_UI_EVENTS_METADATA}
+ ${GENERATED_UI_EVENTS_CLIENT}
DEPENDS
${API_UI_EVENTS_GENERATOR}
${GENERATOR_C_GRAMMAR}
diff --git a/src/nvim/api/autocmd.c b/src/nvim/api/autocmd.c
new file mode 100644
index 0000000000..8a7dd00b2a
--- /dev/null
+++ b/src/nvim/api/autocmd.c
@@ -0,0 +1,776 @@
+// 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 <stdbool.h>
+#include <stdio.h>
+
+#include "lauxlib.h"
+#include "nvim/api/autocmd.h"
+#include "nvim/api/private/defs.h"
+#include "nvim/api/private/helpers.h"
+#include "nvim/ascii.h"
+#include "nvim/buffer.h"
+#include "nvim/eval/typval.h"
+#include "nvim/fileio.h"
+#include "nvim/lua/executor.h"
+
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+# include "api/autocmd.c.generated.h"
+#endif
+
+#define AUCMD_MAX_PATTERNS 256
+
+// Copy string or array of strings into an empty array.
+// Get the event number, unless it is an error. Then goto `goto_name`.
+#define GET_ONE_EVENT(event_nr, event_str, goto_name) \
+ char_u *__next_ev; \
+ event_T event_nr = \
+ event_name2nr((char_u *)event_str.data.string.data, &__next_ev); \
+ if (event_nr >= NUM_EVENTS) { \
+ api_set_error(err, kErrorTypeValidation, "unexpected event"); \
+ goto goto_name; \
+ }
+
+
+// ID for associating autocmds created via nvim_create_autocmd
+// Used to delete autocmds from nvim_del_autocmd
+static int64_t next_autocmd_id = 1;
+
+/// Get autocmds that match the requirements passed to {opts}.
+///
+/// @param opts Optional Parameters:
+/// - event : Name or list of name of events to match against
+/// - group (string|int): Name or id of group to match against
+/// - pattern: Pattern or list of patterns to match against. Cannot be used with {buffer}
+/// - buffer: Buffer number or list of buffer numbers for buffer local autocommands
+/// |autocmd-buflocal|. Cannot be used with {pattern}
+///
+/// @return A list of autocmds that match
+Array nvim_get_autocmds(Dict(get_autocmds) *opts, Error *err)
+ FUNC_API_SINCE(9)
+{
+ // TODO(tjdevries): Would be cool to add nvim_get_autocmds({ id = ... })
+
+ Array autocmd_list = ARRAY_DICT_INIT;
+ char_u *pattern_filters[AUCMD_MAX_PATTERNS];
+ char_u pattern_buflocal[BUFLOCAL_PAT_LEN];
+
+ Array buffers = ARRAY_DICT_INIT;
+
+ bool event_set[NUM_EVENTS] = { false };
+ bool check_event = false;
+
+ int group = 0;
+
+ switch (opts->group.type) {
+ case kObjectTypeNil:
+ break;
+ case kObjectTypeString:
+ group = augroup_find(opts->group.data.string.data);
+ if (group < 0) {
+ api_set_error(err, kErrorTypeValidation, "invalid augroup passed.");
+ goto cleanup;
+ }
+ break;
+ case kObjectTypeInteger:
+ group = (int)opts->group.data.integer;
+ char *name = augroup_name(group);
+ if (!augroup_exists(name)) {
+ api_set_error(err, kErrorTypeValidation, "invalid augroup passed.");
+ goto cleanup;
+ }
+ break;
+ default:
+ api_set_error(err, kErrorTypeValidation, "group must be a string or an integer.");
+ goto cleanup;
+ }
+
+ if (opts->event.type != kObjectTypeNil) {
+ check_event = true;
+
+ Object v = opts->event;
+ if (v.type == kObjectTypeString) {
+ GET_ONE_EVENT(event_nr, v, cleanup);
+ event_set[event_nr] = true;
+ } else if (v.type == kObjectTypeArray) {
+ FOREACH_ITEM(v.data.array, event_v, {
+ if (event_v.type != kObjectTypeString) {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "Every event must be a string in 'event'");
+ goto cleanup;
+ }
+
+ GET_ONE_EVENT(event_nr, event_v, cleanup);
+ event_set[event_nr] = true;
+ })
+ } else {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "Not a valid 'event' value. Must be a string or an array");
+ goto cleanup;
+ }
+ }
+
+ if (opts->pattern.type != kObjectTypeNil && opts->buffer.type != kObjectTypeNil) {
+ api_set_error(err, kErrorTypeValidation,
+ "Cannot use both 'pattern' and 'buffer'");
+ goto cleanup;
+ }
+
+ int pattern_filter_count = 0;
+ if (opts->pattern.type != kObjectTypeNil) {
+ Object v = opts->pattern;
+ if (v.type == kObjectTypeString) {
+ pattern_filters[pattern_filter_count] = (char_u *)v.data.string.data;
+ pattern_filter_count += 1;
+ } else if (v.type == kObjectTypeArray) {
+ if (v.data.array.size > AUCMD_MAX_PATTERNS) {
+ api_set_error(err, kErrorTypeValidation,
+ "Too many patterns. Please limit yourself to %d or fewer",
+ AUCMD_MAX_PATTERNS);
+ goto cleanup;
+ }
+
+ FOREACH_ITEM(v.data.array, item, {
+ if (item.type != kObjectTypeString) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'pattern': must be a string");
+ goto cleanup;
+ }
+
+ pattern_filters[pattern_filter_count] = (char_u *)item.data.string.data;
+ pattern_filter_count += 1;
+ });
+ } else {
+ api_set_error(err, kErrorTypeValidation,
+ "Not a valid 'pattern' value. Must be a string or an array");
+ goto cleanup;
+ }
+ }
+
+ if (opts->buffer.type == kObjectTypeInteger || opts->buffer.type == kObjectTypeBuffer) {
+ buf_T *buf = find_buffer_by_handle((Buffer)opts->buffer.data.integer, err);
+ if (ERROR_SET(err)) {
+ goto cleanup;
+ }
+
+ snprintf((char *)pattern_buflocal, BUFLOCAL_PAT_LEN, "<buffer=%d>", (int)buf->handle);
+ ADD(buffers, CSTR_TO_OBJ((char *)pattern_buflocal));
+ } else if (opts->buffer.type == kObjectTypeArray) {
+ if (opts->buffer.data.array.size > AUCMD_MAX_PATTERNS) {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "Too many buffers. Please limit yourself to %d or fewer", AUCMD_MAX_PATTERNS);
+ goto cleanup;
+ }
+
+ FOREACH_ITEM(opts->buffer.data.array, bufnr, {
+ if (bufnr.type != kObjectTypeInteger && bufnr.type != kObjectTypeBuffer) {
+ api_set_error(err, kErrorTypeValidation, "Invalid value for 'buffer': must be an integer");
+ goto cleanup;
+ }
+
+ buf_T *buf = find_buffer_by_handle((Buffer)bufnr.data.integer, err);
+ if (ERROR_SET(err)) {
+ goto cleanup;
+ }
+
+ snprintf((char *)pattern_buflocal, BUFLOCAL_PAT_LEN, "<buffer=%d>", (int)buf->handle);
+ ADD(buffers, CSTR_TO_OBJ((char *)pattern_buflocal));
+ });
+ } else if (opts->buffer.type != kObjectTypeNil) {
+ api_set_error(err, kErrorTypeValidation,
+ "Invalid value for 'buffer': must be an integer or array of integers");
+ goto cleanup;
+ }
+
+ FOREACH_ITEM(buffers, bufnr, {
+ pattern_filters[pattern_filter_count] = (char_u *)bufnr.data.string.data;
+ pattern_filter_count += 1;
+ });
+
+ FOR_ALL_AUEVENTS(event) {
+ if (check_event && !event_set[event]) {
+ continue;
+ }
+
+ for (AutoPat *ap = au_get_autopat_for_event(event); ap != NULL; ap = ap->next) {
+ if (ap->cmds == NULL) {
+ continue;
+ }
+
+ // Skip autocmds from invalid groups if passed.
+ if (group != 0 && ap->group != group) {
+ continue;
+ }
+
+ // Skip 'pattern' from invalid patterns if passed.
+ if (pattern_filter_count > 0) {
+ bool passed = false;
+ for (int i = 0; i < pattern_filter_count; i++) {
+ assert(i < AUCMD_MAX_PATTERNS);
+ assert(pattern_filters[i]);
+
+ char_u *pat = pattern_filters[i];
+ int patlen = (int)STRLEN(pat);
+
+ if (aupat_is_buflocal(pat, patlen)) {
+ aupat_normalize_buflocal_pat(pattern_buflocal,
+ pat,
+ patlen,
+ aupat_get_buflocal_nr(pat, patlen));
+
+ pat = pattern_buflocal;
+ }
+
+ if (strequal((char *)ap->pat, (char *)pat)) {
+ passed = true;
+ break;
+ }
+ }
+
+ if (!passed) {
+ continue;
+ }
+ }
+
+ for (AutoCmd *ac = ap->cmds; ac != NULL; ac = ac->next) {
+ if (aucmd_exec_is_deleted(ac->exec)) {
+ continue;
+ }
+
+ Dictionary autocmd_info = ARRAY_DICT_INIT;
+
+ if (ap->group != AUGROUP_DEFAULT) {
+ PUT(autocmd_info, "group", INTEGER_OBJ(ap->group));
+ }
+
+ if (ac->id > 0) {
+ PUT(autocmd_info, "id", INTEGER_OBJ(ac->id));
+ }
+
+ if (ac->desc != NULL) {
+ PUT(autocmd_info, "desc", CSTR_TO_OBJ(ac->desc));
+ }
+
+ PUT(autocmd_info,
+ "command",
+ STRING_OBJ(cstr_to_string(aucmd_exec_to_string(ac, ac->exec))));
+
+ PUT(autocmd_info,
+ "pattern",
+ STRING_OBJ(cstr_to_string((char *)ap->pat)));
+
+ PUT(autocmd_info,
+ "event",
+ STRING_OBJ(cstr_to_string((char *)event_nr2name(event))));
+
+ PUT(autocmd_info, "once", BOOLEAN_OBJ(ac->once));
+
+ if (ap->buflocal_nr) {
+ PUT(autocmd_info, "buflocal", BOOLEAN_OBJ(true));
+ PUT(autocmd_info, "buffer", INTEGER_OBJ(ap->buflocal_nr));
+ } else {
+ PUT(autocmd_info, "buflocal", BOOLEAN_OBJ(false));
+ }
+
+ // TODO(sctx): It would be good to unify script_ctx to actually work with lua
+ // right now it's just super weird, and never really gives you the info that
+ // you would expect from this.
+ //
+ // I think we should be able to get the line number, filename, etc. from lua
+ // when we're executing something, and it should be easy to then save that
+ // info here.
+ //
+ // I think it's a big loss not getting line numbers of where options, autocmds,
+ // etc. are set (just getting "Sourced (lua)" or something is not that helpful.
+ //
+ // Once we do that, we can put these into the autocmd_info, but I don't think it's
+ // useful to do that at this time.
+ //
+ // PUT(autocmd_info, "sid", INTEGER_OBJ(ac->script_ctx.sc_sid));
+ // PUT(autocmd_info, "lnum", INTEGER_OBJ(ac->script_ctx.sc_lnum));
+
+ ADD(autocmd_list, DICTIONARY_OBJ(autocmd_info));
+ }
+ }
+ }
+
+cleanup:
+ api_free_array(buffers);
+ return autocmd_list;
+}
+
+/// Create an autocmd.
+///
+/// @param event The event or events to register this autocmd
+/// Required keys:
+/// event: string | ArrayOf(string)
+///
+/// Examples:
+/// - event: "pat1,pat2,pat3",
+/// - event: "pat1"
+/// - event: { "pat1" }
+/// - event: { "pat1", "pat2", "pat3" }
+///
+/// @param opts Optional Parameters:
+/// - callback: (string|function)
+/// - (string): The name of the viml function to execute when triggering this autocmd
+/// - (function): The lua function to execute when triggering this autocmd
+/// - NOTE: Cannot be used with {command}
+/// - command: (string) command
+/// - vimscript command
+/// - NOTE: Cannot be used with {callback}
+/// Eg. command = "let g:value_set = v:true"
+/// - pattern: (string|table)
+/// - pattern or patterns to match against
+/// - defaults to "*".
+/// - NOTE: Cannot be used with {buffer}
+/// - buffer: (bufnr)
+/// - create a |autocmd-buflocal| autocmd.
+/// - NOTE: Cannot be used with {pattern}
+/// - group: (string|int) The augroup name or id
+/// - once: (boolean) - See |autocmd-once|
+/// - nested: (boolean) - See |autocmd-nested|
+/// - desc: (string) - Description of the autocmd
+///
+/// @returns opaque value to use with nvim_del_autocmd
+Integer nvim_create_autocmd(uint64_t channel_id, Object event, Dict(create_autocmd) *opts,
+ Error *err)
+ FUNC_API_SINCE(9)
+{
+ int64_t autocmd_id = -1;
+
+ const char_u pattern_buflocal[BUFLOCAL_PAT_LEN];
+ int au_group = AUGROUP_DEFAULT;
+ char *desc = NULL;
+
+ Array patterns = ARRAY_DICT_INIT;
+ Array event_array = ARRAY_DICT_INIT;
+
+ AucmdExecutable aucmd = AUCMD_EXECUTABLE_INIT;
+ Callback cb = CALLBACK_NONE;
+
+
+ if (!unpack_string_or_array(&event_array, &event, "event", err)) {
+ goto cleanup;
+ }
+
+ if (opts->callback.type != kObjectTypeNil && opts->command.type != kObjectTypeNil) {
+ api_set_error(err, kErrorTypeValidation,
+ "cannot pass both: 'callback' and 'command' for the same autocmd");
+ goto cleanup;
+ } else if (opts->callback.type != kObjectTypeNil) {
+ // TODO(tjdevries): It's possible we could accept callable tables,
+ // but we don't do that many other places, so for the moment let's
+ // not do that.
+
+ Object *callback = &opts->callback;
+ if (callback->type == kObjectTypeLuaRef) {
+ if (callback->data.luaref == LUA_NOREF) {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "must pass an actual value");
+ goto cleanup;
+ }
+
+ if (!nlua_ref_is_function(callback->data.luaref)) {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "must pass a function for callback");
+ goto cleanup;
+ }
+
+ cb.type = kCallbackLua;
+ cb.data.luaref = api_new_luaref(callback->data.luaref);
+ } else if (callback->type == kObjectTypeString) {
+ cb.type = kCallbackFuncref;
+ cb.data.funcref = vim_strsave((char_u *)callback->data.string.data);
+ } else {
+ api_set_error(err,
+ kErrorTypeException,
+ "'callback' must be a lua function or name of vim function");
+ goto cleanup;
+ }
+
+ aucmd.type = CALLABLE_CB;
+ aucmd.callable.cb = cb;
+ } else if (opts->command.type != kObjectTypeNil) {
+ Object *command = &opts->command;
+ if (command->type == kObjectTypeString) {
+ aucmd.type = CALLABLE_EX;
+ aucmd.callable.cmd = vim_strsave((char_u *)command->data.string.data);
+ } else {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "'command' must be a string");
+ goto cleanup;
+ }
+ } else {
+ api_set_error(err, kErrorTypeValidation, "must pass one of: 'command', 'callback'");
+ goto cleanup;
+ }
+
+ bool is_once = api_object_to_bool(opts->once, "once", false, err);
+ bool is_nested = api_object_to_bool(opts->nested, "nested", false, err);
+
+ switch (opts->group.type) {
+ case kObjectTypeNil:
+ break;
+ case kObjectTypeString:
+ au_group = augroup_find(opts->group.data.string.data);
+ if (au_group == AUGROUP_ERROR) {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "invalid augroup: %s", opts->group.data.string.data);
+ goto cleanup;
+ }
+ break;
+ case kObjectTypeInteger:
+ au_group = (int)opts->group.data.integer;
+ char *name = augroup_name(au_group);
+ if (!augroup_exists(name)) {
+ api_set_error(err, kErrorTypeValidation, "invalid augroup: %d", au_group);
+ goto cleanup;
+ }
+ break;
+ default:
+ api_set_error(err, kErrorTypeValidation, "'group' must be a string or an integer.");
+ goto cleanup;
+ }
+
+ if (opts->pattern.type != kObjectTypeNil && opts->buffer.type != kObjectTypeNil) {
+ api_set_error(err, kErrorTypeValidation,
+ "cannot pass both: 'pattern' and 'buffer' for the same autocmd");
+ goto cleanup;
+ } else if (opts->pattern.type != kObjectTypeNil) {
+ Object *v = &opts->pattern;
+
+ if (v->type == kObjectTypeString) {
+ char_u *pat = (char_u *)v->data.string.data;
+ size_t patlen = aucmd_pattern_length(pat);
+ while (patlen) {
+ ADD(patterns, STRING_OBJ(cbuf_to_string((char *)pat, patlen)));
+
+ pat = aucmd_next_pattern(pat, patlen);
+ patlen = aucmd_pattern_length(pat);
+ }
+ } else if (v->type == kObjectTypeArray) {
+ if (!check_autocmd_string_array(patterns, "pattern", err)) {
+ goto cleanup;
+ }
+
+ Array array = v->data.array;
+ for (size_t i = 0; i < array.size; i++) {
+ char_u *pat = (char_u *)array.items[i].data.string.data;
+ size_t patlen = aucmd_pattern_length(pat);
+ while (patlen) {
+ ADD(patterns, STRING_OBJ(cbuf_to_string((char *)pat, patlen)));
+
+ pat = aucmd_next_pattern(pat, patlen);
+ patlen = aucmd_pattern_length(pat);
+ }
+ }
+ } else {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "'pattern' must be a string");
+ goto cleanup;
+ }
+ } else if (opts->buffer.type != kObjectTypeNil) {
+ if (opts->buffer.type != kObjectTypeInteger) {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "'buffer' must be an integer");
+ goto cleanup;
+ }
+
+ buf_T *buf = find_buffer_by_handle((Buffer)opts->buffer.data.integer, err);
+ if (ERROR_SET(err)) {
+ goto cleanup;
+ }
+
+ snprintf((char *)pattern_buflocal, BUFLOCAL_PAT_LEN, "<buffer=%d>", (int)buf->handle);
+ ADD(patterns, STRING_OBJ(cstr_to_string((char *)pattern_buflocal)));
+ }
+
+ if (opts->desc.type != kObjectTypeNil) {
+ if (opts->desc.type == kObjectTypeString) {
+ desc = opts->desc.data.string.data;
+ } else {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "'desc' must be a string");
+ goto cleanup;
+ }
+ }
+
+ if (patterns.size == 0) {
+ ADD(patterns, STRING_OBJ(STATIC_CSTR_TO_STRING("*")));
+ }
+
+ if (event_array.size == 0) {
+ api_set_error(err, kErrorTypeValidation, "'event' is a required key");
+ goto cleanup;
+ }
+
+ autocmd_id = next_autocmd_id++;
+ FOREACH_ITEM(event_array, event_str, {
+ GET_ONE_EVENT(event_nr, event_str, cleanup);
+
+ int retval;
+
+ for (size_t i = 0; i < patterns.size; i++) {
+ Object pat = patterns.items[i];
+
+ // See: TODO(sctx)
+ WITH_SCRIPT_CONTEXT(channel_id, {
+ retval = autocmd_register(autocmd_id,
+ event_nr,
+ (char_u *)pat.data.string.data,
+ (int)pat.data.string.size,
+ au_group,
+ is_once,
+ is_nested,
+ desc,
+ aucmd);
+ });
+
+ if (retval == FAIL) {
+ api_set_error(err, kErrorTypeException, "Failed to set autocmd");
+ goto cleanup;
+ }
+ }
+ });
+
+
+cleanup:
+ aucmd_exec_free(&aucmd);
+ api_free_array(event_array);
+ api_free_array(patterns);
+
+ return autocmd_id;
+}
+
+/// Delete an autocmd by {id}. Autocmds only return IDs when created
+/// via the API. Will not error if called and no autocmds match
+/// the {id}.
+///
+/// @param id Integer The ID returned by nvim_create_autocmd
+void nvim_del_autocmd(Integer id)
+ FUNC_API_SINCE(9)
+{
+ autocmd_delete_id(id);
+}
+
+/// Create or get an augroup.
+///
+/// To get an existing augroup ID, do:
+/// <pre>
+/// local id = vim.api.nvim_create_augroup(name, {
+/// clear = false
+/// })
+/// </pre>
+///
+/// @param name String: The name of the augroup to create
+/// @param opts Parameters
+/// - clear (bool): Whether to clear existing commands or not.
+/// Defaults to true.
+/// See |autocmd-groups|
+///
+/// @returns opaque value to use with nvim_del_augroup_by_id
+Integer nvim_create_augroup(uint64_t channel_id, String name, Dict(create_augroup) *opts,
+ Error *err)
+ FUNC_API_SINCE(9)
+{
+ char *augroup_name = name.data;
+ bool clear_autocmds = api_object_to_bool(opts->clear, "clear", true, err);
+
+ int augroup = -1;
+ WITH_SCRIPT_CONTEXT(channel_id, {
+ augroup = augroup_add(augroup_name);
+ if (augroup == AUGROUP_ERROR) {
+ api_set_error(err, kErrorTypeException, "Failed to set augroup");
+ return -1;
+ }
+
+ if (clear_autocmds) {
+ FOR_ALL_AUEVENTS(event) {
+ aupat_del_for_event_and_group(event, augroup);
+ }
+ }
+ });
+
+ return augroup;
+}
+
+/// Delete an augroup by {id}. {id} can only be returned when augroup was
+/// created with |nvim_create_augroup|.
+///
+/// NOTE: behavior differs from augroup-delete.
+///
+/// When deleting an augroup, autocmds contained by this augroup will also be deleted and cleared.
+/// This augroup will no longer exist
+void nvim_del_augroup_by_id(Integer id)
+ FUNC_API_SINCE(9)
+{
+ char *name = augroup_name((int)id);
+ augroup_del(name, false);
+}
+
+/// Delete an augroup by {name}.
+///
+/// NOTE: behavior differs from augroup-delete.
+///
+/// When deleting an augroup, autocmds contained by this augroup will also be deleted and cleared.
+/// This augroup will no longer exist
+void nvim_del_augroup_by_name(String name)
+ FUNC_API_SINCE(9)
+{
+ augroup_del(name.data, false);
+}
+
+/// Do one autocmd.
+///
+/// @param event The event or events to execute
+/// @param opts Optional Parameters:
+/// - buffer (number) - buffer number
+/// - NOTE: Cannot be used with {pattern}
+/// - pattern (string|table) - optional, defaults to "*".
+/// - NOTE: Cannot be used with {buffer}
+/// - group (string|int) - autocmd group name or id
+/// - modeline (boolean) - Default true, see |<nomodeline>|
+void nvim_do_autocmd(Object event, Dict(do_autocmd) *opts, Error *err)
+ FUNC_API_SINCE(9)
+{
+ int au_group = AUGROUP_ALL;
+ bool modeline = true;
+
+ buf_T *buf = curbuf;
+ bool set_buf = false;
+
+ char_u *pattern = NULL;
+ bool set_pattern = false;
+
+ Array event_array = ARRAY_DICT_INIT;
+
+ if (!unpack_string_or_array(&event_array, &event, "event", err)) {
+ goto cleanup;
+ }
+
+ switch (opts->group.type) {
+ case kObjectTypeNil:
+ break;
+ case kObjectTypeString:
+ au_group = augroup_find(opts->group.data.string.data);
+ if (au_group == AUGROUP_ERROR) {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "invalid augroup: %s", opts->group.data.string.data);
+ goto cleanup;
+ }
+ break;
+ case kObjectTypeInteger:
+ au_group = (int)opts->group.data.integer;
+ char *name = augroup_name(au_group);
+ if (!augroup_exists(name)) {
+ api_set_error(err, kErrorTypeValidation, "invalid augroup: %d", au_group);
+ goto cleanup;
+ }
+ break;
+ default:
+ api_set_error(err, kErrorTypeValidation, "'group' must be a string or an integer.");
+ goto cleanup;
+ }
+
+ if (opts->buffer.type != kObjectTypeNil) {
+ Object buf_obj = opts->buffer;
+ if (buf_obj.type != kObjectTypeInteger && buf_obj.type != kObjectTypeBuffer) {
+ api_set_error(err, kErrorTypeException, "invalid buffer: %d", buf_obj.type);
+ goto cleanup;
+ }
+
+ buf = find_buffer_by_handle((Buffer)buf_obj.data.integer, err);
+ set_buf = true;
+
+ if (ERROR_SET(err)) {
+ goto cleanup;
+ }
+ }
+
+ if (opts->pattern.type != kObjectTypeNil) {
+ if (opts->pattern.type != kObjectTypeString) {
+ api_set_error(err, kErrorTypeValidation, "'pattern' must be a string");
+ goto cleanup;
+ }
+
+ pattern = vim_strsave((char_u *)opts->pattern.data.string.data);
+ set_pattern = true;
+ }
+
+ modeline = api_object_to_bool(opts->modeline, "modeline", true, err);
+
+ if (set_pattern && set_buf) {
+ api_set_error(err, kErrorTypeValidation, "must not set 'buffer' and 'pattern'");
+ goto cleanup;
+ }
+
+ bool did_aucmd = false;
+ FOREACH_ITEM(event_array, event_str, {
+ GET_ONE_EVENT(event_nr, event_str, cleanup)
+
+ did_aucmd |= apply_autocmds_group(event_nr, pattern, NULL, true, au_group, buf, NULL);
+ })
+
+ if (did_aucmd && modeline) {
+ do_modelines(0);
+ }
+
+cleanup:
+ api_free_array(event_array);
+ XFREE_CLEAR(pattern);
+}
+
+static bool check_autocmd_string_array(Array arr, char *k, Error *err)
+{
+ for (size_t i = 0; i < arr.size; i++) {
+ if (arr.items[i].type != kObjectTypeString) {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "All entries in '%s' must be strings",
+ k);
+ return false;
+ }
+
+ // Disallow newlines in the middle of the line.
+ const String l = arr.items[i].data.string;
+ if (memchr(l.data, NL, l.size)) {
+ api_set_error(err, kErrorTypeValidation,
+ "String cannot contain newlines");
+ return false;
+ }
+ }
+ return true;
+}
+
+static bool unpack_string_or_array(Array *array, Object *v, char *k, Error *err)
+{
+ if (v->type == kObjectTypeString) {
+ ADD(*array, copy_object(*v));
+ } else if (v->type == kObjectTypeArray) {
+ if (!check_autocmd_string_array(v->data.array, k, err)) {
+ return false;
+ }
+ *array = copy_array(v->data.array);
+ } else {
+ api_set_error(err,
+ kErrorTypeValidation,
+ "'%s' must be an array or a string.",
+ k);
+ return false;
+ }
+
+ return true;
+}
+
+#undef GET_ONE_EVENT
diff --git a/src/nvim/api/autocmd.h b/src/nvim/api/autocmd.h
new file mode 100644
index 0000000000..f9432830d9
--- /dev/null
+++ b/src/nvim/api/autocmd.h
@@ -0,0 +1,11 @@
+#ifndef NVIM_API_AUTOCMD_H
+#define NVIM_API_AUTOCMD_H
+
+#include <stdint.h>
+
+#include "nvim/api/private/defs.h"
+
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+# include "api/autocmd.h.generated.h"
+#endif
+#endif // NVIM_API_AUTOCMD_H
diff --git a/src/nvim/api/buffer.c b/src/nvim/api/buffer.c
index 2d5403d4b8..9f0cadd5ce 100644
--- a/src/nvim/api/buffer.c
+++ b/src/nvim/api/buffer.c
@@ -133,7 +133,7 @@ Integer nvim_buf_line_count(Buffer buffer, Error *err)
/// - buffer handle
/// - on_reload: Lua callback invoked on reload. The entire buffer
/// content should be considered changed. Args:
-/// - the string "detach"
+/// - the string "reload"
/// - buffer handle
/// - utf_sizes: include UTF-32 and UTF-16 size of the replaced
/// region, as args to `on_lines`.
@@ -287,8 +287,8 @@ ArrayOf(String) nvim_buf_get_lines(uint64_t channel_id,
}
bool oob = false;
- start = normalize_index(buf, start, &oob);
- end = normalize_index(buf, end, &oob);
+ start = normalize_index(buf, start, true, &oob);
+ end = normalize_index(buf, end, true, &oob);
if (strict_indexing && oob) {
api_set_error(err, kErrorTypeValidation, "Index out of bounds");
@@ -374,15 +374,14 @@ void nvim_buf_set_lines(uint64_t channel_id, Buffer buffer, Integer start, Integ
}
bool oob = false;
- start = normalize_index(buf, start, &oob);
- end = normalize_index(buf, end, &oob);
+ start = normalize_index(buf, start, true, &oob);
+ end = normalize_index(buf, end, true, &oob);
if (strict_indexing && oob) {
api_set_error(err, kErrorTypeValidation, "Index out of bounds");
return;
}
-
if (start > end) {
api_set_error(err,
kErrorTypeValidation,
@@ -554,13 +553,13 @@ void nvim_buf_set_text(uint64_t channel_id, Buffer buffer, Integer start_row, In
// check range is ordered and everything!
// start_row, end_row within buffer len (except add text past the end?)
- start_row = normalize_index(buf, start_row, &oob);
+ start_row = normalize_index(buf, start_row, false, &oob);
if (oob || start_row == buf->b_ml.ml_line_count + 1) {
api_set_error(err, kErrorTypeValidation, "start_row out of bounds");
return;
}
- end_row = normalize_index(buf, end_row, &oob);
+ end_row = normalize_index(buf, end_row, false, &oob);
if (oob || end_row == buf->b_ml.ml_line_count + 1) {
api_set_error(err, kErrorTypeValidation, "end_row out of bounds");
return;
@@ -598,12 +597,11 @@ void nvim_buf_set_text(uint64_t channel_id, Buffer buffer, Integer start_row, In
if (start_row == end_row) {
old_byte = (bcount_t)end_col - start_col;
} else {
- const char *bufline;
old_byte += (bcount_t)strlen(str_at_start) - start_col;
for (int64_t i = 1; i < end_row - start_row; i++) {
int64_t lnum = start_row + i;
- bufline = (char *)ml_get_buf(buf, lnum, false);
+ const char *bufline = (char *)ml_get_buf(buf, lnum, false);
old_byte += (bcount_t)(strlen(bufline))+1;
}
old_byte += (bcount_t)end_col+1;
@@ -757,6 +755,108 @@ end:
try_end(err);
}
+/// Gets a range from the buffer.
+///
+/// This differs from |nvim_buf_get_lines()| in that it allows retrieving only
+/// portions of a line.
+///
+/// Indexing is zero-based. Column indices are end-exclusive.
+///
+/// Prefer |nvim_buf_get_lines()| when retrieving entire lines.
+///
+/// @param channel_id
+/// @param buffer Buffer handle, or 0 for current buffer
+/// @param start_row First line index
+/// @param start_col Starting byte offset of first line
+/// @param end_row Last line index
+/// @param end_col Ending byte offset of last line (exclusive)
+/// @param opts Optional parameters. Currently unused.
+/// @param[out] err Error details, if any
+/// @return Array of lines, or empty array for unloaded buffer.
+ArrayOf(String) nvim_buf_get_text(uint64_t channel_id, Buffer buffer,
+ Integer start_row, Integer start_col,
+ Integer end_row, Integer end_col,
+ Dictionary opts, Error *err)
+ FUNC_API_SINCE(9)
+{
+ Array rv = ARRAY_DICT_INIT;
+
+ if (opts.size > 0) {
+ api_set_error(err, kErrorTypeValidation, "opts dict isn't empty");
+ return rv;
+ }
+
+ buf_T *buf = find_buffer_by_handle(buffer, err);
+
+ if (!buf) {
+ return rv;
+ }
+
+ // return sentinel value if the buffer isn't loaded
+ if (buf->b_ml.ml_mfp == NULL) {
+ return rv;
+ }
+
+ bool oob = false;
+ start_row = normalize_index(buf, start_row, false, &oob);
+ end_row = normalize_index(buf, end_row, false, &oob);
+
+ if (oob) {
+ api_set_error(err, kErrorTypeValidation, "Index out of bounds");
+ return rv;
+ }
+
+ // nvim_buf_get_lines doesn't care if the start row is greater than the end
+ // row (it will just return an empty array), but nvim_buf_get_text does in
+ // order to maintain symmetry with nvim_buf_set_text.
+ if (start_row > end_row) {
+ api_set_error(err, kErrorTypeValidation, "start is higher than end");
+ return rv;
+ }
+
+ bool replace_nl = (channel_id != VIML_INTERNAL_CALL);
+
+ if (start_row == end_row) {
+ String line = buf_get_text(buf, start_row, start_col, end_col, replace_nl, err);
+ if (ERROR_SET(err)) {
+ return rv;
+ }
+
+ ADD(rv, STRING_OBJ(line));
+ return rv;
+ }
+
+ rv.size = (size_t)(end_row - start_row) + 1;
+ rv.items = xcalloc(rv.size, sizeof(Object));
+
+ rv.items[0] = STRING_OBJ(buf_get_text(buf, start_row, start_col, MAXCOL-1, replace_nl, err));
+ if (ERROR_SET(err)) {
+ goto end;
+ }
+
+ if (rv.size > 2) {
+ Array tmp = ARRAY_DICT_INIT;
+ tmp.items = &rv.items[1];
+ if (!buf_collect_lines(buf, rv.size - 2, start_row + 1, replace_nl, &tmp, err)) {
+ goto end;
+ }
+ }
+
+ rv.items[rv.size-1] = STRING_OBJ(buf_get_text(buf, end_row, 0, end_col, replace_nl, err));
+ if (ERROR_SET(err)) {
+ goto end;
+ }
+
+end:
+ if (ERROR_SET(err)) {
+ api_free_array(rv);
+ rv.size = 0;
+ rv.items = NULL;
+ }
+
+ return rv;
+}
+
/// Returns the byte offset of a line (0-indexed). |api-indexing|
///
/// Line 1 (index=0) has offset 0. UTF-8 bytes are counted. EOL is one byte.
@@ -852,11 +952,11 @@ ArrayOf(Dictionary) nvim_buf_get_keymap(uint64_t channel_id, Buffer buffer, Stri
/// @see |nvim_set_keymap()|
///
/// @param buffer Buffer handle, or 0 for current buffer
-void nvim_buf_set_keymap(Buffer buffer, String mode, String lhs, String rhs, Dict(keymap) *opts,
- Error *err)
+void nvim_buf_set_keymap(uint64_t channel_id, Buffer buffer, String mode, String lhs, String rhs,
+ Dict(keymap) *opts, Error *err)
FUNC_API_SINCE(6)
{
- modify_keymap(buffer, false, mode, lhs, rhs, opts, err);
+ modify_keymap(channel_id, buffer, false, mode, lhs, rhs, opts, err);
}
/// Unmaps a buffer-local |mapping| for the given mode.
@@ -864,11 +964,11 @@ void nvim_buf_set_keymap(Buffer buffer, String mode, String lhs, String rhs, Dic
/// @see |nvim_del_keymap()|
///
/// @param buffer Buffer handle, or 0 for current buffer
-void nvim_buf_del_keymap(Buffer buffer, String mode, String lhs, Error *err)
+void nvim_buf_del_keymap(uint64_t channel_id, Buffer buffer, String mode, String lhs, Error *err)
FUNC_API_SINCE(6)
{
String rhs = { .data = "", .size = 0 };
- modify_keymap(buffer, true, mode, lhs, rhs, NULL, err);
+ modify_keymap(channel_id, buffer, true, mode, lhs, rhs, NULL, err);
}
/// Gets a map of buffer-local |user-commands|.
@@ -1278,8 +1378,8 @@ Object nvim_buf_call(Buffer buffer, LuaRef fun, Error *err)
/// @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)
+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);
@@ -1386,11 +1486,11 @@ static void fix_cursor(linenr_T lo, linenr_T hi, linenr_T extra)
}
// Normalizes 0-based indexes to buffer line numbers
-static int64_t normalize_index(buf_T *buf, int64_t index, bool *oob)
+static int64_t normalize_index(buf_T *buf, int64_t index, bool end_exclusive, bool *oob)
{
int64_t line_count = buf->b_ml.ml_line_count;
// Fix if < 0
- index = index < 0 ? line_count + index +1 : index;
+ index = index < 0 ? line_count + index + (int)end_exclusive : index;
// Check for oob
if (index > line_count) {
diff --git a/src/nvim/api/deprecated.c b/src/nvim/api/deprecated.c
index 18243fec2b..6a41df0aa9 100644
--- a/src/nvim/api/deprecated.c
+++ b/src/nvim/api/deprecated.c
@@ -22,11 +22,11 @@
/// @deprecated
/// @see nvim_exec
-String nvim_command_output(String command, Error *err)
+String nvim_command_output(uint64_t channel_id, String command, Error *err)
FUNC_API_SINCE(1)
FUNC_API_DEPRECATED_SINCE(7)
{
- return nvim_exec(command, true, err);
+ return nvim_exec(channel_id, command, true, err);
}
/// @deprecated Use nvim_exec_lua() instead.
@@ -51,11 +51,10 @@ Integer nvim_buf_get_number(Buffer buffer, Error *err)
FUNC_API_SINCE(1)
FUNC_API_DEPRECATED_SINCE(2)
{
- Integer rv = 0;
buf_T *buf = find_buffer_by_handle(buffer, err);
if (!buf) {
- return rv;
+ return 0;
}
return buf->b_fnum;
diff --git a/src/nvim/api/extmark.c b/src/nvim/api/extmark.c
index 3a968f07ab..e355f82f4d 100644
--- a/src/nvim/api/extmark.c
+++ b/src/nvim/api/extmark.c
@@ -8,6 +8,7 @@
#include "nvim/api/extmark.h"
#include "nvim/api/private/defs.h"
#include "nvim/api/private/helpers.h"
+#include "nvim/decoration_provider.h"
#include "nvim/extmark.h"
#include "nvim/lua/executor.h"
#include "nvim/memline.h"
@@ -445,6 +446,27 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, Object start, Object e
/// - 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.
+/// - sign_text: string of length 1-2 used to display in the
+/// sign column.
+/// Note: ranges are unsupported and decorations are only
+/// applied to start_row
+/// - sign_hl_group: name of the highlight group used to
+/// highlight the sign column text.
+/// Note: ranges are unsupported and decorations are only
+/// applied to start_row
+/// - number_hl_group: name of the highlight group used to
+/// highlight the number column.
+/// Note: ranges are unsupported and decorations are only
+/// applied to start_row
+/// - line_hl_group: name of the highlight group used to
+/// highlight the whole line.
+/// Note: ranges are unsupported and decorations are only
+/// applied to start_row
+/// - cursorline_hl_group: name of the highlight group used to
+/// highlight the line when the cursor is on the same line
+/// as the mark and 'cursorline' is enabled.
+/// Note: ranges are unsupported and decorations are only
+/// applied to start_row
///
/// @param[out] err Error details, if any
/// @return Id of the created/updated extmark
@@ -519,10 +541,25 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
goto error;
}
- if (HAS_KEY(opts->hl_group)) {
- decor.hl_id = object_to_hl_id(opts->hl_group, "hl_group", err);
- if (ERROR_SET(err)) {
- goto error;
+ struct {
+ const char *name;
+ Object *opt;
+ int *dest;
+ } hls[] = {
+ { "hl_group" , &opts->hl_group , &decor.hl_id },
+ { "sign_hl_group" , &opts->sign_hl_group , &decor.sign_hl_id },
+ { "number_hl_group" , &opts->number_hl_group , &decor.number_hl_id },
+ { "line_hl_group" , &opts->line_hl_group , &decor.line_hl_id },
+ { "cursorline_hl_group", &opts->cursorline_hl_group, &decor.cursorline_hl_id },
+ { NULL, NULL, NULL },
+ };
+
+ for (int j = 0; hls[j].name && hls[j].dest; j++) {
+ if (HAS_KEY(*hls[j].opt)) {
+ *hls[j].dest = object_to_hl_id(*hls[j].opt, hls[j].name, err);
+ if (ERROR_SET(err)) {
+ goto error;
+ }
}
}
@@ -622,6 +659,17 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
goto error;
}
+ if (opts->sign_text.type == kObjectTypeString) {
+ if (!init_sign_text(&decor.sign_text,
+ (char_u *)opts->sign_text.data.string.data)) {
+ api_set_error(err, kErrorTypeValidation, "sign_text is not a valid value");
+ goto error;
+ }
+ } else if (HAS_KEY(opts->sign_text)) {
+ api_set_error(err, kErrorTypeValidation, "sign_text is not a String");
+ goto error;
+ }
+
bool right_gravity = true;
OPTION_TO_BOOL(right_gravity, right_gravity, true);
@@ -709,6 +757,7 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, Integer line, Integer
error:
clear_virttext(&decor.virt_text);
+ xfree(decor.sign_text);
return 0;
}
diff --git a/src/nvim/api/keysets.lua b/src/nvim/api/keysets.lua
index f6dce1905e..435e8195dd 100644
--- a/src/nvim/api/keysets.lua
+++ b/src/nvim/api/keysets.lua
@@ -22,6 +22,11 @@ return {
"virt_lines_above";
"virt_lines_leftcol";
"strict";
+ "sign_text";
+ "sign_hl_group";
+ "number_hl_group";
+ "line_hl_group";
+ "cursorline_hl_group";
};
keymap = {
"noremap";
@@ -83,7 +88,10 @@ return {
"standout";
"strikethrough";
"underline";
+ "underlineline";
"undercurl";
+ "underdot";
+ "underdash";
"italic";
"reverse";
"nocombine";
@@ -97,6 +105,7 @@ return {
"special"; "sp";
"link";
"fallback";
+ "blend";
"temp";
};
highlight_cterm = {
@@ -104,10 +113,39 @@ return {
"standout";
"strikethrough";
"underline";
+ "underlineline";
"undercurl";
+ "underdot";
+ "underdash";
"italic";
"reverse";
"nocombine";
};
+ -- Autocmds
+ create_autocmd = {
+ "buffer";
+ "callback";
+ "command";
+ "desc";
+ "group";
+ "once";
+ "nested";
+ "pattern";
+ };
+ do_autocmd = {
+ "buffer";
+ "group";
+ "modeline";
+ "pattern";
+ };
+ get_autocmds = {
+ "event";
+ "group";
+ "pattern";
+ "buffer";
+ };
+ create_augroup = {
+ "clear";
+ };
}
diff --git a/src/nvim/api/private/converter.c b/src/nvim/api/private/converter.c
index 3d4ff202fe..82ec1ad0d8 100644
--- a/src/nvim/api/private/converter.c
+++ b/src/nvim/api/private/converter.c
@@ -57,14 +57,21 @@ typedef struct {
const size_t len_ = (size_t)(len); \
const blob_T *const blob_ = (blob); \
kvi_push(edata->stack, STRING_OBJ(((String) { \
- .data = len_ != 0 ? xmemdup(blob_->bv_ga.ga_data, len_) : NULL, \
+ .data = len_ != 0 ? xmemdupz(blob_->bv_ga.ga_data, len_) : xstrdup(""), \
.size = len_ \
}))); \
} while (0)
#define TYPVAL_ENCODE_CONV_FUNC_START(tv, fun) \
do { \
- TYPVAL_ENCODE_CONV_NIL(tv); \
+ ufunc_T *fp = find_func(fun); \
+ 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); \
+ kvi_push(edata->stack, LUAREF_OBJ(ref)); \
+ } else { \
+ TYPVAL_ENCODE_CONV_NIL(tv); \
+ } \
goto typval_encode_stop_converting_one_item; \
} while (0)
@@ -231,14 +238,6 @@ 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,
diff --git a/src/nvim/api/private/dispatch.c b/src/nvim/api/private/dispatch.c
index 8ab7743e01..ba2e560d63 100644
--- a/src/nvim/api/private/dispatch.c
+++ b/src/nvim/api/private/dispatch.c
@@ -6,22 +6,31 @@
#include <msgpack.h>
#include <stdbool.h>
-#include "nvim/api/buffer.h"
#include "nvim/api/deprecated.h"
-#include "nvim/api/extmark.h"
#include "nvim/api/private/defs.h"
#include "nvim/api/private/dispatch.h"
#include "nvim/api/private/helpers.h"
+#include "nvim/log.h"
+#include "nvim/map.h"
+#include "nvim/msgpack_rpc/helpers.h"
+#include "nvim/vim.h"
+
+// ===========================================================================
+// NEW API FILES MUST GO HERE.
+//
+// When creating a new API file, you must include it here,
+// so that the dispatcher can find the C functions that you are creating!
+// ===========================================================================
+#include "nvim/api/autocmd.h"
+#include "nvim/api/buffer.h"
+#include "nvim/api/extmark.h"
#include "nvim/api/tabpage.h"
#include "nvim/api/ui.h"
#include "nvim/api/vim.h"
#include "nvim/api/vimscript.h"
#include "nvim/api/win_config.h"
#include "nvim/api/window.h"
-#include "nvim/log.h"
-#include "nvim/map.h"
-#include "nvim/msgpack_rpc/helpers.h"
-#include "nvim/vim.h"
+#include "nvim/ui_client.h"
static Map(String, MsgpackRpcRequestHandler) methods = MAP_INIT;
@@ -30,6 +39,13 @@ static void msgpack_rpc_add_method_handler(String method, MsgpackRpcRequestHandl
map_put(String, MsgpackRpcRequestHandler)(&methods, method, handler);
}
+void msgpack_rpc_add_redraw(void)
+{
+ msgpack_rpc_add_method_handler(STATIC_CSTR_AS_STRING("redraw"),
+ (MsgpackRpcRequestHandler) { .fn = ui_client_handle_redraw,
+ .fast = true });
+}
+
/// @param name API method name
/// @param name_len name size (includes terminating NUL)
MsgpackRpcRequestHandler msgpack_rpc_get_handler_for(const char *name, size_t name_len,
diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c
index 2b107a3f27..9f41393c6b 100644
--- a/src/nvim/api/private/helpers.c
+++ b/src/nvim/api/private/helpers.c
@@ -111,7 +111,7 @@ bool try_leave(const TryState *const tstate, Error *const err)
/// try_enter()/try_leave() pair should be used instead.
void try_start(void)
{
- ++trylevel;
+ trylevel++;
}
/// End try block, set the error message if any and return true if an error
@@ -396,19 +396,14 @@ void set_option_to(uint64_t channel_id, void *to, int type, String name, Object
stringval = value.data.string.data;
}
- const sctx_T save_current_sctx = current_sctx;
- current_sctx.sc_sid =
- channel_id == LUA_INTERNAL_CALL ? SID_LUA : SID_API_CLIENT;
- current_sctx.sc_lnum = 0;
- current_channel_id = channel_id;
+ WITH_SCRIPT_CONTEXT(channel_id, {
+ const int opt_flags = (type == SREQ_WIN && !(flags & SOPT_GLOBAL))
+ ? 0 : (type == SREQ_GLOBAL)
+ ? OPT_GLOBAL : OPT_LOCAL;
- const int opt_flags = (type == SREQ_WIN && !(flags & SOPT_GLOBAL))
- ? 0 : (type == SREQ_GLOBAL)
- ? OPT_GLOBAL : OPT_LOCAL;
- set_option_value_for(name.data, numval, stringval,
- opt_flags, type, to, err);
-
- current_sctx = save_current_sctx;
+ set_option_value_for(name.data, numval, stringval,
+ opt_flags, type, to, err);
+ });
}
@@ -591,8 +586,8 @@ Array string_to_array(const String input, bool crlf)
/// @param buffer Buffer handle for a specific buffer, or 0 for the current
/// buffer, or -1 to signify global behavior ("all buffers")
/// @param is_unmap When true, removes the mapping that matches {lhs}.
-void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String rhs,
- Dict(keymap) *opts, Error *err)
+void modify_keymap(uint64_t channel_id, 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);
@@ -605,6 +600,8 @@ void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String
return;
}
+ const sctx_T save_current_sctx = api_set_sctx(channel_id);
+
if (opts != NULL && opts->callback.type == kObjectTypeLuaRef) {
lua_funcref = opts->callback.data.luaref;
opts->callback.data.luaref = LUA_NOREF;
@@ -716,6 +713,7 @@ void modify_keymap(Buffer buffer, bool is_unmap, String mode, String lhs, String
parsed_args.rhs_lua = LUA_NOREF; // don't clear ref on success
fail_and_free:
+ current_sctx = save_current_sctx;
NLUA_CLEAR_REF(parsed_args.rhs_lua);
xfree(parsed_args.rhs);
xfree(parsed_args.orig_rhs);
@@ -758,6 +756,52 @@ bool buf_collect_lines(buf_T *buf, size_t n, int64_t start, bool replace_nl, Arr
return true;
}
+/// Returns a substring of a buffer line
+///
+/// @param buf Buffer handle
+/// @param lnum Line number (1-based)
+/// @param start_col Starting byte offset into line (0-based)
+/// @param end_col Ending byte offset into line (0-based, exclusive)
+/// @param replace_nl Replace newlines ('\n') with null ('\0')
+/// @param err Error object
+/// @return The text between start_col and end_col on line lnum of buffer buf
+String buf_get_text(buf_T *buf, int64_t lnum, int64_t start_col, int64_t end_col, bool replace_nl,
+ Error *err)
+{
+ String rv = STRING_INIT;
+
+ if (lnum >= MAXLNUM) {
+ api_set_error(err, kErrorTypeValidation, "Line index is too high");
+ return rv;
+ }
+
+ const char *bufstr = (char *)ml_get_buf(buf, (linenr_T)lnum, false);
+ size_t line_length = strlen(bufstr);
+
+ start_col = start_col < 0 ? (int64_t)line_length + start_col + 1 : start_col;
+ end_col = end_col < 0 ? (int64_t)line_length + end_col + 1 : end_col;
+
+ if (start_col >= MAXCOL || end_col >= MAXCOL) {
+ api_set_error(err, kErrorTypeValidation, "Column index is too high");
+ return rv;
+ }
+
+ if (start_col > end_col) {
+ api_set_error(err, kErrorTypeValidation, "start_col must be less than end_col");
+ return rv;
+ }
+
+ if ((size_t)start_col >= line_length) {
+ return rv;
+ }
+
+ rv = cstrn_to_string(&bufstr[start_col], (size_t)(end_col - start_col));
+ if (replace_nl) {
+ strchrsub(rv.data, '\n', '\0');
+ }
+
+ return rv;
+}
void api_free_string(String value)
{
@@ -993,8 +1037,7 @@ static void set_option_value_for(char *key, int numval, char *stringval, int opt
aco_save_T aco;
try_start();
- switch (opt_type)
- {
+ switch (opt_type) {
case SREQ_WIN:
if (switch_win_noblock(&switchwin, (win_T *)from, win_find_tabpage((win_T *)from), true)
== FAIL) {
@@ -1569,3 +1612,69 @@ err:
NLUA_CLEAR_REF(luaref);
NLUA_CLEAR_REF(compl_luaref);
}
+
+int find_sid(uint64_t channel_id)
+{
+ switch (channel_id) {
+ case VIML_INTERNAL_CALL:
+ // TODO(autocmd): Figure out what this should be
+ // return SID_API_CLIENT;
+ case LUA_INTERNAL_CALL:
+ return SID_LUA;
+ default:
+ return SID_API_CLIENT;
+ }
+}
+
+/// Sets sctx for API calls.
+///
+/// @param channel_id api clients id. Used to determine if it's a internal
+/// call or a rpc call.
+/// @return returns previous value of current_sctx. To be used
+/// to be used for restoring sctx to previous state.
+sctx_T api_set_sctx(uint64_t channel_id)
+{
+ sctx_T old_current_sctx = current_sctx;
+ if (channel_id != VIML_INTERNAL_CALL) {
+ current_sctx.sc_sid =
+ channel_id == LUA_INTERNAL_CALL ? SID_LUA : SID_API_CLIENT;
+ current_sctx.sc_lnum = 0;
+ }
+ return old_current_sctx;
+}
+
+// adapted from sign.c:sign_define_init_text.
+// TODO(lewis6991): Consider merging
+int init_sign_text(char_u **sign_text, char_u *text)
+{
+ char_u *s;
+
+ char_u *endp = text + (int)STRLEN(text);
+
+ // Count cells and check for non-printable chars
+ int cells = 0;
+ for (s = text; s < endp; s += utfc_ptr2len(s)) {
+ if (!vim_isprintc(utf_ptr2char(s))) {
+ break;
+ }
+ cells += utf_ptr2cells(s);
+ }
+ // Currently must be empty, one or two display cells
+ if (s != endp || cells > 2) {
+ return FAIL;
+ }
+ if (cells < 1) {
+ return OK;
+ }
+
+ // Allocate one byte more if we need to pad up
+ // with a space.
+ size_t len = (size_t)(endp - text + ((cells == 1) ? 1 : 0));
+ *sign_text = vim_strnsave(text, len);
+
+ if (cells == 1) {
+ STRCPY(*sign_text + len - 1, " ");
+ }
+
+ return OK;
+}
diff --git a/src/nvim/api/private/helpers.h b/src/nvim/api/private/helpers.h
index 6d0aec9c90..bc7c2e6a60 100644
--- a/src/nvim/api/private/helpers.h
+++ b/src/nvim/api/private/helpers.h
@@ -138,10 +138,29 @@ typedef struct {
msg_list = saved_msg_list; /* Restore the exception context. */ \
} while (0)
+// Useful macro for executing some `code` for each item in an array.
+#define FOREACH_ITEM(a, __foreach_item, code) \
+ for (size_t __foreach_i = 0; __foreach_i < (a).size; __foreach_i++) { \
+ Object __foreach_item = (a).items[__foreach_i]; \
+ code; \
+ }
+
+
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "api/private/helpers.h.generated.h"
# include "keysets.h.generated.h"
#endif
+#define WITH_SCRIPT_CONTEXT(channel_id, code) \
+ do { \
+ const sctx_T save_current_sctx = current_sctx; \
+ current_sctx.sc_sid = \
+ (channel_id) == LUA_INTERNAL_CALL ? SID_LUA : SID_API_CLIENT; \
+ current_sctx.sc_lnum = 0; \
+ current_channel_id = channel_id; \
+ code; \
+ current_sctx = save_current_sctx; \
+ } while (0);
+
#endif // NVIM_API_PRIVATE_HELPERS_H
diff --git a/src/nvim/api/tabpage.c b/src/nvim/api/tabpage.c
index 14b6be8eeb..b994d18c43 100644
--- a/src/nvim/api/tabpage.c
+++ b/src/nvim/api/tabpage.c
@@ -102,11 +102,10 @@ void nvim_tabpage_del_var(Tabpage tabpage, String name, Error *err)
Window nvim_tabpage_get_win(Tabpage tabpage, Error *err)
FUNC_API_SINCE(1)
{
- Window rv = 0;
tabpage_T *tab = find_tab_by_handle(tabpage, err);
if (!tab || !valid_tabpage(tab)) {
- return rv;
+ return 0;
}
if (tab == curtab) {
@@ -130,11 +129,10 @@ Window nvim_tabpage_get_win(Tabpage tabpage, Error *err)
Integer nvim_tabpage_get_number(Tabpage tabpage, Error *err)
FUNC_API_SINCE(1)
{
- Integer rv = 0;
tabpage_T *tab = find_tab_by_handle(tabpage, err);
if (!tab) {
- return rv;
+ return 0;
}
return tabpage_index(tab);
diff --git a/src/nvim/api/ui_events.in.h b/src/nvim/api/ui_events.in.h
index 03fe5c5058..db348359eb 100644
--- a/src/nvim/api/ui_events.in.h
+++ b/src/nvim/api/ui_events.in.h
@@ -78,13 +78,13 @@ void hl_attr_define(Integer id, HlAttrs rgb_attrs, HlAttrs cterm_attrs,
void hl_group_set(String name, Integer id)
FUNC_API_SINCE(6) FUNC_API_BRIDGE_IMPL;
void grid_resize(Integer grid, Integer width, Integer height)
- FUNC_API_SINCE(5) FUNC_API_REMOTE_IMPL FUNC_API_COMPOSITOR_IMPL;
+ FUNC_API_SINCE(5) FUNC_API_REMOTE_IMPL FUNC_API_COMPOSITOR_IMPL FUNC_API_CLIENT_IMPL;
void grid_clear(Integer grid)
FUNC_API_SINCE(5) FUNC_API_REMOTE_IMPL;
void grid_cursor_goto(Integer grid, Integer row, Integer col)
FUNC_API_SINCE(5) FUNC_API_REMOTE_IMPL FUNC_API_COMPOSITOR_IMPL;
void grid_line(Integer grid, Integer row, Integer col_start, Array data)
- FUNC_API_SINCE(5) FUNC_API_REMOTE_ONLY;
+ FUNC_API_SINCE(5) FUNC_API_REMOTE_ONLY FUNC_API_CLIENT_IMPL;
void grid_scroll(Integer grid, Integer top, Integer bot,
Integer left, Integer right, Integer rows, Integer cols)
FUNC_API_SINCE(5) FUNC_API_REMOTE_IMPL FUNC_API_COMPOSITOR_IMPL;
diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c
index 11bb1750e4..d1ca7662f6 100644
--- a/src/nvim/api/vim.c
+++ b/src/nvim/api/vim.c
@@ -22,6 +22,7 @@
#include "nvim/charset.h"
#include "nvim/context.h"
#include "nvim/decoration.h"
+#include "nvim/decoration_provider.h"
#include "nvim/edit.h"
#include "nvim/eval.h"
#include "nvim/eval/typval.h"
@@ -122,22 +123,24 @@ Dictionary nvim__get_hl_defs(Integer ns_id, Error *err)
abort();
}
-/// Set a highlight group.
-///
-/// @param ns_id number of namespace for this highlight. Use value 0
-/// to set a highlight group in the global (`:highlight`)
-/// namespace.
-/// @param name highlight group name, like ErrorMsg
-/// @param val highlight definition map, like |nvim_get_hl_by_name|.
-/// in addition the following keys are also recognized:
-/// `default`: don't override existing definition,
-/// like `hi default`
-/// `ctermfg`: sets foreground of cterm color
-/// `ctermbg`: sets background of cterm color
-/// `cterm` : cterm attribute map. sets attributed for
-/// cterm colors. similer to `hi cterm`
-/// Note: by default cterm attributes are
-/// same as attributes of gui color
+/// Sets a highlight group.
+///
+/// Note: Unlike the `:highlight` command which can update a highlight group,
+/// this function completely replaces the definition. For example:
+/// ``nvim_set_hl(0, 'Visual', {})`` will clear the highlight group 'Visual'.
+///
+/// @param ns_id Namespace id for this highlight |nvim_create_namespace()|.
+/// Use 0 to set a highlight group globally |:highlight|.
+/// @param name Highlight group name, e.g. "ErrorMsg"
+/// @param val Highlight definition map, like |synIDattr()|. In
+/// addition, the following keys are recognized:
+/// - default: Don't override existing definition |:hi-default|
+/// - ctermfg: Sets foreground of cterm color |highlight-ctermfg|
+/// - ctermbg: Sets background of cterm color |highlight-ctermbg|
+/// - cterm: cterm attribute map, like
+/// |highlight-args|.
+/// Note: Attributes default to those set for `gui`
+/// if not set.
/// @param[out] err Error details, if any
///
// TODO(bfredl): val should take update vs reset flag
@@ -216,7 +219,7 @@ void nvim_feedkeys(String keys, String mode, Boolean escape_ks)
bool execute = false;
bool dangerous = false;
- for (size_t i = 0; i < mode.size; ++i) {
+ for (size_t i = 0; i < mode.size; i++) {
switch (mode.data[i]) {
case 'n':
remap = false; break;
@@ -718,15 +721,15 @@ Object nvim_get_option_value(String name, Dict(option) *opts, Error *err)
break;
case 2:
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;
+ 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:
@@ -1135,6 +1138,7 @@ Integer nvim_open_term(Buffer buffer, DictionaryOf(LuaRef) opts, Error *err)
TerminalOptions topts;
Channel *chan = channel_alloc(kChannelStreamInternal);
chan->stream.internal.cb = cb;
+ chan->stream.internal.closed = false;
topts.data = chan;
// NB: overridden in terminal_check_size if a window is already
// displaying the buffer
@@ -1582,6 +1586,7 @@ ArrayOf(Dictionary) nvim_get_keymap(uint64_t channel_id, String mode)
/// nmap <nowait> <Space><NL> <Nop>
/// </pre>
///
+/// @param channel_id
/// @param mode Mode short-name (map command prefix: "n", "i", "v", "x", …)
/// or "!" for |:map!|, or empty string for |:map|.
/// @param lhs Left-hand-side |{lhs}| of the mapping.
@@ -1593,10 +1598,11 @@ ArrayOf(Dictionary) nvim_get_keymap(uint64_t channel_id, String mode)
/// 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)
+void nvim_set_keymap(uint64_t channel_id, String mode, String lhs, String rhs, Dict(keymap) *opts,
+ Error *err)
FUNC_API_SINCE(6)
{
- modify_keymap(-1, false, mode, lhs, rhs, opts, err);
+ modify_keymap(channel_id, -1, false, mode, lhs, rhs, opts, err);
}
/// Unmaps a global |mapping| for the given mode.
@@ -1604,10 +1610,10 @@ void nvim_set_keymap(String mode, String lhs, String rhs, Dict(keymap) *opts, Er
/// To unmap a buffer-local mapping, use |nvim_buf_del_keymap()|.
///
/// @see |nvim_set_keymap()|
-void nvim_del_keymap(String mode, String lhs, Error *err)
+void nvim_del_keymap(uint64_t channel_id, String mode, String lhs, Error *err)
FUNC_API_SINCE(6)
{
- nvim_buf_del_keymap(-1, mode, lhs, err);
+ nvim_buf_del_keymap(channel_id, -1, mode, lhs, err);
}
/// Gets a map of global (non-buffer-local) Ex commands.
@@ -1874,7 +1880,7 @@ static void write_msg(String message, bool to_err)
} \
line_buf[pos++] = message.data[i];
- ++no_wait_return;
+ no_wait_return++;
for (uint32_t i = 0; i < message.size; i++) {
if (got_int) {
break;
@@ -1885,7 +1891,7 @@ static void write_msg(String message, bool to_err)
PUSH_CHAR(i, out_pos, out_line_buf, msg);
}
}
- --no_wait_return;
+ no_wait_return--;
msg_end();
}
@@ -1951,7 +1957,7 @@ Dictionary nvim__stats(void)
Dictionary rv = ARRAY_DICT_INIT;
PUT(rv, "fsync", INTEGER_OBJ(g_stats.fsync));
PUT(rv, "redraw", INTEGER_OBJ(g_stats.redraw));
- PUT(rv, "lua_refcount", INTEGER_OBJ(nlua_refcount));
+ PUT(rv, "lua_refcount", INTEGER_OBJ(nlua_get_global_ref_count()));
return rv;
}
@@ -1985,14 +1991,13 @@ Array nvim_get_proc_children(Integer pid, Error *err)
size_t proc_count;
int rv = os_proc_children((int)pid, &proc_list, &proc_count);
- if (rv != 0) {
+ if (rv == 2) {
// syscall failed (possibly because of kernel options), try shelling out.
DLOG("fallback to vim._os_proc_children()");
Array a = ARRAY_DICT_INIT;
ADD(a, INTEGER_OBJ(pid));
- String s = cstr_to_string("return vim._os_proc_children(select(1, ...))");
+ String s = STATIC_CSTR_AS_STRING("return vim._os_proc_children(...)");
Object o = nlua_exec(s, a, err);
- api_free_string(s);
api_free_array(a);
if (o.type == kObjectTypeArray) {
rvobj = o.data.array;
@@ -2235,7 +2240,7 @@ Array nvim_get_mark(String name, Dictionary opts, Error *err)
/// - winid: (number) |window-ID| of the window to use as context for statusline.
/// - maxwidth: (number) Maximum width of statusline.
/// - fillchar: (string) Character to fill blank spaces in the statusline (see
-/// 'fillchars').
+/// 'fillchars'). Treated as single-width even if it isn't.
/// - highlights: (boolean) Return highlight information.
/// - use_tabline: (boolean) Evaluate tabline instead of statusline. When |TRUE|, {winid}
/// is ignored.
@@ -2271,11 +2276,12 @@ Dictionary nvim_eval_statusline(String str, Dict(eval_statusline) *opts, Error *
if (HAS_KEY(opts->fillchar)) {
if (opts->fillchar.type != kObjectTypeString || opts->fillchar.data.string.size == 0
- || char2cells(fillchar = utf_ptr2char((char_u *)opts->fillchar.data.string.data)) != 1
- || (size_t)utf_char2len(fillchar) != opts->fillchar.data.string.size) {
- api_set_error(err, kErrorTypeValidation, "fillchar must be a single-width character");
+ || ((size_t)utf_ptr2len((char_u *)opts->fillchar.data.string.data)
+ != opts->fillchar.data.string.size)) {
+ api_set_error(err, kErrorTypeValidation, "fillchar must be a single character");
return result;
}
+ fillchar = utf_ptr2char((char_u *)opts->fillchar.data.string.data);
}
if (HAS_KEY(opts->highlights)) {
@@ -2323,7 +2329,7 @@ Dictionary nvim_eval_statusline(String str, Dict(eval_statusline) *opts, Error *
maxwidth = (int)opts->maxwidth.data.integer;
} else {
- maxwidth = use_tabline ? Columns : wp->w_width;
+ maxwidth = (use_tabline || global_stl_height() > 0) ? Columns : wp->w_width;
}
char buf[MAXPATHL];
@@ -2411,6 +2417,8 @@ Dictionary nvim_eval_statusline(String str, Dict(eval_statusline) *opts, Error *
/// 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>|
+/// - fargs: (table) The args split by unescaped whitespace (when more than one
+/// argument is allowed), if any |<f-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>|
diff --git a/src/nvim/api/vimscript.c b/src/nvim/api/vimscript.c
index 640144b234..4123674fe7 100644
--- a/src/nvim/api/vimscript.c
+++ b/src/nvim/api/vimscript.c
@@ -37,7 +37,7 @@
/// @param[out] err Error details (Vim error), if any
/// @return Output (non-error, non-shell |:!|) if `output` is true,
/// else empty string.
-String nvim_exec(String src, Boolean output, Error *err)
+String nvim_exec(uint64_t channel_id, String src, Boolean output, Error *err)
FUNC_API_SINCE(7)
{
const int save_msg_silent = msg_silent;
@@ -52,11 +52,16 @@ String nvim_exec(String src, Boolean output, Error *err)
if (output) {
msg_silent++;
}
+
+ const sctx_T save_current_sctx = api_set_sctx(channel_id);
+
do_source_str(src.data, "nvim_exec()");
if (output) {
capture_ga = save_capture_ga;
msg_silent = save_msg_silent;
}
+
+ current_sctx = save_current_sctx;
try_end(err);
if (ERROR_SET(err)) {
diff --git a/src/nvim/api/win_config.c b/src/nvim/api/win_config.c
index ceb7f71423..d8ccd67bcd 100644
--- a/src/nvim/api/win_config.c
+++ b/src/nvim/api/win_config.c
@@ -131,7 +131,7 @@
/// An empty string can be used to turn off a specific border, for instance,
/// [ "", "", "", ">", "", "", "", "<" ]
/// will only make vertical borders but not horizontal ones.
-/// By default, `FloatBorder` highlight is used, which links to `VertSplit`
+/// By default, `FloatBorder` highlight is used, which links to `WinSeparator`
/// when not defined. It could also be specified by character:
/// [ {"+", "MyCorner"}, {"x", "MyBorder"} ].
/// - noautocmd: If true then no buffer-related autocommand events such as
diff --git a/src/nvim/api/window.c b/src/nvim/api/window.c
index fc7823a070..be43708604 100644
--- a/src/nvim/api/window.c
+++ b/src/nvim/api/window.c
@@ -71,6 +71,7 @@ ArrayOf(Integer, 2) nvim_win_get_cursor(Window window, Error *err)
}
/// Sets the (1,0)-indexed cursor position in the window. |api-indexing|
+/// This scrolls the window even if it is not the current one.
///
/// @param window Window handle, or 0 for current window
/// @param pos (row, col) tuple representing the new position
@@ -118,6 +119,8 @@ void nvim_win_set_cursor(Window window, ArrayOf(Integer, 2) pos, Error *err)
update_topline_win(win);
redraw_later(win, VALID);
+ redraw_for_cursorline(win);
+ win->w_redr_status = true;
}
/// Gets the window height
diff --git a/src/nvim/aucmd.c b/src/nvim/aucmd.c
deleted file mode 100644
index d7f73fa4a1..0000000000
--- a/src/nvim/aucmd.c
+++ /dev/null
@@ -1,123 +0,0 @@
-// This is an open source non-commercial project. Dear PVS-Studio, please check
-// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-
-#include "nvim/aucmd.h"
-#include "nvim/buffer.h"
-#include "nvim/eval.h"
-#include "nvim/ex_docmd.h"
-#include "nvim/ex_getln.h"
-#include "nvim/fileio.h"
-#include "nvim/main.h"
-#include "nvim/os/os.h"
-#include "nvim/ui.h"
-#include "nvim/vim.h"
-
-#ifdef INCLUDE_GENERATED_DECLARATIONS
-# include "aucmd.c.generated.h"
-#endif
-
-void do_autocmd_uienter(uint64_t chanid, bool attached)
-{
- static bool recursive = false;
-
- if (recursive) {
- return; // disallow recursion
- }
- recursive = true;
-
- save_v_event_T save_v_event;
- dict_T *dict = get_v_event(&save_v_event);
- assert(chanid < VARNUMBER_MAX);
- tv_dict_add_nr(dict, S_LEN("chan"), (varnumber_T)chanid);
- tv_dict_set_keys_readonly(dict);
- apply_autocmds(attached ? EVENT_UIENTER : EVENT_UILEAVE,
- NULL, NULL, false, curbuf);
- restore_v_event(dict, &save_v_event);
-
- recursive = false;
-}
-
-void init_default_autocmds(void)
-{
- // open terminals when opening files that start with term://
-#define PROTO "term://"
- do_cmdline_cmd("augroup nvim_terminal");
- do_cmdline_cmd("autocmd BufReadCmd " PROTO "* ++nested "
- "if !exists('b:term_title')|call termopen("
- // Capture the command string
- "matchstr(expand(\"<amatch>\"), "
- "'\\c\\m" PROTO "\\%(.\\{-}//\\%(\\d\\+:\\)\\?\\)\\?\\zs.*'), "
- // capture the working directory
- "{'cwd': expand(get(matchlist(expand(\"<amatch>\"), "
- "'\\c\\m" PROTO "\\(.\\{-}\\)//'), 1, ''))})"
- "|endif");
- do_cmdline_cmd("augroup END");
-#undef PROTO
-
- // limit syntax synchronization in the command window
- do_cmdline_cmd("augroup nvim_cmdwin");
- do_cmdline_cmd("autocmd! CmdwinEnter [:>] syntax sync minlines=1 maxlines=1");
- do_cmdline_cmd("augroup END");
-}
-
-static void focusgained_event(void **argv)
-{
- bool *gainedp = argv[0];
- do_autocmd_focusgained(*gainedp);
- xfree(gainedp);
-}
-void aucmd_schedule_focusgained(bool gained)
-{
- bool *gainedp = xmalloc(sizeof(*gainedp));
- *gainedp = gained;
- loop_schedule_deferred(&main_loop,
- event_create(focusgained_event, 1, gainedp));
-}
-
-static void do_autocmd_focusgained(bool gained)
-{
- static bool recursive = false;
- static Timestamp last_time = (time_t)0;
- bool need_redraw = false;
-
- if (recursive) {
- return; // disallow recursion
- }
- recursive = true;
- need_redraw |= apply_autocmds((gained ? EVENT_FOCUSGAINED : EVENT_FOCUSLOST),
- NULL, NULL, false, curbuf);
-
- // When activated: Check if any file was modified outside of Vim.
- // Only do this when not done within the last two seconds as:
- // 1. Some filesystems have modification time granularity in seconds. Fat32
- // has a granularity of 2 seconds.
- // 2. We could get multiple notifications in a row.
- if (gained && last_time + (Timestamp)2000 < os_now()) {
- need_redraw = check_timestamps(true);
- last_time = os_now();
- }
-
- if (need_redraw) {
- // Something was executed, make sure the cursor is put back where it
- // belongs.
- need_wait_return = false;
-
- if (State & CMDLINE) {
- redrawcmdline();
- } else if ((State & NORMAL) || (State & INSERT)) {
- if (must_redraw != 0) {
- update_screen(0);
- }
-
- setcursor();
- }
-
- ui_flush();
- }
-
- if (need_maketitle) {
- maketitle();
- }
-
- recursive = false;
-}
diff --git a/src/nvim/aucmd.h b/src/nvim/aucmd.h
deleted file mode 100644
index 9a4dd79a78..0000000000
--- a/src/nvim/aucmd.h
+++ /dev/null
@@ -1,11 +0,0 @@
-#ifndef NVIM_AUCMD_H
-#define NVIM_AUCMD_H
-
-#include <stdint.h>
-
-#ifdef INCLUDE_GENERATED_DECLARATIONS
-# include "aucmd.h.generated.h"
-#endif
-
-#endif // NVIM_AUCMD_H
-
diff --git a/src/nvim/autocmd.c b/src/nvim/autocmd.c
index 9117dde089..df336d8703 100644
--- a/src/nvim/autocmd.c
+++ b/src/nvim/autocmd.c
@@ -2,7 +2,9 @@
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
// autocmd.c: Autocommand related functions
+#include <signal.h>
+#include "lauxlib.h"
#include "nvim/api/private/helpers.h"
#include "nvim/ascii.h"
#include "nvim/autocmd.h"
@@ -13,8 +15,11 @@
#include "nvim/eval.h"
#include "nvim/eval/userfunc.h"
#include "nvim/ex_docmd.h"
+#include "nvim/ex_getln.h"
#include "nvim/fileio.h"
#include "nvim/getchar.h"
+#include "nvim/lua/executor.h"
+#include "nvim/map.h"
#include "nvim/option.h"
#include "nvim/os/input.h"
#include "nvim/regexp.h"
@@ -28,6 +33,14 @@
# include "autocmd.c.generated.h"
#endif
+// Naming Conventions:
+// - general autocmd behavior start with au_
+// - AutoCmd start with aucmd_
+// - Autocmd.exec stat with aucmd_exec
+// - AutoPat start with aupat_
+// - Groups start with augroup_
+// - Events start with event_
+
//
// The autocommands are stored in a list for each event.
// Autocommands for the same pattern, that are consecutive, are joined
@@ -67,21 +80,20 @@
// Code for automatic commands.
static AutoPatCmd *active_apc_list = NULL; // stack of active autocommands
-/// List of autocmd group names
-static garray_T augroups = { 0, 0, sizeof(char_u *), 10, NULL };
-#define AUGROUP_NAME(i) (((char **)augroups.ga_data)[i])
-#define BUFLOCAL_PAT_LEN 25
+// ID for associating autocmds created via nvim_create_autocmd
+// Used to delete autocmds from nvim_del_autocmd
+static int next_augroup_id = 1;
// use get_deleted_augroup() to get this
static const char *deleted_augroup = NULL;
-// The ID of the current group. Group 0 is the default one.
+// The ID of the current group.
static int current_augroup = AUGROUP_DEFAULT;
-static int au_need_clean = false; // need to delete marked patterns
+// Whether we need to delete marked patterns.
+// While deleting autocmds, they aren't actually remover, just marked.
+static int au_need_clean = false;
-static event_T last_event;
-static int last_group;
static int autocmd_blocked = 0; // block all autocmds
static bool autocmd_nested = false;
@@ -89,6 +101,31 @@ static bool autocmd_include_groups = false;
static char_u *old_termresponse = NULL;
+/// Iterates over all the AutoPats for a particular event
+#define FOR_ALL_AUPATS_IN_EVENT(event, ap) \
+ for (AutoPat *ap = first_autopat[event]; ap != NULL; ap = ap->next) // NOLINT
+
+// Map of autocmd group names and ids.
+// name -> ID
+// ID -> name
+static Map(String, int) map_augroup_name_to_id = MAP_INIT;
+static Map(int, String) map_augroup_id_to_name = MAP_INIT;
+
+static void augroup_map_del(int id, char *name)
+{
+ if (name != NULL) {
+ String key = map_key(String, int)(&map_augroup_name_to_id, cstr_as_string(name));
+ map_del(String, int)(&map_augroup_name_to_id, key);
+ api_free_string(key);
+ }
+ if (id > 0) {
+ String mapped = map_get(int, String)(&map_augroup_id_to_name, id);
+ api_free_string(mapped);
+ map_del(int, String)(&map_augroup_id_to_name, id);
+ }
+}
+
+
static inline const char *get_deleted_augroup(void) FUNC_ATTR_ALWAYS_INLINE
{
if (deleted_augroup == NULL) {
@@ -98,48 +135,28 @@ static inline const char *get_deleted_augroup(void) FUNC_ATTR_ALWAYS_INLINE
}
// Show the autocommands for one AutoPat.
-static void show_autocmd(AutoPat *ap, event_T event)
+static void aupat_show(AutoPat *ap)
{
- AutoCmd *ac;
-
// Check for "got_int" (here and at various places below), which is set
// when "q" has been hit for the "--more--" prompt
if (got_int) {
return;
}
+
// pattern has been removed
if (ap->pat == NULL) {
return;
}
- msg_putchar('\n');
- if (got_int) {
- return;
- }
- if (event != last_event || ap->group != last_group) {
- if (ap->group != AUGROUP_DEFAULT) {
- if (AUGROUP_NAME(ap->group) == NULL) {
- msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
- } else {
- msg_puts_attr(AUGROUP_NAME(ap->group), HL_ATTR(HLF_T));
- }
- msg_puts(" ");
- }
- msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
- last_event = event;
- last_group = ap->group;
- msg_putchar('\n');
- if (got_int) {
- return;
- }
- }
msg_col = 4;
msg_outtrans(ap->pat);
- for (ac = ap->cmds; ac != NULL; ac = ac->next) {
- if (ac->cmd == NULL) { // skip removed commands
+ for (AutoCmd *ac = ap->cmds; ac != NULL; ac = ac->next) {
+ // skip removed commands
+ if (aucmd_exec_is_deleted(ac->exec)) {
continue;
}
+
if (msg_col >= 14) {
msg_putchar('\n');
}
@@ -147,7 +164,7 @@ static void show_autocmd(AutoPat *ap, event_T event)
if (got_int) {
return;
}
- msg_outtrans(ac->cmd);
+ msg_outtrans((char_u *)aucmd_exec_to_string(ac, ac->exec));
if (p_verbose > 0) {
last_set_msg(ac->script_ctx);
}
@@ -163,27 +180,95 @@ static void show_autocmd(AutoPat *ap, event_T event)
}
}
+static void au_show_for_all_events(int group)
+{
+ FOR_ALL_AUEVENTS(event) {
+ au_show_for_event(group, event);
+ }
+}
+
+static void au_show_for_event(int group, event_T event)
+{
+ // Return early if there are no autocmds for this event
+ if (au_event_is_empty(event)) {
+ return;
+ }
+
+ int previous_group = AUGROUP_ERROR;
+ FOR_ALL_AUPATS_IN_EVENT(event, ap) {
+ if (group != AUGROUP_ALL && group != ap->group) {
+ continue;
+ }
+
+ char *name = augroup_name(ap->group);
+
+ msg_putchar('\n');
+ // When switching groups, we need to show the new group information.
+ if (ap->group != previous_group) {
+ // show the group name, if it's not the default group
+ if (ap->group != AUGROUP_DEFAULT) {
+ if (name == NULL) {
+ msg_puts_attr(get_deleted_augroup(), HL_ATTR(HLF_E));
+ } else {
+ msg_puts_attr(name, HL_ATTR(HLF_T));
+ }
+ msg_puts(" ");
+ }
+
+ // show the event name
+ msg_puts_attr(event_nr2name(event), HL_ATTR(HLF_T));
+ msg_putchar('\n');
+ }
+
+ if (got_int) {
+ return;
+ }
+
+ aupat_show(ap);
+
+ previous_group = ap->group;
+ }
+}
+
// Mark an autocommand handler for deletion.
-static void au_remove_pat(AutoPat *ap)
+static void aupat_del(AutoPat *ap)
{
XFREE_CLEAR(ap->pat);
ap->buflocal_nr = -1;
au_need_clean = true;
}
+void aupat_del_for_event_and_group(event_T event, int group)
+{
+ FOR_ALL_AUPATS_IN_EVENT(event, ap) {
+ if (ap->group == group) {
+ aupat_del(ap);
+ }
+ }
+
+ au_cleanup();
+}
+
// Mark all commands for a pattern for deletion.
-static void au_remove_cmds(AutoPat *ap)
+static void aupat_remove_cmds(AutoPat *ap)
{
for (AutoCmd *ac = ap->cmds; ac != NULL; ac = ac->next) {
- XFREE_CLEAR(ac->cmd);
+ aucmd_exec_free(&ac->exec);
+
+ if (ac->desc != NULL) {
+ XFREE_CLEAR(ac->desc);
+ }
}
au_need_clean = true;
}
// Delete one command from an autocmd pattern.
-static void au_del_cmd(AutoCmd *ac)
+static void aucmd_del(AutoCmd *ac)
{
- XFREE_CLEAR(ac->cmd);
+ aucmd_exec_free(&ac->exec);
+ if (ac->desc != NULL) {
+ XFREE_CLEAR(ac->desc);
+ }
au_need_clean = true;
}
@@ -191,19 +276,15 @@ static void au_del_cmd(AutoCmd *ac)
/// This is only done when not executing autocommands.
static void au_cleanup(void)
{
- AutoPat *ap, **prev_ap;
- event_T event;
-
if (autocmd_busy || !au_need_clean) {
return;
}
// Loop over all events.
- for (event = (event_T)0; (int)event < NUM_EVENTS;
- event = (event_T)((int)event + 1)) {
+ FOR_ALL_AUEVENTS(event) {
// Loop over all autocommand patterns.
- prev_ap = &(first_autopat[(int)event]);
- for (ap = *prev_ap; ap != NULL; ap = *prev_ap) {
+ AutoPat **prev_ap = &(first_autopat[(int)event]);
+ for (AutoPat *ap = *prev_ap; ap != NULL; ap = *prev_ap) {
bool has_cmd = false;
// Loop over all commands for this pattern.
@@ -211,9 +292,13 @@ static void au_cleanup(void)
for (AutoCmd *ac = *prev_ac; ac != NULL; ac = *prev_ac) {
// Remove the command if the pattern is to be deleted or when
// the command has been marked for deletion.
- if (ap->pat == NULL || ac->cmd == NULL) {
+ if (ap->pat == NULL || aucmd_exec_is_deleted(ac->exec)) {
*prev_ac = ac->next;
- xfree(ac->cmd);
+ aucmd_exec_free(&ac->exec);
+ if (ac->desc != NULL) {
+ XFREE_CLEAR(ac->desc);
+ }
+
xfree(ac);
} else {
has_cmd = true;
@@ -224,7 +309,7 @@ static void au_cleanup(void)
if (ap->pat != NULL && !has_cmd) {
// Pattern was not marked for deletion, but all of its commands were.
// So mark the pattern for deletion.
- au_remove_pat(ap);
+ aupat_del(ap);
}
// Remove the pattern if it has been marked for deletion.
@@ -250,28 +335,30 @@ static void au_cleanup(void)
au_need_clean = false;
}
+
+// Get the first AutoPat for a particular event.
+AutoPat *au_get_autopat_for_event(event_T event)
+{
+ return first_autopat[(int)event];
+}
+
// Called when buffer is freed, to remove/invalidate related buffer-local
// autocmds.
void aubuflocal_remove(buf_T *buf)
{
- AutoPat *ap;
- event_T event;
- AutoPatCmd *apc;
-
// invalidate currently executing autocommands
- for (apc = active_apc_list; apc; apc = apc->next) {
+ for (AutoPatCmd *apc = active_apc_list; apc; apc = apc->next) {
if (buf->b_fnum == apc->arg_bufnr) {
apc->arg_bufnr = 0;
}
}
// invalidate buflocals looping through events
- for (event = (event_T)0; (int)event < NUM_EVENTS;
- event = (event_T)((int)event + 1)) {
- // loop over all autocommand patterns
- for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next) {
+ FOR_ALL_AUEVENTS(event) {
+ FOR_ALL_AUPATS_IN_EVENT(event, ap) {
if (ap->buflocal_nr == buf->b_fnum) {
- au_remove_pat(ap);
+ aupat_del(ap);
+
if (p_verbose >= 6) {
verbose_enter();
smsg(_("auto-removing autocommand: %s <buffer=%d>"),
@@ -284,60 +371,74 @@ void aubuflocal_remove(buf_T *buf)
au_cleanup();
}
-// Add an autocmd group name.
+// Add an autocmd group name or return existing group matching name.
// Return its ID.
-static int au_new_group(char_u *name)
+int augroup_add(char *name)
{
- int i = au_find_group(name);
- if (i == AUGROUP_ERROR) { // the group doesn't exist yet, add it.
- // First try using a free entry.
- for (i = 0; i < augroups.ga_len; i++) {
- if (AUGROUP_NAME(i) == NULL) {
- break;
- }
- }
- if (i == augroups.ga_len) {
- ga_grow(&augroups, 1);
- }
+ assert(STRICMP(name, "end") != 0);
- AUGROUP_NAME(i) = xstrdup((char *)name);
- if (i == augroups.ga_len) {
- augroups.ga_len++;
- }
+ int existing_id = augroup_find(name);
+ if (existing_id > 0) {
+ assert(existing_id != AUGROUP_DELETED);
+ return existing_id;
+ }
+
+ if (existing_id == AUGROUP_DELETED) {
+ augroup_map_del(existing_id, name);
}
- return i;
+ int next_id = next_augroup_id++;
+ String name_key = cstr_to_string(name);
+ String name_val = cstr_to_string(name);
+ map_put(String, int)(&map_augroup_name_to_id, name_key, next_id);
+ map_put(int, String)(&map_augroup_id_to_name, next_id, name_val);
+
+ return next_id;
}
-static void au_del_group(char_u *name)
+/// Delete the augroup that matches name.
+/// @param stupid_legacy_mode bool: This parameter determines whether to run the augroup
+/// deletion in the same fashion as `:augroup! {name}` where if there are any remaining
+/// autocmds left in the augroup, it will change the name of the augroup to `--- DELETED ---`
+/// but leave the autocmds existing. These are _separate_ augroups, so if you do this for
+/// multiple augroups, you will have a bunch of `--- DELETED ---` augroups at the same time.
+/// There is no way, as far as I could tell, how to actually delete them at this point as a user
+///
+/// I did not consider this good behavior, so now when NOT in stupid_legacy_mode, we actually
+/// delete these groups and their commands, like you would expect (and don't leave hanging
+/// `--- DELETED ---` groups around)
+void augroup_del(char *name, bool stupid_legacy_mode)
{
- int i = au_find_group(name);
+ int i = augroup_find(name);
if (i == AUGROUP_ERROR) { // the group doesn't exist
semsg(_("E367: No such group: \"%s\""), name);
} else if (i == current_augroup) {
emsg(_("E936: Cannot delete the current group"));
} else {
- event_T event;
- AutoPat *ap;
- int in_use = false;
-
- for (event = (event_T)0; (int)event < NUM_EVENTS;
- event = (event_T)((int)event + 1)) {
- for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next) {
- if (ap->group == i && ap->pat != NULL) {
- give_warning((char_u *)_("W19: Deleting augroup that is still in use"), true);
- in_use = true;
- event = NUM_EVENTS;
- break;
+ if (stupid_legacy_mode) {
+ FOR_ALL_AUEVENTS(event) {
+ FOR_ALL_AUPATS_IN_EVENT(event, ap) {
+ if (ap->group == i && ap->pat != NULL) {
+ give_warning((char_u *)_("W19: Deleting augroup that is still in use"), true);
+ map_put(String, int)(&map_augroup_name_to_id, cstr_as_string(name), AUGROUP_DELETED);
+ augroup_map_del(ap->group, NULL);
+ return;
+ }
}
}
- }
- xfree(AUGROUP_NAME(i));
- if (in_use) {
- AUGROUP_NAME(i) = (char *)get_deleted_augroup();
} else {
- AUGROUP_NAME(i) = NULL;
+ FOR_ALL_AUEVENTS(event) {
+ FOR_ALL_AUPATS_IN_EVENT(event, ap) {
+ if (ap->group == i) {
+ aupat_del(ap);
+ }
+ }
+ }
}
+
+ // Remove the group because it's not currently in use.
+ augroup_map_del(i, name);
+ au_cleanup();
}
}
@@ -346,25 +447,67 @@ static void au_del_group(char_u *name)
/// @param name augroup name
///
/// @return the ID or AUGROUP_ERROR (< 0) for error.
-static int au_find_group(const char_u *name)
+int augroup_find(const char *name)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
- for (int i = 0; i < augroups.ga_len; i++) {
- if (AUGROUP_NAME(i) != NULL && AUGROUP_NAME(i) != get_deleted_augroup()
- && STRCMP(AUGROUP_NAME(i), name) == 0) {
- return i;
- }
+ int existing_id = map_get(String, int)(&map_augroup_name_to_id, cstr_as_string((char *)name));
+ if (existing_id == AUGROUP_DELETED) {
+ return existing_id;
+ }
+
+ if (existing_id > 0) {
+ return existing_id;
}
+
return AUGROUP_ERROR;
}
+/// Gets the name for a particular group.
+char *augroup_name(int group)
+{
+ assert(group != 0);
+
+ if (group == AUGROUP_DELETED) {
+ return (char *)get_deleted_augroup();
+ }
+
+ if (group == AUGROUP_ALL) {
+ group = current_augroup;
+ }
+
+ // next_augroup_id is the "source of truth" about what autocmds have existed
+ //
+ // The map_size is not the source of truth because groups can be removed from
+ // the map. When this happens, the map size is reduced. That's why this function
+ // relies on next_augroup_id instead.
+
+ // "END" is always considered the last augroup ID.
+ // Used for expand_get_event_name and expand_get_augroup_name
+ if (group == next_augroup_id) {
+ return "END";
+ }
+
+ // If it's larger than the largest group, then it doesn't have a name
+ if (group > next_augroup_id) {
+ return NULL;
+ }
+
+ String key = map_get(int, String)(&map_augroup_id_to_name, group);
+ if (key.data != NULL) {
+ return key.data;
+ }
+
+ // If it's not in the map anymore, then it must have been deleted.
+ return (char *)get_deleted_augroup();
+}
+
/// Return true if augroup "name" exists.
///
/// @param name augroup name
-bool au_has_group(const char_u *name)
+bool augroup_exists(const char *name)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
- return au_find_group(name) != AUGROUP_ERROR;
+ return augroup_find(name) > 0;
}
/// ":augroup {name}".
@@ -374,20 +517,27 @@ void do_augroup(char_u *arg, int del_group)
if (*arg == NUL) {
emsg(_(e_argreq));
} else {
- au_del_group(arg);
+ augroup_del((char *)arg, true);
}
} else if (STRICMP(arg, "end") == 0) { // ":aug end": back to group 0
current_augroup = AUGROUP_DEFAULT;
} else if (*arg) { // ":aug xxx": switch to group xxx
- current_augroup = au_new_group(arg);
+ current_augroup = augroup_add((char *)arg);
} else { // ":aug": list the group names
msg_start();
- for (int i = 0; i < augroups.ga_len; i++) {
- if (AUGROUP_NAME(i) != NULL) {
- msg_puts(AUGROUP_NAME(i));
- msg_puts(" ");
+
+ String name;
+ int value;
+ map_foreach(&map_augroup_name_to_id, name, value, {
+ if (value > 0) {
+ msg_puts(name.data);
+ } else {
+ msg_puts(augroup_name(value));
}
- }
+
+ msg_puts(" ");
+ });
+
msg_clr_eos();
msg_end();
}
@@ -396,35 +546,45 @@ void do_augroup(char_u *arg, int del_group)
#if defined(EXITFREE)
void free_all_autocmds(void)
{
- for (current_augroup = -1; current_augroup < augroups.ga_len;
- current_augroup++) {
- do_autocmd((char_u *)"", true);
- }
-
- for (int i = 0; i < augroups.ga_len; i++) {
- char *const s = ((char **)(augroups.ga_data))[i];
- if ((const char *)s != get_deleted_augroup()) {
- xfree(s);
+ FOR_ALL_AUEVENTS(event) {
+ FOR_ALL_AUPATS_IN_EVENT(event, ap) {
+ aupat_del(ap);
}
}
- ga_clear(&augroups);
+
+ au_need_clean = true;
+ au_cleanup();
+
+ // Delete the augroup_map, including free the data
+ String name;
+ int id;
+ map_foreach(&map_augroup_name_to_id, name, id, {
+ (void)id;
+ api_free_string(name);
+ })
+ map_destroy(String, int)(&map_augroup_name_to_id);
+
+ map_foreach(&map_augroup_id_to_name, id, name, {
+ (void)id;
+ api_free_string(name);
+ })
+ map_destroy(int, String)(&map_augroup_id_to_name);
}
#endif
// Return the event number for event name "start".
// Return NUM_EVENTS if the event name was not found.
// Return a pointer to the next event name in "end".
-static event_T event_name2nr(const char_u *start, char_u **end)
+event_T event_name2nr(const char_u *start, char_u **end)
{
const char_u *p;
int i;
- int len;
// the event name ends with end of line, '|', a blank or a comma
for (p = start; *p && !ascii_iswhite(*p) && *p != ',' && *p != '|'; p++) {
}
for (i = 0; event_names[i].name != NULL; i++) {
- len = (int)event_names[i].len;
+ int len = (int)event_names[i].len;
if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0) {
break;
}
@@ -444,12 +604,10 @@ static event_T event_name2nr(const char_u *start, char_u **end)
/// @param[in] event Event to return name for.
///
/// @return Event name, static string. Returns "Unknown" for unknown events.
-static const char *event_nr2name(event_T event)
+const char *event_nr2name(event_T event)
FUNC_ATTR_NONNULL_RET FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_CONST
{
- int i;
-
- for (i = 0; event_names[i].name != NULL; i++) {
+ for (int i = 0; event_names[i].name != NULL; i++) {
if (event_names[i].event == event) {
return event_names[i].name;
}
@@ -457,33 +615,6 @@ static const char *event_nr2name(event_T event)
return "Unknown";
}
-/// Scan over the events. "*" stands for all events.
-/// true when group name was found
-static char_u *find_end_event(char_u *arg, int have_group)
-{
- char_u *pat;
- char_u *p;
-
- if (*arg == '*') {
- if (arg[1] && !ascii_iswhite(arg[1])) {
- semsg(_("E215: Illegal character after *: %s"), arg);
- return NULL;
- }
- pat = arg + 1;
- } else {
- for (pat = arg; *pat && *pat != '|' && !ascii_iswhite(*pat); pat = p) {
- if ((int)event_name2nr(pat, &p) >= NUM_EVENTS) {
- if (have_group) {
- semsg(_("E216: No such event: %s"), pat);
- } else {
- semsg(_("E216: No such group or event: %s"), pat);
- }
- return NULL;
- }
- }
- }
- return pat;
-}
/// Return true if "event" is included in 'eventignore'.
///
@@ -529,11 +660,8 @@ int check_ei(void)
// Returns the old value of 'eventignore' in allocated memory.
char_u *au_event_disable(char *what)
{
- char_u *new_ei;
- char_u *save_ei;
-
- save_ei = vim_strsave(p_ei);
- new_ei = vim_strnsave(p_ei, STRLEN(p_ei) + STRLEN(what));
+ char_u *save_ei = vim_strsave(p_ei);
+ char_u *new_ei = vim_strnsave(p_ei, STRLEN(p_ei) + STRLEN(what));
if (*what == ',' && *p_ei == NUL) {
STRCPY(new_ei, what + 1);
} else {
@@ -588,11 +716,10 @@ void au_event_restore(char_u *old_ei)
void do_autocmd(char_u *arg_in, int forceit)
{
char_u *arg = arg_in;
- char_u *pat;
char_u *envpat = NULL;
char_u *cmd;
int need_free = false;
- int nested = false;
+ bool nested = false;
bool once = false;
int group;
@@ -601,12 +728,12 @@ void do_autocmd(char_u *arg_in, int forceit)
group = AUGROUP_ALL; // no argument, use all groups
} else {
// Check for a legal group name. If not, use AUGROUP_ALL.
- group = au_get_grouparg(&arg);
+ group = arg_augroup_get(&arg);
}
// Scan over the events.
// If we find an illegal name, return here, don't do anything.
- pat = find_end_event(arg, group != AUGROUP_ALL);
+ char_u *pat = arg_event_skip(arg, group != AUGROUP_ALL);
if (pat == NULL) {
return;
}
@@ -643,37 +770,22 @@ void do_autocmd(char_u *arg_in, int forceit)
}
cmd = skipwhite(cmd);
+
+ bool invalid_flags = false;
for (size_t i = 0; i < 2; i++) {
if (*cmd != NUL) {
- // Check for "++once" flag.
- if (STRNCMP(cmd, "++once", 6) == 0 && ascii_iswhite(cmd[6])) {
- if (once) {
- semsg(_(e_duparg2), "++once");
- }
- once = true;
- cmd = skipwhite(cmd + 6);
- }
-
- // Check for "++nested" flag.
- if ((STRNCMP(cmd, "++nested", 8) == 0 && ascii_iswhite(cmd[8]))) {
- if (nested) {
- semsg(_(e_duparg2), "++nested");
- }
- nested = true;
- cmd = skipwhite(cmd + 8);
- }
+ invalid_flags |= arg_autocmd_flag_get(&once, &cmd, "++once", 6);
+ invalid_flags |= arg_autocmd_flag_get(&nested, &cmd, "++nested", 8);
- // Check for the old (deprecated) "nested" flag.
- if (STRNCMP(cmd, "nested", 6) == 0 && ascii_iswhite(cmd[6])) {
- if (nested) {
- semsg(_(e_duparg2), "nested");
- }
- nested = true;
- cmd = skipwhite(cmd + 6);
- }
+ // Check the deprecated "nested" flag.
+ invalid_flags |= arg_autocmd_flag_get(&nested, &cmd, "nested", 6);
}
}
+ if (invalid_flags) {
+ return;
+ }
+
// Find the start of the commands.
// Expand <sfile> in it.
if (*cmd != NUL) {
@@ -685,36 +797,37 @@ void do_autocmd(char_u *arg_in, int forceit)
}
}
+ bool is_showing = !forceit && *cmd == NUL;
+
// Print header when showing autocommands.
- if (!forceit && *cmd == NUL) {
+ if (is_showing) {
// Highlight title
msg_puts_title(_("\n--- Autocommands ---"));
- }
- // Loop over the events.
- last_event = (event_T)-1; // for listing the event name
- last_group = AUGROUP_ERROR; // for listing the group name
- if (*arg == '*' || *arg == NUL || *arg == '|') {
- if (!forceit && *cmd != NUL) {
- emsg(_(e_cannot_define_autocommands_for_all_events));
+ if (*arg == '*' || *arg == '|' || *arg == NUL) {
+ au_show_for_all_events(group);
} else {
- for (event_T event = (event_T)0; event < NUM_EVENTS;
- event = (event_T)(event + 1)) {
+ event_T event = event_name2nr(arg, &arg);
+ assert(event < NUM_EVENTS);
+ au_show_for_event(group, event);
+ }
+ } else {
+ if (*arg == '*' || *arg == NUL || *arg == '|') {
+ if (!forceit && *cmd != NUL) {
+ emsg(_(e_cannot_define_autocommands_for_all_events));
+ } else {
+ do_all_autocmd_events(pat, once, nested, cmd, forceit, group);
+ }
+ } else {
+ while (*arg && *arg != '|' && !ascii_iswhite(*arg)) {
+ event_T event = event_name2nr(arg, &arg);
+ assert(event < NUM_EVENTS);
if (do_autocmd_event(event, pat, once, nested, cmd, forceit, group)
== FAIL) {
break;
}
}
}
- } else {
- while (*arg && *arg != '|' && !ascii_iswhite(*arg)) {
- event_T event = event_name2nr(arg, &arg);
- assert(event < NUM_EVENTS);
- if (do_autocmd_event(event, pat, once, nested, cmd, forceit, group)
- == FAIL) {
- break;
- }
- }
}
if (need_free) {
@@ -723,30 +836,14 @@ void do_autocmd(char_u *arg_in, int forceit)
xfree(envpat);
}
-// Find the group ID in a ":autocmd" or ":doautocmd" argument.
-// The "argp" argument is advanced to the following argument.
-//
-// Returns the group ID or AUGROUP_ALL.
-static int au_get_grouparg(char_u **argp)
+void do_all_autocmd_events(char_u *pat, bool once, int nested, char_u *cmd, bool delete, int group)
{
- char_u *group_name;
- char_u *p;
- char_u *arg = *argp;
- int group = AUGROUP_ALL;
-
- for (p = arg; *p && !ascii_iswhite(*p) && *p != '|'; p++) {
- }
- if (p > arg) {
- group_name = vim_strnsave(arg, (size_t)(p - arg));
- group = au_find_group(group_name);
- if (group == AUGROUP_ERROR) {
- group = AUGROUP_ALL; // no match, use all groups
- } else {
- *argp = skipwhite(p); // match, skip over group name
+ FOR_ALL_AUEVENTS(event) {
+ if (do_autocmd_event(event, pat, once, nested, cmd, delete, group)
+ == FAIL) {
+ return;
}
- xfree(group_name);
}
- return group;
}
// do_autocmd() for one event.
@@ -756,232 +853,302 @@ static int au_get_grouparg(char_u **argp)
// If *cmd == NUL: show entries.
// If forceit == true: delete entries.
// If group is not AUGROUP_ALL: only use this group.
-static int do_autocmd_event(event_T event, char_u *pat, bool once, int nested, char_u *cmd,
- int forceit, int group)
+int do_autocmd_event(event_T event, char_u *pat, bool once, int nested, char_u *cmd, bool delete,
+ int group)
+ FUNC_ATTR_NONNULL_ALL
{
+ // Cannot be used to show all patterns. See au_show_for_event or au_show_for_all_events
+ assert(*pat != NUL || delete);
+
AutoPat *ap;
AutoPat **prev_ap;
- AutoCmd *ac;
- AutoCmd **prev_ac;
- int brace_level;
- char_u *endpat;
int findgroup;
- int allgroups;
- int patlen;
- int is_buflocal;
int buflocal_nr;
char_u buflocal_pat[BUFLOCAL_PAT_LEN]; // for "<buffer=X>"
+ bool is_adding_cmd = *cmd != NUL;
+
if (group == AUGROUP_ALL) {
findgroup = current_augroup;
} else {
findgroup = group;
}
- allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
- // Show or delete all patterns for an event.
- if (*pat == NUL) {
- for (ap = first_autopat[event]; ap != NULL; ap = ap->next) {
- if (forceit) { // delete the AutoPat, if it's in the current group
- if (ap->group == findgroup) {
- au_remove_pat(ap);
- }
- } else if (group == AUGROUP_ALL || ap->group == group) {
- show_autocmd(ap, event);
- }
- }
+ // Delete all aupat for an event.
+ if (*pat == NUL && delete) {
+ aupat_del_for_event_and_group(event, findgroup);
+ return OK;
}
// Loop through all the specified patterns.
- for (; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat)) {
- // Find end of the pattern.
- // Watch out for a comma in braces, like "*.\{obj,o\}".
- endpat = pat;
- // ignore single comma
- if (*endpat == ',') {
- continue;
- }
- brace_level = 0;
- for (; *endpat && (*endpat != ',' || brace_level || endpat[-1] == '\\');
- endpat++) {
- if (*endpat == '{') {
- brace_level++;
- } else if (*endpat == '}') {
- brace_level--;
- }
- }
- patlen = (int)(endpat - pat);
-
- // detect special <buflocal[=X]> buffer-local patterns
- is_buflocal = false;
- buflocal_nr = 0;
-
- if (patlen >= 8 && STRNCMP(pat, "<buffer", 7) == 0
- && pat[patlen - 1] == '>') {
- // "<buffer...>": Error will be printed only for addition.
- // printing and removing will proceed silently.
- is_buflocal = true;
- if (patlen == 8) {
- // "<buffer>"
- buflocal_nr = curbuf->b_fnum;
- } else if (patlen > 9 && pat[7] == '=') {
- if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0) {
- // "<buffer=abuf>"
- buflocal_nr = autocmd_bufnr;
- } else if (skipdigits(pat + 8) == pat + patlen - 1) {
- // "<buffer=123>"
- buflocal_nr = atoi((char *)pat + 8);
- }
- }
- }
+ int patlen = (int)aucmd_pattern_length(pat);
+ while (patlen) {
+ // detect special <buffer[=X]> buffer-local patterns
+ int is_buflocal = aupat_is_buflocal(pat, patlen);
if (is_buflocal) {
+ buflocal_nr = aupat_get_buflocal_nr(pat, patlen);
+
// normalize pat into standard "<buffer>#N" form
- snprintf((char *)buflocal_pat,
- BUFLOCAL_PAT_LEN,
- "<buffer=%d>",
- buflocal_nr);
+ aupat_normalize_buflocal_pat(buflocal_pat, pat, patlen, buflocal_nr);
- pat = buflocal_pat; // can modify pat and patlen
- patlen = (int)STRLEN(buflocal_pat); // but not endpat
+ pat = buflocal_pat;
+ patlen = (int)STRLEN(buflocal_pat);
}
- // Find AutoPat entries with this pattern. When adding a command it
- // always goes at or after the last one, so start at the end.
- if (!forceit && *cmd != NUL && last_autopat[(int)event] != NULL) {
- prev_ap = &last_autopat[(int)event];
- } else {
+ if (delete) {
+ assert(*pat != NUL);
+
+ // Find AutoPat entries with this pattern.
+ // always goes at or after the last one, so start at the end.
prev_ap = &first_autopat[(int)event];
- }
- while ((ap = *prev_ap) != NULL) {
- if (ap->pat != NULL) {
- // Accept a pattern when:
- // - a group was specified and it's that group, or a group was
- // not specified and it's the current group, or a group was
- // not specified and we are listing
- // - the length of the pattern matches
- // - the pattern matches.
- // For <buffer[=X]>, this condition works because we normalize
- // all buffer-local patterns.
- if ((allgroups || ap->group == findgroup) && ap->patlen == patlen
- && STRNCMP(pat, ap->pat, patlen) == 0) {
- // Remove existing autocommands.
- // If adding any new autocmd's for this AutoPat, don't
- // delete the pattern from the autopat list, append to
- // this list.
- if (forceit) {
- if (*cmd != NUL && ap->next == NULL) {
- au_remove_cmds(ap);
+ while ((ap = *prev_ap) != NULL) {
+ if (ap->pat != NULL) {
+ // Accept a pattern when:
+ // - a group was specified and it's that group
+ // - the length of the pattern matches
+ // - the pattern matches.
+ // For <buffer[=X]>, this condition works because we normalize
+ // all buffer-local patterns.
+ if (ap->group == findgroup
+ && ap->patlen == patlen
+ && STRNCMP(pat, ap->pat, patlen) == 0) {
+ // Remove existing autocommands.
+ // If adding any new autocmd's for this AutoPat, don't
+ // delete the pattern from the autopat list, append to
+ // this list.
+ if (is_adding_cmd && ap->next == NULL) {
+ aupat_remove_cmds(ap);
break;
}
- au_remove_pat(ap);
- } else if (*cmd == NUL) {
- // Show autocmd's for this autopat, or buflocals <buffer=X>
- show_autocmd(ap, event);
- } else if (ap->next == NULL) {
- // Add autocmd to this autopat, if it's the last one.
- break;
+ aupat_del(ap);
}
}
+ prev_ap = &ap->next;
}
- prev_ap = &ap->next;
}
- // Add a new command.
- if (*cmd != NUL) {
- // If the pattern we want to add a command to does appear at the
- // end of the list (or not is not in the list at all), add the
- // pattern at the end of the list.
- if (ap == NULL) {
- // refuse to add buffer-local ap if buffer number is invalid
- if (is_buflocal
- && (buflocal_nr == 0 || buflist_findnr(buflocal_nr) == NULL)) {
- semsg(_("E680: <buffer=%d>: invalid buffer number "), buflocal_nr);
- return FAIL;
- }
+ if (is_adding_cmd) {
+ AucmdExecutable exec = AUCMD_EXECUTABLE_INIT;
+ exec.type = CALLABLE_EX;
+ exec.callable.cmd = cmd;
+ autocmd_register(0, event, pat, patlen, group, once, nested, NULL, exec);
+ }
- ap = xmalloc(sizeof(AutoPat));
- ap->pat = vim_strnsave(pat, (size_t)patlen);
- ap->patlen = patlen;
+ pat = aucmd_next_pattern(pat, (size_t)patlen);
+ patlen = (int)aucmd_pattern_length(pat);
+ }
- if (is_buflocal) {
- ap->buflocal_nr = buflocal_nr;
- ap->reg_prog = NULL;
- } else {
- char_u *reg_pat;
+ au_cleanup(); // may really delete removed patterns/commands now
+ return OK;
+}
- ap->buflocal_nr = 0;
- reg_pat = file_pat_to_reg_pat(pat, endpat, &ap->allow_dirs, true);
- if (reg_pat != NULL) {
- ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
- }
- xfree(reg_pat);
- if (reg_pat == NULL || ap->reg_prog == NULL) {
- xfree(ap->pat);
- xfree(ap);
- return FAIL;
- }
- }
+int autocmd_register(int64_t id, event_T event, char_u *pat, int patlen, int group, bool once,
+ bool nested, char *desc, AucmdExecutable aucmd)
+{
+ // 0 is not a valid group.
+ assert(group != 0);
- // need to initialize last_mode for the first ModeChanged autocmd
- if (event == EVENT_MODECHANGED && !has_event(EVENT_MODECHANGED)) {
- xfree(last_mode);
- last_mode = get_mode();
- }
+ AutoPat *ap;
+ AutoPat **prev_ap;
+ AutoCmd *ac;
+ int findgroup;
+ char_u buflocal_pat[BUFLOCAL_PAT_LEN]; // for "<buffer=X>"
- // 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;
- }
+ if (patlen > (int)STRLEN(pat)) {
+ return FAIL;
+ }
- ap->cmds = NULL;
- *prev_ap = ap;
- last_autopat[(int)event] = ap;
- ap->next = NULL;
- if (group == AUGROUP_ALL) {
- ap->group = current_augroup;
- } else {
- ap->group = group;
+ if (group == AUGROUP_ALL) {
+ findgroup = current_augroup;
+ } else {
+ findgroup = group;
+ }
+
+
+ // detect special <buffer[=X]> buffer-local patterns
+ int is_buflocal = aupat_is_buflocal(pat, patlen);
+ int buflocal_nr = 0;
+
+ if (is_buflocal) {
+ buflocal_nr = aupat_get_buflocal_nr(pat, patlen);
+
+ // normalize pat into standard "<buffer>#N" form
+ aupat_normalize_buflocal_pat(buflocal_pat, pat, patlen, buflocal_nr);
+
+ pat = buflocal_pat;
+ patlen = (int)STRLEN(buflocal_pat);
+ }
+
+ if (last_autopat[(int)event] != NULL) {
+ prev_ap = &last_autopat[(int)event];
+ } else {
+ prev_ap = &first_autopat[(int)event];
+ }
+
+ while ((ap = *prev_ap) != NULL) {
+ if (ap->pat != NULL) {
+ // Accept a pattern when:
+ // - a group was specified and it's that group
+ // - the length of the pattern matches
+ // - the pattern matches.
+ // For <buffer[=X]>, this condition works because we normalize
+ // all buffer-local patterns.
+ if (ap->group == findgroup
+ && ap->patlen == patlen
+ && STRNCMP(pat, ap->pat, patlen) == 0) {
+ if (ap->next == NULL) {
+ // Add autocmd to this autopat, if it's the last one.
+ break;
}
}
+ }
+ prev_ap = &ap->next;
+ }
+
+ // If the pattern we want to add a command to does appear at the
+ // end of the list (or not is not in the list at all), add the
+ // pattern at the end of the list.
+ if (ap == NULL) {
+ // refuse to add buffer-local ap if buffer number is invalid
+ if (is_buflocal
+ && (buflocal_nr == 0 || buflist_findnr(buflocal_nr) == NULL)) {
+ semsg(_("E680: <buffer=%d>: invalid buffer number "), buflocal_nr);
+ return FAIL;
+ }
- // Add the autocmd at the end of the AutoCmd list.
- prev_ac = &(ap->cmds);
- while ((ac = *prev_ac) != NULL) {
- prev_ac = &ac->next;
+ ap = xmalloc(sizeof(AutoPat));
+ ap->pat = vim_strnsave(pat, (size_t)patlen);
+ ap->patlen = patlen;
+
+ if (is_buflocal) {
+ ap->buflocal_nr = buflocal_nr;
+ ap->reg_prog = NULL;
+ } else {
+ char_u *reg_pat;
+
+ ap->buflocal_nr = 0;
+ reg_pat = file_pat_to_reg_pat(pat, pat + patlen, &ap->allow_dirs, true);
+ if (reg_pat != NULL) {
+ ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
}
- ac = xmalloc(sizeof(AutoCmd));
- ac->cmd = vim_strsave(cmd);
- ac->script_ctx = current_sctx;
- ac->script_ctx.sc_lnum += sourcing_lnum;
- ac->next = NULL;
- *prev_ac = ac;
- ac->once = once;
- ac->nested = nested;
+ xfree(reg_pat);
+ if (reg_pat == NULL || ap->reg_prog == NULL) {
+ xfree(ap->pat);
+ xfree(ap);
+ return FAIL;
+ }
+ }
+
+ // need to initialize last_mode for the first ModeChanged autocmd
+ if (event == EVENT_MODECHANGED && !has_event(EVENT_MODECHANGED)) {
+ xfree(last_mode);
+ 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;
+ ap->next = NULL;
+ if (group == AUGROUP_ALL) {
+ ap->group = current_augroup;
+ } else {
+ ap->group = group;
}
}
- au_cleanup(); // may really delete removed patterns/commands now
+ // Add the autocmd at the end of the AutoCmd list.
+ AutoCmd **prev_ac = &(ap->cmds);
+ while ((ac = *prev_ac) != NULL) {
+ prev_ac = &ac->next;
+ }
+
+ ac = xmalloc(sizeof(AutoCmd));
+ *prev_ac = ac;
+
+ ac->id = id;
+ ac->exec = aucmd_exec_copy(aucmd);
+ ac->script_ctx = current_sctx;
+ ac->script_ctx.sc_lnum += sourcing_lnum;
+ nlua_set_sctx(&ac->script_ctx);
+ ac->next = NULL;
+ ac->once = once;
+ ac->nested = nested;
+ ac->desc = NULL;
+
+ // TODO(tjdevries): What to do about :autocmd and where/how to show lua stuffs there.
+ // perhaps: <lua>DESCRIPTION or similar
+ if (desc != NULL) {
+ ac->desc = xstrdup(desc);
+ } else {
+ ac->desc = aucmd_exec_default_desc(aucmd);
+ }
+
return OK;
}
+size_t aucmd_pattern_length(char_u *pat)
+{
+ if (*pat == NUL) {
+ return 0;
+ }
+
+ char_u *endpat;
+
+ for (; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat)) {
+ // Find end of the pattern.
+ // Watch out for a comma in braces, like "*.\{obj,o\}".
+ endpat = pat;
+ // ignore single comma
+ if (*endpat == ',') {
+ continue;
+ }
+ int brace_level = 0;
+ for (; *endpat && (*endpat != ',' || brace_level || endpat[-1] == '\\');
+ endpat++) {
+ if (*endpat == '{') {
+ brace_level++;
+ } else if (*endpat == '}') {
+ brace_level--;
+ }
+ }
+
+ return (size_t)(endpat - pat);
+ }
+
+ return STRLEN(pat);
+}
+
+char_u *aucmd_next_pattern(char_u *pat, size_t patlen)
+{
+ pat = pat + patlen;
+ if (*pat == ',') {
+ pat = pat + 1;
+ }
+
+ return pat;
+}
+
/// Implementation of ":doautocmd [group] event [fname]".
/// Return OK for success, FAIL for failure;
///
/// @param do_msg give message for no matching autocmds?
int do_doautocmd(char_u *arg, bool do_msg, bool *did_something)
{
- char_u *fname;
int nothing_done = true;
- int group;
if (did_something != NULL) {
*did_something = false;
}
// Check for a legal group name. If not, use AUGROUP_ALL.
- group = au_get_grouparg(&arg);
+ int group = arg_augroup_get(&arg);
if (*arg == '*') {
emsg(_("E217: Can't execute autocommands for ALL events"));
@@ -990,7 +1157,7 @@ int do_doautocmd(char_u *arg, bool do_msg, bool *did_something)
// Scan over the events.
// If we find an illegal name, return here, don't do anything.
- fname = find_end_event(arg, group != AUGROUP_ALL);
+ char_u *fname = arg_event_skip(arg, group != AUGROUP_ALL);
if (fname == NULL) {
return FAIL;
}
@@ -1354,11 +1521,9 @@ bool has_cursorhold(void) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
/// Return true if the CursorHold/CursorHoldI event can be triggered.
bool trigger_cursorhold(void) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
- int state;
-
if (!did_cursorhold && has_cursorhold() && reg_recording == 0
&& typebuf.tb_len == 0 && !ins_compl_active()) {
- state = get_real_state();
+ int state = get_real_state();
if (state == NORMAL_BUSY || (state & INSERT) != 0) {
return true;
}
@@ -1378,23 +1543,12 @@ bool trigger_cursorhold(void) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
/// @param eap Ex command arguments
///
/// @return true if some commands were executed.
-static bool apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, bool force,
- int group, buf_T *buf, exarg_T *eap)
+bool apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io, bool force, int group,
+ buf_T *buf, exarg_T *eap)
{
char_u *sfname = NULL; // short file name
- char_u *tail;
- bool save_changed;
- buf_T *old_curbuf;
bool retval = false;
- char_u *save_sourcing_name;
- linenr_T save_sourcing_lnum;
- char_u *save_autocmd_fname;
- int save_autocmd_bufnr;
- char_u *save_autocmd_match;
- int save_autocmd_busy;
- int save_autocmd_nested;
static int nesting = 0;
- AutoPatCmd patcmd;
AutoPat *ap;
char_u *save_cmdarg;
long save_cmdbang;
@@ -1402,7 +1556,7 @@ static bool apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io,
proftime_T wait_time;
bool did_save_redobuff = false;
save_redo_T save_redo;
- const bool save_KeyTyped = KeyTyped;
+ const bool save_KeyTyped = KeyTyped; // NOLINT
// Quickly return if there are no autocommands for this event or
// autocommands are blocked.
@@ -1451,13 +1605,13 @@ static bool apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io,
}
// Save the autocmd_* variables and info about the current buffer.
- save_autocmd_fname = autocmd_fname;
- save_autocmd_bufnr = autocmd_bufnr;
- save_autocmd_match = autocmd_match;
- save_autocmd_busy = autocmd_busy;
- save_autocmd_nested = autocmd_nested;
- save_changed = curbuf->b_changed;
- old_curbuf = curbuf;
+ char_u *save_autocmd_fname = autocmd_fname;
+ int save_autocmd_bufnr = autocmd_bufnr;
+ char_u *save_autocmd_match = autocmd_match;
+ int save_autocmd_busy = autocmd_busy;
+ int save_autocmd_nested = autocmd_nested;
+ bool save_changed = curbuf->b_changed;
+ buf_T *old_curbuf = curbuf;
// Set the file name to be used for <afile>.
// Make a copy to avoid that changing a buffer name or directory makes it
@@ -1550,9 +1704,9 @@ static bool apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io,
// Don't redraw while doing autocommands.
RedrawingDisabled++;
- save_sourcing_name = sourcing_name;
+ char_u *save_sourcing_name = sourcing_name;
sourcing_name = NULL; // don't free this one
- save_sourcing_lnum = sourcing_lnum;
+ linenr_T save_sourcing_lnum = sourcing_lnum;
sourcing_lnum = 0; // no line number here
const sctx_T save_current_sctx = current_sctx;
@@ -1585,9 +1739,10 @@ static bool apply_autocmds_group(event_T event, char_u *fname, char_u *fname_io,
did_filetype = true;
}
- tail = path_tail(fname);
+ char_u *tail = path_tail(fname);
// Find first autocommand that matches
+ AutoPatCmd patcmd;
patcmd.curpat = first_autopat[(int)event];
patcmd.nextcmd = NULL;
patcmd.group = group;
@@ -1814,9 +1969,13 @@ void auto_next_pat(AutoPatCmd *apc, int stop_at_last)
/// @return allocated string, or NULL for end of autocommands.
char_u *getnextac(int c, void *cookie, int indent, bool do_concat)
{
+ // These arguments are required for do_cmdline.
+ (void)c;
+ (void)indent;
+ (void)do_concat;
+
AutoPatCmd *acp = (AutoPatCmd *)cookie;
char_u *retval;
- AutoCmd *ac;
// Can be called again after returning the last line.
if (acp->curpat == NULL) {
@@ -1826,7 +1985,8 @@ char_u *getnextac(int c, void *cookie, int indent, bool do_concat)
// repeat until we find an autocommand to execute
for (;;) {
// skip removed commands
- while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL) {
+ while (acp->nextcmd != NULL
+ && aucmd_exec_is_deleted(acp->nextcmd->exec)) {
if (acp->nextcmd->last) {
acp->nextcmd = NULL;
} else {
@@ -1852,18 +2012,38 @@ char_u *getnextac(int c, void *cookie, int indent, bool do_concat)
}
}
- ac = acp->nextcmd;
+ AutoCmd *ac = acp->nextcmd;
if (p_verbose >= 9) {
verbose_enter_scroll();
- smsg(_("autocommand %s"), ac->cmd);
+ smsg(_("autocommand %s"), aucmd_exec_to_string(ac, ac->exec));
msg_puts("\n"); // don't overwrite this either
verbose_leave_scroll();
}
- retval = vim_strsave(ac->cmd);
+
+ if (ac->exec.type == CALLABLE_CB) {
+ typval_T argsin = TV_INITIAL_VALUE;
+ typval_T rettv = TV_INITIAL_VALUE;
+ callback_call(&ac->exec.callable.cb, 0, &argsin, &rettv);
+
+ // TODO(tjdevries):
+ //
+ // Major Hack Alert:
+ // We just return "not-null" and continue going.
+ // This would be a good candidate for a refactor. You would need to refactor:
+ // 1. do_cmdline to accept something besides a string
+ // OR
+ // 2. make where we call do_cmdline for autocmds not have to return anything,
+ // and instead we loop over all the matches and just execute one-by-one.
+ // However, my expectation would be that could be expensive.
+ retval = vim_strsave((char_u *)"");
+ } else {
+ retval = vim_strsave(ac->exec.callable.cmd);
+ }
+
// Remove one-shot ("once") autocmd in anticipation of its execution.
if (ac->once) {
- au_del_cmd(ac);
+ aucmd_del(ac);
}
autocmd_nested = ac->nested;
current_sctx = ac->script_ctx;
@@ -1885,12 +2065,10 @@ char_u *getnextac(int c, void *cookie, int indent, bool do_concat)
/// @param buf buffer the file is open in
bool has_autocmd(event_T event, char_u *sfname, buf_T *buf) FUNC_ATTR_WARN_UNUSED_RESULT
{
- AutoPat *ap;
- char_u *fname;
char_u *tail = path_tail(sfname);
bool retval = false;
- fname = (char_u *)FullName_save((char *)sfname, false);
+ char_u *fname = (char_u *)FullName_save((char *)sfname, false);
if (fname == NULL) {
return false;
}
@@ -1903,7 +2081,7 @@ bool has_autocmd(event_T event, char_u *sfname, buf_T *buf) FUNC_ATTR_WARN_UNUSE
forward_slash(fname);
#endif
- for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next) {
+ for (AutoPat *ap = first_autopat[(int)event]; ap != NULL; ap = ap->next) {
if (ap->pat != NULL && ap->cmds != NULL
&& (ap->buflocal_nr == 0
? match_file_pat(NULL,
@@ -1928,31 +2106,21 @@ bool has_autocmd(event_T event, char_u *sfname, buf_T *buf) FUNC_ATTR_WARN_UNUSE
// Function given to ExpandGeneric() to obtain the list of autocommand group
// names.
-char_u *get_augroup_name(expand_T *xp, int idx)
+char_u *expand_get_augroup_name(expand_T *xp, int idx)
{
- if (idx == augroups.ga_len) { // add "END" add the end
- return (char_u *)"END";
- }
- if (idx >= augroups.ga_len) { // end of list
- return NULL;
- }
- if (AUGROUP_NAME(idx) == NULL || AUGROUP_NAME(idx) == get_deleted_augroup()) {
- // skip deleted entries
- return (char_u *)"";
- }
- return (char_u *)AUGROUP_NAME(idx);
+ // Required for ExpandGeneric
+ (void)xp;
+
+ return (char_u *)augroup_name(idx + 1);
}
/// @param doautocmd true for :doauto*, false for :autocmd
char_u *set_context_in_autocmd(expand_T *xp, char_u *arg, int doautocmd)
{
- char_u *p;
- int group;
-
// check for a group name, skip it if present
autocmd_include_groups = false;
- p = arg;
- group = au_get_grouparg(&arg);
+ char_u *p = arg;
+ int group = arg_augroup_get(&arg);
// If there only is a group name that's what we expand.
if (*arg == NUL && group != AUGROUP_ALL && !ascii_iswhite(arg[-1])) {
@@ -1993,16 +2161,24 @@ char_u *set_context_in_autocmd(expand_T *xp, char_u *arg, int doautocmd)
}
// Function given to ExpandGeneric() to obtain the list of event names.
-char_u *get_event_name(expand_T *xp, int idx)
+char_u *expand_get_event_name(expand_T *xp, int idx)
{
- if (idx < augroups.ga_len) { // First list group names, if wanted
- if (!autocmd_include_groups || AUGROUP_NAME(idx) == NULL
- || AUGROUP_NAME(idx) == get_deleted_augroup()) {
- return (char_u *)""; // skip deleted entries
+ // xp is a required parameter to be used with ExpandGeneric
+ (void)xp;
+
+ // List group names
+ char *name = augroup_name(idx + 1);
+ if (name != NULL) {
+ // skip when not including groups or skip deleted entries
+ if (!autocmd_include_groups || name == get_deleted_augroup()) {
+ return (char_u *)"";
}
- return (char_u *)AUGROUP_NAME(idx);
+
+ return (char_u *)name;
}
- return (char_u *)event_names[idx - augroups.ga_len].name;
+
+ // List event names
+ return (char_u *)event_names[idx - next_augroup_id].name;
}
/// Check whether given autocommand is supported
@@ -2031,10 +2207,7 @@ bool autocmd_supported(const char *const event)
/// @param arg autocommand string
bool au_exists(const char *const arg) FUNC_ATTR_WARN_UNUSED_RESULT
{
- event_T event;
- AutoPat *ap;
buf_T *buflocal_buf = NULL;
- int group;
bool retval = false;
// Make a copy so that we can change the '#' chars to a NUL.
@@ -2045,7 +2218,7 @@ bool au_exists(const char *const arg) FUNC_ATTR_WARN_UNUSED_RESULT
}
// First, look for an autocmd group name.
- group = au_find_group((char_u *)arg_save);
+ int group = augroup_find(arg_save);
char *event_name;
if (group == AUGROUP_ERROR) {
// Didn't match a group name, assume the first argument is an event.
@@ -2069,7 +2242,7 @@ bool au_exists(const char *const arg) FUNC_ATTR_WARN_UNUSED_RESULT
char *pattern = p; // "pattern" is NULL when there is no pattern.
// Find the index (enum) for the event name.
- event = event_name2nr((char_u *)event_name, (char_u **)&p);
+ event_T event = event_name2nr((char_u *)event_name, (char_u **)&p);
// return false if the event name is not recognized
if (event == NUM_EVENTS) {
@@ -2079,7 +2252,7 @@ bool au_exists(const char *const arg) FUNC_ATTR_WARN_UNUSED_RESULT
// Find the first autocommand for this event.
// If there isn't any, return false;
// If there is one and no pattern given, return true;
- ap = first_autopat[(int)event];
+ AutoPat *ap = first_autopat[(int)event];
if (ap == NULL) {
goto theend;
}
@@ -2109,3 +2282,360 @@ theend:
xfree(arg_save);
return retval;
}
+
+// Checks if a pattern is buflocal
+bool aupat_is_buflocal(char_u *pat, int patlen)
+{
+ return patlen >= 8
+ && STRNCMP(pat, "<buffer", 7) == 0
+ && (pat)[patlen - 1] == '>';
+}
+
+int aupat_get_buflocal_nr(char_u *pat, int patlen)
+{
+ assert(aupat_is_buflocal(pat, patlen));
+
+ // "<buffer>"
+ if (patlen == 8) {
+ return curbuf->b_fnum;
+ }
+
+ if (patlen > 9 && (pat)[7] == '=') {
+ // "<buffer=abuf>"
+ if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13) == 0) {
+ return autocmd_bufnr;
+ }
+
+ // "<buffer=123>"
+ if (skipdigits(pat + 8) == pat + patlen - 1) {
+ return atoi((char *)pat + 8);
+ }
+ }
+
+ return 0;
+}
+
+// normalize buffer pattern
+void aupat_normalize_buflocal_pat(char_u *dest, char_u *pat, int patlen, int buflocal_nr)
+{
+ assert(aupat_is_buflocal(pat, patlen));
+
+ if (buflocal_nr == 0) {
+ buflocal_nr = curbuf->handle;
+ }
+
+ // normalize pat into standard "<buffer>#N" form
+ snprintf((char *)dest,
+ BUFLOCAL_PAT_LEN,
+ "<buffer=%d>",
+ buflocal_nr);
+}
+
+int autocmd_delete_event(int group, event_T event, char_u *pat)
+ FUNC_ATTR_NONNULL_ALL
+{
+ return do_autocmd_event(event, pat, false, false, (char_u *)"", true, group);
+}
+
+/// Deletes an autocmd by ID.
+/// Only autocmds created via the API have IDs associated with them. There
+/// is no way to delete a specific autocmd created via :autocmd
+void autocmd_delete_id(int64_t id)
+{
+ FOR_ALL_AUEVENTS(event) {
+ FOR_ALL_AUPATS_IN_EVENT(event, ap) {
+ for (AutoCmd *ac = ap->cmds; ac != NULL; ac = ac->next) {
+ if (ac->id == id) {
+ aucmd_del(ac);
+ }
+ }
+ }
+ }
+}
+
+// ===========================================================================
+// AucmdExecutable Functions
+// ===========================================================================
+char *aucmd_exec_default_desc(AucmdExecutable acc)
+{
+ size_t msglen = 100;
+
+ switch (acc.type) {
+ case CALLABLE_CB:
+ switch (acc.callable.cb.type) {
+ case kCallbackLua: {
+ char *msg = (char *)xmallocz(msglen);
+ snprintf(msg, msglen, "<Lua function %d>", acc.callable.cb.data.luaref);
+ return msg;
+ }
+ case kCallbackFuncref: {
+ // TODO(tjdevries): Is this enough space for this?
+ char *msg = (char *)xmallocz(msglen);
+ snprintf(msg, msglen, "<vim function: %s>", acc.callable.cb.data.funcref);
+ return msg;
+ }
+ case kCallbackPartial: {
+ char *msg = (char *)xmallocz(msglen);
+ snprintf(msg, msglen, "<vim partial: %s>", acc.callable.cb.data.partial->pt_name);
+ return msg;
+ }
+ default:
+ return NULL;
+ }
+ default:
+ return NULL;
+ }
+}
+
+char *aucmd_exec_to_string(AutoCmd *ac, AucmdExecutable acc)
+{
+ switch (acc.type) {
+ case CALLABLE_EX:
+ return (char *)acc.callable.cmd;
+ case CALLABLE_CB:
+ return ac->desc;
+ case CALLABLE_NONE:
+ return "This is not possible";
+ }
+
+ abort();
+}
+
+void aucmd_exec_free(AucmdExecutable *acc)
+{
+ switch (acc->type) {
+ case CALLABLE_EX:
+ XFREE_CLEAR(acc->callable.cmd);
+ break;
+ case CALLABLE_CB:
+ callback_free(&acc->callable.cb);
+ break;
+ case CALLABLE_NONE:
+ return;
+ }
+
+ acc->type = CALLABLE_NONE;
+}
+
+AucmdExecutable aucmd_exec_copy(AucmdExecutable src)
+{
+ AucmdExecutable dest = AUCMD_EXECUTABLE_INIT;
+
+ switch (src.type) {
+ case CALLABLE_EX:
+ dest.type = CALLABLE_EX;
+ dest.callable.cmd = vim_strsave(src.callable.cmd);
+ return dest;
+ case CALLABLE_CB:
+ dest.type = CALLABLE_CB;
+ callback_copy(&dest.callable.cb, &src.callable.cb);
+ return dest;
+ case CALLABLE_NONE:
+ return dest;
+ }
+
+ abort();
+}
+
+bool aucmd_exec_is_deleted(AucmdExecutable acc)
+{
+ switch (acc.type) {
+ case CALLABLE_EX:
+ return acc.callable.cmd == NULL;
+ case CALLABLE_CB:
+ return acc.callable.cb.type == kCallbackNone;
+ case CALLABLE_NONE:
+ return true;
+ }
+
+ abort();
+}
+
+bool au_event_is_empty(event_T event)
+{
+ return first_autopat[event] == NULL;
+}
+
+// Arg Parsing Functions
+
+/// Scan over the events. "*" stands for all events.
+/// true when group name was found
+static char_u *arg_event_skip(char_u *arg, int have_group)
+{
+ char_u *pat;
+ char_u *p;
+
+ if (*arg == '*') {
+ if (arg[1] && !ascii_iswhite(arg[1])) {
+ semsg(_("E215: Illegal character after *: %s"), arg);
+ return NULL;
+ }
+ pat = arg + 1;
+ } else {
+ for (pat = arg; *pat && *pat != '|' && !ascii_iswhite(*pat); pat = p) {
+ if ((int)event_name2nr(pat, &p) >= NUM_EVENTS) {
+ if (have_group) {
+ semsg(_("E216: No such event: %s"), pat);
+ } else {
+ semsg(_("E216: No such group or event: %s"), pat);
+ }
+ return NULL;
+ }
+ }
+ }
+ return pat;
+}
+
+// Find the group ID in a ":autocmd" or ":doautocmd" argument.
+// The "argp" argument is advanced to the following argument.
+//
+// Returns the group ID or AUGROUP_ALL.
+static int arg_augroup_get(char_u **argp)
+{
+ char_u *p;
+ char_u *arg = *argp;
+ int group = AUGROUP_ALL;
+
+ for (p = arg; *p && !ascii_iswhite(*p) && *p != '|'; p++) {
+ }
+ if (p > arg) {
+ char_u *group_name = vim_strnsave(arg, (size_t)(p - arg));
+ group = augroup_find((char *)group_name);
+ if (group == AUGROUP_ERROR) {
+ group = AUGROUP_ALL; // no match, use all groups
+ } else {
+ *argp = skipwhite(p); // match, skip over group name
+ }
+ xfree(group_name);
+ }
+ return group;
+}
+
+/// Handles grabbing arguments from `:autocmd` such as ++once and ++nested
+static bool arg_autocmd_flag_get(bool *flag, char_u **cmd_ptr, char *pattern, int len)
+{
+ if (STRNCMP(*cmd_ptr, pattern, len) == 0 && ascii_iswhite((*cmd_ptr)[len])) {
+ if (*flag) {
+ semsg(_(e_duparg2), pattern);
+ return true;
+ }
+
+ *flag = true;
+ *cmd_ptr = skipwhite((*cmd_ptr) + len);
+ }
+
+ return false;
+}
+
+
+// UI Enter
+void do_autocmd_uienter(uint64_t chanid, bool attached)
+{
+ static bool recursive = false;
+
+ if (recursive) {
+ return; // disallow recursion
+ }
+ recursive = true;
+
+ save_v_event_T save_v_event;
+ dict_T *dict = get_v_event(&save_v_event);
+ assert(chanid < VARNUMBER_MAX);
+ tv_dict_add_nr(dict, S_LEN("chan"), (varnumber_T)chanid);
+ tv_dict_set_keys_readonly(dict);
+ apply_autocmds(attached ? EVENT_UIENTER : EVENT_UILEAVE,
+ NULL, NULL, false, curbuf);
+ restore_v_event(dict, &save_v_event);
+
+ recursive = false;
+}
+
+// FocusGained
+
+static void focusgained_event(void **argv)
+{
+ bool *gainedp = argv[0];
+ do_autocmd_focusgained(*gainedp);
+ xfree(gainedp);
+}
+
+void autocmd_schedule_focusgained(bool gained)
+{
+ bool *gainedp = xmalloc(sizeof(*gainedp));
+ *gainedp = gained;
+ loop_schedule_deferred(&main_loop,
+ event_create(focusgained_event, 1, gainedp));
+}
+
+static void do_autocmd_focusgained(bool gained)
+{
+ static bool recursive = false;
+ static Timestamp last_time = (time_t)0;
+ bool need_redraw = false;
+
+ if (recursive) {
+ return; // disallow recursion
+ }
+ recursive = true;
+ need_redraw |= apply_autocmds((gained ? EVENT_FOCUSGAINED : EVENT_FOCUSLOST),
+ NULL, NULL, false, curbuf);
+
+ // When activated: Check if any file was modified outside of Vim.
+ // Only do this when not done within the last two seconds as:
+ // 1. Some filesystems have modification time granularity in seconds. Fat32
+ // has a granularity of 2 seconds.
+ // 2. We could get multiple notifications in a row.
+ if (gained && last_time + (Timestamp)2000 < os_now()) {
+ need_redraw = check_timestamps(true);
+ last_time = os_now();
+ }
+
+ if (need_redraw) {
+ // Something was executed, make sure the cursor is put back where it
+ // belongs.
+ need_wait_return = false;
+
+ if (State & CMDLINE) {
+ redrawcmdline();
+ } else if ((State & NORMAL) || (State & INSERT)) {
+ if (must_redraw != 0) {
+ update_screen(0);
+ }
+
+ setcursor();
+ }
+
+ ui_flush();
+ }
+
+ if (need_maketitle) {
+ maketitle();
+ }
+
+ recursive = false;
+}
+
+// initialization
+
+void init_default_autocmds(void)
+{
+ // open terminals when opening files that start with term://
+#define PROTO "term://"
+ do_cmdline_cmd("augroup nvim_terminal");
+ do_cmdline_cmd("autocmd BufReadCmd " PROTO "* ++nested "
+ "if !exists('b:term_title')|call termopen("
+ // Capture the command string
+ "matchstr(expand(\"<amatch>\"), "
+ "'\\c\\m" PROTO "\\%(.\\{-}//\\%(\\d\\+:\\)\\?\\)\\?\\zs.*'), "
+ // capture the working directory
+ "{'cwd': expand(get(matchlist(expand(\"<amatch>\"), "
+ "'\\c\\m" PROTO "\\(.\\{-}\\)//'), 1, ''))})"
+ "|endif");
+ do_cmdline_cmd("augroup END");
+#undef PROTO
+
+ // limit syntax synchronization in the command window
+ do_cmdline_cmd("augroup nvim_cmdwin");
+ do_cmdline_cmd("autocmd! CmdwinEnter [:>] syntax sync minlines=1 maxlines=1");
+ do_cmdline_cmd("augroup END");
+}
diff --git a/src/nvim/autocmd.h b/src/nvim/autocmd.h
index 63c5abd4f8..53ec7f2bb7 100644
--- a/src/nvim/autocmd.h
+++ b/src/nvim/autocmd.h
@@ -4,6 +4,11 @@
#include "nvim/buffer_defs.h"
#include "nvim/ex_cmds_defs.h"
+// event_T definition
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+# include "auevents_enum.generated.h"
+#endif
+
// Struct to save values in before executing autocommands for a buffer that is
// not the current buffer.
typedef struct {
@@ -18,22 +23,23 @@ typedef struct {
} aco_save_T;
typedef struct AutoCmd {
- char_u *cmd; // Command to be executed (NULL when
- // command has been removed)
+ AucmdExecutable exec;
bool once; // "One shot": removed after execution
bool nested; // If autocommands nest here
bool last; // last command in list
+ int64_t id; // ID used for uniquely tracking an autocmd.
sctx_T script_ctx; // script context where defined
- struct AutoCmd *next; // Next AutoCmd in list
+ char *desc; // Description for the autocmd.
+ struct AutoCmd *next; // Next AutoCmd in list
} AutoCmd;
typedef struct AutoPat {
- struct AutoPat *next; // next AutoPat in AutoPat list; MUST
- // be the first entry
- char_u *pat; // pattern as typed (NULL when pattern
- // has been removed)
- regprog_T *reg_prog; // compiled regprog for pattern
- AutoCmd *cmds; // list of commands to do
+ struct AutoPat *next; // next AutoPat in AutoPat list; MUST
+ // be the first entry
+ char_u *pat; // pattern as typed (NULL when pattern
+ // has been removed)
+ regprog_T *reg_prog; // compiled regprog for pattern
+ AutoCmd *cmds; // list of commands to do
int group; // group ID
int patlen; // strlen() of pat
int buflocal_nr; // !=0 for buffer-local AutoPat
@@ -41,13 +47,7 @@ typedef struct AutoPat {
char last; // last pattern for apply_autocmds()
} AutoPat;
-#ifdef INCLUDE_GENERATED_DECLARATIONS
-# include "auevents_enum.generated.h"
-#endif
-
-///
/// Struct used to keep status while executing autocommands for an event.
-///
typedef struct AutoPatCmd {
AutoPat *curpat; // next AutoPat to examine
AutoCmd *nextcmd; // next AutoCmd to execute
@@ -75,8 +75,16 @@ EXTERN bool au_did_filetype INIT(= false);
# include "autocmd.h.generated.h"
#endif
-#define AUGROUP_DEFAULT -1 // default autocmd group
-#define AUGROUP_ERROR -2 // erroneous autocmd group
-#define AUGROUP_ALL -3 // all autocmd groups
+#define AUGROUP_DEFAULT (-1) // default autocmd group
+#define AUGROUP_ERROR (-2) // erroneous autocmd group
+#define AUGROUP_ALL (-3) // all autocmd groups
+#define AUGROUP_DELETED (-4) // all autocmd groups
+// #define AUGROUP_NS -5 // TODO(tjdevries): Support namespaced based augroups
+
+#define BUFLOCAL_PAT_LEN 25
+
+/// Iterates over all the events for auto commands
+#define FOR_ALL_AUEVENTS(event) \
+ for (event_T event = (event_T)0; (int)event < (int)NUM_EVENTS; event = (event_T)((int)event + 1)) // NOLINT
#endif // NVIM_AUTOCMD_H
diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c
index 38b045b31c..bfaee82311 100644
--- a/src/nvim/buffer.c
+++ b/src/nvim/buffer.c
@@ -34,6 +34,7 @@
#include "nvim/channel.h"
#include "nvim/charset.h"
#include "nvim/cursor.h"
+#include "nvim/decoration.h"
#include "nvim/diff.h"
#include "nvim/digraph.h"
#include "nvim/eval.h"
@@ -222,7 +223,7 @@ int open_buffer(int read_stdin, exarg_T *eap, int flags)
|| (S_ISCHR(perm)
&& is_dev_fd_file(curbuf->b_ffname))
# endif
- )) {
+ )) { // NOLINT(whitespace/parens)
read_fifo = true;
}
if (read_fifo) {
@@ -400,7 +401,7 @@ bool buf_valid(buf_T *buf)
/// there to be only one window with this buffer. e.g. when
/// ":quit" is supposed to close the window but autocommands
/// close all other windows.
-/// @returns true when we got to the end and b_nwindows was decremented.
+/// @return true when we got to the end and b_nwindows was decremented.
bool close_buffer(win_T *win, buf_T *buf, int action, bool abort_if_last)
{
bool unload_buf = (action != 0);
@@ -586,9 +587,7 @@ bool close_buffer(win_T *win, buf_T *buf, int action, bool abort_if_last)
// No need to check `unload_buf`: in that case the function returned above.
buf_updates_unload(buf, false);
- /*
- * Remove the buffer from the list.
- */
+ // Remove the buffer from the list.
if (wipe_buf) {
if (buf->b_sfname != buf->b_ffname) {
XFREE_CLEAR(buf->b_sfname);
@@ -736,10 +735,8 @@ void buf_freeall(buf_T *buf, int flags)
buf->b_flags &= ~BF_READERR; // a read error is no longer relevant
}
-/*
- * Free a buffer structure and the things it contains related to the buffer
- * itself (not the file, that must have been done already).
- */
+/// Free a buffer structure and the things it contains related to the buffer
+/// itself (not the file, that must have been done already).
static void free_buffer(buf_T *buf)
{
pmap_del(handle_T)(&buffer_handles, buf->b_fnum);
@@ -812,9 +809,7 @@ static void free_buffer_stuff(buf_T *buf, int free_flags)
buf_updates_unload(buf, false);
}
-/*
- * Free the b_wininfo list for buffer "buf".
- */
+/// Free the b_wininfo list for buffer "buf".
static void clear_wininfo(buf_T *buf)
{
wininfo_T *wip;
@@ -826,9 +821,7 @@ static void clear_wininfo(buf_T *buf)
}
}
-/*
- * Go to another buffer. Handles the result of the ATTENTION dialog.
- */
+/// Go to another buffer. Handles the result of the ATTENTION dialog.
void goto_buffer(exarg_T *eap, int start, int dir, int count)
{
bufref_T old_curbuf;
@@ -1032,10 +1025,8 @@ char *do_bufdel(int command, char_u *arg, int addr_count, int start_bnr, int end
}
-/*
- * Make the current buffer empty.
- * Used when it is wiped out and it's the last buffer.
- */
+/// Make the current buffer empty.
+/// Used when it is wiped out and it's the last buffer.
static int empty_curbuf(int close_others, int forceit, int action)
{
int retval;
@@ -1409,15 +1400,15 @@ int do_buffer(int action, int start, int dir, int count, int forceit)
}
-/*
- * Set current buffer to "buf". Executes autocommands and closes current
- * buffer. "action" tells how to close the current buffer:
- * DOBUF_GOTO free or hide it
- * DOBUF_SPLIT nothing
- * DOBUF_UNLOAD unload it
- * DOBUF_DEL delete it
- * DOBUF_WIPE wipe it out
- */
+/// Set current buffer to "buf". Executes autocommands and closes current
+/// buffer.
+///
+/// @param action tells how to close the current buffer:
+/// DOBUF_GOTO free or hide it
+/// DOBUF_SPLIT nothing
+/// DOBUF_UNLOAD unload it
+/// DOBUF_DEL delete it
+/// DOBUF_WIPE wipe it out
void set_curbuf(buf_T *buf, int action)
{
buf_T *prevbuf;
@@ -1441,7 +1432,7 @@ void set_curbuf(buf_T *buf, int action)
set_bufref(&prevbufref, prevbuf);
set_bufref(&newbufref, buf);
- // Autocommands may delete the curren buffer and/or the buffer we want to go
+ // Autocommands may delete the current buffer and/or the buffer we want to go
// to. In those cases don't close the buffer.
if (!apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, false, curbuf)
|| (bufref_valid(&prevbufref) && bufref_valid(&newbufref)
@@ -1454,6 +1445,7 @@ void set_curbuf(buf_T *buf, int action)
}
if (bufref_valid(&prevbufref) && !aborting()) {
win_T *previouswin = curwin;
+
// Do not sync when in Insert mode and the buffer is open in
// another window, might be a timer doing something in another
// window.
@@ -1476,9 +1468,7 @@ void set_curbuf(buf_T *buf, int action)
// An autocommand may have deleted "buf", already entered it (e.g., when
// it did ":bunload") or aborted the script processing!
// If curwin->w_buffer is null, enter_buffer() will make it valid again
- if ((buf_valid(buf) && buf != curbuf
- && !aborting()
- ) || curwin->w_buffer == NULL) {
+ if ((buf_valid(buf) && buf != curbuf && !aborting()) || curwin->w_buffer == NULL) {
enter_buffer(buf);
if (old_tw != curbuf->b_p_tw) {
check_colorcolumn(curwin);
@@ -1490,11 +1480,9 @@ void set_curbuf(buf_T *buf, int action)
}
}
-/*
- * Enter a new current buffer.
- * Old curbuf must have been abandoned already! This also means "curbuf" may
- * be pointing to freed memory.
- */
+/// Enter a new current buffer.
+/// Old curbuf must have been abandoned already! This also means "curbuf" may
+/// be pointing to freed memory.
void enter_buffer(buf_T *buf)
{
// Get the buffer in the current window.
@@ -1581,8 +1569,8 @@ void enter_buffer(buf_T *buf)
redraw_later(curwin, NOT_VALID);
}
-// Change to the directory of the current buffer.
-// Don't do this while still starting up.
+/// Change to the directory of the current buffer.
+/// Don't do this while still starting up.
void do_autochdir(void)
{
if (p_acd) {
@@ -1659,7 +1647,7 @@ static inline void buf_init_changedtick(buf_T *const buf)
/// @param flags BLN_ defines
/// @param bufnr
///
-/// @return pointer to the buffer
+/// @return pointer to the buffer
buf_T *buflist_new(char_u *ffname_arg, char_u *sfname_arg, linenr_T lnum, int flags)
{
char_u *ffname = ffname_arg;
@@ -1701,14 +1689,12 @@ buf_T *buflist_new(char_u *ffname_arg, char_u *sfname_arg, linenr_T lnum, int fl
return buf;
}
- /*
- * If the current buffer has no name and no contents, use the current
- * buffer. Otherwise: Need to allocate a new buffer structure.
- *
- * This is the ONLY place where a new buffer structure is allocated!
- * (A spell file buffer is allocated in spell.c, but that's not a normal
- * buffer.)
- */
+ // If the current buffer has no name and no contents, use the current
+ // buffer. Otherwise: Need to allocate a new buffer structure.
+ //
+ // This is the ONLY place where a new buffer structure is allocated!
+ // (A spell file buffer is allocated in spell.c, but that's not a normal
+ // buffer.)
buf = NULL;
if ((flags & BLN_CURBUF) && curbuf_reusable()) {
assert(curbuf != NULL);
@@ -1735,7 +1721,7 @@ buf_T *buflist_new(char_u *ffname_arg, char_u *sfname_arg, linenr_T lnum, int fl
buf = xcalloc(1, sizeof(buf_T));
// init b: variables
buf->b_vars = tv_dict_alloc();
- buf->b_signcols_valid = false;
+ buf->b_signcols.valid = false;
init_var_dict(buf->b_vars, &buf->b_bufvar, VAR_SCOPE);
buf_init_changedtick(buf);
}
@@ -1779,9 +1765,7 @@ buf_T *buflist_new(char_u *ffname_arg, char_u *sfname_arg, linenr_T lnum, int fl
// need to reload lmaps and set b:keymap_name
curbuf->b_kmap_state |= KEYMAP_INIT;
} else {
- /*
- * put new buffer at the end of the buffer list
- */
+ // put new buffer at the end of the buffer list
buf->b_next = NULL;
if (firstbuf == NULL) { // buffer list is empty
buf->b_prev = NULL;
@@ -1873,11 +1857,9 @@ bool curbuf_reusable(void)
&& !curbufIsChanged());
}
-/*
- * Free the memory for the options of a buffer.
- * If "free_p_ff" is true also free 'fileformat', 'buftype' and
- * 'fileencoding'.
- */
+/// Free the memory for the options of a buffer.
+/// If "free_p_ff" is true also free 'fileformat', 'buftype' and
+/// 'fileencoding'.
void free_buf_options(buf_T *buf, int free_p_ff)
{
if (free_p_ff) {
@@ -2037,7 +2019,7 @@ int buflist_getfile(int n, linenr_T lnum, int options, int forceit)
return FAIL;
}
-// Go to the last known line number for the current buffer.
+/// Go to the last known line number for the current buffer.
void buflist_getfpos(void)
{
pos_T *fpos;
@@ -2057,10 +2039,9 @@ void buflist_getfpos(void)
}
}
-/*
- * Find file in buffer list by name (it has to be for the current window).
- * Returns NULL if not found.
- */
+/// Find file in buffer list by name (it has to be for the current window).
+///
+/// @return buffer or NULL if not found
buf_T *buflist_findname_exp(char_u *fname)
{
char_u *ffname;
@@ -2074,7 +2055,7 @@ buf_T *buflist_findname_exp(char_u *fname)
#else
false
#endif
- );
+ ); // NOLINT(whitespace/parens)
if (ffname != NULL) {
buf = buflist_findname(ffname);
xfree(ffname);
@@ -2082,12 +2063,11 @@ buf_T *buflist_findname_exp(char_u *fname)
return buf;
}
-/*
- * Find file in buffer list by name (it has to be for the current window).
- * "ffname" must have a full path.
- * Skips dummy buffers.
- * Returns NULL if not found.
- */
+/// Find file in buffer list by name (it has to be for the current window).
+/// "ffname" must have a full path.
+/// Skips dummy buffers.
+///
+/// @return buffer or NULL if not found
buf_T *buflist_findname(char_u *ffname)
{
FileID file_id;
@@ -2095,11 +2075,10 @@ buf_T *buflist_findname(char_u *ffname)
return buflist_findname_file_id(ffname, &file_id, file_id_valid);
}
-/*
- * Same as buflist_findname(), but pass the FileID structure to avoid
- * getting it twice for the same file.
- * Returns NULL if not found.
- */
+/// Same as buflist_findname(), but pass the FileID structure to avoid
+/// getting it twice for the same file.
+///
+/// @return buffer or NULL if not found
static buf_T *buflist_findname_file_id(char_u *ffname, FileID *file_id, bool file_id_valid)
{
// Start at the last buffer, expect to find a match sooner.
@@ -2113,13 +2092,13 @@ static buf_T *buflist_findname_file_id(char_u *ffname, FileID *file_id, bool fil
}
/// Find file in buffer list by a regexp pattern.
-/// Return fnum of the found buffer.
-/// Return < 0 for error.
///
/// @param pattern_end pointer to first char after pattern
/// @param unlisted find unlisted buffers
/// @param diffmode find diff-mode buffers only
/// @param curtab_only find buffers in current tab only
+///
+/// @return fnum of the found buffer or < 0 for error.
int buflist_findpat(const char_u *pattern, const char_u *pattern_end, bool unlisted, bool diffmode,
bool curtab_only)
FUNC_ATTR_NONNULL_ARG(1)
@@ -2143,7 +2122,6 @@ int buflist_findpat(const char_u *pattern, const char_u *pattern_end, bool unlis
match = -1;
}
} else {
- //
// Try four ways of matching a listed buffer:
// attempt == 0: without '^' or '$' (at any position)
// attempt == 1: with '^' at start (only at position 0)
@@ -2151,7 +2129,6 @@ int buflist_findpat(const char_u *pattern, const char_u *pattern_end, bool unlis
// attempt == 3: with '^' at start and '$' at end (only full match)
// Repeat this for finding an unlisted buffer if there was no matching
// listed buffer.
- //
pat = file_pat_to_reg_pat(pattern, pattern_end, NULL, false);
if (pat == NULL) {
@@ -2249,11 +2226,10 @@ static int buf_time_compare(const void *s1, const void *s2)
return buf1->b_last_used > buf2->b_last_used ? -1 : 1;
}
-/*
- * Find all buffer names that match.
- * For command line expansion of ":buf" and ":sbuf".
- * Return OK if matches found, FAIL otherwise.
- */
+/// Find all buffer names that match.
+/// For command line expansion of ":buf" and ":sbuf".
+///
+/// @return OK if matches found, FAIL otherwise.
int ExpandBufnames(char_u *pat, int *num_file, char_u ***file, int options)
{
int count = 0;
@@ -2377,7 +2353,7 @@ int ExpandBufnames(char_u *pat, int *num_file, char_u ***file, int options)
/// Check for a match on the file name for buffer "buf" with regprog "prog".
///
-/// @param ignore_case When true, ignore case. Use 'fic' otherwise.
+/// @param ignore_case When true, ignore case. Use 'fic' otherwise.
static char_u *buflist_match(regmatch_T *rmp, buf_T *buf, bool ignore_case)
{
// First try the short file name, then the long file name.
@@ -2390,8 +2366,9 @@ static char_u *buflist_match(regmatch_T *rmp, buf_T *buf, bool ignore_case)
/// Try matching the regexp in "prog" with file name "name".
///
-/// @param ignore_case When true, ignore case. Use 'fileignorecase' otherwise.
-/// @return "name" when there is a match, NULL when not.
+/// @param ignore_case When true, ignore case. Use 'fileignorecase' otherwise.
+///
+/// @return "name" when there is a match, NULL when not.
static char_u *fname_match(regmatch_T *rmp, char_u *name, bool ignore_case)
{
char_u *match = NULL;
@@ -2526,12 +2503,13 @@ static bool wininfo_other_tab_diff(wininfo_T *wip)
return false;
}
-// Find info for the current window in buffer "buf".
-// If not found, return the info for the most recently used window.
-// When "need_options" is true skip entries where wi_optset is false.
-// When "skip_diff_buffer" is true avoid windows with 'diff' set that is in
-// another tab page.
-// Returns NULL when there isn't any info.
+/// Find info for the current window in buffer "buf".
+/// If not found, return the info for the most recently used window.
+///
+/// @param need_options when true, skip entries where wi_optset is false.
+/// @param skip_diff_buffer when true, avoid windows with 'diff' set that is in another tab page.
+///
+/// @return NULL when there isn't any info.
static wininfo_T *find_wininfo(buf_T *buf, bool need_options, bool skip_diff_buffer)
FUNC_ATTR_NONNULL_ALL
{
@@ -2568,12 +2546,10 @@ static wininfo_T *find_wininfo(buf_T *buf, bool need_options, bool skip_diff_buf
return wip;
}
-/*
- * Reset the local window options to the values last used in this window.
- * If the buffer wasn't used in this window before, use the values from
- * the most recently used window. If the values were never set, use the
- * global values for the window.
- */
+/// Reset the local window options to the values last used in this window.
+/// If the buffer wasn't used in this window before, use the values from
+/// the most recently used window. If the values were never set, use the
+/// global values for the window.
void get_winopts(buf_T *buf)
{
clear_winopt(&curwin->w_onebuf_opt);
@@ -2608,11 +2584,10 @@ void get_winopts(buf_T *buf)
didset_window_options(curwin);
}
-/*
- * Find the position (lnum and col) for the buffer 'buf' for the current
- * window.
- * Returns a pointer to no_position if no position is found.
- */
+/// Find the position (lnum and col) for the buffer 'buf' for the current
+/// window.
+///
+/// @return a pointer to no_position if no position is found.
pos_T *buflist_findfpos(buf_T *buf)
{
static pos_T no_position = { 1, 0, 0 };
@@ -2621,15 +2596,13 @@ pos_T *buflist_findfpos(buf_T *buf)
return (wip == NULL) ? &no_position : &(wip->wi_fpos);
}
-/*
- * Find the lnum for the buffer 'buf' for the current window.
- */
+/// Find the lnum for the buffer 'buf' for the current window.
linenr_T buflist_findlnum(buf_T *buf)
{
return buflist_findfpos(buf)->lnum;
}
-// List all known file names (for :files and :buffers command).
+/// List all known file names (for :files and :buffers command).
void buflist_list(exarg_T *eap)
{
buf_T *buf = firstbuf;
@@ -2657,8 +2630,7 @@ void buflist_list(exarg_T *eap)
for (;
buf != NULL && !got_int;
buf = buflist_data != NULL
- ? (++p < buflist_data + buflist.ga_len ? *p : NULL)
- : buf->b_next) {
+ ? (++p < buflist_data + buflist.ga_len ? *p : NULL) : buf->b_next) {
const bool is_terminal = buf->terminal;
const bool job_running = buf->terminal && terminal_running(buf->terminal);
@@ -2721,10 +2693,8 @@ void buflist_list(exarg_T *eap)
if (vim_strchr(eap->arg, 't') && buf->b_last_used) {
undo_fmt_time(IObuff + len, (size_t)(IOSIZE - len), buf->b_last_used);
} else {
- vim_snprintf((char *)IObuff + len, (size_t)(IOSIZE - len),
- _("line %" PRId64),
- buf == curbuf ? (int64_t)curwin->w_cursor.lnum
- : (int64_t)buflist_findlnum(buf));
+ vim_snprintf((char *)IObuff + len, (size_t)(IOSIZE - len), _("line %" PRId64),
+ buf == curbuf ? (int64_t)curwin->w_cursor.lnum : (int64_t)buflist_findlnum(buf));
}
msg_outtrans(IObuff);
@@ -2736,12 +2706,11 @@ void buflist_list(exarg_T *eap)
}
}
-/*
- * Get file name and line number for file 'fnum'.
- * Used by DoOneCmd() for translating '%' and '#'.
- * Used by insert_reg() and cmdline_paste() for '#' register.
- * Return FAIL if not found, OK for success.
- */
+/// Get file name and line number for file 'fnum'.
+/// Used by DoOneCmd() for translating '%' and '#'.
+/// Used by insert_reg() and cmdline_paste() for '#' register.
+///
+/// @return FAIL if not found, OK for success.
int buflist_name_nr(int fnum, char_u **fname, linenr_T *lnum)
{
buf_T *buf;
@@ -2827,10 +2796,8 @@ int setfname(buf_T *buf, char_u *ffname_arg, char_u *sfname_arg, bool message)
return OK;
}
-/*
- * Crude way of changing the name of a buffer. Use with care!
- * The name should be relative to the current directory.
- */
+/// Crude way of changing the name of a buffer. Use with care!
+/// The name should be relative to the current directory.
void buf_set_name(int fnum, char_u *name)
{
buf_T *buf;
@@ -2850,15 +2817,10 @@ void buf_set_name(int fnum, char_u *name)
}
}
-/*
- * Take care of what needs to be done when the name of buffer "buf" has
- * changed.
- */
+/// Take care of what needs to be done when the name of buffer "buf" has changed.
void buf_name_changed(buf_T *buf)
{
- /*
- * If the file name changed, also change the name of the swapfile
- */
+ // If the file name changed, also change the name of the swapfile
if (buf->b_ml.ml_mfp != NULL) {
ml_setname(buf);
}
@@ -2872,12 +2834,11 @@ void buf_name_changed(buf_T *buf)
ml_timestamp(buf); // reset timestamp
}
-/*
- * set alternate file name for current window
- *
- * Used by do_one_cmd(), do_write() and do_ecmd().
- * Return the buffer.
- */
+/// Set alternate file name for current window
+///
+/// Used by do_one_cmd(), do_write() and do_ecmd().
+///
+/// @return the buffer.
buf_T *setaltfname(char_u *ffname, char_u *sfname, linenr_T lnum)
{
buf_T *buf;
@@ -2908,12 +2869,10 @@ char_u *getaltfname(bool errmsg)
return fname;
}
-/*
- * Add a file name to the buflist and return its number.
- * Uses same flags as buflist_new(), except BLN_DUMMY.
- *
- * used by qf_init(), main() and doarglist()
- */
+/// Add a file name to the buflist and return its number.
+/// Uses same flags as buflist_new(), except BLN_DUMMY.
+///
+/// Used by qf_init(), main() and doarglist()
int buflist_add(char_u *fname, int flags)
{
buf_T *buf;
@@ -2926,9 +2885,7 @@ int buflist_add(char_u *fname, int flags)
}
#if defined(BACKSLASH_IN_FILENAME)
-/*
- * Adjust slashes in file names. Called after 'shellslash' was set.
- */
+/// Adjust slashes in file names. Called after 'shellslash' was set.
void buflist_slash_adjust(void)
{
FOR_ALL_BUFFERS(bp) {
@@ -2943,10 +2900,8 @@ void buflist_slash_adjust(void)
#endif
-/*
- * Set alternate cursor position for the current buffer and window "win".
- * Also save the local window option values.
- */
+/// Set alternate cursor position for the current buffer and window "win".
+/// Also save the local window option values.
void buflist_altfpos(win_T *win)
{
buflist_setfpos(curbuf, win, win->w_cursor.lnum, win->w_cursor.col, true);
@@ -3009,8 +2964,8 @@ static bool otherfile_buf(buf_T *buf, char_u *ffname, FileID *file_id_p, bool fi
return true;
}
-// Set file_id for a buffer.
-// Must always be called when b_fname is changed!
+/// Set file_id for a buffer.
+/// Must always be called when b_fname is changed!
void buf_set_file_id(buf_T *buf)
{
FileID file_id;
@@ -3150,7 +3105,7 @@ static char_u *lasttitle = NULL;
static char_u *lasticon = NULL;
-// Put the title name in the title bar and icon of the window.
+/// Put the title name in the title bar and icon of the window.
void maketitle(void)
{
char_u *title_str = NULL;
@@ -3348,8 +3303,8 @@ void maketitle(void)
///
/// @param str desired title string
/// @param[in,out] last current title string
-//
-/// @return true if resettitle() is to be called.
+///
+/// @return true if resettitle() is to be called.
static bool value_change(char_u *str, char_u **last)
FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -3406,18 +3361,18 @@ typedef enum {
/// If maxwidth is not zero, the string will be filled at any middle marker
/// or truncated if too long, fillchar is used for all whitespace.
///
-/// @param wp The window to build a statusline for
-/// @param out The output buffer to write the statusline to
-/// Note: This should not be NameBuff
-/// @param outlen The length of the output buffer
-/// @param fmt The statusline format string
-/// @param use_sandbox Use a sandboxed environment when evaluating fmt
-/// @param fillchar Character to use when filling empty space in the statusline
-/// @param maxwidth The maximum width to make the statusline
-/// @param hltab HL attributes (can be NULL)
-/// @param tabtab Tab clicks definition (can be NULL).
+/// @param wp The window to build a statusline for
+/// @param out The output buffer to write the statusline to
+/// Note: This should not be NameBuff
+/// @param outlen The length of the output buffer
+/// @param fmt The statusline format string
+/// @param use_sandbox Use a sandboxed environment when evaluating fmt
+/// @param fillchar Character to use when filling empty space in the statusline
+/// @param maxwidth The maximum width to make the statusline
+/// @param hltab HL attributes (can be NULL)
+/// @param tabtab Tab clicks definition (can be NULL).
///
-/// @return The final width of the statusline
+/// @return The final width of the statusline
int build_stl_str_hl(win_T *wp, char_u *out, size_t outlen, char_u *fmt, int use_sandbox,
int fillchar, int maxwidth, stl_hlrec_t **hltab, StlClickRecord **tabtab)
{
@@ -3438,8 +3393,12 @@ int build_stl_str_hl(win_T *wp, char_u *out, size_t outlen, char_u *fmt, int use
if (stl_items == NULL) {
stl_items = xmalloc(sizeof(stl_item_t) * stl_items_len);
stl_groupitems = xmalloc(sizeof(int) * stl_items_len);
- stl_hltab = xmalloc(sizeof(stl_hlrec_t) * stl_items_len);
- stl_tabtab = xmalloc(sizeof(StlClickRecord) * stl_items_len);
+
+ // Allocate one more, because the last element is used to indicate the
+ // end of the list.
+ stl_hltab = xmalloc(sizeof(stl_hlrec_t) * (stl_items_len + 1));
+ stl_tabtab = xmalloc(sizeof(StlClickRecord) * (stl_items_len + 1));
+
stl_separator_locations = xmalloc(sizeof(int) * stl_items_len);
}
@@ -3514,8 +3473,8 @@ int build_stl_str_hl(win_T *wp, char_u *out, size_t outlen, char_u *fmt, int use
stl_items = xrealloc(stl_items, sizeof(stl_item_t) * new_len);
stl_groupitems = xrealloc(stl_groupitems, sizeof(int) * new_len);
- stl_hltab = xrealloc(stl_hltab, sizeof(stl_hlrec_t) * new_len);
- stl_tabtab = xrealloc(stl_tabtab, sizeof(StlClickRecord) * new_len);
+ stl_hltab = xrealloc(stl_hltab, sizeof(stl_hlrec_t) * (new_len + 1));
+ stl_tabtab = xrealloc(stl_tabtab, sizeof(StlClickRecord) * (new_len + 1));
stl_separator_locations =
xrealloc(stl_separator_locations, sizeof(int) * new_len);
@@ -3675,8 +3634,7 @@ int build_stl_str_hl(win_T *wp, char_u *out, size_t outlen, char_u *fmt, int use
}
}
// If the group is shorter than the minimum width, add padding characters.
- } else if (
- abs(stl_items[stl_groupitems[groupdepth]].minwid) > group_len) {
+ } else if (abs(stl_items[stl_groupitems[groupdepth]].minwid) > group_len) {
long min_group_width = stl_items[stl_groupitems[groupdepth]].minwid;
// If the group is left-aligned, add characters to the right.
if (min_group_width < 0) {
@@ -4502,7 +4460,7 @@ int build_stl_str_hl(win_T *wp, char_u *out, size_t outlen, char_u *fmt, int use
char_u *start = stl_items[stl_separator_locations[i]].start;
char_u *seploc = start + dislocation;
STRMOVE(seploc, start);
- for (char_u *s = start; s < seploc; ) {
+ for (char_u *s = start; s < seploc;) {
MB_CHAR2BYTES(fillchar, s);
}
@@ -4576,12 +4534,10 @@ int build_stl_str_hl(win_T *wp, char_u *out, size_t outlen, char_u *fmt, int use
}
return width;
-}
+} // NOLINT(readability/fn_size)
-/*
- * Get relative cursor position in window into "buf[buflen]", in the form 99%,
- * using "Top", "Bot" or "All" when appropriate.
- */
+/// Get relative cursor position in window into "buf[buflen]", in the form 99%,
+/// using "Top", "Bot" or "All" when appropriate.
void get_rel_pos(win_T *wp, char_u *buf, int buflen)
{
// Need at least 3 chars for writing.
@@ -4618,7 +4574,7 @@ void get_rel_pos(win_T *wp, char_u *buf, int buflen)
/// @param buflen length of the string buffer
/// @param add_file if true, add "file" before the arg number
///
-/// @return true if it was appended.
+/// @return true if it was appended.
static bool append_arg_number(win_T *wp, char_u *buf, int buflen, bool add_file)
FUNC_ATTR_NONNULL_ALL
{
@@ -4647,12 +4603,12 @@ static bool append_arg_number(win_T *wp, char_u *buf, int buflen, bool add_file)
return true;
}
-// Make "*ffname" a full file name, set "*sfname" to "*ffname" if not NULL.
-// "*ffname" becomes a pointer to allocated memory (or NULL).
-// When resolving a link both "*sfname" and "*ffname" will point to the same
-// allocated memory.
-// The "*ffname" and "*sfname" pointer values on call will not be freed.
-// Note that the resulting "*ffname" pointer should be considered not allocated.
+/// Make "*ffname" a full file name, set "*sfname" to "*ffname" if not NULL.
+/// "*ffname" becomes a pointer to allocated memory (or NULL).
+/// When resolving a link both "*sfname" and "*ffname" will point to the same
+/// allocated memory.
+/// The "*ffname" and "*sfname" pointer values on call will not be freed.
+/// Note that the resulting "*ffname" pointer should be considered not allocated.
void fname_expand(buf_T *buf, char_u **ffname, char_u **sfname)
{
if (*ffname == NULL) { // no file name given, nothing to do
@@ -4676,9 +4632,7 @@ void fname_expand(buf_T *buf, char_u **ffname, char_u **sfname)
#endif
}
-/*
- * Get the file name for an argument list entry.
- */
+/// Get the file name for an argument list entry.
char_u *alist_name(aentry_T *aep)
{
buf_T *bp;
@@ -4720,8 +4674,7 @@ void do_arg_all(int count, int forceit, int keep_tabs)
assert(firstwin != NULL); // satisfy coverity
if (ARGCOUNT <= 0) {
- /* Don't give an error message. We don't want it when the ":all"
- * command is in the .vimrc. */
+ // Don't give an error message. We don't want it when the ":all" command is in the .vimrc.
return;
}
setpcmark();
@@ -4729,9 +4682,9 @@ void do_arg_all(int count, int forceit, int keep_tabs)
opened_len = ARGCOUNT;
opened = xcalloc((size_t)opened_len, 1);
- /* Autocommands may do anything to the argument list. Make sure it's not
- * freed while we are working here by "locking" it. We still have to
- * watch out for its size to be changed. */
+ // Autocommands may do anything to the argument list. Make sure it's not
+ // freed while we are working here by "locking" it. We still have to
+ // watch out for its size to be changed.
alist = curwin->w_alist;
alist->al_refcount++;
@@ -4739,13 +4692,11 @@ void do_arg_all(int count, int forceit, int keep_tabs)
old_curtab = curtab;
- /*
- * Try closing all windows that are not in the argument list.
- * Also close windows that are not full width;
- * When 'hidden' or "forceit" set the buffer becomes hidden.
- * Windows that have a changed buffer and can't be hidden won't be closed.
- * When the ":tab" modifier was used do this for all tab pages.
- */
+ // Try closing all windows that are not in the argument list.
+ // Also close windows that are not full width;
+ // When 'hidden' or "forceit" set the buffer becomes hidden.
+ // Windows that have a changed buffer and can't be hidden won't be closed.
+ // When the ":tab" modifier was used do this for all tab pages.
if (had_tab > 0) {
goto_tabpage_tp(first_tabpage, true, true);
}
@@ -4790,8 +4741,7 @@ void do_arg_all(int count, int forceit, int keep_tabs)
}
if (wp->w_alist != alist) {
- /* Use the current argument list for all windows
- * containing a file from it. */
+ // Use the current argument list for all windows containing a file from it.
alist_unlink(wp->w_alist);
wp->w_alist = alist;
wp->w_alist->al_refcount++;
@@ -4805,8 +4755,7 @@ void do_arg_all(int count, int forceit, int keep_tabs)
if (i == opened_len && !keep_tabs) { // close this window
if (buf_hide(buf) || forceit || buf->b_nwindows > 1
|| !bufIsChanged(buf)) {
- /* If the buffer was changed, and we would like to hide it,
- * try autowriting. */
+ // If the buffer was changed, and we would like to hide it, try autowriting.
if (!buf_hide(buf) && buf->b_nwindows <= 1 && bufIsChanged(buf)) {
bufref_T bufref;
set_bufref(&bufref, buf);
@@ -4845,10 +4794,8 @@ void do_arg_all(int count, int forceit, int keep_tabs)
goto_tabpage_tp(tpnext, true, true);
}
- /*
- * Open a window for files in the argument list that don't have one.
- * ARGCOUNT may change while doing this, because of autocommands.
- */
+ // Open a window for files in the argument list that don't have one.
+ // ARGCOUNT may change while doing this, because of autocommands.
if (count > opened_len || count <= 0) {
count = opened_len;
}
@@ -4903,9 +4850,7 @@ void do_arg_all(int count, int forceit, int keep_tabs)
autocmd_no_leave--;
}
- /*
- * edit file "i"
- */
+ // edit file "i"
curwin->w_arg_idx = i;
if (i == 0) {
new_curwin = curwin;
@@ -4957,15 +4902,13 @@ void do_arg_all(int count, int forceit, int keep_tabs)
xfree(opened);
}
-/// @return true if "buf" is a prompt buffer.
+/// @return true if "buf" is a prompt buffer.
bool bt_prompt(buf_T *buf)
{
return buf != NULL && buf->b_p_bt[0] == 'p';
}
-/*
- * Open a window for a number of buffers.
- */
+/// Open a window for a number of buffers.
void ex_buffer_all(exarg_T *eap)
{
buf_T *buf;
@@ -4993,10 +4936,8 @@ void ex_buffer_all(exarg_T *eap)
setpcmark();
- /*
- * Close superfluous windows (two windows for the same buffer).
- * Also close windows that are not full-width.
- */
+ // Close superfluous windows (two windows for the same buffer).
+ // Also close windows that are not full-width.
if (had_tab > 0) {
goto_tabpage_tp(first_tabpage, true, true);
}
@@ -5006,8 +4947,8 @@ void ex_buffer_all(exarg_T *eap)
wpnext = wp->w_next;
if ((wp->w_buffer->b_nwindows > 1
|| ((cmdmod.split & WSP_VERT)
- ? wp->w_height + wp->w_status_height < Rows - p_ch
- - tabline_height()
+ ? wp->w_height + wp->w_hsep_height + wp->w_status_height < Rows - p_ch
+ - tabline_height() - global_stl_height()
: wp->w_width != Columns)
|| (had_tab > 0 && wp != firstwin))
&& !ONE_WINDOW
@@ -5030,7 +4971,6 @@ void ex_buffer_all(exarg_T *eap)
goto_tabpage_tp(tpnext, true, true);
}
- //
// Go through the buffer list. When a buffer doesn't have a window yet,
// open one. Otherwise move the window to the right position.
// Watch out for autocommands that delete buffers or windows!
@@ -5126,9 +5066,7 @@ void ex_buffer_all(exarg_T *eap)
win_enter(firstwin, false); // back to first window
autocmd_no_leave--;
- /*
- * Close superfluous windows.
- */
+ // Close superfluous windows.
for (wp = lastwin; open_wins > count;) {
r = (buf_hide(wp->w_buffer) || !bufIsChanged(wp->w_buffer)
|| autowrite(wp->w_buffer, false) == OK);
@@ -5149,15 +5087,13 @@ void ex_buffer_all(exarg_T *eap)
}
-/*
- * do_modelines() - process mode lines for the current file
- *
- * "flags" can be:
- * OPT_WINONLY only set options local to window
- * OPT_NOWIN don't set options local to window
- *
- * Returns immediately if the "ml" option isn't set.
- */
+/// do_modelines() - process mode lines for the current file
+///
+/// @param flags
+/// OPT_WINONLY only set options local to window
+/// OPT_NOWIN don't set options local to window
+///
+/// Returns immediately if the "ml" option isn't set.
void do_modelines(int flags)
{
linenr_T lnum;
@@ -5263,10 +5199,8 @@ static int chk_modeline(linenr_T lnum, int flags)
break;
}
- /*
- * Find end of set command: ':' or end of line.
- * Skip over "\:", replacing it with ":".
- */
+ // Find end of set command: ':' or end of line.
+ // Skip over "\:", replacing it with ":".
for (e = s; *e != ':' && *e != NUL; e++) {
if (e[0] == '\\' && e[1] == ':') {
STRMOVE(e, e + 1);
@@ -5276,13 +5210,11 @@ static int chk_modeline(linenr_T lnum, int flags)
end = true;
}
- /*
- * If there is a "set" command, require a terminating ':' and
- * ignore the stuff after the ':'.
- * "vi:set opt opt opt: foo" -- foo not interpreted
- * "vi:opt opt opt: foo" -- foo interpreted
- * Accept "se" for compatibility with Elvis.
- */
+ // If there is a "set" command, require a terminating ':' and
+ // ignore the stuff after the ':'.
+ // "vi:set opt opt opt: foo" -- foo not interpreted
+ // "vi:opt opt opt: foo" -- foo interpreted
+ // Accept "se" for compatibility with Elvis.
if (STRNCMP(s, "set ", (size_t)4) == 0
|| STRNCMP(s, "se ", (size_t)3) == 0) {
if (*e != ':') { // no terminating ':'?
@@ -5321,36 +5253,36 @@ static int chk_modeline(linenr_T lnum, int flags)
return retval;
}
-// Return true if "buf" is a help buffer.
+/// @return true if "buf" is a help buffer.
bool bt_help(const buf_T *const buf)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
return buf != NULL && buf->b_help;
}
-// Return true if "buf" is a normal buffer, 'buftype' is empty.
+/// @return true if "buf" is a normal buffer, 'buftype' is empty.
bool bt_normal(const buf_T *const buf)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
return buf != NULL && buf->b_p_bt[0] == NUL;
}
-// Return true if "buf" is the quickfix buffer.
+/// @return true if "buf" is the quickfix buffer.
bool bt_quickfix(const buf_T *const buf)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
return buf != NULL && buf->b_p_bt[0] == 'q';
}
-// Return true if "buf" is a terminal buffer.
+/// @return true if "buf" is a terminal buffer.
bool bt_terminal(const buf_T *const buf)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
return buf != NULL && buf->b_p_bt[0] == 't';
}
-// Return true if "buf" is a "nofile", "acwrite", "terminal" or "prompt"
-// buffer. This means the buffer name is not a file name.
+/// @return true if "buf" is a "nofile", "acwrite", "terminal" or "prompt" /
+/// buffer. This means the buffer name is not a file name.
bool bt_nofile(const buf_T *const buf)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -5360,8 +5292,8 @@ bool bt_nofile(const buf_T *const buf)
|| buf->b_p_bt[0] == 'p');
}
-// Return true if "buf" is a "nowrite", "nofile", "terminal" or "prompt"
-// buffer.
+/// @return true if "buf" is a "nowrite", "nofile", "terminal" or "prompt"
+/// buffer.
bool bt_dontwrite(const buf_T *const buf)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -5380,8 +5312,8 @@ bool bt_dontwrite_msg(const buf_T *const buf)
return false;
}
-// Return true if the buffer should be hidden, according to 'hidden', ":hide"
-// and 'bufhidden'.
+/// @return true if the buffer should be hidden, according to 'hidden', ":hide"
+/// and 'bufhidden'.
bool buf_hide(const buf_T *const buf)
{
// 'bufhidden' overrules 'hidden' and ":hide", check it first
@@ -5396,23 +5328,17 @@ bool buf_hide(const buf_T *const buf)
return p_hid || cmdmod.hide;
}
-/*
- * Return special buffer name.
- * Returns NULL when the buffer has a normal file name.
- */
+/// @return special buffer name or
+/// NULL when the buffer has a normal file name.
char_u *buf_spname(buf_T *buf)
{
if (bt_quickfix(buf)) {
- win_T *win;
- tabpage_T *tp;
-
- // For location list window, w_llist_ref points to the location list.
- // For quickfix window, w_llist_ref is NULL.
- if (find_win_for_buf(buf, &win, &tp) && win->w_llist_ref != NULL) {
- return (char_u *)_(msg_loclist);
- } else {
+ // Differentiate between the quickfix and location list buffers using
+ // the buffer number stored in the global quickfix stack.
+ if (buf->b_fnum == qf_stack_get_bufnr()) {
return (char_u *)_(msg_qflist);
}
+ return (char_u *)_(msg_loclist);
}
// There is no _file_ when 'buftype' is "nofile", b_sfname
// contains the name as specified by the user.
@@ -5440,7 +5366,7 @@ char_u *buf_spname(buf_T *buf)
/// @param[out] wp stores the found window
/// @param[out] tp stores the found tabpage
///
-/// @return true if a window was found for the buffer.
+/// @return true if a window was found for the buffer.
bool find_win_for_buf(buf_T *buf, win_T **wp, tabpage_T **tp)
{
*wp = NULL;
@@ -5462,15 +5388,23 @@ static int buf_signcols_inner(buf_T *buf, int maximum)
int linesum = 0;
linenr_T curline = 0;
+ buf->b_signcols.sentinel = 0;
+
FOR_ALL_SIGNS_IN_BUF(buf, sign) {
if (sign->se_lnum > curline) {
+ // Counted all signs, now add extmark signs
+ if (curline > 0) {
+ linesum += decor_signcols(buf, &decor_state, (int)curline-1, (int)curline-1,
+ maximum-linesum);
+ }
+ curline = sign->se_lnum;
if (linesum > signcols) {
signcols = linesum;
+ buf->b_signcols.sentinel = curline;
if (signcols >= maximum) {
return maximum;
}
}
- curline = sign->se_lnum;
linesum = 0;
}
if (sign->se_has_text_or_icon) {
@@ -5478,6 +5412,9 @@ static int buf_signcols_inner(buf_T *buf, int maximum)
}
}
+ if (curline > 0) {
+ linesum += decor_signcols(buf, &decor_state, (int)curline-1, (int)curline-1, maximum-linesum);
+ }
if (linesum > signcols) {
signcols = linesum;
if (signcols >= maximum) {
@@ -5485,26 +5422,113 @@ static int buf_signcols_inner(buf_T *buf, int maximum)
}
}
+ // Check extmarks between signs
+ linesum = decor_signcols(buf, &decor_state, 0, (int)buf->b_ml.ml_line_count-1, maximum);
+
+ if (linesum > signcols) {
+ signcols = linesum;
+ buf->b_signcols.sentinel = curline;
+ if (signcols >= maximum) {
+ return maximum;
+ }
+ }
+
return signcols;
}
+/// Invalidate the signcolumn if needed after deleting
+/// signs between line1 and line2 (inclusive).
+///
+/// @param buf buffer to check
+/// @param line1 start of region being deleted
+/// @param line2 end of region being deleted
+void buf_signcols_del_check(buf_T *buf, linenr_T line1, linenr_T line2)
+{
+ if (!buf->b_signcols.valid) {
+ return;
+ }
+
+ if (!buf->b_signcols.sentinel) {
+ buf->b_signcols.valid = false;
+ return;
+ }
+
+ linenr_T sent = buf->b_signcols.sentinel;
+
+ if (sent >= line1 && sent <= line2) {
+ // Only invalidate when removing signs at the sentinel line.
+ buf->b_signcols.valid = false;
+ }
+}
+
+/// Re-calculate the signcolumn after adding a sign.
+///
+/// @param buf buffer to check
+/// @param added sign being added
+void buf_signcols_add_check(buf_T *buf, sign_entry_T *added)
+{
+ if (!buf->b_signcols.valid) {
+ return;
+ }
+
+ if (!added || !buf->b_signcols.sentinel) {
+ buf->b_signcols.valid = false;
+ return;
+ }
+
+ if (added->se_lnum == buf->b_signcols.sentinel) {
+ if (buf->b_signcols.size == buf->b_signcols.max) {
+ buf->b_signcols.max++;
+ }
+ buf->b_signcols.size++;
+ return;
+ }
+
+ sign_entry_T *s;
+
+ // Get first sign for added lnum
+ for (s = added; s->se_prev && s->se_lnum == s->se_prev->se_lnum; s = s->se_prev) {}
+
+ // Count signs for lnum
+ int linesum = 1;
+ for (; s->se_next && s->se_lnum == s->se_next->se_lnum; s = s->se_next) {
+ linesum++;
+ }
+ linesum += decor_signcols(buf, &decor_state, (int)s->se_lnum-1, (int)s->se_lnum-1,
+ SIGN_SHOW_MAX-linesum);
+
+ if (linesum > buf->b_signcols.size) {
+ buf->b_signcols.size = linesum;
+ buf->b_signcols.max = linesum;
+ buf->b_signcols.sentinel = added->se_lnum;
+ }
+}
+
int buf_signcols(buf_T *buf, int maximum)
{
- if (!buf->b_signcols_valid) {
+ // The maximum can be determined from 'signcolumn' which is window scoped so
+ // need to invalidate signcols if the maximum is greater than the previous
+ // maximum.
+ if (maximum > buf->b_signcols.max) {
+ buf->b_signcols.valid = false;
+ }
+
+ if (!buf->b_signcols.valid) {
int signcols = buf_signcols_inner(buf, maximum);
// Check if we need to redraw
- if (signcols != buf->b_signcols) {
- buf->b_signcols = signcols;
+ if (signcols != buf->b_signcols.size) {
+ buf->b_signcols.size = signcols;
+ buf->b_signcols.max = maximum;
redraw_buf_later(buf, NOT_VALID);
}
- buf->b_signcols_valid = true;
+ buf->b_signcols.valid = true;
}
- return buf->b_signcols;
+ return buf->b_signcols.size;
}
-// Get "buf->b_fname", use "[No Name]" if it is NULL.
+/// Get "buf->b_fname", use "[No Name]" if it is NULL.
char_u *buf_get_fname(const buf_T *buf)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
{
@@ -5514,9 +5538,7 @@ char_u *buf_get_fname(const buf_T *buf)
return buf->b_fname;
}
-/*
- * Set 'buflisted' for curbuf to "on" and trigger autocommands if it changed.
- */
+/// Set 'buflisted' for curbuf to "on" and trigger autocommands if it changed.
void set_buflisted(int on)
{
if (on != curbuf->b_p_bl) {
@@ -5534,7 +5556,7 @@ void set_buflisted(int on)
///
/// @param buf buffer to check
///
-/// @return true if the buffer's contents have changed
+/// @return true if the buffer's contents have changed
bool buf_contents_changed(buf_T *buf)
FUNC_ATTR_NONNULL_ALL
{
@@ -5615,4 +5637,3 @@ void buf_open_scratch(handle_T bufnr, char *bufname)
set_option_value("swf", 0L, NULL, OPT_LOCAL);
RESET_BINDING(curwin);
}
-
diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h
index 7ae5df164f..f9541a55a3 100644
--- a/src/nvim/buffer_defs.h
+++ b/src/nvim/buffer_defs.h
@@ -862,8 +862,12 @@ struct file_buffer {
// may use a different synblock_T.
sign_entry_T *b_signlist; // list of placed signs
- int b_signcols; // last calculated number of sign columns
- bool b_signcols_valid; // calculated sign columns is valid
+ struct {
+ int size; // last calculated number of sign columns
+ bool valid; // calculated sign columns is valid
+ linenr_T sentinel; // a line number which is holding up the signcolumn
+ int max; // Maximum value size is valid for.
+ } b_signcols;
Terminal *terminal; // Terminal instance associated with the buffer
@@ -874,6 +878,7 @@ struct file_buffer {
MarkTree b_marktree[1];
Map(uint32_t, uint32_t) b_extmark_ns[1]; // extmark namespaces
size_t b_virt_line_blocks; // number of virt_line blocks
+ size_t b_signs; // number of sign extmarks
// array of channel_id:s which have asked to receive updates for this
// buffer.
@@ -1227,7 +1232,13 @@ struct window_S {
struct {
int stl;
int stlnc;
+ int horiz;
+ int horizup;
+ int horizdown;
int vert;
+ int vertleft;
+ int vertright;
+ int verthoriz;
int fold;
int foldopen; ///< when fold is open
int foldclosed; ///< when fold is closed
@@ -1273,7 +1284,8 @@ struct window_S {
int w_status_height; // number of status lines (0 or 1)
int w_wincol; // Leftmost column of window in screen.
int w_width; // Width of window, excluding separation.
- int w_vsep_width; // Number of separator columns (0 or 1).
+ int w_hsep_height; // Number of horizontal separator rows (0 or 1)
+ int w_vsep_width; // Number of vertical separator columns (0 or 1).
pos_save_T w_save_cursor; // backup of cursor pos and topline
// inner size of window, which can be overridden by external UI
@@ -1353,6 +1365,7 @@ struct window_S {
// recomputed
int w_nrwidth; // width of 'number' and 'relativenumber'
// column being used
+ int w_scwidth; // width of 'signcolumn'
/*
* === end of cached values ===
diff --git a/src/nvim/change.c b/src/nvim/change.c
index 6ac759d5e0..6c3dbf72e4 100644
--- a/src/nvim/change.c
+++ b/src/nvim/change.c
@@ -42,7 +42,7 @@
/// Careful: may trigger autocommands that reload the buffer.
void change_warning(buf_T *buf, int col)
{
- static char *w_readonly = N_("W10: Warning: Changing a readonly file");
+ static const char *w_readonly = N_("W10: Warning: Changing a readonly file");
if (buf->b_did_warn == false
&& curbufIsChanged() == 0
@@ -140,10 +140,6 @@ void changed_internal(void)
/// Careful: may trigger autocommands that reload the buffer.
static void changed_common(linenr_T lnum, colnr_T col, linenr_T lnume, long xtra)
{
- int i;
- pos_T *p;
- int add;
-
// mark the buffer as modified
changed();
@@ -158,13 +154,14 @@ static void changed_common(linenr_T lnum, colnr_T col, linenr_T lnume, long xtra
// Create a new entry if a new undo-able change was started or we
// don't have an entry yet.
if (curbuf->b_new_change || curbuf->b_changelistlen == 0) {
+ int add;
if (curbuf->b_changelistlen == 0) {
add = true;
} else {
// Don't create a new entry when the line number is the same
// as the last one and the column is not too far away. Avoids
// creating many entries for typing "xxxxx".
- p = &curbuf->b_changelist[curbuf->b_changelistlen - 1].mark;
+ pos_T *p = &curbuf->b_changelist[curbuf->b_changelistlen - 1].mark;
if (p->lnum != lnum) {
add = true;
} else {
@@ -223,26 +220,27 @@ static void changed_common(linenr_T lnum, colnr_T col, linenr_T lnume, long xtra
// values for the cursor.
// Update the folds for this window. Can't postpone this, because
// a following operator might work on the whole fold: ">>dd".
- foldUpdate(wp, lnum, lnume + xtra - 1);
+ linenr_T last = lnume + xtra - 1; // last line after the change
+ foldUpdate(wp, lnum, last);
// The change may cause lines above or below the change to become
// included in a fold. Set lnum/lnume to the first/last line that
// might be displayed differently.
// Set w_cline_folded here as an efficient way to update it when
- // inserting lines just above a closed fold. */
+ // inserting lines just above a closed fold.
bool folded = hasFoldingWin(wp, lnum, &lnum, NULL, false, NULL);
if (wp->w_cursor.lnum == lnum) {
wp->w_cline_folded = folded;
}
- folded = hasFoldingWin(wp, lnume, NULL, &lnume, false, NULL);
- if (wp->w_cursor.lnum == lnume) {
+ folded = hasFoldingWin(wp, last, NULL, &last, false, NULL);
+ if (wp->w_cursor.lnum == last) {
wp->w_cline_folded = folded;
}
// If the changed line is in a range of previously folded lines,
// compare with the first line in that range.
if (wp->w_cursor.lnum <= lnum) {
- i = find_wl_entry(wp, lnum);
+ int i = find_wl_entry(wp, lnum);
if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum) {
changed_line_abv_curs_win(wp);
}
@@ -263,7 +261,7 @@ static void changed_common(linenr_T lnum, colnr_T col, linenr_T lnume, long xtra
// For entries below the change: Correct the lnums for
// inserted/deleted lines. Makes it possible to stop displaying
// after the change.
- for (i = 0; i < wp->w_lines_valid; i++) {
+ for (int i = 0; i < wp->w_lines_valid; i++) {
if (wp->w_lines[i].wl_valid) {
if (wp->w_lines[i].wl_lnum >= lnum) {
if (wp->w_lines[i].wl_lnum < lnume) {
@@ -351,12 +349,10 @@ void changed_bytes(linenr_T lnum, colnr_T col)
// Diff highlighting in other diff windows may need to be updated too.
if (curwin->w_p_diff) {
- linenr_T wlnum;
-
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
if (wp->w_p_diff && wp != curwin) {
redraw_later(wp, VALID);
- wlnum = diff_lnum_win(lnum, wp);
+ linenr_T wlnum = diff_lnum_win(lnum, wp);
if (wlnum > 0) {
changedOneline(wp->w_buffer, wlnum);
}
@@ -412,7 +408,7 @@ void deleted_lines(linenr_T lnum, long count)
/// be triggered to display the cursor.
void deleted_lines_mark(linenr_T lnum, long count)
{
- // if we deleted the entire buffer, we need to implicity add a new empty line
+ // if we deleted the entire buffer, we need to implicitly add a new empty line
bool made_empty = (count > 0) && curbuf->b_ml.ml_flags & ML_EMPTY;
mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM,
@@ -672,21 +668,18 @@ void ins_char_bytes(char_u *buf, size_t charlen)
/// Caller must have prepared for undo.
void ins_str(char_u *s)
{
- char_u *oldp, *newp;
int newlen = (int)STRLEN(s);
- int oldlen;
- colnr_T col;
linenr_T lnum = curwin->w_cursor.lnum;
if (virtual_active() && curwin->w_cursor.coladd > 0) {
coladvance_force(getviscol());
}
- col = curwin->w_cursor.col;
- oldp = ml_get(lnum);
- oldlen = (int)STRLEN(oldp);
+ colnr_T col = curwin->w_cursor.col;
+ char_u *oldp = ml_get(lnum);
+ int oldlen = (int)STRLEN(oldp);
- newp = (char_u *)xmalloc((size_t)oldlen + (size_t)newlen + 1);
+ char_u *newp = (char_u *)xmalloc((size_t)oldlen + (size_t)newlen + 1);
if (col > 0) {
memmove(newp, oldp, (size_t)col);
}
@@ -718,13 +711,9 @@ int del_char(bool fixpos)
int del_chars(long count, int fixpos)
{
int bytes = 0;
- long i;
- char_u *p;
- int l;
-
- p = get_cursor_pos_ptr();
- for (i = 0; i < count && *p != NUL; i++) {
- l = utfc_ptr2len(p);
+ char_u *p = get_cursor_pos_ptr();
+ for (long i = 0; i < count && *p != NUL; i++) {
+ int l = utfc_ptr2len(p);
bytes += l;
p += l;
}
@@ -767,12 +756,11 @@ int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine)
if (p_deco && use_delcombine
&& utfc_ptr2len(oldp + col) >= count) {
int cc[MAX_MCO];
- int n;
(void)utfc_ptr2char(oldp + col, cc);
if (cc[0] != NUL) {
// Find the last composing char, there can be several.
- n = col;
+ int n = col;
do {
col = n;
count = utf_ptr2len(oldp + n);
@@ -827,23 +815,18 @@ int copy_indent(int size, char_u *src)
{
char_u *p = NULL;
char_u *line = NULL;
- char_u *s;
- int todo;
int ind_len;
int line_len = 0;
int tab_pad;
- int ind_done;
- int round;
- int ind_col;
// Round 1: compute the number of characters needed for the indent
// Round 2: copy the characters.
- for (round = 1; round <= 2; round++) {
- todo = size;
+ for (int round = 1; round <= 2; round++) {
+ int todo = size;
ind_len = 0;
- ind_done = 0;
- ind_col = 0;
- s = src;
+ int ind_done = 0;
+ int ind_col = 0;
+ char_u *s = src;
// Count/copy the usable portion of the source line.
while (todo > 0 && ascii_iswhite(*s)) {
@@ -1064,7 +1047,6 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment)
if (!trunc_line && do_si && *saved_line != NUL
&& (p_extra == NULL || first_char != '{')) {
char_u *ptr;
- char_u last_char;
old_cursor = curwin->w_cursor;
ptr = saved_line;
@@ -1074,8 +1056,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment)
lead_len = 0;
}
if (dir == FORWARD) {
- // Skip preprocessor directives, unless they are
- // recognised as comments.
+ // Skip preprocessor directives, unless they are recognised as comments.
if (lead_len == 0 && ptr[0] == '#') {
while (ptr[0] == '#' && curwin->w_cursor.lnum > 1) {
ptr = ml_get(--curwin->w_cursor.lnum);
@@ -1118,7 +1099,7 @@ int open_line(int dir, int flags, int second_line_indent, bool *did_do_comment)
while (p > ptr && ascii_iswhite(*p)) {
p--;
}
- last_char = *p;
+ char_u last_char = *p;
// find the character just before the '{' or ';'
if (last_char == '{' || last_char == ';') {
@@ -1895,10 +1876,8 @@ void del_lines(long nlines, bool undo)
/// If "include_space" is set, include trailing whitespace while calculating the length.
int get_leader_len(char_u *line, char_u **flags, bool backward, bool include_space)
{
- int i, j;
- int result;
+ int j;
int got_com = false;
- int found_one;
char_u part_buf[COM_MAX_LEN]; // buffer for one option part
char_u *string; // pointer to comment string
char_u *list;
@@ -1906,7 +1885,8 @@ int get_leader_len(char_u *line, char_u **flags, bool backward, bool include_spa
char_u *prev_list;
char_u *saved_flags = NULL;
- result = i = 0;
+ int result = 0;
+ int i = 0;
while (ascii_iswhite(line[i])) { // leading white space is ignored
i++;
}
@@ -1914,7 +1894,7 @@ int get_leader_len(char_u *line, char_u **flags, bool backward, bool include_spa
// Repeat to match several nested comment strings.
while (line[i] != NUL) {
// scan through the 'comments' option for a match
- found_one = false;
+ int found_one = false;
for (list = curbuf->b_p_com; *list;) {
// Get one option part into part_buf[]. Advance "list" to next
// one. Put "string" at start of string.
@@ -2040,20 +2020,19 @@ int get_leader_len(char_u *line, char_u **flags, bool backward, bool include_spa
int get_last_leader_offset(char_u *line, char_u **flags)
{
int result = -1;
- int i, j;
+ int j;
int lower_check_bound = 0;
char_u *string;
char_u *com_leader;
char_u *com_flags;
char_u *list;
- int found_one;
char_u part_buf[COM_MAX_LEN]; // buffer for one option part
// Repeat to match several nested comment strings.
- i = (int)STRLEN(line);
+ int i = (int)STRLEN(line);
while (--i >= lower_check_bound) {
// scan through the 'comments' option for a match
- found_one = false;
+ int found_one = false;
for (list = curbuf->b_p_com; *list;) {
char_u *flags_save = list;
diff --git a/src/nvim/channel.c b/src/nvim/channel.c
index d79c0acc4a..f87b3a2f8f 100644
--- a/src/nvim/channel.c
+++ b/src/nvim/channel.c
@@ -138,8 +138,14 @@ bool channel_close(uint64_t id, ChannelPart part, const char **error)
*error = (const char *)e_invstream;
return false;
}
- api_free_luaref(chan->stream.internal.cb);
- chan->stream.internal.cb = LUA_NOREF;
+ if (chan->term) {
+ api_free_luaref(chan->stream.internal.cb);
+ chan->stream.internal.cb = LUA_NOREF;
+ chan->stream.internal.closed = true;
+ terminal_close(chan->term, 0);
+ } else {
+ channel_decref(chan);
+ }
break;
default:
@@ -536,7 +542,11 @@ size_t channel_send(uint64_t id, char *data, size_t len, bool data_owned, const
}
if (chan->streamtype == kChannelStreamInternal) {
- if (!chan->term) {
+ if (chan->is_rpc) {
+ *error = _("Can't send raw data to rpc channel");
+ goto retfree;
+ }
+ if (!chan->term || chan->stream.internal.closed) {
*error = _("Can't send data to closed stream");
goto retfree;
}
diff --git a/src/nvim/channel.h b/src/nvim/channel.h
index 50d6b3600a..5cec5731eb 100644
--- a/src/nvim/channel.h
+++ b/src/nvim/channel.h
@@ -44,6 +44,7 @@ typedef struct {
typedef struct {
LuaRef cb;
+ bool closed;
} InternalState;
typedef struct {
diff --git a/src/nvim/charset.c b/src/nvim/charset.c
index 583a040ed1..986a89b0a5 100644
--- a/src/nvim/charset.c
+++ b/src/nvim/charset.c
@@ -159,7 +159,7 @@ int buf_init_chartab(buf_T *buf, int global)
if ((*p == '^') && (p[1] != NUL)) {
tilde = true;
- ++p;
+ p++;
}
if (ascii_isdigit(*p)) {
@@ -170,7 +170,7 @@ int buf_init_chartab(buf_T *buf, int global)
c2 = -1;
if ((*p == '-') && (p[1] != NUL)) {
- ++p;
+ p++;
if (ascii_isdigit(*p)) {
c2 = getdigits_int((char_u **)&p, true, 0);
@@ -243,7 +243,7 @@ int buf_init_chartab(buf_T *buf, int global)
}
}
}
- ++c;
+ c++;
}
c = *p;
@@ -268,15 +268,12 @@ int buf_init_chartab(buf_T *buf, int global)
/// @param bufsize
void trans_characters(char_u *buf, int bufsize)
{
- int len; // length of string needing translation
- int room; // room in buffer after string
- char_u *trs; // translated character
- int trs_len; // length of trs[]
-
- len = (int)STRLEN(buf);
- room = bufsize - len;
+ char_u *trs; // translated character
+ int len = (int)STRLEN(buf); // length of string needing translation
+ int room = bufsize - len; // room in buffer after string
while (*buf != 0) {
+ int trs_len; // length of trs[]
// Assume a multi-byte character doesn't need translation.
if ((trs_len = utfc_ptr2len(buf)) > 1) {
len -= trs_len;
@@ -292,7 +289,7 @@ void trans_characters(char_u *buf, int bufsize)
memmove(buf + trs_len, buf + 1, (size_t)len);
}
memmove(buf, trs, (size_t)trs_len);
- --len;
+ len--;
}
buf += trs_len;
}
@@ -873,14 +870,11 @@ bool vim_isprintc_strict(int c)
bool in_win_border(win_T *wp, colnr_T vcol)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
{
- int width1; // width of first line (after line number)
- int width2; // width of further lines
-
if (wp->w_width_inner == 0) {
// there is no border
return false;
}
- width1 = wp->w_width_inner - win_col_off(wp);
+ int width1 = wp->w_width_inner - win_col_off(wp); // width of first line (after line number)
if ((int)vcol < width1 - 1) {
return false;
@@ -889,7 +883,7 @@ bool in_win_border(win_T *wp, colnr_T vcol)
if ((int)vcol == width1 - 1) {
return true;
}
- width2 = width1 + win_col_off2(wp);
+ int width2 = width1 + win_col_off2(wp); // width of further lines
if (width2 <= 0) {
return false;
@@ -911,27 +905,26 @@ bool in_win_border(win_T *wp, colnr_T vcol)
/// @param end
void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *end)
{
- colnr_T vcol;
char_u *ptr; // points to current char
char_u *posptr; // points to char at pos->col
- char_u *line; // start of the line
int incr;
int head;
long *vts = wp->w_buffer->b_p_vts_array;
int ts = (int)wp->w_buffer->b_p_ts;
- int c;
- vcol = 0;
- line = ptr = ml_get_buf(wp->w_buffer, pos->lnum, false);
+ colnr_T vcol = 0;
+ char_u *line = ptr = ml_get_buf(wp->w_buffer, pos->lnum, false); // start of the line
if (pos->col == MAXCOL) {
// continue until the NUL
posptr = NULL;
} else {
- // Special check for an empty line, which can happen on exit, when
- // ml_get_buf() always returns an empty string.
- if (*ptr == NUL) {
- pos->col = 0;
+ // In a few cases the position can be beyond the end of the line.
+ for (colnr_T i = 0; i < pos->col; i++) {
+ if (ptr[i] == NUL) {
+ pos->col = i;
+ break;
+ }
}
posptr = ptr + pos->col;
posptr -= utf_head_off(line, posptr);
@@ -947,7 +940,7 @@ void getvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *en
&& !wp->w_p_bri) {
for (;;) {
head = 0;
- c = *ptr;
+ int c = *ptr;
// make sure we don't go past the end of the line
if (c == NUL) {
@@ -1064,19 +1057,16 @@ colnr_T getvcol_nolist(pos_T *posp)
void getvvcol(win_T *wp, pos_T *pos, colnr_T *start, colnr_T *cursor, colnr_T *end)
{
colnr_T col;
- colnr_T coladd;
- colnr_T endadd;
- char_u *ptr;
if (virtual_active()) {
// For virtual mode, only want one value
getvcol(wp, pos, &col, NULL, NULL);
- coladd = pos->coladd;
- endadd = 0;
+ colnr_T coladd = pos->coladd;
+ colnr_T endadd = 0;
// Cannot put the cursor on part of a wide character.
- ptr = ml_get_buf(wp->w_buffer, pos->lnum, false);
+ char_u *ptr = ml_get_buf(wp->w_buffer, pos->lnum, false);
if (pos->col < (colnr_T)STRLEN(ptr)) {
int c = utf_ptr2char(ptr + pos->col);
@@ -1312,9 +1302,9 @@ char_u *skiptowhite_esc(char_u *p)
{
while (*p != ' ' && *p != '\t' && *p != NUL) {
if (((*p == '\\') || (*p == Ctrl_V)) && (*(p + 1) != NUL)) {
- ++p;
+ p++;
}
- ++p;
+ p++;
}
return p;
}
@@ -1439,7 +1429,7 @@ bool vim_isblankline(char_u *lbuf)
/// @param unptr Returns the unsigned result.
/// @param maxlen Max length of string to check.
/// @param strict If true, fail if the number has unexpected trailing
-/// alpha-numeric chars: *len is set to 0 and nothing else is
+/// alphanumeric chars: *len is set to 0 and nothing else is
/// returned.
void vim_str2nr(const char_u *const start, int *const prep, int *const len, const int what,
varnumber_T *const nptr, uvarnumber_T *const unptr, const int maxlen,
@@ -1500,7 +1490,7 @@ void vim_str2nr(const char_u *const start, int *const prep, int *const len, cons
} else if ((what & (STR2NR_HEX | STR2NR_OCT | STR2NR_OOCT | STR2NR_BIN))
&& !STRING_ENDED(ptr + 1) && ptr[0] == '0' && ptr[1] != '8'
&& ptr[1] != '9') {
- pre = ptr[1];
+ pre = (char_u)ptr[1];
// Detect hexadecimal: 0x or 0X followed by hex digit.
if ((what & STR2NR_HEX)
&& !STRING_ENDED(ptr + 2)
@@ -1585,7 +1575,7 @@ vim_str2nr_hex:
#undef PARSE_NUMBER
vim_str2nr_proceed:
- // Check for an alpha-numeric character immediately following, that is
+ // Check for an alphanumeric character immediately following, that is
// most likely a typo.
if (strict && ptr - (const char *)start != maxlen && ASCII_ISALNUM(*ptr)) {
return;
@@ -1684,7 +1674,7 @@ bool rem_backslash(const char_u *str)
/// @param p
void backslash_halve(char_u *p)
{
- for (; *p; ++p) {
+ for (; *p; p++) {
if (rem_backslash(p)) {
STRMOVE(p, p + 1);
}
diff --git a/src/nvim/context.c b/src/nvim/context.c
index 614a3ce30e..9434b4e0ea 100644
--- a/src/nvim/context.c
+++ b/src/nvim/context.c
@@ -256,7 +256,8 @@ static inline void ctx_save_funcs(Context *ctx, bool scriptonly)
size_t cmd_len = sizeof("func! ") + STRLEN(name);
char *cmd = xmalloc(cmd_len);
snprintf(cmd, cmd_len, "func! %s", name);
- String func_body = nvim_exec(cstr_as_string(cmd), true, &err);
+ String func_body = nvim_exec(VIML_INTERNAL_CALL, cstr_as_string(cmd),
+ true, &err);
xfree(cmd);
if (!ERROR_SET(&err)) {
ADD(ctx->funcs, STRING_OBJ(func_body));
diff --git a/src/nvim/cursor.c b/src/nvim/cursor.c
index 55f55a46b2..d924119fdf 100644
--- a/src/nvim/cursor.c
+++ b/src/nvim/cursor.c
@@ -25,9 +25,7 @@
# include "cursor.c.generated.h"
#endif
-/*
- * Get the screen position of the cursor.
- */
+/// @return the screen position of the cursor.
int getviscol(void)
{
colnr_T x;
@@ -36,9 +34,7 @@ int getviscol(void)
return (int)x;
}
-/*
- * Get the screen position of character col with a coladd in the cursor line.
- */
+/// @return the screen position of character col with a coladd in the cursor line.
int getviscol2(colnr_T col, colnr_T coladd)
{
colnr_T x;
@@ -51,11 +47,9 @@ int getviscol2(colnr_T col, colnr_T coladd)
return (int)x;
}
-/*
- * Go to column "wcol", and add/insert white space as necessary to get the
- * cursor in that column.
- * The caller must have saved the cursor line for undo!
- */
+/// Go to column "wcol", and add/insert white space as necessary to get the
+/// cursor in that column.
+/// The caller must have saved the cursor line for undo!
int coladvance_force(colnr_T wcol)
{
int rc = coladvance2(&curwin->w_cursor, true, false, wcol);
@@ -70,15 +64,13 @@ int coladvance_force(colnr_T wcol)
return rc;
}
-/*
- * Try to advance the Cursor to the specified screen column.
- * If virtual editing: fine tune the cursor position.
- * Note that all virtual positions off the end of a line should share
- * a curwin->w_cursor.col value (n.b. this is equal to STRLEN(line)),
- * beginning at coladd 0.
- *
- * return OK if desired column is reached, FAIL if not
- */
+/// Try to advance the Cursor to the specified screen column.
+/// If virtual editing: fine tune the cursor position.
+/// Note that all virtual positions off the end of a line should share
+/// a curwin->w_cursor.col value (n.b. this is equal to STRLEN(line)),
+/// beginning at coladd 0.
+///
+/// @return OK if desired column is reached, FAIL if not
int coladvance(colnr_T wcol)
{
int rc = getvpos(&curwin->w_cursor, wcol);
@@ -100,19 +92,16 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a
{
colnr_T wcol = wcol_arg;
int idx;
- char_u *ptr;
- char_u *line;
colnr_T col = 0;
- int csize = 0;
- int one_more;
int head = 0;
- one_more = (State & INSERT)
- || (State & TERM_FOCUS)
- || restart_edit != NUL
- || (VIsual_active && *p_sel != 'o')
- || ((get_ve_flags() & VE_ONEMORE) && wcol < MAXCOL);
- line = ml_get_buf(curbuf, pos->lnum, false);
+ int one_more = (State & INSERT)
+ || (State & TERM_FOCUS)
+ || restart_edit != NUL
+ || (VIsual_active && *p_sel != 'o')
+ || ((get_ve_flags() & VE_ONEMORE) && wcol < MAXCOL);
+
+ char_u *line = ml_get_buf(curbuf, pos->lnum, false);
if (wcol >= MAXCOL) {
idx = (int)STRLEN(line) - 1 + one_more;
@@ -121,11 +110,12 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a
if ((addspaces || finetune) && !VIsual_active) {
curwin->w_curswant = linetabsize(line) + one_more;
if (curwin->w_curswant > 0) {
- --curwin->w_curswant;
+ curwin->w_curswant--;
}
}
} else {
int width = curwin->w_width_inner - win_col_off(curwin);
+ int csize = 0;
if (finetune
&& curwin->w_p_wrap
@@ -139,15 +129,15 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a
if (wcol / width > (colnr_T)csize / width
&& ((State & INSERT) == 0 || (int)wcol > csize + 1)) {
- /* In case of line wrapping don't move the cursor beyond the
- * right screen edge. In Insert mode allow going just beyond
- * the last character (like what happens when typing and
- * reaching the right window edge). */
+ // In case of line wrapping don't move the cursor beyond the
+ // right screen edge. In Insert mode allow going just beyond
+ // the last character (like what happens when typing and
+ // reaching the right window edge).
wcol = (csize / width + 1) * width - 1;
}
}
- ptr = line;
+ char_u *ptr = line;
while (col <= wcol && *ptr != NUL) {
// Count a tab for what it's worth (if list mode not on)
csize = win_lbr_chartabsize(curwin, line, ptr, col, &head);
@@ -155,12 +145,10 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a
col += csize;
}
idx = (int)(ptr - line);
- /*
- * Handle all the special cases. The virtual_active() check
- * is needed to ensure that a virtual position off the end of
- * a line has the correct indexing. The one_more comparison
- * replaces an explicit add of one_more later on.
- */
+ // Handle all the special cases. The virtual_active() check
+ // is needed to ensure that a virtual position off the end of
+ // a line has the correct indexing. The one_more comparison
+ // replaces an explicit add of one_more later on.
if (col > wcol || (!virtual_active() && one_more == 0)) {
idx -= 1;
// Don't count the chars from 'showbreak'.
@@ -172,8 +160,7 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a
&& addspaces
&& wcol >= 0
&& ((col != wcol && col != wcol + 1) || csize > 1)) {
- /* 'virtualedit' is set: The difference between wcol and col is
- * filled with spaces. */
+ // 'virtualedit' is set: The difference between wcol and col is filled with spaces.
if (line[idx] == NUL) {
// Append spaces
@@ -256,29 +243,23 @@ static int coladvance2(pos_T *pos, bool addspaces, bool finetune, colnr_T wcol_a
return OK;
}
-/*
- * Return in "pos" the position of the cursor advanced to screen column "wcol".
- * return OK if desired column is reached, FAIL if not
- */
+/// Return in "pos" the position of the cursor advanced to screen column "wcol".
+///
+/// @return OK if desired column is reached, FAIL if not
int getvpos(pos_T *pos, colnr_T wcol)
{
return coladvance2(pos, false, virtual_active(), wcol);
}
-/*
- * Increment the cursor position. See inc() for return values.
- */
+/// Increment the cursor position. See inc() for return values.
int inc_cursor(void)
{
return inc(&curwin->w_cursor);
}
-/*
- * dec(p)
- *
- * Decrement the line pointer 'p' crossing line boundaries as necessary.
- * Return 1 when crossing a line, -1 when at start of file, 0 otherwise.
- */
+/// Decrement the line pointer 'p' crossing line boundaries as necessary.
+///
+/// @return 1 when crossing a line, -1 when at start of file, 0 otherwise.
int dec_cursor(void)
{
return dec(&curwin->w_cursor);
@@ -314,34 +295,29 @@ linenr_T get_cursor_rel_lnum(win_T *wp, linenr_T lnum)
return (lnum < cursor) ? -retval : retval;
}
-// Make sure "pos.lnum" and "pos.col" are valid in "buf".
-// This allows for the col to be on the NUL byte.
+/// Make sure "pos.lnum" and "pos.col" are valid in "buf".
+/// This allows for the col to be on the NUL byte.
void check_pos(buf_T *buf, pos_T *pos)
{
- char_u *line;
- colnr_T len;
-
if (pos->lnum > buf->b_ml.ml_line_count) {
pos->lnum = buf->b_ml.ml_line_count;
}
if (pos->col > 0) {
- line = ml_get_buf(buf, pos->lnum, false);
- len = (colnr_T)STRLEN(line);
+ char_u *line = ml_get_buf(buf, pos->lnum, false);
+ colnr_T len = (colnr_T)STRLEN(line);
if (pos->col > len) {
pos->col = len;
}
}
}
-/*
- * Make sure curwin->w_cursor.lnum is valid.
- */
+/// Make sure curwin->w_cursor.lnum is valid.
void check_cursor_lnum(void)
{
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) {
- /* If there is a closed fold at the end of the file, put the cursor in
- * its first line. Otherwise in the last line. */
+ // If there is a closed fold at the end of the file, put the cursor in
+ // its first line. Otherwise in the last line.
if (!hasFolding(curbuf->b_ml.ml_line_count,
&curwin->w_cursor.lnum, NULL)) {
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
@@ -352,9 +328,7 @@ void check_cursor_lnum(void)
}
}
-/*
- * Make sure curwin->w_cursor.col is valid.
- */
+/// Make sure curwin->w_cursor.col is valid.
void check_cursor_col(void)
{
check_cursor_col_win(curwin);
@@ -364,19 +338,18 @@ void check_cursor_col(void)
/// @see mb_check_adjust_col
void check_cursor_col_win(win_T *win)
{
- colnr_T len;
colnr_T oldcol = win->w_cursor.col;
colnr_T oldcoladd = win->w_cursor.col + win->w_cursor.coladd;
unsigned int cur_ve_flags = get_ve_flags();
- len = (colnr_T)STRLEN(ml_get_buf(win->w_buffer, win->w_cursor.lnum, false));
+ colnr_T len = (colnr_T)STRLEN(ml_get_buf(win->w_buffer, win->w_cursor.lnum, false));
if (len == 0) {
win->w_cursor.col = 0;
} else if (win->w_cursor.col >= len) {
- /* Allow cursor past end-of-line when:
- * - in Insert mode or restarting Insert mode
- * - in Visual mode and 'selection' isn't "old"
- * - 'virtualedit' is set */
+ // Allow cursor past end-of-line when:
+ // - in Insert mode or restarting Insert mode
+ // - in Visual mode and 'selection' isn't "old"
+ // - 'virtualedit' is set */
if ((State & INSERT) || restart_edit
|| (VIsual_active && *p_sel != 'o')
|| (cur_ve_flags & VE_ONEMORE)
@@ -419,32 +392,27 @@ void check_cursor_col_win(win_T *win)
}
}
-/*
- * make sure curwin->w_cursor in on a valid character
- */
+/// Make sure curwin->w_cursor in on a valid character
void check_cursor(void)
{
check_cursor_lnum();
check_cursor_col();
}
-/*
- * Make sure curwin->w_cursor is not on the NUL at the end of the line.
- * Allow it when in Visual mode and 'selection' is not "old".
- */
+/// Make sure curwin->w_cursor is not on the NUL at the end of the line.
+/// Allow it when in Visual mode and 'selection' is not "old".
void adjust_cursor_col(void)
{
if (curwin->w_cursor.col > 0
&& (!VIsual_active || *p_sel == 'o')
&& gchar_cursor() == NUL) {
- --curwin->w_cursor.col;
+ curwin->w_cursor.col--;
}
}
-/*
- * When curwin->w_leftcol has changed, adjust the cursor position.
- * Return true if the cursor was moved.
- */
+/// When curwin->w_leftcol has changed, adjust the cursor position.
+///
+/// @return true if the cursor was moved.
bool leftcol_changed(void)
{
// TODO(hinidu): I think it should be colnr_T or int, but p_siso is long.
@@ -457,10 +425,8 @@ bool leftcol_changed(void)
lastcol = curwin->w_leftcol + curwin->w_width_inner - curwin_col_off() - 1;
validate_virtcol();
- /*
- * If the cursor is right or left of the screen, move it to last or first
- * character.
- */
+ // If the cursor is right or left of the screen, move it to last or first
+ // character.
if (curwin->w_virtcol > (colnr_T)(lastcol - p_siso)) {
retval = true;
coladvance((colnr_T)(lastcol - p_siso));
@@ -469,11 +435,9 @@ bool leftcol_changed(void)
coladvance((colnr_T)(curwin->w_leftcol + p_siso));
}
- /*
- * If the start of the character under the cursor is not on the screen,
- * advance the cursor one more char. If this fails (last char of the
- * line) adjust the scrolling.
- */
+ // If the start of the character under the cursor is not on the screen,
+ // advance the cursor one more char. If this fails (last char of the
+ // line) adjust the scrolling.
getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e);
if (e > (colnr_T)lastcol) {
retval = true;
@@ -498,27 +462,21 @@ int gchar_cursor(void)
return utf_ptr2char(get_cursor_pos_ptr());
}
-/*
- * Write a character at the current cursor position.
- * It is directly written into the block.
- */
+/// Write a character at the current cursor position.
+/// It is directly written into the block.
void pchar_cursor(char_u c)
{
*(ml_get_buf(curbuf, curwin->w_cursor.lnum, true)
+ curwin->w_cursor.col) = c;
}
-/*
- * Return pointer to cursor line.
- */
+/// @return pointer to cursor line.
char_u *get_cursor_line_ptr(void)
{
return ml_get_buf(curbuf, curwin->w_cursor.lnum, false);
}
-/*
- * Return pointer to cursor position.
- */
+/// @return pointer to cursor position.
char_u *get_cursor_pos_ptr(void)
{
return ml_get_buf(curbuf, curwin->w_cursor.lnum, false) +
diff --git a/src/nvim/cursor_shape.c b/src/nvim/cursor_shape.c
index 6b0a5dfe12..cb8c8cddf6 100644
--- a/src/nvim/cursor_shape.c
+++ b/src/nvim/cursor_shape.c
@@ -74,8 +74,7 @@ Array mode_style_array(void)
PUT(dic, "hl_id", INTEGER_OBJ(cur->id));
PUT(dic, "id_lm", INTEGER_OBJ(cur->id_lm));
PUT(dic, "attr_id", INTEGER_OBJ(cur->id ? syn_id2attr(cur->id) : 0));
- PUT(dic, "attr_id_lm", INTEGER_OBJ(cur->id_lm ? syn_id2attr(cur->id_lm)
- : 0));
+ PUT(dic, "attr_id_lm", INTEGER_OBJ(cur->id_lm ? syn_id2attr(cur->id_lm) : 0));
}
PUT(dic, "name", STRING_OBJ(cstr_to_string(cur->full_name)));
PUT(dic, "short_name", STRING_OBJ(cstr_to_string(cur->name)));
@@ -95,7 +94,6 @@ Array mode_style_array(void)
/// @returns error message for an illegal option, NULL otherwise.
char *parse_shape_opt(int what)
{
- char_u *modep;
char_u *colonp;
char_u *commap;
char_u *slashp;
@@ -120,7 +118,7 @@ char *parse_shape_opt(int what)
}
}
// Repeat for all comma separated parts.
- modep = p_guicursor;
+ char_u *modep = p_guicursor;
while (modep != NULL && *modep != NUL) {
colonp = vim_strchr(modep, ':');
commap = vim_strchr(modep, ',');
@@ -147,7 +145,7 @@ char *parse_shape_opt(int what)
if (len == 1 && TOLOWER_ASC(modep[0]) == 'a') {
all_idx = SHAPE_IDX_COUNT - 1;
} else {
- for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx) {
+ for (idx = 0; idx < SHAPE_IDX_COUNT; idx++) {
if (STRNICMP(modep, shape_table[idx].name, len) == 0) {
break;
}
@@ -170,9 +168,7 @@ char *parse_shape_opt(int what)
// Parse the part after the colon
for (p = colonp + 1; *p && *p != ',';) {
{
- /*
- * First handle the ones with a number argument.
- */
+ // First handle the ones with a number argument.
i = *p;
len = 0;
if (STRNICMP(p, "ver", 3) == 0) {
@@ -245,7 +241,7 @@ char *parse_shape_opt(int what)
} // if (what != SHAPE_MOUSE)
if (*p == '-') {
- ++p;
+ p++;
}
}
}
diff --git a/src/nvim/debugger.c b/src/nvim/debugger.c
index 75ebf0084e..cd823546b4 100644
--- a/src/nvim/debugger.c
+++ b/src/nvim/debugger.c
@@ -58,7 +58,6 @@ void do_debug(char_u *cmd)
tasave_T typeaheadbuf;
bool typeahead_saved = false;
int save_ignore_script = 0;
- int save_ex_normal_busy;
int n;
char_u *cmdline = NULL;
char_u *p;
@@ -117,7 +116,7 @@ void do_debug(char_u *cmd)
// with the commands being executed. Reset "ex_normal_busy" to avoid
// the side effects of using ":normal". Save the stuff buffer and make
// it empty. Set ignore_script to avoid reading from script input.
- save_ex_normal_busy = ex_normal_busy;
+ int save_ex_normal_busy = ex_normal_busy;
ex_normal_busy = 0;
if (!debug_greedy) {
save_typeahead(&typeaheadbuf);
@@ -201,7 +200,7 @@ void do_debug(char_u *cmd)
if (last_cmd != 0) {
// Check that the tail matches.
p++;
- while (*p != NUL && *p == *tail) {
+ while (*p != NUL && *p == (char_u)(*tail)) {
p++;
tail++;
}
@@ -390,11 +389,10 @@ static char_u *debug_skipped_name;
/// Called from do_one_cmd() before executing a command.
void dbg_check_breakpoint(exarg_T *eap)
{
- char *p;
-
debug_skipped = false;
if (debug_breakpoint_name != NULL) {
if (!eap->skip) {
+ char *p;
// replace K_SNR with "<SNR>"
if (debug_breakpoint_name[0] == K_SPECIAL
&& debug_breakpoint_name[1] == KS_EXTRA
@@ -430,12 +428,10 @@ void dbg_check_breakpoint(exarg_T *eap)
/// @return true when the debug mode is entered this time.
bool dbg_check_skipped(exarg_T *eap)
{
- int prev_got_int;
-
if (debug_skipped) {
// Save the value of got_int and reset it. We don't want a previous
// interruption cause flushing the input buffer.
- prev_got_int = got_int;
+ int prev_got_int = got_int;
got_int = false;
debug_breakpoint_name = debug_skipped_name;
// eap->skip is true
@@ -482,12 +478,11 @@ static int dbg_parsearg(char_u *arg, garray_T *gap)
{
char_u *p = arg;
char_u *q;
- struct debuggy *bp;
bool here = false;
ga_grow(gap, 1);
- bp = &DEBUGGY(gap, gap->ga_len);
+ struct debuggy *bp = &DEBUGGY(gap, gap->ga_len);
// Find "func" or "file".
if (STRNCMP(p, "func", 4) == 0) {
@@ -564,16 +559,13 @@ static int dbg_parsearg(char_u *arg, garray_T *gap)
/// ":breakadd". Also used for ":profile".
void ex_breakadd(exarg_T *eap)
{
- struct debuggy *bp;
- garray_T *gap;
-
- gap = &dbg_breakp;
+ garray_T *gap = &dbg_breakp;
if (eap->cmdidx == CMD_profile) {
gap = &prof_ga;
}
if (dbg_parsearg(eap->arg, gap) == OK) {
- bp = &DEBUGGY(gap, gap->ga_len);
+ struct debuggy *bp = &DEBUGGY(gap, gap->ga_len);
bp->dbg_forceit = eap->forceit;
if (bp->dbg_type != DBG_EXPR) {
@@ -616,20 +608,18 @@ void ex_debuggreedy(exarg_T *eap)
void ex_breakdel(exarg_T *eap)
{
struct debuggy *bp, *bpi;
- int nr;
int todel = -1;
bool del_all = false;
linenr_T best_lnum = 0;
- garray_T *gap;
+ garray_T *gap = &dbg_breakp;
- gap = &dbg_breakp;
if (eap->cmdidx == CMD_profdel) {
gap = &prof_ga;
}
if (ascii_isdigit(*eap->arg)) {
// ":breakdel {nr}"
- nr = atoi((char *)eap->arg);
+ int nr = atoi((char *)eap->arg);
for (int i = 0; i < gap->ga_len; i++) {
if (DEBUGGY(gap, i).dbg_nr == nr) {
todel = i;
@@ -693,13 +683,11 @@ void ex_breakdel(exarg_T *eap)
/// ":breaklist".
void ex_breaklist(exarg_T *eap)
{
- struct debuggy *bp;
-
if (GA_EMPTY(&dbg_breakp)) {
msg(_("No breakpoints defined"));
} else {
for (int i = 0; i < dbg_breakp.ga_len; i++) {
- bp = &BREAKP(i);
+ struct debuggy *bp = &BREAKP(i);
if (bp->dbg_type == DBG_FILE) {
home_replace(NULL, bp->dbg_name, NameBuff, MAXPATHL, true);
}
diff --git a/src/nvim/decoration.c b/src/nvim/decoration.c
index 935b233752..94bf1feeee 100644
--- a/src/nvim/decoration.c
+++ b/src/nvim/decoration.c
@@ -1,10 +1,12 @@
// 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 "nvim/buffer.h"
#include "nvim/decoration.h"
#include "nvim/extmark.h"
#include "nvim/highlight.h"
#include "nvim/lua/executor.h"
+#include "nvim/move.h"
#include "nvim/screen.h"
#include "nvim/syntax.h"
#include "nvim/vim.h"
@@ -65,8 +67,10 @@ void bufhl_add_hl_pos_offset(buf_T *buf, int src_id, int hl_id, lpos_T pos_start
void decor_redraw(buf_T *buf, int row1, int row2, Decoration *decor)
{
- if ((!decor || decor->hl_id) && row2 >= row1) {
- redraw_buf_range_later(buf, row1+1, row2+1);
+ if (row2 >= row1) {
+ if (!decor || decor->hl_id || decor_has_sign(decor)) {
+ redraw_buf_range_later(buf, row1+1, row2+1);
+ }
}
if (decor && kv_size(decor->virt_text)) {
@@ -82,9 +86,18 @@ void decor_redraw(buf_T *buf, int row1, int row2, Decoration *decor)
void decor_remove(buf_T *buf, int row, int row2, Decoration *decor)
{
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--;
+ if (decor) {
+ if (kv_size(decor->virt_lines)) {
+ assert(buf->b_virt_line_blocks > 0);
+ buf->b_virt_line_blocks--;
+ }
+ if (decor_has_sign(decor)) {
+ assert(buf->b_signs > 0);
+ buf->b_signs--;
+ }
+ if (row2 >= row && decor->sign_text) {
+ buf_signcols_del_check(buf, row+1, row2+1);
+ }
}
decor_free(decor);
}
@@ -97,6 +110,7 @@ void decor_free(Decoration *decor)
clear_virttext(&kv_A(decor->virt_lines, i).line);
}
kv_destroy(decor->virt_lines);
+ xfree(decor->sign_text);
xfree(decor);
}
}
@@ -180,9 +194,18 @@ bool decor_redraw_start(buf_T *buf, int top_row, DecorState *state)
Decoration decor = get_decor(mark);
+ // Exclude non-paired marks unless they contain virt_text or a sign
+ if (!mt_paired(mark)
+ && !kv_size(decor.virt_text)
+ && !decor_has_sign(&decor)) {
+ goto next_mark;
+ }
+
mtpos_t altpos = marktree_get_altpos(buf->b_marktree, mark, NULL);
- if ((!mt_end(mark) && altpos.row < top_row
+ // Exclude start marks if the end mark position is above the top row
+ // Exclude end marks if we have already added the start mark
+ if ((mt_start(mark) && altpos.row < top_row
&& !kv_size(decor.virt_text))
|| (mt_end(mark) && altpos.row >= top_row)) {
goto next_mark;
@@ -329,6 +352,144 @@ next_mark:
return attr;
}
+void decor_redraw_signs(buf_T *buf, int row, int *num_signs, sign_attrs_T sattrs[])
+{
+ if (!buf->b_signs) {
+ return;
+ }
+
+ MarkTreeIter itr[1] = { 0 };
+ marktree_itr_get(buf->b_marktree, row, 0, itr);
+
+ while (true) {
+ mtkey_t mark = marktree_itr_current(itr);
+ if (mark.pos.row < 0 || mark.pos.row > row) {
+ break;
+ }
+
+ if (mt_end(mark) || marktree_decor_level(mark) < kDecorLevelVisible) {
+ goto next_mark;
+ }
+
+ Decoration *decor = mark.decor_full;
+
+ if (!decor || !decor_has_sign(decor)) {
+ goto next_mark;
+ }
+
+ int j;
+ for (j = (*num_signs); j > 0; j--) {
+ if (sattrs[j].sat_prio <= decor->priority) {
+ break;
+ }
+ sattrs[j] = sattrs[j-1];
+ }
+ if (j < SIGN_SHOW_MAX) {
+ memset(&sattrs[j], 0, sizeof(sign_attrs_T));
+ sattrs[j].sat_text = decor->sign_text;
+ if (decor->sign_hl_id != 0) {
+ sattrs[j].sat_texthl = syn_id2attr(decor->sign_hl_id);
+ }
+ if (decor->number_hl_id != 0) {
+ sattrs[j].sat_numhl = syn_id2attr(decor->number_hl_id);
+ }
+ if (decor->line_hl_id != 0) {
+ sattrs[j].sat_linehl = syn_id2attr(decor->line_hl_id);
+ }
+ if (decor->cursorline_hl_id != 0) {
+ sattrs[j].sat_culhl = syn_id2attr(decor->cursorline_hl_id);
+ }
+ sattrs[j].sat_prio = decor->priority;
+ (*num_signs)++;
+ }
+
+next_mark:
+ marktree_itr_next(buf->b_marktree, itr);
+ }
+}
+
+// Get the maximum required amount of sign columns needed between row and
+// end_row.
+int decor_signcols(buf_T *buf, DecorState *state, int row, int end_row, int max)
+{
+ int count = 0; // count for the number of signs on a given row
+ int count_remove = 0; // how much to decrement count by when iterating marks for a new row
+ int signcols = 0; // highest value of count
+ int currow = -1; // current row
+
+ if (max <= 1 && buf->b_signs >= (size_t)max) {
+ return max;
+ }
+
+ if (buf->b_signs == 0) {
+ return 0;
+ }
+
+ MarkTreeIter itr[1] = { 0 };
+ marktree_itr_get(buf->b_marktree, 0, -1, itr);
+ while (true) {
+ mtkey_t mark = marktree_itr_current(itr);
+ if (mark.pos.row < 0 || mark.pos.row > end_row) {
+ break;
+ }
+
+ if ((mark.pos.row < row && mt_end(mark))
+ || marktree_decor_level(mark) < kDecorLevelVisible
+ || !mark.decor_full) {
+ goto next_mark;
+ }
+
+ Decoration decor = get_decor(mark);
+
+ if (!decor.sign_text) {
+ goto next_mark;
+ }
+
+ if (mark.pos.row > currow) {
+ count -= count_remove;
+ count_remove = 0;
+ currow = mark.pos.row;
+ }
+
+ if (!mt_paired(mark)) {
+ if (mark.pos.row >= row) {
+ count++;
+ if (count > signcols) {
+ signcols = count;
+ if (signcols >= max) {
+ return max;
+ }
+ }
+ count_remove++;
+ }
+ goto next_mark;
+ }
+
+ mtpos_t altpos = marktree_get_altpos(buf->b_marktree, mark, NULL);
+
+ if (mt_end(mark)) {
+ if (mark.pos.row >= row && altpos.row <= end_row) {
+ count_remove++;
+ }
+ } else {
+ if (altpos.row >= row) {
+ count++;
+ if (count > signcols) {
+ signcols = count;
+ if (signcols >= max) {
+ return max;
+ }
+ }
+ }
+ }
+
+next_mark:
+ marktree_itr_next(buf->b_marktree, itr);
+ }
+
+ return signcols;
+}
+
void decor_redraw_end(DecorState *state)
{
state->buf = NULL;
@@ -362,59 +523,6 @@ void decor_add_ephemeral(int start_row, int start_col, int end_row, int end_col,
}
-DecorProvider *get_decor_provider(NS ns_id, bool force)
-{
- size_t i;
- size_t len = kv_size(decor_providers);
- for (i = 0; i < len; i++) {
- DecorProvider *item = &kv_A(decor_providers, i);
- if (item->ns_id == ns_id) {
- return item;
- } else if (item->ns_id > ns_id) {
- break;
- }
- }
-
- if (!force) {
- return NULL;
- }
-
- // Adding a new provider, so allocate room in the vector
- (void)kv_a(decor_providers, len);
- if (i < len) {
- // New ns_id needs to be inserted between existing providers to maintain
- // ordering, so shift other providers with larger ns_id
- memmove(&kv_A(decor_providers, i + 1),
- &kv_A(decor_providers, i),
- (len - i) * sizeof(kv_a(decor_providers, i)));
- }
- DecorProvider *item = &kv_a(decor_providers, i);
- *item = DECORATION_PROVIDER_INIT(ns_id);
-
- return item;
-}
-
-void decor_provider_clear(DecorProvider *p)
-{
- if (p == NULL) {
- return;
- }
- NLUA_CLEAR_REF(p->redraw_start);
- NLUA_CLEAR_REF(p->redraw_buf);
- NLUA_CLEAR_REF(p->redraw_win);
- NLUA_CLEAR_REF(p->redraw_line);
- NLUA_CLEAR_REF(p->redraw_end);
- p->active = false;
-}
-
-void decor_free_all_mem(void)
-{
- for (size_t i = 0; i < kv_size(decor_providers); i++) {
- decor_provider_clear(&kv_A(decor_providers, i));
- }
- kv_destroy(decor_providers);
-}
-
int decor_virt_lines(win_T *wp, linenr_T lnum, VirtLines *lines)
{
diff --git a/src/nvim/decoration.h b/src/nvim/decoration.h
index 02472d09e4..8df53caa0a 100644
--- a/src/nvim/decoration.h
+++ b/src/nvim/decoration.h
@@ -47,13 +47,18 @@ struct Decoration {
bool virt_text_hide;
bool hl_eol;
bool virt_lines_above;
- // TODO(bfredl): style, signs, etc
+ // TODO(bfredl): style, etc
DecorPriority priority;
int col; // fixed col value, like win_col
int virt_text_width; // width of virt_text
+ char_u *sign_text;
+ int sign_hl_id;
+ int number_hl_id;
+ int line_hl_id;
+ int cursorline_hl_id;
};
#define DECORATION_INIT { KV_INITIAL_VALUE, KV_INITIAL_VALUE, 0, kVTEndOfLine, kHlModeUnknown, \
- false, false, false, DECOR_PRIORITY_BASE, 0, 0 }
+ false, false, false, DECOR_PRIORITY_BASE, 0, 0, NULL, 0, 0, 0, 0 }
typedef struct {
int start_row;
@@ -77,26 +82,16 @@ typedef struct {
int eol_col;
} DecorState;
-typedef struct {
- NS ns_id;
- bool active;
- LuaRef redraw_start;
- LuaRef redraw_buf;
- LuaRef redraw_win;
- LuaRef redraw_line;
- LuaRef redraw_end;
- LuaRef hl_def;
- int hl_valid;
-} DecorProvider;
-
-EXTERN kvec_t(DecorProvider) decor_providers INIT(= KV_INITIAL_VALUE);
EXTERN DecorState decor_state INIT(= { 0 });
-EXTERN bool provider_active INIT(= false);
-#define DECORATION_PROVIDER_INIT(ns_id) (DecorProvider) \
- { ns_id, false, LUA_NOREF, LUA_NOREF, \
- LUA_NOREF, LUA_NOREF, LUA_NOREF, \
- LUA_NOREF, -1 }
+static inline bool decor_has_sign(Decoration *decor)
+{
+ return decor->sign_text
+ || decor->sign_hl_id
+ || decor->number_hl_id
+ || decor->line_hl_id
+ || decor->cursorline_hl_id;
+}
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "decoration.h.generated.h"
diff --git a/src/nvim/decoration_provider.c b/src/nvim/decoration_provider.c
new file mode 100644
index 0000000000..6efcb08b9d
--- /dev/null
+++ b/src/nvim/decoration_provider.c
@@ -0,0 +1,231 @@
+// 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 "nvim/api/extmark.h"
+#include "nvim/api/private/helpers.h"
+#include "nvim/buffer.h"
+#include "nvim/decoration.h"
+#include "nvim/decoration_provider.h"
+#include "nvim/highlight.h"
+#include "nvim/lua/executor.h"
+
+static kvec_t(DecorProvider) decor_providers = KV_INITIAL_VALUE;
+
+#define DECORATION_PROVIDER_INIT(ns_id) (DecorProvider) \
+ { ns_id, false, LUA_NOREF, LUA_NOREF, \
+ LUA_NOREF, LUA_NOREF, LUA_NOREF, \
+ LUA_NOREF, -1 }
+
+static bool decor_provider_invoke(NS ns_id, const char *name, LuaRef ref,
+ Array args, bool default_true, char **perr)
+{
+ Error err = ERROR_INIT;
+
+ textlock++;
+ provider_active = true;
+ Object ret = nlua_call_ref(ref, name, args, true, &err);
+ provider_active = false;
+ textlock--;
+
+ if (!ERROR_SET(&err)
+ && api_object_to_bool(ret, "provider %s retval", default_true, &err)) {
+ return true;
+ }
+
+ if (ERROR_SET(&err)) {
+ const char *ns_name = describe_ns(ns_id);
+ ELOG("error in provider %s:%s: %s", ns_name, name, err.msg);
+ bool verbose_errs = true; // TODO(bfredl):
+ if (verbose_errs && perr && *perr == NULL) {
+ static char errbuf[IOSIZE];
+ snprintf(errbuf, sizeof errbuf, "%s: %s", ns_name, err.msg);
+ *perr = xstrdup(errbuf);
+ }
+ }
+
+ api_free_object(ret);
+ return false;
+}
+
+/// For each provider invoke the 'start' callback
+///
+/// @param[out] providers Decoration providers
+/// @param[out] err Provider err
+void decor_providers_start(DecorProviders *providers, int type, char **err)
+{
+ kvi_init(*providers);
+
+ for (size_t i = 0; i < kv_size(decor_providers); i++) {
+ DecorProvider *p = &kv_A(decor_providers, i);
+ if (!p->active) {
+ continue;
+ }
+
+ bool active;
+ if (p->redraw_start != LUA_NOREF) {
+ FIXED_TEMP_ARRAY(args, 2);
+ args.items[0] = INTEGER_OBJ((int)display_tick);
+ args.items[1] = INTEGER_OBJ(type);
+ active = decor_provider_invoke(p->ns_id, "start", p->redraw_start, args, true, err);
+ } else {
+ active = true;
+ }
+
+ if (active) {
+ kvi_push(*providers, p);
+ }
+ }
+}
+
+/// For each provider run 'win'. If result is not false, then collect the
+/// 'on_line' callback to call inside win_line
+///
+/// @param wp Window
+/// @param providers Decoration providers
+/// @param[out] line_providers Enabled line providers to invoke in win_line
+/// @param[out] err Provider error
+void decor_providers_invoke_win(win_T *wp, DecorProviders *providers,
+ DecorProviders *line_providers, char **err)
+{
+ kvi_init(*line_providers);
+
+ linenr_T knownmax = ((wp->w_valid & VALID_BOTLINE)
+ ? wp->w_botline
+ : (wp->w_topline + wp->w_height_inner));
+
+ for (size_t k = 0; k < kv_size(*providers); k++) {
+ DecorProvider *p = kv_A(*providers, k);
+ if (p && p->redraw_win != LUA_NOREF) {
+ FIXED_TEMP_ARRAY(args, 4);
+ args.items[0] = WINDOW_OBJ(wp->handle);
+ args.items[1] = BUFFER_OBJ(wp->w_buffer->handle);
+ // TODO(bfredl): we are not using this, but should be first drawn line?
+ args.items[2] = INTEGER_OBJ(wp->w_topline-1);
+ args.items[3] = INTEGER_OBJ(knownmax);
+ if (decor_provider_invoke(p->ns_id, "win", p->redraw_win, args, true, err)) {
+ kvi_push(*line_providers, p);
+ }
+ }
+ }
+
+ win_check_ns_hl(wp);
+}
+
+/// For each provider invoke the 'line' callback for a given window row.
+///
+/// @param wp Window
+/// @param providers Decoration providers
+/// @param row Row to invoke line callback for
+/// @param[out] has_decor Set when at least one provider invokes a line callback
+/// @param[out] err Provider error
+void providers_invoke_line(win_T *wp, DecorProviders *providers, int row, bool *has_decor,
+ char **err)
+{
+ for (size_t k = 0; k < kv_size(*providers); k++) {
+ DecorProvider *p = kv_A(*providers, k);
+ if (p && p->redraw_line != LUA_NOREF) {
+ FIXED_TEMP_ARRAY(args, 3);
+ args.items[0] = WINDOW_OBJ(wp->handle);
+ args.items[1] = BUFFER_OBJ(wp->w_buffer->handle);
+ args.items[2] = INTEGER_OBJ(row);
+ if (decor_provider_invoke(p->ns_id, "line", p->redraw_line, args, true, err)) {
+ *has_decor = true;
+ } else {
+ // return 'false' or error: skip rest of this window
+ kv_A(*providers, k) = NULL;
+ }
+
+ win_check_ns_hl(wp);
+ }
+ }
+}
+
+
+/// For each provider invoke the 'buf' callback for a given buffer.
+///
+/// @param buf Buffer
+/// @param providers Decoration providers
+/// @param[out] err Provider error
+void decor_providers_invoke_buf(buf_T *buf, DecorProviders *providers, char **err)
+{
+ for (size_t i = 0; i < kv_size(*providers); i++) {
+ DecorProvider *p = kv_A(*providers, i);
+ if (p && p->redraw_buf != LUA_NOREF) {
+ FIXED_TEMP_ARRAY(args, 1);
+ args.items[0] = BUFFER_OBJ(buf->handle);
+ decor_provider_invoke(p->ns_id, "buf", p->redraw_buf, args, true, err);
+ }
+ }
+}
+
+
+/// For each provider invoke the 'end' callback
+///
+/// @param providers Decoration providers
+/// @param displaytick Display tick
+/// @param[out] err Provider error
+void decor_providers_invoke_end(DecorProviders *providers, char **err)
+{
+ for (size_t i = 0; i < kv_size(*providers); i++) {
+ DecorProvider *p = kv_A(*providers, i);
+ if (p && p->active && p->redraw_end != LUA_NOREF) {
+ FIXED_TEMP_ARRAY(args, 1);
+ args.items[0] = INTEGER_OBJ((int)display_tick);
+ decor_provider_invoke(p->ns_id, "end", p->redraw_end, args, true, err);
+ }
+ }
+}
+
+DecorProvider *get_decor_provider(NS ns_id, bool force)
+{
+ size_t i;
+ size_t len = kv_size(decor_providers);
+ for (i = 0; i < len; i++) {
+ DecorProvider *item = &kv_A(decor_providers, i);
+ if (item->ns_id == ns_id) {
+ return item;
+ } else if (item->ns_id > ns_id) {
+ break;
+ }
+ }
+
+ if (!force) {
+ return NULL;
+ }
+
+ // Adding a new provider, so allocate room in the vector
+ (void)kv_a(decor_providers, len);
+ if (i < len) {
+ // New ns_id needs to be inserted between existing providers to maintain
+ // ordering, so shift other providers with larger ns_id
+ memmove(&kv_A(decor_providers, i + 1),
+ &kv_A(decor_providers, i),
+ (len - i) * sizeof(kv_a(decor_providers, i)));
+ }
+ DecorProvider *item = &kv_a(decor_providers, i);
+ *item = DECORATION_PROVIDER_INIT(ns_id);
+
+ return item;
+}
+
+void decor_provider_clear(DecorProvider *p)
+{
+ if (p == NULL) {
+ return;
+ }
+ NLUA_CLEAR_REF(p->redraw_start);
+ NLUA_CLEAR_REF(p->redraw_buf);
+ NLUA_CLEAR_REF(p->redraw_win);
+ NLUA_CLEAR_REF(p->redraw_line);
+ NLUA_CLEAR_REF(p->redraw_end);
+ p->active = false;
+}
+
+void decor_free_all_mem(void)
+{
+ for (size_t i = 0; i < kv_size(decor_providers); i++) {
+ decor_provider_clear(&kv_A(decor_providers, i));
+ }
+ kv_destroy(decor_providers);
+}
+
diff --git a/src/nvim/decoration_provider.h b/src/nvim/decoration_provider.h
new file mode 100644
index 0000000000..3ec7c80357
--- /dev/null
+++ b/src/nvim/decoration_provider.h
@@ -0,0 +1,26 @@
+#ifndef NVIM_DECORATION_PROVIDER_H
+#define NVIM_DECORATION_PROVIDER_H
+
+#include "nvim/buffer_defs.h"
+
+typedef struct {
+ NS ns_id;
+ bool active;
+ LuaRef redraw_start;
+ LuaRef redraw_buf;
+ LuaRef redraw_win;
+ LuaRef redraw_line;
+ LuaRef redraw_end;
+ LuaRef hl_def;
+ int hl_valid;
+} DecorProvider;
+
+typedef kvec_withinit_t(DecorProvider *, 4) DecorProviders;
+
+EXTERN bool provider_active INIT(= false);
+
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+# include "decoration_provider.h.generated.h"
+#endif
+
+#endif // NVIM_DECORATION_PROVIDER_H
diff --git a/src/nvim/diff.c b/src/nvim/diff.c
index 233753839b..1b8a9f41e9 100644
--- a/src/nvim/diff.c
+++ b/src/nvim/diff.c
@@ -85,9 +85,9 @@ typedef struct {
// used for recording hunks from xdiff
typedef struct {
linenr_T lnum_orig;
- long count_orig;
+ long count_orig;
linenr_T lnum_new;
- long count_new;
+ long count_new;
} diffhunk_T;
// two diff inputs and one result
@@ -166,8 +166,7 @@ void diff_buf_add(buf_T *buf)
return;
}
- int i;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (int i = 0; i < DB_COUNT; i++) {
if (curtab->tp_diffbuf[i] == NULL) {
curtab->tp_diffbuf[i] = buf;
curtab->tp_diff_invalid = true;
@@ -201,7 +200,7 @@ static void diff_buf_clear(void)
static int diff_buf_idx(buf_T *buf)
{
int idx;
- for (idx = 0; idx < DB_COUNT; ++idx) {
+ for (idx = 0; idx < DB_COUNT; idx++) {
if (curtab->tp_diffbuf[idx] == buf) {
break;
}
@@ -218,7 +217,7 @@ static int diff_buf_idx(buf_T *buf)
static int diff_buf_idx_tp(buf_T *buf, tabpage_T *tp)
{
int idx;
- for (idx = 0; idx < DB_COUNT; ++idx) {
+ for (idx = 0; idx < DB_COUNT; idx++) {
if (tp->tp_diffbuf[idx] == buf) {
break;
}
@@ -304,7 +303,6 @@ static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T
diff_T *dprev = NULL;
diff_T *dp = tp->tp_first_diff;
- linenr_T last;
linenr_T lnum_deleted = line1; // lnum of remaining deletion
int n;
int off;
@@ -323,7 +321,7 @@ static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T
dnext->df_lnum[idx] = line1;
dnext->df_count[idx] = inserted;
int i;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (i = 0; i < DB_COUNT; i++) {
if ((tp->tp_diffbuf[i] != NULL) && (i != idx)) {
if (dprev == NULL) {
dnext->df_lnum[i] = line1;
@@ -354,7 +352,7 @@ static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T
// 3 5 6
// compute last line of this change
- last = dp->df_lnum[idx] + dp->df_count[idx] - 1;
+ linenr_T last = dp->df_lnum[idx] + dp->df_count[idx] - 1;
// 1. change completely above line1: nothing to do
if (last >= line1 - 1) {
@@ -421,7 +419,7 @@ static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T
}
int i;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (i = 0; i < DB_COUNT; i++) {
if ((tp->tp_diffbuf[i] != NULL) && (i != idx)) {
dp->df_lnum[i] -= off;
dp->df_count[i] += n;
@@ -442,7 +440,7 @@ static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T
// Check if inserted lines are equal, may reduce the size of the
// diff.
//
- // TODO: also check for equal lines in the middle and perhaps split
+ // TODO(unknown): also check for equal lines in the middle and perhaps split
// the block.
diff_check_unchanged(tp, dp);
}
@@ -453,7 +451,7 @@ static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T
if ((dprev != NULL)
&& (dprev->df_lnum[idx] + dprev->df_count[idx] == dp->df_lnum[idx])) {
int i;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (i = 0; i < DB_COUNT; i++) {
if (tp->tp_diffbuf[i] != NULL) {
dprev->df_count[i] += dp->df_count[i];
}
@@ -474,7 +472,7 @@ static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T
while (dp != NULL) {
// All counts are zero, remove this entry.
int i;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (i = 0; i < DB_COUNT; i++) {
if ((tp->tp_diffbuf[i] != NULL) && (dp->df_count[i] != 0)) {
break;
}
@@ -542,7 +540,7 @@ static void diff_check_unchanged(tabpage_T *tp, diff_T *dp)
// Find the first buffers, use it as the original, compare the other
// buffer lines against this one.
int i_org;
- for (i_org = 0; i_org < DB_COUNT; ++i_org) {
+ for (i_org = 0; i_org < DB_COUNT; i_org++) {
if (tp->tp_diffbuf[i_org] != NULL) {
break;
}
@@ -574,7 +572,7 @@ static void diff_check_unchanged(tabpage_T *tp, diff_T *dp)
false));
int i_new;
- for (i_new = i_org + 1; i_new < DB_COUNT; ++i_new) {
+ for (i_new = i_org + 1; i_new < DB_COUNT; i_new++) {
if (tp->tp_diffbuf[i_new] == NULL) {
continue;
}
@@ -602,7 +600,7 @@ static void diff_check_unchanged(tabpage_T *tp, diff_T *dp)
}
// Line matched in all buffers, remove it from the diff.
- for (i_new = i_org; i_new < DB_COUNT; ++i_new) {
+ for (i_new = i_org; i_new < DB_COUNT; i_new++) {
if (tp->tp_diffbuf[i_new] != NULL) {
if (dir == FORWARD) {
dp->df_lnum[i_new]++;
@@ -628,8 +626,7 @@ static void diff_check_unchanged(tabpage_T *tp, diff_T *dp)
/// @return OK if the diff block doesn't contain invalid line numbers.
static int diff_check_sanity(tabpage_T *tp, diff_T *dp)
{
- int i;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (int i = 0; i < DB_COUNT; i++) {
if (tp->tp_diffbuf[i] != NULL) {
if (dp->df_lnum[i] + dp->df_count[i] - 1
> tp->tp_diffbuf[i]->b_ml.ml_line_count) {
@@ -719,16 +716,13 @@ static void clear_diffout(diffout_T *dout)
/// @return FAIL for failure.
static int diff_write_buffer(buf_T *buf, diffin_T *din)
{
- linenr_T lnum;
- char_u *s;
long len = 0;
- char_u *ptr;
// xdiff requires one big block of memory with all the text.
- for (lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) {
+ for (linenr_T lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) {
len += (long)STRLEN(ml_get_buf(buf, lnum, false)) + 1;
}
- ptr = try_malloc(len);
+ char_u *ptr = try_malloc(len);
if (ptr == NULL) {
// Allocating memory failed. This can happen, because we try to read
// the whole buffer text into memory. Set the failed flag, the diff
@@ -746,8 +740,8 @@ static int diff_write_buffer(buf_T *buf, diffin_T *din)
din->din_mmfile.size = len;
len = 0;
- for (lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) {
- for (s = ml_get_buf(buf, lnum, false); *s != NUL;) {
+ for (linenr_T lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++) {
+ for (char_u *s = ml_get_buf(buf, lnum, false); *s != NUL;) {
if (diff_flags & DIFF_ICASE) {
char_u cbuf[MB_MAXBYTES + 1];
@@ -811,9 +805,6 @@ static int diff_write(buf_T *buf, diffin_T *din)
/// @param eap can be NULL
static void diff_try_update(diffio_T *dio, int idx_orig, exarg_T *eap)
{
- buf_T *buf;
- int idx_new;
-
if (dio->dio_internal) {
ga_init(&dio->dio_diff.dout_ga, sizeof(char *), 1000);
} else {
@@ -833,9 +824,11 @@ static void diff_try_update(diffio_T *dio, int idx_orig, exarg_T *eap)
goto theend;
}
+ buf_T *buf;
+
// :diffupdate!
if (eap != NULL && eap->forceit) {
- for (idx_new = idx_orig; idx_new < DB_COUNT; idx_new++) {
+ for (int idx_new = idx_orig; idx_new < DB_COUNT; idx_new++) {
buf = curtab->tp_diffbuf[idx_new];
if (buf_valid(buf)) {
buf_check_timestamp(buf);
@@ -850,7 +843,7 @@ static void diff_try_update(diffio_T *dio, int idx_orig, exarg_T *eap)
}
// Make a difference between the first buffer and every other.
- for (idx_new = idx_orig + 1; idx_new < DB_COUNT; idx_new++) {
+ for (int idx_new = idx_orig + 1; idx_new < DB_COUNT; idx_new++) {
buf = curtab->tp_diffbuf[idx_new];
if (buf == NULL || buf->b_ml.ml_mfp == NULL) {
continue; // skip buffer that isn't loaded
@@ -893,10 +886,8 @@ int diff_internal(void)
///
static int diff_internal_failed(void)
{
- int idx;
-
// Only need to do something when there is another buffer.
- for (idx = 0; idx < DB_COUNT; idx++) {
+ for (int idx = 0; idx < DB_COUNT; idx++) {
if (curtab->tp_diffbuf[idx] != NULL
&& curtab->tp_diffbuf[idx]->b_diff_failed) {
return true;
@@ -927,7 +918,7 @@ void ex_diffupdate(exarg_T *eap)
// Use the first buffer as the original text.
int idx_orig;
- for (idx_orig = 0; idx_orig < DB_COUNT; ++idx_orig) {
+ for (idx_orig = 0; idx_orig < DB_COUNT; idx_orig++) {
if (curtab->tp_diffbuf[idx_orig] != NULL) {
break;
}
@@ -939,7 +930,7 @@ void ex_diffupdate(exarg_T *eap)
// Only need to do something when there is another buffer.
int idx_new;
- for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new) {
+ for (idx_new = idx_orig + 1; idx_new < DB_COUNT; idx_new++) {
if (curtab->tp_diffbuf[idx_new] != NULL) {
break;
}
@@ -1285,7 +1276,7 @@ void ex_diffpatch(exarg_T *eap)
ex_file(eap);
// Do filetype detection with the new name.
- if (au_has_group((char_u *)"filetypedetect")) {
+ if (augroup_exists("filetypedetect")) {
do_cmdline_cmd(":doau filetypedetect BufRead");
}
}
@@ -1659,7 +1650,7 @@ static void diff_read(int idx_orig, int idx_new, diffio_T *dio)
off = dp->df_lnum[idx_orig] - hunk->lnum_orig;
if (off > 0) {
- for (i = idx_orig; i < idx_new; ++i) {
+ for (i = idx_orig; i < idx_new; i++) {
if (curtab->tp_diffbuf[i] != NULL) {
dp->df_lnum[i] -= off;
}
@@ -1693,7 +1684,7 @@ static void diff_read(int idx_orig, int idx_new, diffio_T *dio)
off = 0;
}
- for (i = idx_orig; i < idx_new; ++i) {
+ for (i = idx_orig; i < idx_new; i++) {
if (curtab->tp_diffbuf[i] != NULL) {
dp->df_count[i] = dpl->df_lnum[i] + dpl->df_count[i]
- dp->df_lnum[i] + off;
@@ -1721,7 +1712,7 @@ static void diff_read(int idx_orig, int idx_new, diffio_T *dio)
// Set values for other buffers, these must be equal to the
// original buffer, otherwise there would have been a change
// already.
- for (i = idx_orig + 1; i < idx_new; ++i) {
+ for (i = idx_orig + 1; i < idx_new; i++) {
if (curtab->tp_diffbuf[i] != NULL) {
diff_copy_entry(dprev, dp, idx_orig, i);
}
@@ -1775,9 +1766,8 @@ static void diff_copy_entry(diff_T *dprev, diff_T *dp, int idx_orig, int idx_new
void diff_clear(tabpage_T *tp)
FUNC_ATTR_NONNULL_ALL
{
- diff_T *p;
diff_T *next_p;
- for (p = tp->tp_first_diff; p != NULL; p = next_p) {
+ for (diff_T *p = tp->tp_first_diff; p != NULL; p = next_p) {
next_p = p->df_next;
xfree(p);
}
@@ -1799,12 +1789,8 @@ void diff_clear(tabpage_T *tp)
/// @return diff status.
int diff_check(win_T *wp, linenr_T lnum)
{
- int idx; // index in tp_diffbuf[] for this buffer
diff_T *dp;
- int maxcount;
- int i;
buf_T *buf = wp->w_buffer;
- int cmp;
if (curtab->tp_diff_invalid) {
// update after a big change
@@ -1821,7 +1807,7 @@ int diff_check(win_T *wp, linenr_T lnum)
return 0;
}
- idx = diff_buf_idx(buf);
+ int idx = diff_buf_idx(buf); // index in tp_diffbuf[] for this buffer
if (idx == DB_COUNT) {
// no diffs for buffer "buf"
@@ -1850,9 +1836,9 @@ int diff_check(win_T *wp, linenr_T lnum)
// Changed or inserted line. If the other buffers have a count of
// zero, the lines were inserted. If the other buffers have the same
// count, check if the lines are identical.
- cmp = false;
+ int cmp = false;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (int i = 0; i < DB_COUNT; i++) {
if ((i != idx) && (curtab->tp_diffbuf[i] != NULL)) {
if (dp->df_count[i] == 0) {
zero = true;
@@ -1869,7 +1855,7 @@ int diff_check(win_T *wp, linenr_T lnum)
if (cmp) {
// Compare all lines. If they are equal the lines were inserted
// in some buffers, deleted in others, but not changed.
- for (i = 0; i < DB_COUNT; ++i) {
+ for (int i = 0; i < DB_COUNT; i++) {
if ((i != idx)
&& (curtab->tp_diffbuf[i] != NULL)
&& (dp->df_count[i] != 0)) {
@@ -1898,8 +1884,8 @@ int diff_check(win_T *wp, linenr_T lnum)
// Insert filler lines above the line just below the change. Will return
// 0 when this buf had the max count.
- maxcount = 0;
- for (i = 0; i < DB_COUNT; ++i) {
+ int maxcount = 0;
+ for (int i = 0; i < DB_COUNT; i++) {
if ((curtab->tp_diffbuf[i] != NULL) && (dp->df_count[i] > maxcount)) {
maxcount = dp->df_count[i];
}
@@ -2030,8 +2016,6 @@ void diff_set_topline(win_T *fromwin, win_T *towin)
buf_T *frombuf = fromwin->w_buffer;
linenr_T lnum = fromwin->w_topline;
diff_T *dp;
- int max_count;
- int i;
int fromidx = diff_buf_idx(frombuf);
if (fromidx == DB_COUNT) {
@@ -2071,9 +2055,9 @@ void diff_set_topline(win_T *fromwin, win_T *towin)
if (lnum >= dp->df_lnum[fromidx]) {
// Inside a change: compute filler lines. With three or more
// buffers we need to know the largest count.
- max_count = 0;
+ int max_count = 0;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (int i = 0; i < DB_COUNT; i++) {
if ((curtab->tp_diffbuf[i] != NULL) && (max_count < dp->df_count[i])) {
max_count = dp->df_count[i];
}
@@ -2219,7 +2203,7 @@ int diffopt_changed(void)
}
if (*p == ',') {
- ++p;
+ p++;
}
}
@@ -2322,7 +2306,7 @@ bool diff_find_change(win_T *wp, linenr_T lnum, int *startp, int *endp)
int off = lnum - dp->df_lnum[idx];
int i;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (i = 0; i < DB_COUNT; i++) {
if ((curtab->tp_diffbuf[i] != NULL) && (i != idx)) {
// Skip lines that are not in the other change (filler lines).
if (off >= dp->df_count[i]) {
@@ -2421,7 +2405,6 @@ bool diff_infold(win_T *wp, linenr_T lnum)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
{
bool other = false;
- diff_T *dp;
// Return if 'diff' isn't set.
if (!wp->w_p_diff) {
@@ -2430,7 +2413,7 @@ bool diff_infold(win_T *wp, linenr_T lnum)
int idx = -1;
int i;
- for (i = 0; i < DB_COUNT; ++i) {
+ for (i = 0; i < DB_COUNT; i++) {
if (curtab->tp_diffbuf[i] == wp->w_buffer) {
idx = i;
} else if (curtab->tp_diffbuf[i] != NULL) {
@@ -2453,7 +2436,7 @@ bool diff_infold(win_T *wp, linenr_T lnum)
return true;
}
- for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) {
+ for (diff_T *dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) {
// If this change is below the line there can't be any further match.
if (dp->df_lnum[idx] - diff_context > lnum) {
break;
@@ -2480,7 +2463,7 @@ void nv_diffgetput(bool put, size_t count)
if (count == 0) {
ea.arg = (char_u *)"";
} else {
- vim_snprintf(buf, 30, "%zu", count);
+ vim_snprintf(buf, sizeof(buf), "%zu", count);
ea.arg = (char_u *)buf;
}
@@ -2505,7 +2488,6 @@ void ex_diffgetput(exarg_T *eap)
int count;
linenr_T off = 0;
diff_T *dp;
- diff_T *dprev;
diff_T *dfree;
int i;
int added;
@@ -2529,7 +2511,7 @@ void ex_diffgetput(exarg_T *eap)
if (*eap->arg == NUL) {
// No argument: Find the other buffer in the list of diff buffers.
- for (idx_other = 0; idx_other < DB_COUNT; ++idx_other) {
+ for (idx_other = 0; idx_other < DB_COUNT; idx_other++) {
if ((curtab->tp_diffbuf[idx_other] != curbuf)
&& (curtab->tp_diffbuf[idx_other] != NULL)) {
if ((eap->cmdidx != CMD_diffput)
@@ -2550,7 +2532,7 @@ void ex_diffgetput(exarg_T *eap)
}
// Check that there isn't a third buffer in the list
- for (i = idx_other + 1; i < DB_COUNT; ++i) {
+ for (i = idx_other + 1; i < DB_COUNT; i++) {
if ((curtab->tp_diffbuf[i] != curbuf)
&& (curtab->tp_diffbuf[i] != NULL)
&& ((eap->cmdidx != CMD_diffput)
@@ -2567,7 +2549,7 @@ void ex_diffgetput(exarg_T *eap)
p--;
}
- for (i = 0; ascii_isdigit(eap->arg[i]) && eap->arg + i < p; ++i) {
+ for (i = 0; ascii_isdigit(eap->arg[i]) && eap->arg + i < p; i++) {
}
if (eap->arg + i == p) {
@@ -2610,9 +2592,9 @@ void ex_diffgetput(exarg_T *eap)
&& (eap->line1 == curbuf->b_ml.ml_line_count)
&& (diff_check(curwin, eap->line1) == 0)
&& ((eap->line1 == 1) || (diff_check(curwin, eap->line1 - 1) == 0))) {
- ++eap->line2;
+ eap->line2++;
} else if (eap->line1 > 0) {
- --eap->line1;
+ eap->line1--;
}
}
@@ -2641,7 +2623,7 @@ void ex_diffgetput(exarg_T *eap)
}
}
- dprev = NULL;
+ diff_T *dprev = NULL;
for (dp = curtab->tp_first_diff; dp != NULL;) {
if (dp->df_lnum[idx_cur] > eap->line2 + off) {
@@ -2703,14 +2685,14 @@ void ex_diffgetput(exarg_T *eap)
buf_empty = buf_is_empty(curbuf);
added = 0;
- for (i = 0; i < count; ++i) {
+ for (i = 0; i < count; i++) {
// remember deleting the last line of the buffer
buf_empty = curbuf->b_ml.ml_line_count == 1;
ml_delete(lnum, false);
added--;
}
- for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; ++i) {
+ for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; i++) {
linenr_T nr = dp->df_lnum[idx_from] + start_skip + i;
if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count) {
break;
@@ -2732,7 +2714,7 @@ void ex_diffgetput(exarg_T *eap)
if ((start_skip == 0) && (end_skip == 0)) {
// Check if there are any other buffers and if the diff is
// equal in them.
- for (i = 0; i < DB_COUNT; ++i) {
+ for (i = 0; i < DB_COUNT; i++) {
if ((curtab->tp_diffbuf[i] != NULL)
&& (i != idx_from)
&& (i != idx_to)
@@ -2835,7 +2817,7 @@ theend:
static void diff_fold_update(diff_T *dp, int skip_idx)
{
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
- for (int i = 0; i < DB_COUNT; ++i) {
+ for (int i = 0; i < DB_COUNT; i++) {
if ((curtab->tp_diffbuf[i] == wp->w_buffer) && (i != skip_idx)) {
foldUpdate(wp, dp->df_lnum[i], dp->df_lnum[i] + dp->df_count[i]);
}
@@ -2924,13 +2906,10 @@ int diff_move_to(int dir, long count)
/// "buf1" in diff mode.
static linenr_T diff_get_corresponding_line_int(buf_T *buf1, linenr_T lnum1)
{
- int idx1;
- int idx2;
- diff_T *dp;
int baseline = 0;
- idx1 = diff_buf_idx(buf1);
- idx2 = diff_buf_idx(curbuf);
+ int idx1 = diff_buf_idx(buf1);
+ int idx2 = diff_buf_idx(curbuf);
if ((idx1 == DB_COUNT)
|| (idx2 == DB_COUNT)
@@ -2948,7 +2927,7 @@ static linenr_T diff_get_corresponding_line_int(buf_T *buf1, linenr_T lnum1)
return lnum1;
}
- for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) {
+ for (diff_T *dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) {
if (dp->df_lnum[idx1] > lnum1) {
return lnum1 - baseline;
}
@@ -3004,11 +2983,8 @@ linenr_T diff_get_corresponding_line(buf_T *buf1, linenr_T lnum1)
linenr_T diff_lnum_win(linenr_T lnum, win_T *wp)
{
diff_T *dp;
- int idx;
- int i;
- linenr_T n;
- idx = diff_buf_idx(curbuf);
+ int idx = diff_buf_idx(curbuf);
if (idx == DB_COUNT) {
// safety check
@@ -3034,14 +3010,14 @@ linenr_T diff_lnum_win(linenr_T lnum, win_T *wp)
}
// Find index for "wp".
- i = diff_buf_idx(wp->w_buffer);
+ int i = diff_buf_idx(wp->w_buffer);
if (i == DB_COUNT) {
// safety check
return (linenr_T)0;
}
- n = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]);
+ linenr_T n = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]);
if (n > dp->df_lnum[i] + dp->df_count[i]) {
n = dp->df_lnum[i] + dp->df_count[i];
}
@@ -3054,16 +3030,14 @@ linenr_T diff_lnum_win(linenr_T lnum, win_T *wp)
///
static int parse_diff_ed(char_u *line, diffhunk_T *hunk)
{
- char_u *p;
- long f1, l1, f2, l2;
- int difftype;
+ long l1, l2;
// The line must be one of three formats:
// change: {first}[,{last}]c{first}[,{last}]
// append: {first}a{first}[,{last}]
// delete: {first}[,{last}]d{first}
- p = line;
- f1 = getdigits(&p, true, 0);
+ char_u *p = line;
+ long f1 = getdigits(&p, true, 0);
if (*p == ',') {
p++;
l1 = getdigits(&p, true, 0);
@@ -3073,8 +3047,8 @@ static int parse_diff_ed(char_u *line, diffhunk_T *hunk)
if (*p != 'a' && *p != 'c' && *p != 'd') {
return FAIL; // invalid diff format
}
- difftype = *p++;
- f2 = getdigits(&p, true, 0);
+ int difftype = *p++;
+ long f2 = getdigits(&p, true, 0);
if (*p == ',') {
p++;
l2 = getdigits(&p, true, 0);
@@ -3108,14 +3082,14 @@ static int parse_diff_ed(char_u *line, diffhunk_T *hunk)
///
static int parse_diff_unified(char_u *line, diffhunk_T *hunk)
{
- char_u *p;
- long oldline, oldcount, newline, newcount;
-
// Parse unified diff hunk header:
// @@ -oldline,oldcount +newline,newcount @@
- p = line;
+ char_u *p = line;
if (*p++ == '@' && *p++ == '@' && *p++ == ' ' && *p++ == '-') {
- oldline = getdigits(&p, true, 0);
+ long oldcount;
+ long newline;
+ long newcount;
+ long oldline = getdigits(&p, true, 0);
if (*p == ',') {
p++;
oldcount = getdigits(&p, true, 0);
@@ -3159,8 +3133,7 @@ static int parse_diff_unified(char_u *line, diffhunk_T *hunk)
/// Callback function for the xdl_diff() function.
/// Stores the diff output in a grow array.
///
-static int xdiff_out(long start_a, long count_a, long start_b, long count_b,
- void *priv)
+static int xdiff_out(long start_a, long count_a, long start_b, long count_b, void *priv)
{
diffout_T *dout = (diffout_T *)priv;
diffhunk_T *p = xmalloc(sizeof(*p));
diff --git a/src/nvim/digraph.c b/src/nvim/digraph.c
index 8eda173cac..6e5389c979 100644
--- a/src/nvim/digraph.c
+++ b/src/nvim/digraph.c
@@ -1506,7 +1506,6 @@ char_u *get_digraph_for_char(int val_arg)
/// @returns composed character, or NUL when ESC was used.
int get_digraph(bool cmdline)
{
- int cc;
no_mapping++;
int c = plain_vgetc();
no_mapping--;
@@ -1526,7 +1525,7 @@ int get_digraph(bool cmdline)
add_to_showcmd(c);
}
no_mapping++;
- cc = plain_vgetc();
+ int cc = plain_vgetc();
no_mapping--;
if (cc != ESC) {
@@ -1555,24 +1554,24 @@ static int getexactdigraph(int char1, int char2, bool meta_char)
// Search user digraphs first.
digr_T *dp = (digr_T *)user_digraphs.ga_data;
- for (int i = 0; i < user_digraphs.ga_len; ++i) {
+ for (int i = 0; i < user_digraphs.ga_len; i++) {
if (((int)dp->char1 == char1) && ((int)dp->char2 == char2)) {
retval = dp->result;
break;
}
- ++dp;
+ dp++;
}
// Search default digraphs.
if (retval == 0) {
dp = digraphdefault;
- for (int i = 0; dp->char1 != 0; ++i) {
+ for (int i = 0; dp->char1 != 0; i++) {
if (((int)dp->char1 == char1) && ((int)dp->char2 == char2)) {
retval = dp->result;
break;
}
- ++dp;
+ dp++;
}
}
@@ -1614,17 +1613,14 @@ int getdigraph(int char1, int char2, bool meta_char)
/// @param str
void putdigraph(char_u *str)
{
- char_u char1, char2;
- digr_T *dp;
-
while (*str != NUL) {
str = skipwhite(str);
if (*str == NUL) {
return;
}
- char1 = *str++;
- char2 = *str++;
+ char_u char1 = *str++;
+ char_u char2 = *str++;
if (char2 == 0) {
emsg(_(e_invarg));
@@ -1644,15 +1640,15 @@ void putdigraph(char_u *str)
int n = getdigits_int(&str, true, 0);
// If the digraph already exists, replace the result.
- dp = (digr_T *)user_digraphs.ga_data;
+ digr_T *dp = (digr_T *)user_digraphs.ga_data;
int i;
- for (i = 0; i < user_digraphs.ga_len; ++i) {
+ for (i = 0; i < user_digraphs.ga_len; i++) {
if (((int)dp->char1 == char1) && ((int)dp->char2 == char2)) {
dp->result = n;
break;
}
- ++dp;
+ dp++;
}
// Add a new digraph to the table.
@@ -1677,14 +1673,13 @@ static void digraph_header(const char *msg)
void listdigraphs(bool use_headers)
{
- digr_T *dp;
result_T previous = 0;
msg_putchar('\n');
- dp = digraphdefault;
+ digr_T *dp = digraphdefault;
- for (int i = 0; dp->char1 != NUL && !got_int; ++i) {
+ for (int i = 0; dp->char1 != NUL && !got_int; i++) {
digr_T tmp;
// May need to convert the result to 'encoding'.
@@ -1749,11 +1744,7 @@ static void printdigraph(const digr_T *dp, result_T *previous)
FUNC_ATTR_NONNULL_ARG(1)
{
char_u buf[30];
- char_u *p;
-
- int list_width;
-
- list_width = 13;
+ int list_width = 13;
if (dp->result != 0) {
if (previous != NULL) {
@@ -1780,7 +1771,7 @@ static void printdigraph(const digr_T *dp, result_T *previous)
}
}
- p = &buf[0];
+ char_u *p = &buf[0];
*p++ = dp->char1;
*p++ = dp->char2;
*p++ = ' ';
@@ -1863,8 +1854,6 @@ char *keymap_init(void)
/// @param eap
void ex_loadkeymap(exarg_T *eap)
{
- char_u *line;
- char_u *p;
char_u *s;
#define KMAP_LLEN 200 // max length of "to" and "from" together
@@ -1887,13 +1876,13 @@ void ex_loadkeymap(exarg_T *eap)
// Get each line of the sourced file, break at the end.
for (;;) {
- line = eap->getline(0, eap->cookie, 0, true);
+ char_u *line = eap->getline(0, eap->cookie, 0, true);
if (line == NULL) {
break;
}
- p = skipwhite(line);
+ char_u *p = skipwhite(line);
if ((*p != '"') && (*p != NUL)) {
kmap_T *kp = GA_APPEND_VIA_PTR(kmap_T, &curbuf->b_kmap_ga);
@@ -1911,7 +1900,7 @@ void ex_loadkeymap(exarg_T *eap)
}
xfree(kp->from);
xfree(kp->to);
- --curbuf->b_kmap_ga.ga_len;
+ curbuf->b_kmap_ga.ga_len--;
}
}
xfree(line);
@@ -1946,7 +1935,6 @@ static void keymap_unload(void)
{
char_u buf[KMAP_MAXLEN + 10];
char_u *save_cpo = p_cpo;
- kmap_T *kp;
if (!(curbuf->b_kmap_state & KEYMAP_LOADED)) {
return;
@@ -1956,7 +1944,7 @@ static void keymap_unload(void)
p_cpo = (char_u *)"C";
// clear the ":lmap"s
- kp = (kmap_T *)curbuf->b_kmap_ga.ga_data;
+ kmap_T *kp = (kmap_T *)curbuf->b_kmap_ga.ga_data;
for (int i = 0; i < curbuf->b_kmap_ga.ga_len; i++) {
vim_snprintf((char *)buf, sizeof(buf), "<buffer> %s", kp[i].from);
diff --git a/src/nvim/edit.c b/src/nvim/edit.c
index 00ffa7cba1..2e36962a4d 100644
--- a/src/nvim/edit.c
+++ b/src/nvim/edit.c
@@ -5116,10 +5116,10 @@ static int ins_complete(int c, bool enable_pum)
|| ctrl_x_mode == CTRL_X_PATH_PATTERNS
|| ctrl_x_mode == CTRL_X_PATH_DEFINES) {
if (compl_startpos.lnum != curwin->w_cursor.lnum) {
- /* line (probably) wrapped, set compl_startpos to the
- * first non_blank in the line, if it is not a wordchar
- * include it to get a better pattern, but then we don't
- * want the "\\<" prefix, check it bellow */
+ // line (probably) wrapped, set compl_startpos to the
+ // first non_blank in the line, if it is not a wordchar
+ // include it to get a better pattern, but then we don't
+ // want the "\\<" prefix, check it below.
compl_col = (colnr_T)getwhitecols(line);
compl_startpos.col = compl_col;
compl_startpos.lnum = curwin->w_cursor.lnum;
@@ -7776,7 +7776,7 @@ int hkmap(int c)
case ';':
c = 't'; break;
default: {
- static char str[] = "zqbcxlsjphmkwonu ydafe rig";
+ static char_u str[] = "zqbcxlsjphmkwonu ydafe rig";
if (c < 'a' || c > 'z') {
return c;
diff --git a/src/nvim/eval.c b/src/nvim/eval.c
index 07f0799bc4..f4ce6e3b39 100644
--- a/src/nvim/eval.c
+++ b/src/nvim/eval.c
@@ -6,6 +6,7 @@
*/
#include <math.h>
+#include <stdlib.h>
#include "auto/config.h"
@@ -330,7 +331,7 @@ void restore_v_event(dict_T *v_event, save_v_event_T *sve)
}
}
-// Return "n1" divided by "n2", taking care of dividing by zero.
+/// @return "n1" divided by "n2", taking care of dividing by zero.
varnumber_T num_divide(varnumber_T n1, varnumber_T n2)
FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -351,7 +352,7 @@ varnumber_T num_divide(varnumber_T n1, varnumber_T n2)
return result;
}
-// Return "n1" modulus "n2", taking care of dividing by zero.
+/// @return "n1" modulus "n2", taking care of dividing by zero.
varnumber_T num_modulus(varnumber_T n1, varnumber_T n2)
FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -359,9 +360,7 @@ varnumber_T num_modulus(varnumber_T n1, varnumber_T n2)
return (n2 == 0) ? 0 : (n1 % n2);
}
-/*
- * Initialize the global and v: variables.
- */
+/// Initialize the global and v: variables.
void eval_init(void)
{
vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
@@ -501,10 +500,8 @@ void eval_clear(void)
#endif
-/*
- * Set an internal variable to a string value. Creates the variable if it does
- * not already exist.
- */
+/// Set an internal variable to a string value. Creates the variable if it does
+/// not already exist.
void set_internal_string_var(const char *name, char_u *value)
FUNC_ATTR_NONNULL_ARG(1)
{
@@ -522,9 +519,10 @@ static char_u *redir_endp = NULL;
static char_u *redir_varname = NULL;
/// Start recording command output to a variable
-/// Returns OK if successfully completed the setup. FAIL otherwise.
///
/// @param append append to an existing variable
+///
+/// @return OK if successfully completed the setup. FAIL otherwise.
int var_redir_start(char_u *name, int append)
{
int save_emsg;
@@ -585,15 +583,13 @@ int var_redir_start(char_u *name, int append)
return OK;
}
-/*
- * Append "value[value_len]" to the variable set by var_redir_start().
- * The actual appending is postponed until redirection ends, because the value
- * appended may in fact be the string we write to, changing it may cause freed
- * memory to be used:
- * :redir => foo
- * :let foo
- * :redir END
- */
+/// Append "value[value_len]" to the variable set by var_redir_start().
+/// The actual appending is postponed until redirection ends, because the value
+/// appended may in fact be the string we write to, changing it may cause freed
+/// memory to be used:
+/// :redir => foo
+/// :let foo
+/// :redir END
void var_redir_str(char_u *value, int value_len)
{
int len;
@@ -613,10 +609,8 @@ void var_redir_str(char_u *value, int value_len)
redir_ga.ga_len += len;
}
-/*
- * Stop redirecting command output to a variable.
- * Frees the allocated memory.
- */
+/// Stop redirecting command output to a variable.
+/// Frees the allocated memory.
void var_redir_stop(void)
{
typval_T tv;
@@ -743,7 +737,7 @@ int eval_to_bool(char_u *arg, bool *error, char_u **nextcmd, int skip)
return retval;
}
-// Call eval1() and give an error message if not done at a lower level.
+/// Call eval1() and give an error message if not done at a lower level.
static int eval1_emsg(char_u **arg, typval_T *rettv, bool evaluate)
FUNC_ATTR_NONNULL_ARG(1, 2)
{
@@ -766,8 +760,8 @@ static int eval1_emsg(char_u **arg, typval_T *rettv, bool evaluate)
return ret;
}
-/// @return whether a typval is a valid expression to pass to eval_expr_typval()
-/// or eval_expr_to_bool(). An empty string returns false;
+/// @return whether a typval is a valid expression to pass to eval_expr_typval()
+/// or eval_expr_to_bool(). An empty string returns false;
bool eval_expr_valid_arg(const typval_T *const tv)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_CONST
{
@@ -866,10 +860,9 @@ char *eval_to_string_skip(const char *arg, const char **nextcmd, const bool skip
return retval;
}
-/*
- * Skip over an expression at "*pp".
- * Return FAIL for an error, OK otherwise.
- */
+/// Skip over an expression at "*pp".
+///
+/// @return FAIL for an error, OK otherwise.
int skip_expr(char_u **pp)
{
typval_T rettv;
@@ -916,10 +909,10 @@ char_u *eval_to_string(char_u *arg, char_u **nextcmd, bool convert)
return (char_u *)retval;
}
-/*
- * Call eval_to_string() without using current local variables and using
- * textlock. When "use_sandbox" is TRUE use the sandbox.
- */
+/// Call eval_to_string() without using current local variables and using
+/// textlock.
+///
+/// @param use_sandbox when TRUE, use the sandbox.
char_u *eval_to_string_safe(char_u *arg, char_u **nextcmd, int use_sandbox)
{
char_u *retval;
@@ -939,11 +932,10 @@ char_u *eval_to_string_safe(char_u *arg, char_u **nextcmd, int use_sandbox)
return retval;
}
-/*
- * Top level evaluation function, returning a number.
- * Evaluates "expr" silently.
- * Returns -1 for an error.
- */
+/// Top level evaluation function, returning a number.
+/// Evaluates "expr" silently.
+///
+/// @return -1 for an error.
varnumber_T eval_to_number(char_u *expr)
{
typval_T rettv;
@@ -963,9 +955,10 @@ varnumber_T eval_to_number(char_u *expr)
return retval;
}
-// Top level evaluation function.
-// Returns an allocated typval_T with the result.
-// Returns NULL when there is an error.
+/// Top level evaluation function.
+///
+/// @return an allocated typval_T with the result or
+/// NULL when there is an error.
typval_T *eval_expr(char_u *arg)
{
typval_T *tv = xmalloc(sizeof(*tv));
@@ -975,11 +968,9 @@ typval_T *eval_expr(char_u *arg)
return tv;
}
-/*
- * Prepare v: variable "idx" to be used.
- * Save the current typeval in "save_tv".
- * When not used yet add the variable to the v: hashtable.
- */
+/// Prepare v: variable "idx" to be used.
+/// Save the current typeval in "save_tv".
+/// When not used yet add the variable to the v: hashtable.
void prepare_vimvar(int idx, typval_T *save_tv)
{
*save_tv = vimvars[idx].vv_tv;
@@ -988,10 +979,8 @@ void prepare_vimvar(int idx, typval_T *save_tv)
}
}
-/*
- * Restore v: variable "idx" to typeval "save_tv".
- * When no longer defined, remove the variable from the v: hashtable.
- */
+/// Restore v: variable "idx" to typeval "save_tv".
+/// When no longer defined, remove the variable from the v: hashtable.
void restore_vimvar(int idx, typval_T *save_tv)
{
hashitem_T *hi;
@@ -1018,11 +1007,10 @@ void find_win_for_curbuf(void)
}
}
-/*
- * Evaluate an expression to a list with suggestions.
- * For the "expr:" part of 'spellsuggest'.
- * Returns NULL when there is an error.
- */
+/// Evaluate an expression to a list with suggestions.
+/// For the "expr:" part of 'spellsuggest'.
+///
+/// @return NULL when there is an error.
list_T *eval_spell_expr(char_u *badword, char_u *expr)
{
typval_T save_val;
@@ -1086,7 +1074,7 @@ int get_spellword(list_T *const list, const char **ret_word)
// Uses argv[0] to argv[argc-1] for the function arguments. argv[argc]
// should have type VAR_UNKNOWN.
//
-// Return OK or FAIL.
+// @return OK or FAIL.
int call_vim_function(const char_u *func, int argc, typval_T *argv, typval_T *rettv)
FUNC_ATTR_NONNULL_ALL
{
@@ -1224,10 +1212,8 @@ void prof_child_exit(proftime_T *tm)
}
-/*
- * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
- * it in "*cp". Doesn't give error messages.
- */
+/// Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
+/// it in "*cp". Doesn't give error messages.
int eval_foldexpr(char_u *arg, int *cp)
{
typval_T tv;
@@ -1268,26 +1254,27 @@ int eval_foldexpr(char_u *arg, int *cp)
return (int)retval;
}
-// ":cons[t] var = expr1" define constant
-// ":cons[t] [name1, name2, ...] = expr1" define constants unpacking list
-// ":cons[t] [name, ..., ; lastname] = expr" define constants unpacking list
+/// ":cons[t] var = expr1" define constant
+/// ":cons[t] [name1, name2, ...] = expr1" define constants unpacking list
+/// ":cons[t] [name, ..., ; lastname] = expr" define constants unpacking list
void ex_const(exarg_T *eap)
{
ex_let_const(eap, true);
}
-// Get a list of lines from a HERE document. The here document is a list of
-// lines surrounded by a marker.
-// cmd << {marker}
-// {line1}
-// {line2}
-// ....
-// {marker}
-//
-// The {marker} is a string. If the optional 'trim' word is supplied before the
-// marker, then the leading indentation before the lines (matching the
-// indentation in the 'cmd' line) is stripped.
-// Returns a List with {lines} or NULL.
+/// Get a list of lines from a HERE document. The here document is a list of
+/// lines surrounded by a marker.
+/// cmd << {marker}
+/// {line1}
+/// {line2}
+/// ....
+/// {marker}
+///
+/// The {marker} is a string. If the optional 'trim' word is supplied before the
+/// marker, then the leading indentation before the lines (matching the
+/// indentation in the 'cmd' line) is stripped.
+///
+/// @return a List with {lines} or NULL.
static list_T *heredoc_get(exarg_T *eap, char_u *cmd)
{
char_u *marker;
@@ -1385,18 +1372,18 @@ static list_T *heredoc_get(exarg_T *eap, char_u *cmd)
return l;
}
-// ":let" list all variable values
-// ":let var1 var2" list variable values
-// ":let var = expr" assignment command.
-// ":let var += expr" assignment command.
-// ":let var -= expr" assignment command.
-// ":let var *= expr" assignment command.
-// ":let var /= expr" assignment command.
-// ":let var %= expr" assignment command.
-// ":let var .= expr" assignment command.
-// ":let var ..= expr" assignment command.
-// ":let [var1, var2] = expr" unpack list.
-// ":let [name, ..., ; lastname] = expr" unpack list.
+/// ":let" list all variable values
+/// ":let var1 var2" list variable values
+/// ":let var = expr" assignment command.
+/// ":let var += expr" assignment command.
+/// ":let var -= expr" assignment command.
+/// ":let var *= expr" assignment command.
+/// ":let var /= expr" assignment command.
+/// ":let var %= expr" assignment command.
+/// ":let var .= expr" assignment command.
+/// ":let var ..= expr" assignment command.
+/// ":let [var1, var2] = expr" unpack list.
+/// ":let [name, ..., ; lastname] = expr" unpack list.
void ex_let(exarg_T *eap)
{
ex_let_const(eap, false);
@@ -1577,13 +1564,12 @@ static int ex_let_vars(char_u *arg_start, typval_T *tv, int copy, int semicolon,
return OK;
}
-/*
- * Skip over assignable variable "var" or list of variables "[var, var]".
- * Used for ":let varvar = expr" and ":for varvar in expr".
- * For "[var, var]" increment "*var_count" for each variable.
- * for "[var, var; var]" set "semicolon".
- * Return NULL for an error.
- */
+/// Skip over assignable variable "var" or list of variables "[var, var]".
+/// Used for ":let varvar = expr" and ":for varvar in expr".
+/// For "[var, var]" increment "*var_count" for each variable.
+/// for "[var, var; var]" set "semicolon".
+///
+/// @return NULL for an error.
static const char_u *skip_var_list(const char_u *arg, int *var_count, int *semicolon)
{
const char_u *p;
@@ -1621,10 +1607,8 @@ static const char_u *skip_var_list(const char_u *arg, int *var_count, int *semic
}
}
-/*
- * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
- * l[idx].
- */
+/// Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
+/// l[idx].
static const char_u *skip_var_one(const char_u *arg)
{
if (*arg == '@' && arg[1] != NUL) {
@@ -1634,10 +1618,9 @@ static const char_u *skip_var_one(const char_u *arg)
NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
}
-/*
- * List variables for hashtab "ht" with prefix "prefix".
- * If "empty" is TRUE also list NULL strings as empty strings.
- */
+/// List variables for hashtab "ht" with prefix "prefix".
+///
+/// @param empty if TRUE also list NULL strings as empty strings.
void list_hashtable_vars(hashtab_T *ht, const char *prefix, int empty, int *first)
{
hashitem_T *hi;
@@ -1666,47 +1649,37 @@ void list_hashtable_vars(hashtab_T *ht, const char *prefix, int empty, int *firs
}
}
-/*
- * List global variables.
- */
+/// List global variables.
static void list_glob_vars(int *first)
{
list_hashtable_vars(&globvarht, "", true, first);
}
-/*
- * List buffer variables.
- */
+/// List buffer variables.
static void list_buf_vars(int *first)
{
list_hashtable_vars(&curbuf->b_vars->dv_hashtab, "b:", true, first);
}
-/*
- * List window variables.
- */
+/// List window variables.
static void list_win_vars(int *first)
{
list_hashtable_vars(&curwin->w_vars->dv_hashtab, "w:", true, first);
}
-/*
- * List tab page variables.
- */
+/// List tab page variables.
static void list_tab_vars(int *first)
{
list_hashtable_vars(&curtab->tp_vars->dv_hashtab, "t:", true, first);
}
-/*
- * List Vim variables.
- */
+/// List Vim variables.
static void list_vim_vars(int *first)
{
list_hashtable_vars(&vimvarht, "v:", false, first);
}
-// List script-local variables, if there is a script.
+/// List script-local variables, if there is a script.
static void list_script_vars(int *first)
{
if (current_sctx.sc_sid > 0 && current_sctx.sc_sid <= ga_scripts.ga_len) {
@@ -1714,9 +1687,7 @@ static void list_script_vars(int *first)
}
}
-/*
- * List variables in "arg".
- */
+/// List variables in "arg".
static const char *list_arg_vars(exarg_T *eap, const char *arg, int *first)
{
int error = FALSE;
@@ -2379,9 +2350,7 @@ char_u *get_lval(char_u *const name, typval_T *const rettv, lval_T *const lp, co
// TODO(ZyX-I): move to eval/executor
-/*
- * Clear lval "lp" that was filled by get_lval().
- */
+/// Clear lval "lp" that was filled by get_lval().
void clear_lval(lval_T *lp)
{
xfree(lp->ll_exp_name);
@@ -2390,12 +2359,11 @@ void clear_lval(lval_T *lp)
// TODO(ZyX-I): move to eval/executor
-/*
- * Set a variable that was parsed by get_lval() to "rettv".
- * "endp" points to just after the parsed name.
- * "op" is NULL, "+" for "+=", "-" for "-=", "*" for "*=", "/" for "/=",
- * "%" for "%=", "." for ".=" or "=" for "=".
- */
+/// Set a variable that was parsed by get_lval() to "rettv".
+///
+/// @param endp points to just after the parsed name.
+/// @param op NULL, "+" for "+=", "-" for "-=", "*" for "*=", "/" for "/=",
+/// "%" for "%=", "." for ".=" or "=" for "=".
static void set_var_lval(lval_T *lp, char_u *endp, typval_T *rettv, int copy, const bool is_const,
const char *op)
{
@@ -2598,12 +2566,12 @@ notify:
// TODO(ZyX-I): move to eval/ex_cmds
-/*
- * Evaluate the expression used in a ":for var in expr" command.
- * "arg" points to "var".
- * Set "*errp" to TRUE for an error, FALSE otherwise;
- * Return a pointer that holds the info. Null when there is an error.
- */
+/// Evaluate the expression used in a ":for var in expr" command.
+/// "arg" points to "var".
+///
+/// @param[out] *errp set to TRUE for an error, FALSE otherwise;
+///
+/// @return a pointer that holds the info. Null when there is an error.
void *eval_for_line(const char_u *arg, bool *errp, char_u **nextcmdp, int skip)
{
forinfo_T *fi = xcalloc(1, sizeof(forinfo_T));
@@ -2675,12 +2643,11 @@ void *eval_for_line(const char_u *arg, bool *errp, char_u **nextcmdp, int skip)
// TODO(ZyX-I): move to eval/ex_cmds
-/*
- * Use the first item in a ":for" list. Advance to the next.
- * Assign the values to the variable (list). "arg" points to the first one.
- * Return TRUE when a valid item was found, FALSE when at end of list or
- * something wrong.
- */
+/// Use the first item in a ":for" list. Advance to the next.
+/// Assign the values to the variable (list). "arg" points to the first one.
+///
+/// @return true when a valid item was found, false when at end of list or
+/// something wrong.
bool next_for_item(void *fi_void, char_u *arg)
{
forinfo_T *fi = (forinfo_T *)fi_void;
@@ -2709,7 +2676,7 @@ bool next_for_item(void *fi_void, char_u *arg)
tv.vval.v_string = vim_strnsave(fi->fi_string + fi->fi_byte_idx, len);
fi->fi_byte_idx += len;
const int result
- = ex_let_vars(arg, &tv, true, fi->fi_semicolon, fi->fi_varcount, false, NULL) == OK;
+ = ex_let_vars(arg, &tv, true, fi->fi_semicolon, fi->fi_varcount, false, NULL) == OK;
xfree(tv.vval.v_string);
return result;
}
@@ -2726,9 +2693,7 @@ bool next_for_item(void *fi_void, char_u *arg)
// TODO(ZyX-I): move to eval/ex_cmds
-/*
- * Free the structure used to store info used by ":for".
- */
+/// Free the structure used to store info used by ":for".
void free_for_info(void *fi_void)
{
forinfo_T *fi = (forinfo_T *)fi_void;
@@ -3177,9 +3142,7 @@ static int do_lock_var(lval_T *lp, char_u *name_end FUNC_ATTR_UNUSED, exarg_T *e
return ret;
}
-/*
- * Delete all "menutrans_" variables.
- */
+/// Delete all "menutrans_" variables.
void del_menutrans_vars(void)
{
hash_lock(&globvarht);
@@ -3201,9 +3164,7 @@ void del_menutrans_vars(void)
static char_u *varnamebuf = NULL;
static size_t varnamebuflen = 0;
-/*
- * Function to concatenate a prefix and a variable name.
- */
+/// Function to concatenate a prefix and a variable name.
char_u *cat_prefix_varname(int prefix, const char_u *name)
FUNC_ATTR_NONNULL_ALL
{
@@ -3221,10 +3182,8 @@ char_u *cat_prefix_varname(int prefix, const char_u *name)
return varnamebuf;
}
-/*
- * Function given to ExpandGeneric() to obtain the list of user defined
- * (global/buffer/window/built-in) variable names.
- */
+/// Function given to ExpandGeneric() to obtain the list of user defined
+/// (global/buffer/window/built-in) variable names.
char_u *get_user_var_name(expand_T *xp, int idx)
{
static size_t gdone;
@@ -3256,9 +3215,7 @@ char_u *get_user_var_name(expand_T *xp, int idx)
}
// b: variables
- // In cmdwin, the alternative buffer should be used.
- hashtab_T *ht
- = is_in_cmdwin() ? &prevwin->w_buffer->b_vars->dv_hashtab : &curbuf->b_vars->dv_hashtab;
+ const hashtab_T *ht = &prevwin_curwin()->w_buffer->b_vars->dv_hashtab;
if (bdone < ht->ht_used) {
if (bdone++ == 0) {
hi = ht->ht_array;
@@ -3272,8 +3229,7 @@ char_u *get_user_var_name(expand_T *xp, int idx)
}
// w: variables
- // In cmdwin, the alternative window should be used.
- ht = is_in_cmdwin() ? &prevwin->w_vars->dv_hashtab : &curwin->w_vars->dv_hashtab;
+ ht = &prevwin_curwin()->w_vars->dv_hashtab;
if (wdone < ht->ht_used) {
if (wdone++ == 0) {
hi = ht->ht_array;
@@ -3312,8 +3268,9 @@ char_u *get_user_var_name(expand_T *xp, int idx)
// TODO(ZyX-I): move to eval/expressions
-/// Return TRUE if "pat" matches "text".
/// Does not use 'cpo' and always uses 'magic'.
+///
+/// @return TRUE if "pat" matches "text".
static int pattern_match(char_u *pat, char_u *text, bool ic)
{
int matches = 0;
@@ -3334,10 +3291,10 @@ static int pattern_match(char_u *pat, char_u *text, bool ic)
/// Handle a name followed by "(". Both for just "name(arg)" and for
/// "expr->name(arg)".
-//
+///
/// @param arg Points to "(", will be advanced
/// @param basetv "expr" for "expr->name(arg)"
-//
+///
/// @return OK or FAIL.
static int eval_func(char_u **const arg, char_u *const name, const int name_len,
typval_T *const rettv, const bool evaluate, typval_T *const basetv)
@@ -3398,13 +3355,12 @@ static int eval_func(char_u **const arg, char_u *const name, const int name_len,
* VAR_UNKNOWN. The function still returns FAIL for a syntax error.
*/
-/*
- * Handle zero level expression.
- * This calls eval1() and handles error message and nextcmd.
- * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
- * Note: "rettv.v_lock" is not set.
- * Return OK or FAIL.
- */
+/// Handle zero level expression.
+/// This calls eval1() and handles error message and nextcmd.
+/// Put the result in "rettv" when returning OK and "evaluate" is TRUE.
+/// Note: "rettv.v_lock" is not set.
+///
+/// @return OK or FAIL.
int eval0(char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate)
{
int ret;
@@ -3437,17 +3393,15 @@ int eval0(char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate)
// TODO(ZyX-I): move to eval/expressions
-/*
- * Handle top level expression:
- * expr2 ? expr1 : expr1
- *
- * "arg" must point to the first non-white of the expression.
- * "arg" is advanced to the next non-white after the recognized expression.
- *
- * Note: "rettv.v_lock" is not set.
- *
- * Return OK or FAIL.
- */
+/// Handle top level expression:
+/// expr2 ? expr1 : expr1
+///
+/// "arg" must point to the first non-white of the expression.
+/// "arg" is advanced to the next non-white after the recognized expression.
+///
+/// Note: "rettv.v_lock" is not set.
+///
+/// @return OK or FAIL.
int eval1(char_u **arg, typval_T *rettv, int evaluate)
{
int result;
@@ -3513,15 +3467,13 @@ int eval1(char_u **arg, typval_T *rettv, int evaluate)
// TODO(ZyX-I): move to eval/expressions
-/*
- * Handle first level expression:
- * expr2 || expr2 || expr2 logical OR
- *
- * "arg" must point to the first non-white of the expression.
- * "arg" is advanced to the next non-white after the recognized expression.
- *
- * Return OK or FAIL.
- */
+/// Handle first level expression:
+/// expr2 || expr2 || expr2 logical OR
+///
+/// "arg" must point to the first non-white of the expression.
+/// "arg" is advanced to the next non-white after the recognized expression.
+///
+/// @return OK or FAIL.
static int eval2(char_u **arg, typval_T *rettv, int evaluate)
{
typval_T var2;
@@ -3584,15 +3536,13 @@ static int eval2(char_u **arg, typval_T *rettv, int evaluate)
// TODO(ZyX-I): move to eval/expressions
-/*
- * Handle second level expression:
- * expr3 && expr3 && expr3 logical AND
- *
- * "arg" must point to the first non-white of the expression.
- * "arg" is advanced to the next non-white after the recognized expression.
- *
- * Return OK or FAIL.
- */
+/// Handle second level expression:
+/// expr3 && expr3 && expr3 logical AND
+///
+/// @param arg must point to the first non-white of the expression.
+/// `arg` is advanced to the next non-white after the recognized expression.
+///
+/// @return OK or FAIL.
static int eval3(char_u **arg, typval_T *rettv, int evaluate)
{
typval_T var2;
@@ -3655,24 +3605,22 @@ static int eval3(char_u **arg, typval_T *rettv, int evaluate)
// TODO(ZyX-I): move to eval/expressions
-/*
- * Handle third level expression:
- * var1 == var2
- * var1 =~ var2
- * var1 != var2
- * var1 !~ var2
- * var1 > var2
- * var1 >= var2
- * var1 < var2
- * var1 <= var2
- * var1 is var2
- * var1 isnot var2
- *
- * "arg" must point to the first non-white of the expression.
- * "arg" is advanced to the next non-white after the recognized expression.
- *
- * Return OK or FAIL.
- */
+/// Handle third level expression:
+/// var1 == var2
+/// var1 =~ var2
+/// var1 != var2
+/// var1 !~ var2
+/// var1 > var2
+/// var1 >= var2
+/// var1 < var2
+/// var1 <= var2
+/// var1 is var2
+/// var1 isnot var2
+///
+/// "arg" must point to the first non-white of the expression.
+/// "arg" is advanced to the next non-white after the recognized expression.
+///
+/// @return OK or FAIL.
static int eval4(char_u **arg, typval_T *rettv, int evaluate)
{
typval_T var2;
@@ -3766,18 +3714,16 @@ static int eval4(char_u **arg, typval_T *rettv, int evaluate)
// TODO(ZyX-I): move to eval/expressions
-/*
- * Handle fourth level expression:
- * + number addition
- * - number subtraction
- * . string concatenation
- * .. string concatenation
- *
- * "arg" must point to the first non-white of the expression.
- * "arg" is advanced to the next non-white after the recognized expression.
- *
- * Return OK or FAIL.
- */
+/// Handle fourth level expression:
+/// + number addition
+/// - number subtraction
+/// . string concatenation
+/// .. string concatenation
+///
+/// @param arg must point to the first non-white of the expression.
+/// `arg` is advanced to the next non-white after the recognized expression.
+///
+/// @return OK or FAIL.
static int eval5(char_u **arg, typval_T *rettv, int evaluate)
{
typval_T var2;
@@ -4323,7 +4269,8 @@ static int eval7(char_u **arg, typval_T *rettv, int evaluate, int want_string)
/// Apply the leading "!" and "-" before an eval7 expression to "rettv".
/// Adjusts "end_leaderp" until it is at "start_leader".
-/// @return OK on success, FAIL on failure.
+///
+/// @return OK on success, FAIL on failure.
static int eval7_leader(typval_T *const rettv, const char_u *const start_leader,
const char_u **const end_leaderp)
FUNC_ATTR_NONNULL_ALL
@@ -4377,7 +4324,7 @@ static int eval7_leader(typval_T *const rettv, const char_u *const start_leader,
/// @param lua_funcname If `rettv` refers to a v:lua function, this must point
/// to the name of the Lua function to call (after the
/// "v:lua." prefix).
-/// @return OK on success, FAIL on failure.
+/// @return OK on success, FAIL on failure.
static int call_func_rettv(char_u **const arg, typval_T *const rettv, const bool evaluate,
dict_T *const selfdict, typval_T *const basetv,
const char_u *const lua_funcname)
@@ -4425,9 +4372,13 @@ static int call_func_rettv(char_u **const arg, typval_T *const rettv, const bool
}
/// Evaluate "->method()".
+///
/// @param verbose if true, give error messages.
-/// @note "*arg" points to the '-'.
-/// @return FAIL or OK. @note "*arg" is advanced to after the ')'.
+/// @param *arg points to the '-'.
+///
+/// @return FAIL or OK.
+///
+/// @note "*arg" is advanced to after the ')'.
static int eval_lambda(char_u **const arg, typval_T *const rettv, const bool evaluate,
const bool verbose)
FUNC_ATTR_NONNULL_ALL
@@ -4464,8 +4415,10 @@ static int eval_lambda(char_u **const arg, typval_T *const rettv, const bool eva
}
/// Evaluate "->method()" or "->v:lua.method()".
-/// @note "*arg" points to the '-'.
-/// @return FAIL or OK. "*arg" is advanced to after the ')'.
+///
+/// @param *arg points to the '-'.
+///
+/// @return FAIL or OK. "*arg" is advanced to after the ')'.
static int eval_method(char_u **const arg, typval_T *const rettv, const bool evaluate,
const bool verbose)
FUNC_ATTR_NONNULL_ALL
@@ -4538,9 +4491,10 @@ static int eval_method(char_u **const arg, typval_T *const rettv, const bool eva
/// Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
/// "*arg" points to the '[' or '.'.
-/// Returns FAIL or OK. "*arg" is advanced to after the ']'.
///
/// @param verbose give error messages
+///
+/// @returns FAIL or OK. "*arg" is advanced to after the ']'.
static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose)
{
bool empty1 = false;
@@ -4845,19 +4799,18 @@ static int eval_index(char_u **arg, typval_T *rettv, int evaluate, int verbose)
/// Get an option value
///
-/// @param[in,out] arg Points to the '&' or '+' before the option name. Is
+/// @param[in,out] arg Points to the '&' or '+' before the option name. Is
/// advanced to the character after the option name.
-/// @param[out] rettv Location where result is saved.
-/// @param[in] evaluate If not true, rettv is not populated.
+/// @param[out] rettv Location where result is saved.
+/// @param[in] evaluate If not true, rettv is not populated.
///
-/// @return OK or FAIL.
+/// @return OK or FAIL.
int get_option_tv(const char **const arg, typval_T *const rettv, const bool evaluate)
FUNC_ATTR_NONNULL_ARG(1)
{
long numval;
char_u *stringval;
int opt_type;
- int c;
bool working = (**arg == '+'); // has("+option")
int ret = OK;
int opt_flags;
@@ -4876,7 +4829,7 @@ int get_option_tv(const char **const arg, typval_T *const rettv, const bool eval
return OK;
}
- c = *option_end;
+ char c = *option_end;
*option_end = NUL;
opt_type = get_option_value(*arg, &numval,
rettv == NULL ? NULL : &stringval, opt_flags);
@@ -4910,10 +4863,9 @@ int get_option_tv(const char **const arg, typval_T *const rettv, const bool eval
return ret;
}
-/*
- * Allocate a variable for a string constant.
- * Return OK or FAIL.
- */
+/// Allocate a variable for a string constant.
+///
+/// @return OK or FAIL.
static int get_string_tv(char_u **arg, typval_T *rettv, int evaluate)
{
char_u *p;
@@ -5050,10 +5002,9 @@ static int get_string_tv(char_u **arg, typval_T *rettv, int evaluate)
return OK;
}
-/*
- * Allocate a variable for a 'str''ing' constant.
- * Return OK or FAIL.
- */
+/// Allocate a variable for a 'str''ing' constant.
+///
+/// @return OK or FAIL.
static int get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate)
{
char_u *p;
@@ -5106,7 +5057,7 @@ static int get_lit_string_tv(char_u **arg, typval_T *rettv, int evaluate)
return OK;
}
-/// @return the function name of the partial.
+/// @return the function name of the partial.
char_u *partial_name(partial_T *pt)
{
if (pt->pt_name != NULL) {
@@ -5145,7 +5096,8 @@ void partial_unref(partial_T *pt)
}
/// Allocate a variable for a List and fill it from "*arg".
-/// Return OK or FAIL.
+///
+/// @return OK or FAIL.
static int get_list_tv(char_u **arg, typval_T *rettv, int evaluate)
{
list_T *l = NULL;
@@ -5283,7 +5235,8 @@ int get_copyID(void)
/// Do garbage collection for lists and dicts.
///
/// @param testing true if called from test_garbagecollect_now().
-/// @returns true if some memory was freed.
+///
+/// @return true if some memory was freed.
bool garbage_collect(bool testing)
{
bool abort = false;
@@ -5461,10 +5414,11 @@ bool garbage_collect(bool testing)
/// Free lists and dictionaries that are no longer referenced.
///
-/// @note This function may only be called from garbage_collect().
+/// @note This function may only be called from garbage_collect().
+///
+/// @param copyID Free lists/dictionaries that don't have this ID.
///
-/// @param copyID Free lists/dictionaries that don't have this ID.
-/// @return true, if something was freed.
+/// @return true, if something was freed.
static int free_unref_items(int copyID)
{
bool did_free = false;
@@ -5699,7 +5653,7 @@ bool set_ref_in_item(typval_T *tv, int copyID, ht_stack_T **ht_stack, list_stack
/// Mark all lists and dicts referenced in given mark
///
-/// @returns true if setting references failed somehow.
+/// @return true if setting references failed somehow.
static inline bool set_ref_in_fmark(fmark_T fm, int copyID)
FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -5713,7 +5667,7 @@ static inline bool set_ref_in_fmark(fmark_T fm, int copyID)
/// Mark all lists and dicts referenced in given list and the list itself
///
-/// @returns true if setting references failed somehow.
+/// @return true if setting references failed somehow.
static inline bool set_ref_list(list_T *list, int copyID)
FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -5729,7 +5683,7 @@ static inline bool set_ref_list(list_T *list, int copyID)
/// Mark all lists and dicts referenced in given dict and the dict itself
///
-/// @returns true if setting references failed somehow.
+/// @return true if setting references failed somehow.
static inline bool set_ref_dict(dict_T *dict, int copyID)
FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -5744,8 +5698,9 @@ static inline bool set_ref_dict(dict_T *dict, int copyID)
}
-// Get the key for *{key: val} into "tv" and advance "arg".
-// Return FAIL when there is no valid key.
+/// Get the key for *{key: val} into "tv" and advance "arg".
+///
+/// @return FAIL when there is no valid key.
static int get_literal_key(char_u **arg, typval_T *tv)
FUNC_ATTR_NONNULL_ALL
{
@@ -5763,9 +5718,10 @@ static int get_literal_key(char_u **arg, typval_T *tv)
return OK;
}
-// Allocate a variable for a Dictionary and fill it from "*arg".
-// "literal" is true for *{key: val}
-// Return OK or FAIL. Returns NOTDONE for {expr}.
+/// Allocate a variable for a Dictionary and fill it from "*arg".
+/// "literal" is true for *{key: val}
+///
+/// @return OK or FAIL. Returns NOTDONE for {expr}.
static int dict_get_tv(char_u **arg, typval_T *rettv, int evaluate, bool literal)
{
dict_T *d = NULL;
@@ -5875,10 +5831,10 @@ failret:
/// This uses strtod(). setlocale(LC_NUMERIC, "C") has been used earlier to
/// make sure this always uses a decimal point.
///
-/// @param[in] text String to convert.
-/// @param[out] ret_value Location where conversion result is saved.
+/// @param[in] text String to convert.
+/// @param[out] ret_value Location where conversion result is saved.
///
-/// @return Length of the text that was consumed.
+/// @return Length of the text that was consumed.
size_t string2float(const char *const text, float_T *const ret_value)
FUNC_ATTR_NONNULL_ALL
{
@@ -5905,9 +5861,9 @@ size_t string2float(const char *const text, float_T *const ret_value)
///
/// If the environment variable was not set, silently assume it is empty.
///
-/// @param arg Points to the '$'. It is advanced to after the name.
-/// @return FAIL if the name is invalid.
+/// @param arg Points to the '$'. It is advanced to after the name.
///
+/// @return FAIL if the name is invalid.
static int get_env_tv(char_u **arg, typval_T *rettv, int evaluate)
{
char_u *name;
@@ -5956,7 +5912,7 @@ void get_arglist_as_rettv(aentry_T *arglist, int argcount, typval_T *rettv)
}
}
-// Prepare "gap" for an assert error and add the sourcing position.
+/// Prepare "gap" for an assert error and add the sourcing position.
void prepare_assert_error(garray_T *gap)
{
char buf[NUMBUFLEN];
@@ -5977,8 +5933,8 @@ void prepare_assert_error(garray_T *gap)
}
}
-// Append "p[clen]" to "gap", escaping unprintable characters.
-// Changes NL to \n, CR to \r, etc.
+/// Append "p[clen]" to "gap", escaping unprintable characters.
+/// Changes NL to \n, CR to \r, etc.
static void ga_concat_esc(garray_T *gap, const char_u *p, int clen)
FUNC_ATTR_NONNULL_ALL
{
@@ -6016,8 +5972,8 @@ static void ga_concat_esc(garray_T *gap, const char_u *p, int clen)
}
}
-// Append "str" to "gap", escaping unprintable characters.
-// Changes NL to \n, CR to \r, etc.
+/// Append "str" to "gap", escaping unprintable characters.
+/// Changes NL to \n, CR to \r, etc.
static void ga_concat_shorten_esc(garray_T *gap, const char_u *str)
FUNC_ATTR_NONNULL_ARG(1)
{
@@ -6051,7 +6007,7 @@ static void ga_concat_shorten_esc(garray_T *gap, const char_u *str)
}
}
-// Fill "gap" with information about an assert error.
+/// Fill "gap" with information about an assert error.
void fill_assert_error(garray_T *gap, typval_T *opt_msg_tv, char_u *exp_str, typval_T *exp_tv,
typval_T *got_tv, assert_type_T atype)
{
@@ -6094,7 +6050,7 @@ void fill_assert_error(garray_T *gap, typval_T *opt_msg_tv, char_u *exp_str, typ
}
}
-// Add an assert error to v:errors.
+/// Add an assert error to v:errors.
void assert_error(garray_T *gap)
{
struct vimvar *vp = &vimvars[VV_ERRORS];
@@ -6268,7 +6224,7 @@ int assert_inrange(typval_T *argvars)
return 0;
}
-// Common for assert_true() and assert_false().
+/// Common for assert_true() and assert_false().
int assert_bool(typval_T *argvars, bool is_true)
FUNC_ATTR_NONNULL_ALL
{
@@ -6436,15 +6392,13 @@ win_T *find_win_by_nr_or_id(typval_T *vp)
int nr = (int)tv_get_number_chk(vp, NULL);
if (nr >= LOWEST_WIN_ID) {
- return win_id2wp(vp);
+ return win_id2wp(tv_get_number(vp));
}
return find_win_by_nr(vp, NULL);
}
-/*
- * Implementation of map() and filter().
- */
+/// Implementation of map() and filter().
void filter_map(typval_T *argvars, typval_T *rettv, int map)
{
typval_T *expr;
@@ -6806,7 +6760,7 @@ theend:
xfree(trans_name);
}
-/// Returns buffer options, variables and other attributes in a dictionary.
+/// @return buffer options, variables and other attributes in a dictionary.
dict_T *get_buffer_info(buf_T *buf)
{
dict_T *const dict = tv_dict_alloc();
@@ -6850,12 +6804,12 @@ dict_T *get_buffer_info(buf_T *buf)
///
/// @note Unlike tv_get_lnum(), this one supports only "$" special string.
///
-/// @param[in] tv Object to get value from. Is expected to be a number or
+/// @param[in] tv Object to get value from. Is expected to be a number or
/// a special string "$".
-/// @param[in] buf Buffer to take last line number from in case tv is "$". May
-/// be NULL, in this case "$" results in zero return.
+/// @param[in] buf Buffer to take last line number from in case tv is "$". May
+/// be NULL, in this case "$" results in zero return.
///
-/// @return Line number or 0 in case of error.
+/// @return Line number or 0 in case of error.
linenr_T tv_get_lnum_buf(const typval_T *const tv, const buf_T *const buf)
FUNC_ATTR_NONNULL_ARG(1) FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -6891,8 +6845,8 @@ void get_qf_loc_list(int is_qf, win_T *wp, typval_T *what_arg, typval_T *rettv)
}
}
-/// Returns information (variables, options, etc.) about a tab page
-/// as a dictionary.
+/// @return information (variables, options, etc.) about a tab page
+/// as a dictionary.
dict_T *get_tabpage_info(tabpage_T *tp, int tp_idx)
{
dict_T *const dict = tv_dict_alloc();
@@ -6911,7 +6865,7 @@ dict_T *get_tabpage_info(tabpage_T *tp, int tp_idx)
return dict;
}
-/// Returns information about a window as a dictionary.
+/// @return information about a window as a dictionary.
dict_T *get_win_info(win_T *wp, int16_t tpnr, int16_t winnr)
{
dict_T *const dict = tv_dict_alloc();
@@ -7064,12 +7018,10 @@ void getwinvar(typval_T *argvars, typval_T *rettv, int off)
}
}
-/*
- * This function is used by f_input() and f_inputdialog() functions. The third
- * argument to f_input() specifies the type of completion to use at the
- * prompt. The third argument to f_inputdialog() specifies the value to return
- * when the user cancels the prompt.
- */
+/// This function is used by f_input() and f_inputdialog() functions. The third
+/// argument to f_input() specifies the type of completion to use at the
+/// prompt. The third argument to f_inputdialog() specifies the value to return
+/// when the user cancels the prompt.
void get_user_input(const typval_T *const argvars, typval_T *const rettv, const bool inputdialog,
const bool secret)
FUNC_ATTR_NONNULL_ALL
@@ -7201,10 +7153,10 @@ void get_user_input(const typval_T *const argvars, typval_T *const rettv, const
/// Turn a dictionary into a list
///
-/// @param[in] tv Dictionary to convert. Is checked for actually being
-/// a dictionary, will give an error if not.
-/// @param[out] rettv Location where result will be saved.
-/// @param[in] what What to save in rettv.
+/// @param[in] tv Dictionary to convert. Is checked for actually being
+/// a dictionary, will give an error if not.
+/// @param[out] rettv Location where result will be saved.
+/// @param[in] what What to save in rettv.
void dict_list(typval_T *const tv, typval_T *const rettv, const DictListType what)
{
if (tv->v_type != VAR_DICT) {
@@ -7257,7 +7209,7 @@ void dict_list(typval_T *const tv, typval_T *const rettv, const DictListType wha
/// @param[out] cmd Returns the command or executable name.
/// @param[out] executable Returns `false` if argv[0] is not executable.
///
-/// @returns Result of `shell_build_argv()` if `cmd_tv` is a String.
+/// @return Result of `shell_build_argv()` if `cmd_tv` is a String.
/// Else, string values of `cmd_tv` copied to a (char **) list with
/// argv[0] resolved to full path ($PATHEXT-resolved on Windows).
char **tv_to_argv(typval_T *cmd_tv, const char **cmd, bool *executable)
@@ -7321,10 +7273,10 @@ char **tv_to_argv(typval_T *cmd_tv, const char **cmd, bool *executable)
/// Fill a dictionary with all applicable maparg() like dictionaries
///
-/// @param dict The dictionary to be filled
-/// @param mp The maphash that contains the mapping information
-/// @param buffer_value The "buffer" value
-/// @param compatible True for compatible with old maparg() dict
+/// @param dict The dictionary to be filled
+/// @param mp The maphash that contains the mapping information
+/// @param buffer_value The "buffer" value
+/// @param compatible True for compatible with old maparg() dict
void mapblock_fill_dict(dict_T *const dict, const mapblock_T *const mp, long buffer_value,
bool compatible)
FUNC_ATTR_NONNULL_ALL
@@ -7621,7 +7573,7 @@ static list_T *string_to_list(const char *str, size_t len, const bool keepempty)
return list;
}
-// os_system wrapper. Handles 'verbose', :profile, and v:shell_error.
+/// os_system wrapper. Handles 'verbose', :profile, and v:shell_error.
void get_system_output_as_rettv(typval_T *argvars, typval_T *rettv, bool retlist)
{
proftime_T wait_time;
@@ -7746,6 +7698,7 @@ bool callback_from_typval(Callback *const callback, typval_T *const arg)
callback->type = kCallbackFuncref;
}
} else if (nlua_is_table_from_lua(arg)) {
+ // TODO(tjdvries): UnifiedCallback
char_u *name = nlua_register_table_as_callable(arg);
if (name != NULL) {
@@ -7775,6 +7728,7 @@ bool callback_call(Callback *const callback, const int argcount_in, typval_T *co
{
partial_T *partial;
char_u *name;
+ Array args = ARRAY_DICT_INIT;
switch (callback->type) {
case kCallbackFuncref:
name = callback->data.funcref;
@@ -7786,6 +7740,12 @@ bool callback_call(Callback *const callback, const int argcount_in, typval_T *co
name = partial_name(partial);
break;
+ case kCallbackLua:
+ nlua_call_ref(callback->data.luaref, NULL, args, false, NULL);
+
+ return false;
+ break;
+
case kCallbackNone:
return false;
break;
@@ -7878,7 +7838,7 @@ void add_timer_info_all(typval_T *rettv)
})
}
-// invoked on the main loop
+/// invoked on the main loop
void timer_due_cb(TimeWatcher *tw, void *data)
{
timer_T *timer = (timer_T *)data;
@@ -7964,8 +7924,8 @@ void timer_stop(timer_T *timer)
time_watcher_close(&timer->tw, timer_close_cb);
}
-// This will be run on the main loop after the last timer_due_cb, so at this
-// point it is safe to free the callback.
+/// This will be run on the main loop after the last timer_due_cb, so at this
+/// point it is safe to free the callback.
static void timer_close_cb(TimeWatcher *tw, void *data)
{
timer_T *timer = (timer_T *)data;
@@ -8227,8 +8187,10 @@ int buf_byteidx_to_charidx(buf_T *buf, int lnum, int byteidx)
}
/// Convert the specified character index of line 'lnum' in buffer 'buf' to a
-/// byte index. Works only for loaded buffers. Returns -1 on failure.
+/// byte index. Works only for loaded buffers.
/// The index of the first byte and the first character is zero.
+///
+/// @return -1 on failure.
int buf_charidx_to_byteidx(buf_T *buf, int lnum, int charidx)
{
if (buf == NULL || buf->b_ml.ml_mfp == NULL) {
@@ -8392,8 +8354,9 @@ pos_T *var2fpos(const typval_T *const tv, const bool dollar_lnum, int *const ret
/// When "fnump" is NULL there is no file number, only 3 items.
/// Note that the column is passed on as-is, the caller may want to decrement
/// it to use 1 for the first column.
-/// Return FAIL when conversion is not possible, doesn't check the position for
-/// validity.
+///
+/// @return FAIL when conversion is not possible, doesn't check the position for
+/// validity.
int list2fpos(typval_T *arg, pos_T *posp, int *fnump, colnr_T *curswantp, bool charcol)
{
list_T *l;
@@ -8455,11 +8418,10 @@ int list2fpos(typval_T *arg, pos_T *posp, int *fnump, colnr_T *curswantp, bool c
return OK;
}
-/*
- * Get the length of an environment variable name.
- * Advance "arg" to the first character after the name.
- * Return 0 for error.
- */
+/// Get the length of an environment variable name.
+/// Advance "arg" to the first character after the name.
+///
+/// @return 0 for error.
static int get_env_len(const char_u **arg)
{
int len;
@@ -8476,9 +8438,11 @@ static int get_env_len(const char_u **arg)
return len;
}
-// Get the length of the name of a function or internal variable.
-// "arg" is advanced to the first non-white character after the name.
-// Return 0 if something is wrong.
+/// Get the length of the name of a function or internal variable.
+///
+/// @param arg is advanced to the first non-white character after the name.
+///
+/// @return 0 if something is wrong.
int get_id_len(const char **const arg)
{
int len;
@@ -8506,15 +8470,15 @@ int get_id_len(const char **const arg)
return len;
}
-/*
- * Get the length of the name of a variable or function.
- * Only the name is recognized, does not handle ".key" or "[idx]".
- * "arg" is advanced to the first non-white character after the name.
- * Return -1 if curly braces expansion failed.
- * Return 0 if something else is wrong.
- * If the name contains 'magic' {}'s, expand them and return the
- * expanded name in an allocated string via 'alias' - caller must free.
- */
+/// Get the length of the name of a variable or function.
+/// Only the name is recognized, does not handle ".key" or "[idx]".
+///
+/// @param arg is advanced to the first non-white character after the name.
+/// If the name contains 'magic' {}'s, expand them and return the
+/// expanded name in an allocated string via 'alias' - caller must free.
+///
+/// @return -1 if curly braces expansion failed or
+/// 0 if something else is wrong.
int get_name_len(const char **const arg, char **alias, bool evaluate, bool verbose)
{
int len;
@@ -8571,12 +8535,15 @@ int get_name_len(const char **const arg, char **alias, bool evaluate, bool verbo
return len;
}
-// Find the end of a variable or function name, taking care of magic braces.
-// If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
-// start and end of the first magic braces item.
-// "flags" can have FNE_INCL_BR and FNE_CHECK_START.
-// Return a pointer to just after the name. Equal to "arg" if there is no
-// valid name.
+/// Find the end of a variable or function name, taking care of magic braces.
+///
+/// @param expr_start if not NULL, then `expr_start` and `expr_end` are set to the
+/// start and end of the first magic braces item.
+///
+/// @param flags can have FNE_INCL_BR and FNE_CHECK_START.
+///
+/// @return a pointer to just after the name. Equal to "arg" if there is no
+/// valid name.
const char_u *find_name_end(const char_u *arg, const char_u **expr_start, const char_u **expr_end,
int flags)
{
@@ -8654,19 +8621,17 @@ const char_u *find_name_end(const char_u *arg, const char_u **expr_start, const
return p;
}
-/*
- * Expands out the 'magic' {}'s in a variable/function name.
- * Note that this can call itself recursively, to deal with
- * constructs like foo{bar}{baz}{bam}
- * The four pointer arguments point to "foo{expre}ss{ion}bar"
- * "in_start" ^
- * "expr_start" ^
- * "expr_end" ^
- * "in_end" ^
- *
- * Returns a new allocated string, which the caller must free.
- * Returns NULL for failure.
- */
+/// Expands out the 'magic' {}'s in a variable/function name.
+/// Note that this can call itself recursively, to deal with
+/// constructs like foo{bar}{baz}{bam}
+/// The four pointer arguments point to "foo{expre}ss{ion}bar"
+/// "in_start" ^
+/// "expr_start" ^
+/// "expr_end" ^
+/// "in_end" ^
+///
+/// @return a new allocated string, which the caller must free or
+/// NULL for failure.
static char_u *make_expanded_name(const char_u *in_start, char_u *expr_start, char_u *expr_end,
char_u *in_end)
{
@@ -8713,44 +8678,36 @@ static char_u *make_expanded_name(const char_u *in_start, char_u *expr_start, ch
return retval;
}
-/*
- * Return TRUE if character "c" can be used in a variable or function name.
- * Does not include '{' or '}' for magic braces.
- */
+/// @return TRUE if character "c" can be used in a variable or function name.
+/// Does not include '{' or '}' for magic braces.
int eval_isnamec(int c)
{
return ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR;
}
-/*
- * Return TRUE if character "c" can be used as the first character in a
- * variable or function name (excluding '{' and '}').
- */
+/// @return TRUE if character "c" can be used as the first character in a
+/// variable or function name (excluding '{' and '}').
int eval_isnamec1(int c)
{
return ASCII_ISALPHA(c) || c == '_';
}
-/*
- * Get number v: variable value.
- */
+/// Get number v: variable value.
varnumber_T get_vim_var_nr(int idx) FUNC_ATTR_PURE
{
return vimvars[idx].vv_nr;
}
-// Get string v: variable value. Uses a static buffer, can only be used once.
-// If the String variable has never been set, return an empty string.
-// Never returns NULL;
+/// Get string v: variable value. Uses a static buffer, can only be used once.
+/// If the String variable has never been set, return an empty string.
+/// Never returns NULL;
char_u *get_vim_var_str(int idx) FUNC_ATTR_PURE FUNC_ATTR_NONNULL_RET
{
return (char_u *)tv_get_string(&vimvars[idx].vv_tv);
}
-/*
- * Get List v: variable value. Caller must take care of reference count when
- * needed.
- */
+/// Get List v: variable value. Caller must take care of reference count when
+/// needed.
list_T *get_vim_var_list(int idx) FUNC_ATTR_PURE
{
return vimvars[idx].vv_list;
@@ -8763,9 +8720,7 @@ dict_T *get_vim_var_dict(int idx) FUNC_ATTR_PURE
return vimvars[idx].vv_dict;
}
-/*
- * Set v:char to character "c".
- */
+/// Set v:char to character "c".
void set_vim_var_char(int c)
{
char buf[MB_MAXBYTES + 1];
@@ -8774,10 +8729,9 @@ void set_vim_var_char(int c)
set_vim_var_string(VV_CHAR, buf, -1);
}
-/*
- * Set v:count to "count" and v:count1 to "count1".
- * When "set_prevcount" is TRUE first set v:prevcount from v:count.
- */
+/// Set v:count to "count" and v:count1 to "count1".
+///
+/// @param set_prevcount if TRUE, first set v:prevcount from v:count.
void set_vcount(long count, long count1, int set_prevcount)
{
if (set_prevcount) {
@@ -8885,9 +8839,7 @@ void set_argv_var(char **argv, int argc)
set_vim_var_list(VV_ARGV, l);
}
-/*
- * Set v:register if needed.
- */
+/// Set v:register if needed.
void set_reg_var(int c)
{
char regname;
@@ -8903,12 +8855,10 @@ void set_reg_var(int c)
}
}
-/*
- * Get or set v:exception. If "oldval" == NULL, return the current value.
- * Otherwise, restore the value to "oldval" and return NULL.
- * Must always be called in pairs to save and restore v:exception! Does not
- * take care of memory allocations.
- */
+/// Get or set v:exception. If "oldval" == NULL, return the current value.
+/// Otherwise, restore the value to "oldval" and return NULL.
+/// Must always be called in pairs to save and restore v:exception! Does not
+/// take care of memory allocations.
char_u *v_exception(char_u *oldval)
{
if (oldval == NULL) {
@@ -8919,12 +8869,10 @@ char_u *v_exception(char_u *oldval)
return NULL;
}
-/*
- * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
- * Otherwise, restore the value to "oldval" and return NULL.
- * Must always be called in pairs to save and restore v:throwpoint! Does not
- * take care of memory allocations.
- */
+/// Get or set v:throwpoint. If "oldval" == NULL, return the current value.
+/// Otherwise, restore the value to "oldval" and return NULL.
+/// Must always be called in pairs to save and restore v:throwpoint! Does not
+/// take care of memory allocations.
char_u *v_throwpoint(char_u *oldval)
{
if (oldval == NULL) {
@@ -8935,12 +8883,10 @@ char_u *v_throwpoint(char_u *oldval)
return NULL;
}
-/*
- * Set v:cmdarg.
- * If "eap" != NULL, use "eap" to generate the value and return the old value.
- * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
- * Must always be called in pairs!
- */
+/// Set v:cmdarg.
+/// If "eap" != NULL, use "eap" to generate the value and return the old value.
+/// If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
+/// Must always be called in pairs!
char_u *set_cmdarg(exarg_T *eap, char_u *oldarg)
{
char_u *oldval = vimvars[VV_CMDARG].vv_str;
@@ -9205,11 +9151,12 @@ void set_selfdict(typval_T *const rettv, dict_T *const selfdict)
make_partial(selfdict, rettv);
}
-// Find variable "name" in the list of variables.
-// Return a pointer to it if found, NULL if not found.
-// Careful: "a:0" variables don't have a name.
-// When "htp" is not NULL we are writing to the variable, set "htp" to the
-// hashtab_T used.
+/// Find variable "name" in the list of variables.
+/// Careful: "a:0" variables don't have a name.
+/// When "htp" is not NULL we are writing to the variable, set "htp" to the
+/// hashtab_T used.
+///
+/// @return a pointer to it if found, NULL if not found.
dictitem_T *find_var(const char *const name, const size_t name_len, hashtab_T **htp,
int no_autoload)
{
@@ -9359,10 +9306,31 @@ static hashtab_T *find_var_ht_dict(const char *name, const size_t name_len, cons
} else if (*name == 'l' && funccal != NULL) { // local variable
*d = &funccal->l_vars;
} else if (*name == 's' // script variable
- && (current_sctx.sc_sid > 0 || current_sctx.sc_sid == SID_STR)
+ && (current_sctx.sc_sid > 0 || current_sctx.sc_sid == SID_STR
+ || current_sctx.sc_sid == SID_LUA)
&& current_sctx.sc_sid <= ga_scripts.ga_len) {
// For anonymous scripts without a script item, create one now so script vars can be used
- if (current_sctx.sc_sid == SID_STR) {
+ if (current_sctx.sc_sid == SID_LUA) {
+ // try to resolve lua filename & line no so it can be shown in lastset messages.
+ nlua_set_sctx(&current_sctx);
+ if (current_sctx.sc_sid != SID_LUA) {
+ // Great we have valid location. Now here this out we'll create a new
+ // script context with the name and lineno of this one. why ?
+ // for behavioral consistency. With this different anonymous exec from
+ // same file can't access each others script local stuff. We need to do
+ // this all other cases except this will act like that otherwise.
+ const LastSet last_set = (LastSet){
+ .script_ctx = current_sctx,
+ .channel_id = LUA_INTERNAL_CALL,
+ };
+ bool should_free;
+ // should_free is ignored as script_sctx will be resolved to a fnmae
+ // & new_script_item will consume it.
+ char_u *sc_name = get_scriptname(last_set, &should_free);
+ new_script_item(sc_name, &current_sctx.sc_sid);
+ }
+ }
+ if (current_sctx.sc_sid == SID_STR || current_sctx.sc_sid == SID_LUA) {
new_script_item(NULL, &current_sctx.sc_sid);
}
*d = &SCRIPT_SV(current_sctx.sc_sid)->sv_dict;
@@ -9386,11 +9354,10 @@ hashtab_T *find_var_ht(const char *name, const size_t name_len, const char **var
return find_var_ht_dict(name, name_len, varname, &d);
}
-/*
- * Get the string value of a (global/local) variable.
- * Note: see tv_get_string() for how long the pointer remains valid.
- * Returns NULL when it doesn't exist.
- */
+/// @return the string value of a (global/local) variable or
+/// NULL when it doesn't exist.
+///
+/// @see tv_get_string() for how long the pointer remains valid.
char_u *get_var_value(const char *const name)
{
dictitem_T *v;
@@ -9402,16 +9369,14 @@ char_u *get_var_value(const char *const name)
return (char_u *)tv_get_string(&v->di_tv);
}
-/*
- * Allocate a new hashtab for a sourced script. It will be used while
- * sourcing this script and when executing functions defined in the script.
- */
+/// Allocate a new hashtab for a sourced script. It will be used while
+/// sourcing this script and when executing functions defined in the script.
void new_script_vars(scid_T id)
{
hashtab_T *ht;
scriptvar_T *sv;
- ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len));
+ ga_grow(&ga_scripts, id - ga_scripts.ga_len);
{
/* Re-allocating ga_data means that an ht_array pointing to
* ht_smallarray becomes invalid. We can recognize this: ht_mask is
@@ -9433,10 +9398,8 @@ void new_script_vars(scid_T id)
}
}
-/*
- * Initialize dictionary "dict" as a scope and set variable "dict_var" to
- * point to it.
- */
+/// Initialize dictionary "dict" as a scope and set variable "dict_var" to
+/// point to it.
void init_var_dict(dict_T *dict, ScopeDictDictItem *dict_var, int scope)
{
hash_init(&dict->dv_hashtab);
@@ -9452,9 +9415,7 @@ void init_var_dict(dict_T *dict, ScopeDictDictItem *dict_var, int scope)
QUEUE_INIT(&dict->watchers);
}
-/*
- * Unreference a dictionary initialized by init_var_dict().
- */
+/// Unreference a dictionary initialized by init_var_dict().
void unref_var_dict(dict_T *dict)
{
/* Now the dict needs to be freed if no one else is using it, go back to
@@ -9463,19 +9424,15 @@ void unref_var_dict(dict_T *dict)
tv_dict_unref(dict);
}
-/*
- * Clean up a list of internal variables.
- * Frees all allocated variables and the value they contain.
- * Clears hashtab "ht", does not free it.
- */
+/// Clean up a list of internal variables.
+/// Frees all allocated variables and the value they contain.
+/// Clears hashtab "ht", does not free it.
void vars_clear(hashtab_T *ht)
{
vars_clear_ext(ht, TRUE);
}
-/*
- * Like vars_clear(), but only free the value if "free_val" is TRUE.
- */
+/// Like vars_clear(), but only free the value if "free_val" is TRUE.
void vars_clear_ext(hashtab_T *ht, int free_val)
{
int todo;
@@ -9504,10 +9461,8 @@ void vars_clear_ext(hashtab_T *ht, int free_val)
ht->ht_used = 0;
}
-/*
- * Delete a variable from hashtab "ht" at item "hi".
- * Clear the variable value and free the dictitem.
- */
+/// Delete a variable from hashtab "ht" at item "hi".
+/// Clear the variable value and free the dictitem.
static void delete_var(hashtab_T *ht, hashitem_T *hi)
{
dictitem_T *di = TV_DICT_HI2DI(hi);
@@ -9517,9 +9472,7 @@ static void delete_var(hashtab_T *ht, hashitem_T *hi)
xfree(di);
}
-/*
- * List the value of one internal variable.
- */
+/// List the value of one internal variable.
static void list_one_var(dictitem_T *v, const char *prefix, int *first)
{
char *const s = encode_tv2echo(&v->di_tv, NULL);
@@ -9952,11 +9905,9 @@ int var_item_copy(const vimconv_T *const conv, typval_T *const from, typval_T *c
return ret;
}
-/*
- * ":echo expr1 ..." print each argument separated with a space, add a
- * newline at the end.
- * ":echon expr1 ..." print each argument plain.
- */
+/// ":echo expr1 ..." print each argument separated with a space, add a
+/// newline at the end.
+/// ":echon expr1 ..." print each argument plain.
void ex_echo(exarg_T *eap)
{
char_u *arg = eap->arg;
@@ -10030,21 +9981,17 @@ void ex_echo(exarg_T *eap)
}
}
-/*
- * ":echohl {name}".
- */
+/// ":echohl {name}".
void ex_echohl(exarg_T *eap)
{
echo_attr = syn_name2attr(eap->arg);
}
-/*
- * ":execute expr1 ..." execute the result of an expression.
- * ":echomsg expr1 ..." Print a message
- * ":echoerr expr1 ..." Print an error
- * Each gets spaces around each argument and a newline at the end for
- * echo commands
- */
+/// ":execute expr1 ..." execute the result of an expression.
+/// ":echomsg expr1 ..." Print a message
+/// ":echoerr expr1 ..." Print an error
+/// Each gets spaces around each argument and a newline at the end for
+/// echo commands
void ex_execute(exarg_T *eap)
{
char_u *arg = eap->arg;
@@ -10121,12 +10068,12 @@ void ex_execute(exarg_T *eap)
eap->nextcmd = check_nextcmd(arg);
}
-/*
- * Skip over the name of an option: "&option", "&g:option" or "&l:option".
- * "arg" points to the "&" or '+' when called, to "option" when returning.
- * Returns NULL when no option name found. Otherwise pointer to the char
- * after the option name.
- */
+/// Skip over the name of an option: "&option", "&g:option" or "&l:option".
+///
+/// @param arg points to the "&" or '+' when called, to "option" when returning.
+///
+/// @return NULL when no option name found. Otherwise pointer to the char
+/// after the option name.
static const char *find_option_end(const char **const arg, int *const opt_flags)
{
const char *p = *arg;
@@ -10189,9 +10136,7 @@ void func_do_profile(ufunc_T *fp)
fp->uf_profiling = TRUE;
}
-/*
- * Dump the profiling results for all functions in file "fd".
- */
+/// Dump the profiling results for all functions in file "fd".
void func_dump_profile(FILE *fd)
{
hashitem_T *hi;
@@ -10311,9 +10256,7 @@ static void prof_func_line(FILE *fd, int count, proftime_T *total, proftime_T *s
}
}
-/*
- * Compare function for total time sorting.
- */
+/// Compare function for total time sorting.
static int prof_total_cmp(const void *s1, const void *s2)
{
ufunc_T *p1 = *(ufunc_T **)s1;
@@ -10321,9 +10264,7 @@ static int prof_total_cmp(const void *s1, const void *s2)
return profile_cmp(p1->uf_tm_total, p2->uf_tm_total);
}
-/*
- * Compare function for self time sorting.
- */
+/// Compare function for self time sorting.
static int prof_self_cmp(const void *s1, const void *s2)
{
ufunc_T *p1 = *(ufunc_T **)s1;
@@ -10405,12 +10346,10 @@ bool script_autoload(const char *const name, const size_t name_len, const bool r
return ret;
}
-/*
- * Called when starting to read a function line.
- * "sourcing_lnum" must be correct!
- * When skipping lines it may not actually be executed, but we won't find out
- * until later and we need to store the time now.
- */
+/// Called when starting to read a function line.
+/// "sourcing_lnum" must be correct!
+/// When skipping lines it may not actually be executed, but we won't find out
+/// until later and we need to store the time now.
void func_line_start(void *cookie)
{
funccall_T *fcp = (funccall_T *)cookie;
@@ -10430,9 +10369,7 @@ void func_line_start(void *cookie)
}
}
-/*
- * Called when actually executing a function line.
- */
+/// Called when actually executing a function line.
void func_line_exec(void *cookie)
{
funccall_T *fcp = (funccall_T *)cookie;
@@ -10443,9 +10380,7 @@ void func_line_exec(void *cookie)
}
}
-/*
- * Called when done with a function line.
- */
+/// Called when done with a function line.
void func_line_end(void *cookie)
{
funccall_T *fcp = (funccall_T *)cookie;
@@ -10580,10 +10515,8 @@ int store_session_globals(FILE *fd)
return OK;
}
-/*
- * Display script name where an item was last set.
- * Should only be invoked when 'verbose' is non-zero.
- */
+/// Display script name where an item was last set.
+/// Should only be invoked when 'verbose' is non-zero.
void last_set_msg(sctx_T script_ctx)
{
const LastSet last_set = (LastSet){
@@ -10936,7 +10869,8 @@ repeat:
/// Perform a substitution on "str" with pattern "pat" and substitute "sub".
/// When "sub" is NULL "expr" is used, must be a VAR_FUNC or VAR_PARTIAL.
/// "flags" can be "g" to do a global substitute.
-/// Returns an allocated string, NULL for error.
+///
+/// @return an allocated string, NULL for error.
char_u *do_string_sub(char_u *str, char_u *pat, char_u *sub, typval_T *expr, char_u *flags)
{
int sublen;
@@ -11272,7 +11206,7 @@ void invoke_prompt_callback(void)
tv_clear(&rettv);
}
-// Return true When the interrupt callback was invoked.
+/// @return true when the interrupt callback was invoked.
bool invoke_prompt_interrupt(void)
{
typval_T rettv;
diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c
index c6baa105b0..9579a996bc 100644
--- a/src/nvim/eval/funcs.c
+++ b/src/nvim/eval/funcs.c
@@ -175,7 +175,7 @@ char_u *get_expr_name(expand_T *xp, int idx)
///
/// @param[in] name Name of the function.
///
-/// Returns pointer to the function definition or NULL if not found.
+/// @return pointer to the function definition or NULL if not found.
const VimLFuncDef *find_internal_func(const char *const name)
FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE FUNC_ATTR_NONNULL_ALL
{
@@ -229,9 +229,7 @@ int call_internal_method(const char_u *const fname, const int argcount, typval_T
return ERROR_NONE;
}
-/*
- * Return TRUE for a non-zero Number and a non-empty String.
- */
+/// @return TRUE for a non-zero Number and a non-empty String.
static int non_zero_arg(typval_T *argvars)
{
return ((argvars[0].v_type == VAR_NUMBER
@@ -243,11 +241,11 @@ static int non_zero_arg(typval_T *argvars)
&& *argvars[0].vval.v_string != NUL));
}
-// Apply a floating point C function on a typval with one float_T.
-//
-// Some versions of glibc on i386 have an optimization that makes it harder to
-// call math functions indirectly from inside an inlined function, causing
-// compile-time errors. Avoid `inline` in that case. #3072
+/// Apply a floating point C function on a typval with one float_T.
+///
+/// Some versions of glibc on i386 have an optimization that makes it harder to
+/// call math functions indirectly from inside an inlined function, causing
+/// compile-time errors. Avoid `inline` in that case. #3072
static void float_op_wrapper(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
float_T f;
@@ -293,9 +291,7 @@ end:
api_clear_error(&err);
}
-/*
- * "abs(expr)" function
- */
+/// "abs(expr)" function
static void f_abs(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (argvars[0].v_type == VAR_FLOAT) {
@@ -315,9 +311,7 @@ static void f_abs(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "add(list, item)" function
- */
+/// "add(list, item)" function
static void f_add(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = 1; // Default: failed.
@@ -345,9 +339,7 @@ static void f_add(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "and(expr, expr)" function
- */
+/// "and(expr, expr)" function
static void f_and(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL)
@@ -363,7 +355,7 @@ static void f_api_info(typval_T *argvars, typval_T *rettv, FunPtr fptr)
api_free_dictionary(metadata);
}
-// "append(lnum, string/list)" function
+/// "append(lnum, string/list)" function
static void f_append(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const linenr_T lnum = tv_get_lnum(&argvars[0]);
@@ -371,7 +363,7 @@ static void f_append(typval_T *argvars, typval_T *rettv, FunPtr fptr)
set_buffer_lines(curbuf, lnum, true, &argvars[1], rettv);
}
-// "appendbufline(buf, lnum, string/list)" function
+/// "appendbufline(buf, lnum, string/list)" function
static void f_appendbufline(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
buf_T *const buf = tv_get_buf(&argvars[0], false);
@@ -403,9 +395,7 @@ static void f_argc(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "argidx()" function
- */
+/// "argidx()" function
static void f_argidx(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = curwin->w_arg_idx;
@@ -421,9 +411,7 @@ static void f_arglistid(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "argv(nr)" function
- */
+/// "argv(nr)" function
static void f_argv(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
aentry_T *arglist = NULL;
@@ -458,31 +446,31 @@ static void f_argv(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "assert_beeps(cmd [, error])" function
+/// "assert_beeps(cmd [, error])" function
static void f_assert_beeps(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = assert_beeps(argvars, false);
}
-// "assert_nobeep(cmd [, error])" function
+/// "assert_nobeep(cmd [, error])" function
static void f_assert_nobeep(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = assert_beeps(argvars, true);
}
-// "assert_equal(expected, actual[, msg])" function
+/// "assert_equal(expected, actual[, msg])" function
static void f_assert_equal(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = assert_equal_common(argvars, ASSERT_EQUAL);
}
-// "assert_equalfile(fname-one, fname-two[, msg])" function
+/// "assert_equalfile(fname-one, fname-two[, msg])" function
static void f_assert_equalfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = assert_equalfile(argvars);
}
-// "assert_notequal(expected, actual[, msg])" function
+/// "assert_notequal(expected, actual[, msg])" function
static void f_assert_notequal(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = assert_equal_common(argvars, ASSERT_NOTEQUAL);
@@ -536,15 +524,13 @@ static void f_assert_notmatch(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = assert_match_common(argvars, ASSERT_NOTMATCH);
}
-// "assert_true(actual[, msg])" function
+/// "assert_true(actual[, msg])" function
static void f_assert_true(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = assert_bool(argvars, true);
}
-/*
- * "atan2()" function
- */
+/// "atan2()" function
static void f_atan2(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
float_T fx;
@@ -558,27 +544,21 @@ static void f_atan2(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "browse(save, title, initdir, default)" function
- */
+/// "browse(save, title, initdir, default)" function
static void f_browse(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_string = NULL;
rettv->v_type = VAR_STRING;
}
-/*
- * "browsedir(title, initdir)" function
- */
+/// "browsedir(title, initdir)" function
static void f_browsedir(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
f_browse(argvars, rettv, NULL);
}
-/*
- * Find a buffer by number or exact name.
- */
+/// Find a buffer by number or exact name.
static buf_T *find_buffer(typval_T *avar)
{
buf_T *buf = NULL;
@@ -605,7 +585,7 @@ static buf_T *find_buffer(typval_T *avar)
return buf;
}
-// "bufadd(expr)" function
+/// "bufadd(expr)" function
static void f_bufadd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char_u *name = (char_u *)tv_get_string(&argvars[0]);
@@ -613,17 +593,13 @@ static void f_bufadd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = buflist_add(*name == NUL ? NULL : name, 0);
}
-/*
- * "bufexists(expr)" function
- */
+/// "bufexists(expr)" function
static void f_bufexists(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
}
-/*
- * "buflisted(expr)" function
- */
+/// "buflisted(expr)" function
static void f_buflisted(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
buf_T *buf;
@@ -632,7 +608,7 @@ static void f_buflisted(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
}
-// "bufload(expr)" function
+/// "bufload(expr)" function
static void f_bufload(typval_T *argvars, typval_T *unused, FunPtr fptr)
{
buf_T *buf = get_buf_arg(&argvars[0]);
@@ -647,9 +623,7 @@ static void f_bufload(typval_T *argvars, typval_T *unused, FunPtr fptr)
}
}
-/*
- * "bufloaded(expr)" function
- */
+/// "bufloaded(expr)" function
static void f_bufloaded(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
buf_T *buf;
@@ -658,9 +632,7 @@ static void f_bufloaded(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
}
-/*
- * "bufname(expr)" function
- */
+/// "bufname(expr)" function
static void f_bufname(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const buf_T *buf;
@@ -676,9 +648,7 @@ static void f_bufname(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "bufnr(expr)" function
- */
+/// "bufnr(expr)" function
static void f_bufnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const buf_T *buf;
@@ -750,9 +720,7 @@ static void f_bufwinnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
buf_win_common(argvars, rettv, true);
}
-/*
- * Get buffer by number or pattern.
- */
+/// Get buffer by number or pattern.
buf_T *tv_get_buf(typval_T *tv, int curtab_only)
{
char_u *name = tv->vval.v_string;
@@ -820,9 +788,7 @@ buf_T *get_buf_arg(typval_T *arg)
return buf;
}
-/*
- * "byte2line(byte)" function
- */
+/// "byte2line(byte)" function
static void f_byte2line(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
long boff = tv_get_number(&argvars[0]) - 1;
@@ -857,17 +823,13 @@ static void byteidx(typval_T *argvars, typval_T *rettv, int comp)
rettv->vval.v_number = (varnumber_T)(t - str);
}
-/*
- * "byteidx()" function
- */
+/// "byteidx()" function
static void f_byteidx(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
byteidx(argvars, rettv, FALSE);
}
-/*
- * "byteidxcomp()" function
- */
+/// "byteidxcomp()" function
static void f_byteidxcomp(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
byteidx(argvars, rettv, TRUE);
@@ -894,6 +856,7 @@ static void f_call(typval_T *argvars, typval_T *rettv, FunPtr fptr)
partial = argvars[0].vval.v_partial;
func = partial_name(partial);
} else if (nlua_is_table_from_lua(&argvars[0])) {
+ // TODO(tjdevries): UnifiedCallback
func = nlua_register_table_as_callable(&argvars[0]);
owned = true;
} else {
@@ -918,15 +881,13 @@ static void f_call(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "changenr()" function
- */
+/// "changenr()" function
static void f_changenr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = curbuf->b_u_seq_cur;
}
-// "chanclose(id[, stream])" function
+/// "chanclose(id[, stream])" function
static void f_chanclose(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -965,7 +926,7 @@ static void f_chanclose(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "chansend(id, data)" function
+/// "chansend(id, data)" function
static void f_chansend(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -1006,9 +967,7 @@ static void f_chansend(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "char2nr(string)" function
- */
+/// "char2nr(string)" function
static void f_char2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (argvars[1].v_type != VAR_UNKNOWN) {
@@ -1020,9 +979,10 @@ static void f_char2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = utf_ptr2char((const char_u *)tv_get_string(&argvars[0]));
}
-/// Get the current cursor column and store it in 'rettv'. If 'charcol' is true,
-/// returns the character index of the column. Otherwise, returns the byte index
-/// of the column.
+/// Get the current cursor column and store it in 'rettv'.
+///
+/// @return the character index of the column if 'charcol' is true,
+/// otherwise the byte index of the column.
static void get_col(typval_T *argvars, typval_T *rettv, bool charcol)
{
colnr_T col = 0;
@@ -1063,7 +1023,7 @@ static void f_charcol(typval_T *argvars, typval_T *rettv, FunPtr fptr)
get_col(argvars, rettv, true);
}
-// "charidx()" function
+/// "charidx()" function
static void f_charidx(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = -1;
@@ -1109,7 +1069,7 @@ static void f_charidx(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = len > 0 ? len - 1 : 0;
}
-// "chdir(dir)" function
+/// "chdir(dir)" function
static void f_chdir(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char_u *cwd;
@@ -1146,9 +1106,7 @@ static void f_chdir(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "cindent(lnum)" function
- */
+/// "cindent(lnum)" function
static void f_cindent(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
pos_T pos;
@@ -1179,9 +1137,7 @@ static win_T *get_optional_window(typval_T *argvars, int idx)
return win;
}
-/*
- * "clearmatches()" function
- */
+/// "clearmatches()" function
static void f_clearmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
win_T *win = get_optional_window(argvars, 0);
@@ -1197,9 +1153,7 @@ static void f_col(typval_T *argvars, typval_T *rettv, FunPtr fptr)
get_col(argvars, rettv, false);
}
-/*
- * "complete()" function
- */
+/// "complete()" function
static void f_complete(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if ((State & INSERT) == 0) {
@@ -1226,17 +1180,13 @@ static void f_complete(typval_T *argvars, typval_T *rettv, FunPtr fptr)
set_completion(startcol - 1, argvars[1].vval.v_list);
}
-/*
- * "complete_add()" function
- */
+/// "complete_add()" function
static void f_complete_add(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, false);
}
-/*
- * "complete_check()" function
- */
+/// "complete_check()" function
static void f_complete_check(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int saved = RedrawingDisabled;
@@ -1247,7 +1197,7 @@ static void f_complete_check(typval_T *argvars, typval_T *rettv, FunPtr fptr)
RedrawingDisabled = saved;
}
-// "complete_info()" function
+/// "complete_info()" function
static void f_complete_info(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_dict_alloc_ret(rettv);
@@ -1264,9 +1214,7 @@ static void f_complete_info(typval_T *argvars, typval_T *rettv, FunPtr fptr)
get_complete_info(what_list, rettv->vval.v_dict);
}
-/*
- * "confirm(message, buttons[, default [, type]])" function
- */
+/// "confirm(message, buttons[, default [, type]])" function
static void f_confirm(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char buf[NUMBUFLEN];
@@ -1321,17 +1269,13 @@ static void f_confirm(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "copy()" function
- */
+/// "copy()" function
static void f_copy(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
var_item_copy(NULL, &argvars[0], rettv, false, 0);
}
-/*
- * "count()" function
- */
+/// "count()" function
static void f_count(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
long n = 0;
@@ -1422,11 +1366,9 @@ static void f_count(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = n;
}
-/*
- * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
- *
- * Checks the existence of a cscope connection.
- */
+/// "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
+///
+/// Checks the existence of a cscope connection.
static void f_cscope_connection(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int num = 0;
@@ -1558,7 +1500,7 @@ static void f_ctxsize(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
/// Set the cursor position.
-/// If 'charcol' is true, then use the column number as a character offet.
+/// If 'charcol' is true, then use the column number as a character offset.
/// Otherwise use the column number as a byte offset.
static void set_cursorpos(typval_T *argvars, typval_T *rettv, bool charcol)
{
@@ -1621,13 +1563,14 @@ static void set_cursorpos(typval_T *argvars, typval_T *rettv, bool charcol)
/// "cursor(list)"
///
/// Moves the cursor to the specified line and column.
-/// Returns 0 when the position could be set, -1 otherwise.
+///
+/// @return 0 when the position could be set, -1 otherwise.
static void f_cursor(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
set_cursorpos(argvars, rettv, false);
}
-// "debugbreak()" function
+/// "debugbreak()" function
static void f_debugbreak(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int pid;
@@ -1651,7 +1594,7 @@ static void f_debugbreak(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "deepcopy()" function
+/// "deepcopy()" function
static void f_deepcopy(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int noref = 0;
@@ -1668,7 +1611,7 @@ static void f_deepcopy(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "delete()" function
+/// "delete()" function
static void f_delete(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = -1;
@@ -1704,7 +1647,7 @@ static void f_delete(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// dictwatcheradd(dict, key, funcref) function
+/// dictwatcheradd(dict, key, funcref) function
static void f_dictwatcheradd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (check_secure()) {
@@ -1742,7 +1685,7 @@ static void f_dictwatcheradd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
callback);
}
-// dictwatcherdel(dict, key, funcref) function
+/// dictwatcherdel(dict, key, funcref) function
static void f_dictwatcherdel(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (check_secure()) {
@@ -1851,25 +1794,19 @@ static void f_deletebufline(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "did_filetype()" function
- */
+/// "did_filetype()" function
static void f_did_filetype(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = did_filetype;
}
-/*
- * "diff_filler()" function
- */
+/// "diff_filler()" function
static void f_diff_filler(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = MAX(0, diff_check(curwin, tv_get_lnum(argvars)));
}
-/*
- * "diff_hlID()" function
- */
+/// "diff_hlID()" function
static void f_diff_hlID(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
linenr_T lnum = tv_get_lnum(argvars);
@@ -1921,9 +1858,7 @@ static void f_diff_hlID(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)(hlID + 1);
}
-/*
- * "empty({expr})" function
- */
+/// "empty({expr})" function
static void f_empty(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
bool n = true;
@@ -2020,9 +1955,7 @@ static void f_environ(typval_T *argvars, typval_T *rettv, FunPtr fptr)
os_free_fullenv(env);
}
-/*
- * "escape({string}, {chars})" function
- */
+/// "escape({string}, {chars})" function
static void f_escape(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char buf[NUMBUFLEN];
@@ -2046,9 +1979,7 @@ static void f_getenv(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->v_type = VAR_STRING;
}
-/*
- * "eval()" function
- */
+/// "eval()" function
static void f_eval(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *s = tv_get_string_chk(&argvars[0]);
@@ -2069,17 +2000,13 @@ static void f_eval(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "eventhandler()" function
- */
+/// "eventhandler()" function
static void f_eventhandler(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = vgetc_busy;
}
-/*
- * "executable()" function
- */
+/// "executable()" function
static void f_executable(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (tv_check_for_string(&argvars[0]) == FAIL) {
@@ -2187,21 +2114,22 @@ static void execute_common(typval_T *argvars, typval_T *rettv, FunPtr fptr, int
capture_ga = save_capture_ga;
}
-// "execute(command)" function
+/// "execute(command)" function
static void f_execute(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
execute_common(argvars, rettv, fptr, 0);
}
-// "win_execute(win_id, command)" function
+/// "win_execute(win_id, command)" function
static void f_win_execute(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
- tabpage_T *tp;
- win_T *wp = win_id2wp_tp(argvars, &tp);
// Return an empty string if something fails.
rettv->v_type = VAR_STRING;
rettv->vval.v_string = NULL;
+ int id = tv_get_number(argvars);
+ tabpage_T *tp;
+ win_T *wp = win_id2wp_tp(id, &tp);
if (wp != NULL && tp != NULL) {
WIN_EXECUTE(wp, tp, execute_common(argvars, rettv, fptr, 1));
}
@@ -2222,9 +2150,7 @@ static void f_exepath(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = (char_u *)path;
}
-/*
- * "exists()" function
- */
+/// "exists()" function
static void f_exists(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int n = false;
@@ -2264,9 +2190,7 @@ static void f_exists(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = n;
}
-/*
- * "expand()" function
- */
+/// "expand()" function
static void f_expand(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
size_t len;
@@ -2351,8 +2275,8 @@ static void f_menu_get(typval_T *argvars, typval_T *rettv, FunPtr fptr)
menu_get((char_u *)tv_get_string(&argvars[0]), modes, rettv->vval.v_list);
}
-// "expandcmd()" function
-// Expand all the special characters in a command string.
+/// "expandcmd()" function
+/// Expand all the special characters in a command string.
static void f_expandcmd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char *errormsg = NULL;
@@ -2412,10 +2336,8 @@ static void f_flatten(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "extend(list, list [, idx])" function
- * "extend(dict, dict [, action])" function
- */
+/// "extend(list, list [, idx])" function
+/// "extend(dict, dict [, action])" function
static void f_extend(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *const arg_errmsg = N_("extend() argument");
@@ -2492,9 +2414,7 @@ static void f_extend(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "feedkeys()" function
- */
+/// "feedkeys()" function
static void f_feedkeys(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
// This is not allowed in the sandbox. If the commands would still be
@@ -2523,10 +2443,9 @@ static void f_filereadable(typval_T *argvars, typval_T *rettv, FunPtr fptr)
(*p && !os_isdir((const char_u *)p) && os_file_is_readable(p));
}
-/*
- * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
- * rights to write into.
- */
+/// @return 0 for not writable
+/// 1 for writable file
+/// 2 for a dir which we have rights to write into.
static void f_filewritable(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *filename = tv_get_string(&argvars[0]);
@@ -2593,33 +2512,25 @@ static void findfilendir(typval_T *argvars, typval_T *rettv, int find_what)
}
-/*
- * "filter()" function
- */
+/// "filter()" function
static void f_filter(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
filter_map(argvars, rettv, FALSE);
}
-/*
- * "finddir({fname}[, {path}[, {count}]])" function
- */
+/// "finddir({fname}[, {path}[, {count}]])" function
static void f_finddir(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
findfilendir(argvars, rettv, FINDFILE_DIR);
}
-/*
- * "findfile({fname}[, {path}[, {count}]])" function
- */
+/// "findfile({fname}[, {path}[, {count}]])" function
static void f_findfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
findfilendir(argvars, rettv, FINDFILE_FILE);
}
-/*
- * "float2nr({float})" function
- */
+/// "float2nr({float})" function
static void f_float2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
float_T f;
@@ -2635,9 +2546,7 @@ static void f_float2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "fmod()" function
- */
+/// "fmod()" function
static void f_fmod(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
float_T fx;
@@ -2651,18 +2560,14 @@ static void f_fmod(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "fnameescape({string})" function
- */
+/// "fnameescape({string})" function
static void f_fnameescape(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_string = (char_u *)vim_strsave_fnameescape(tv_get_string(&argvars[0]), false);
rettv->v_type = VAR_STRING;
}
-/*
- * "fnamemodify({fname}, {mods})" function
- */
+/// "fnamemodify({fname}, {mods})" function
static void f_fnamemodify(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char_u *fbuf = NULL;
@@ -2691,9 +2596,7 @@ static void f_fnamemodify(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
-/*
- * "foldclosed()" function
- */
+/// "foldclosed()" function
static void foldclosed_both(typval_T *argvars, typval_T *rettv, int end)
{
const linenr_T lnum = tv_get_lnum(argvars);
@@ -2712,25 +2615,19 @@ static void foldclosed_both(typval_T *argvars, typval_T *rettv, int end)
rettv->vval.v_number = -1;
}
-/*
- * "foldclosed()" function
- */
+/// "foldclosed()" function
static void f_foldclosed(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
foldclosed_both(argvars, rettv, FALSE);
}
-/*
- * "foldclosedend()" function
- */
+/// "foldclosedend()" function
static void f_foldclosedend(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
foldclosed_both(argvars, rettv, TRUE);
}
-/*
- * "foldlevel()" function
- */
+/// "foldlevel()" function
static void f_foldlevel(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const linenr_T lnum = tv_get_lnum(argvars);
@@ -2739,9 +2636,7 @@ static void f_foldlevel(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "foldtext()" function
- */
+/// "foldtext()" function
static void f_foldtext(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
linenr_T foldstart;
@@ -2794,9 +2689,7 @@ static void f_foldtext(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "foldtextresult(lnum)" function
- */
+/// "foldtextresult(lnum)" function
static void f_foldtextresult(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char_u *text;
@@ -2827,9 +2720,7 @@ static void f_foldtextresult(typval_T *argvars, typval_T *rettv, FunPtr fptr)
entered = false;
}
-/*
- * "foreground()" function
- */
+/// "foreground()" function
static void f_foreground(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
}
@@ -2856,9 +2747,7 @@ static void f_garbagecollect(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "get()" function
- */
+/// "get()" function
static void f_get(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
listitem_T *li;
@@ -3018,12 +2907,12 @@ static void f_getbufinfo(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * Get line or list of lines from buffer "buf" into "rettv".
- * Return a range (from start to end) of lines in rettv from the specified
- * buffer.
- * If 'retlist' is TRUE, then the lines are returned as a Vim List.
- */
+/// Get line or list of lines from buffer "buf" into "rettv".
+///
+/// @param retlist if TRUE, then the lines are returned as a Vim List.
+///
+/// @return range (from start to end) of lines in rettv from the specified
+/// buffer.
static void get_buffer_lines(buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv)
{
rettv->v_type = (retlist ? VAR_LIST : VAR_STRING);
@@ -3056,9 +2945,7 @@ static void get_buffer_lines(buf_T *buf, linenr_T start, linenr_T end, int retli
}
}
-/*
- * "getbufline()" function
- */
+/// "getbufline()" function
static void f_getbufline(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
buf_T *const buf = tv_get_buf_from_arg(&argvars[0]);
@@ -3071,9 +2958,7 @@ static void f_getbufline(typval_T *argvars, typval_T *rettv, FunPtr fptr)
get_buffer_lines(buf, lnum, end, true, rettv);
}
-/*
- * "getbufvar()" function
- */
+/// "getbufvar()" function
static void f_getbufvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
bool done = false;
@@ -3133,7 +3018,7 @@ f_getbufvar_end:
}
}
-// "getchangelist()" function
+/// "getchangelist()" function
static void f_getchangelist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_list_alloc_ret(rettv, 2);
@@ -3173,7 +3058,7 @@ static void f_getchangelist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "getchar()" and "getcharstr()" functions
+/// "getchar()" and "getcharstr()" functions
static void getchar_common(typval_T *argvars, typval_T *rettv)
FUNC_ATTR_NONNULL_ALL
{
@@ -3225,7 +3110,7 @@ static void getchar_common(typval_T *argvars, typval_T *rettv)
set_vim_var_nr(VV_MOUSE_COL, 0);
rettv->vval.v_number = n;
- if (IS_SPECIAL(n) || mod_mask != 0) {
+ if (n != 0 && (IS_SPECIAL(n) || mod_mask != 0)) {
char_u temp[10]; // modifier: 3, mbyte-char: 6, NUL: 1
int i = 0;
@@ -3275,13 +3160,13 @@ static void getchar_common(typval_T *argvars, typval_T *rettv)
}
}
-// "getchar()" function
+/// "getchar()" function
static void f_getchar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
getchar_common(argvars, rettv);
}
-// "getcharstr()" function
+/// "getcharstr()" function
static void f_getcharstr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
getchar_common(argvars, rettv);
@@ -3301,9 +3186,7 @@ static void f_getcharstr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "getcharmod()" function
- */
+/// "getcharmod()" function
static void f_getcharmod(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = mod_mask;
@@ -3370,9 +3253,7 @@ static void f_getcharpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
getpos_both(argvars, rettv, false, true);
}
-/*
- * "getcharsearch()" function
- */
+/// "getcharsearch()" function
static void f_getcharsearch(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_dict_alloc_ret(rettv);
@@ -3384,26 +3265,20 @@ static void f_getcharsearch(typval_T *argvars, typval_T *rettv, FunPtr fptr)
tv_dict_add_nr(dict, S_LEN("until"), last_csearch_until());
}
-/*
- * "getcmdline()" function
- */
+/// "getcmdline()" function
static void f_getcmdline(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
rettv->vval.v_string = get_cmdline_str();
}
-/*
- * "getcmdpos()" function
- */
+/// "getcmdpos()" function
static void f_getcmdpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = get_cmdline_pos() + 1;
}
-/*
- * "getcmdtype()" function
- */
+/// "getcmdtype()" function
static void f_getcmdtype(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
@@ -3411,9 +3286,7 @@ static void f_getcmdtype(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string[0] = get_cmdline_type();
}
-/*
- * "getcmdwintype()" function
- */
+/// "getcmdwintype()" function
static void f_getcmdwintype(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
@@ -3422,7 +3295,7 @@ static void f_getcmdwintype(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string[0] = cmdwin_type;
}
-// "getcompletion()" function
+/// "getcompletion()" function
static void f_getcompletion(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char_u *pat;
@@ -3621,18 +3494,14 @@ static void f_getcwd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
xfree(cwd);
}
-/*
- * "getfontname()" function
- */
+/// "getfontname()" function
static void f_getfontname(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
rettv->vval.v_string = NULL;
}
-/*
- * "getfperm({fname})" function
- */
+/// "getfperm({fname})" function
static void f_getfperm(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char *perm = NULL;
@@ -3652,9 +3521,7 @@ static void f_getfperm(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = (char_u *)perm;
}
-/*
- * "getfsize({fname})" function
- */
+/// "getfsize({fname})" function
static void f_getfsize(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *fname = tv_get_string(&argvars[0]);
@@ -3679,9 +3546,7 @@ static void f_getfsize(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "getftime({fname})" function
- */
+/// "getftime({fname})" function
static void f_getftime(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *fname = tv_get_string(&argvars[0]);
@@ -3694,9 +3559,7 @@ static void f_getftime(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "getftype({fname})" function
- */
+/// "getftype({fname})" function
static void f_getftype(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char_u *type = NULL;
@@ -3730,7 +3593,7 @@ static void f_getftype(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = type;
}
-// "getjumplist()" function
+/// "getjumplist()" function
static void f_getjumplist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_list_alloc_ret(rettv, kListLenMayKnow);
@@ -3761,9 +3624,7 @@ static void f_getjumplist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "getline(lnum, [end])" function
- */
+/// "getline(lnum, [end])" function
static void f_getline(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
linenr_T end;
@@ -3807,9 +3668,7 @@ static void f_getmarklist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
get_buf_local_marks(buf, rettv->vval.v_list);
}
-/*
- * "getmatches()" function
- */
+/// "getmatches()" function
static void f_getmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
matchitem_T *cur;
@@ -3864,7 +3723,7 @@ static void f_getmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "getmousepos()" function
+/// "getmousepos()" function
static void f_getmousepos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
dict_T *d;
@@ -3875,7 +3734,7 @@ static void f_getmousepos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
varnumber_T winid = 0;
varnumber_T winrow = 0;
varnumber_T wincol = 0;
- linenr_T line = 0;
+ linenr_T lnum = 0;
varnumber_T column = 0;
tv_dict_alloc_ret(rettv);
@@ -3886,7 +3745,7 @@ static void f_getmousepos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
wp = mouse_find_win(&grid, &row, &col);
if (wp != NULL) {
- int height = wp->w_height + wp->w_status_height;
+ int height = wp->w_height + wp->w_hsep_height + wp->w_status_height;
// The height is adjusted by 1 when there is a bottom border. This is not
// necessary for a top border since `row` starts at -1 in that case.
if (row < height + wp->w_border_adj[2]) {
@@ -3894,18 +3753,8 @@ static void f_getmousepos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
winrow = row + 1 + wp->w_border_adj[0]; // Adjust by 1 for top border
wincol = col + 1 + wp->w_border_adj[3]; // Adjust by 1 for left border
if (row >= 0 && row < wp->w_height && col >= 0 && col < wp->w_width) {
- char_u *p;
- int count;
-
- mouse_comp_pos(wp, &row, &col, &line);
-
- // limit to text length plus one
- p = ml_get_buf(wp->w_buffer, line, false);
- count = (int)STRLEN(p);
- if (col > count) {
- col = count;
- }
-
+ (void)mouse_comp_pos(wp, &row, &col, &lnum);
+ col = vcol2col(wp, lnum, col);
column = col + 1;
}
}
@@ -3913,13 +3762,11 @@ static void f_getmousepos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
tv_dict_add_nr(d, S_LEN("winid"), winid);
tv_dict_add_nr(d, S_LEN("winrow"), winrow);
tv_dict_add_nr(d, S_LEN("wincol"), wincol);
- tv_dict_add_nr(d, S_LEN("line"), (varnumber_T)line);
+ tv_dict_add_nr(d, S_LEN("line"), (varnumber_T)lnum);
tv_dict_add_nr(d, S_LEN("column"), column);
}
-/*
- * "getpid()" function
- */
+/// "getpid()" function
static void f_getpid(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = os_get_pid();
@@ -4056,9 +3903,7 @@ static void f_gettabinfo(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "gettabvar()" function
- */
+/// "gettabvar()" function
static void f_gettabvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
bool done = false;
@@ -4096,15 +3941,13 @@ static void f_gettabvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "gettabwinvar()" function
- */
+/// "gettabwinvar()" function
static void f_gettabwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
getwinvar(argvars, rettv, 1);
}
-// "gettagstack()" function
+/// "gettagstack()" function
static void f_gettagstack(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
win_T *wp = curwin; // default is current window
@@ -4129,7 +3972,7 @@ static void f_getwininfo(typval_T *argvars, typval_T *rettv, FunPtr fptr)
tv_list_alloc_ret(rettv, kListLenMayKnow);
if (argvars[0].v_type != VAR_UNKNOWN) {
- wparg = win_id2wp(argvars);
+ wparg = win_id2wp(tv_get_number(&argvars[0]));
if (wparg == NULL) {
return;
}
@@ -4156,12 +3999,12 @@ static void f_getwininfo(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// Dummy timer callback. Used by f_wait().
+/// Dummy timer callback. Used by f_wait().
static void dummy_timer_due_cb(TimeWatcher *tw, void *data)
{
}
-// Dummy timer close callback. Used by f_wait().
+/// Dummy timer close callback. Used by f_wait().
static void dummy_timer_close_cb(TimeWatcher *tw, void *data)
{
xfree(tw);
@@ -4224,7 +4067,7 @@ static void f_wait(typval_T *argvars, typval_T *rettv, FunPtr fptr)
time_watcher_close(tw, dummy_timer_close_cb);
}
-// "win_screenpos()" function
+/// "win_screenpos()" function
static void f_win_screenpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_list_alloc_ret(rettv, 2);
@@ -4233,16 +4076,14 @@ static void f_win_screenpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
tv_list_append_number(rettv->vval.v_list, wp == NULL ? 0 : wp->w_wincol + 1);
}
-//
-// Move the window wp into a new split of targetwin in a given direction
-//
+/// Move the window wp into a new split of targetwin in a given direction
static void win_move_into_split(win_T *wp, win_T *targetwin, int size, int flags)
{
int dir;
int height = wp->w_height;
win_T *oldwin = curwin;
- if (wp == targetwin) {
+ if (wp == targetwin || wp == aucmd_win) {
return;
}
@@ -4273,7 +4114,7 @@ static void win_move_into_split(win_T *wp, win_T *targetwin, int size, int flags
}
}
-// "win_splitmove()" function
+/// "win_splitmove()" function
static void f_win_splitmove(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
win_T *wp;
@@ -4313,7 +4154,7 @@ static void f_win_splitmove(typval_T *argvars, typval_T *rettv, FunPtr fptr)
win_move_into_split(wp, targetwin, size, flags);
}
-// "getwinpos({timeout})" function
+/// "getwinpos({timeout})" function
static void f_getwinpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_list_alloc_ret(rettv, 2);
@@ -4321,17 +4162,13 @@ static void f_getwinpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
tv_list_append_number(rettv->vval.v_list, -1);
}
-/*
- * "getwinposx()" function
- */
+/// "getwinposx()" function
static void f_getwinposx(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = -1;
}
-/*
- * "getwinposy()" function
- */
+/// "getwinposy()" function
static void f_getwinposy(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = -1;
@@ -4343,9 +4180,7 @@ static void f_getwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
getwinvar(argvars, rettv, 0);
}
-/*
- * "glob()" function
- */
+/// "glob()" function
static void f_glob(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int options = WILD_SILENT|WILD_USE_NL;
@@ -4443,7 +4278,7 @@ static void f_globpath(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "glob2regpat()" function
+/// "glob2regpat()" function
static void f_glob2regpat(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *const pat = tv_get_string_chk(&argvars[0]); // NULL on type error
@@ -4779,9 +4614,7 @@ static void f_haslocaldir(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "hasmapto()" function
- */
+/// "hasmapto()" function
static void f_hasmapto(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *mode;
@@ -4804,9 +4637,7 @@ static void f_hasmapto(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "histadd()" function
- */
+/// "histadd()" function
static void f_histadd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
HistoryType histype;
@@ -4829,9 +4660,7 @@ static void f_histadd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "histdel()" function
- */
+/// "histdel()" function
static void f_histdel(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int n;
@@ -4854,9 +4683,7 @@ static void f_histdel(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = n;
}
-/*
- * "histget()" function
- */
+/// "histget()" function
static void f_histget(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
HistoryType type;
@@ -4878,9 +4705,7 @@ static void f_histget(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->v_type = VAR_STRING;
}
-/*
- * "histnr()" function
- */
+/// "histnr()" function
static void f_histnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *const history = tv_get_string_chk(&argvars[0]);
@@ -4893,25 +4718,19 @@ static void f_histnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = i;
}
-/*
- * "highlightID(name)" function
- */
+/// "highlightID(name)" function
static void f_hlID(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = syn_name2id(tv_get_string(&argvars[0]));
}
-/*
- * "highlight_exists()" function
- */
+/// "highlight_exists()" function
static void f_hlexists(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = highlight_exists(tv_get_string(&argvars[0]));
}
-/*
- * "hostname()" function
- */
+/// "hostname()" function
static void f_hostname(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char hostname[256];
@@ -4921,9 +4740,7 @@ static void f_hostname(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = vim_strsave((char_u *)hostname);
}
-/*
- * iconv() function
- */
+/// iconv() function
static void f_iconv(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
vimconv_T vimconv;
@@ -4951,9 +4768,7 @@ static void f_iconv(typval_T *argvars, typval_T *rettv, FunPtr fptr)
xfree(to);
}
-/*
- * "indent()" function
- */
+/// "indent()" function
static void f_indent(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const linenr_T lnum = tv_get_lnum(argvars);
@@ -4964,9 +4779,7 @@ static void f_indent(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "index()" function
- */
+/// "index()" function
static void f_index(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
long idx = 0;
@@ -5040,26 +4853,20 @@ static void f_index(typval_T *argvars, typval_T *rettv, FunPtr fptr)
static bool inputsecret_flag = false;
-/*
- * "input()" function
- * Also handles inputsecret() when inputsecret is set.
- */
+/// "input()" function
+/// Also handles inputsecret() when inputsecret is set.
static void f_input(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
get_user_input(argvars, rettv, FALSE, inputsecret_flag);
}
-/*
- * "inputdialog()" function
- */
+/// "inputdialog()" function
static void f_inputdialog(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
get_user_input(argvars, rettv, TRUE, inputsecret_flag);
}
-/*
- * "inputlist()" function
- */
+/// "inputlist()" function
static void f_inputlist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int selected;
@@ -5125,9 +4932,7 @@ static void f_inputsecret(typval_T *argvars, typval_T *rettv, FunPtr fptr)
inputsecret_flag = false;
}
-/*
- * "insert()" function
- */
+/// "insert()" function
static void f_insert(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
list_T *l;
@@ -5199,32 +5004,26 @@ static void f_insert(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "interrupt()" function
+/// "interrupt()" function
static void f_interrupt(typval_T *argvars FUNC_ATTR_UNUSED, typval_T *rettv FUNC_ATTR_UNUSED,
FunPtr fptr FUNC_ATTR_UNUSED)
{
got_int = true;
}
-/*
- * "invert(expr)" function
- */
+/// "invert(expr)" function
static void f_invert(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = ~tv_get_number_chk(&argvars[0], NULL);
}
-/*
- * "isdirectory()" function
- */
+/// "isdirectory()" function
static void f_isdirectory(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = os_isdir((const char_u *)tv_get_string(&argvars[0]));
}
-/*
- * "islocked()" function
- */
+/// "islocked()" function
static void f_islocked(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
lval_T lv;
@@ -5267,7 +5066,7 @@ static void f_islocked(typval_T *argvars, typval_T *rettv, FunPtr fptr)
clear_lval(&lv);
}
-// "isinf()" function
+/// "isinf()" function
static void f_isinf(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (argvars[0].v_type == VAR_FLOAT
@@ -5276,7 +5075,7 @@ static void f_isinf(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "isnan()" function
+/// "isnan()" function
static void f_isnan(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = argvars[0].v_type == VAR_FLOAT
@@ -5294,15 +5093,13 @@ static void f_id(typval_T *argvars, typval_T *rettv, FunPtr fptr)
dummy_ap, argvars);
}
-/*
- * "items(dict)" function
- */
+/// "items(dict)" function
static void f_items(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
dict_list(argvars, rettv, 2);
}
-// "jobpid(id)" function
+/// "jobpid(id)" function
static void f_jobpid(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -5326,7 +5123,7 @@ static void f_jobpid(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = proc->pid;
}
-// "jobresize(job, width, height)" function
+/// "jobresize(job, width, height)" function
static void f_jobresize(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -5473,7 +5270,7 @@ static dict_T *create_environment(const dictitem_T *job_env, const bool clear_en
return env;
}
-// "jobstart()" function
+/// "jobstart()" function
static void f_jobstart(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -5594,7 +5391,7 @@ static void f_jobstart(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "jobstop()" function
+/// "jobstop()" function
static void f_jobstop(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -5627,7 +5424,7 @@ static void f_jobstop(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "jobwait(ids[, timeout])" function
+/// "jobwait(ids[, timeout])" function
static void f_jobwait(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -5726,9 +5523,7 @@ static void f_jobwait(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_list = rv;
}
-/*
- * "join()" function
- */
+/// "join()" function
static void f_join(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (argvars[0].v_type != VAR_LIST) {
@@ -5793,17 +5588,13 @@ static void f_json_encode(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = (char_u *)encode_tv2json(&argvars[0], NULL);
}
-/*
- * "keys()" function
- */
+/// "keys()" function
static void f_keys(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
dict_list(argvars, rettv, 0);
}
-/*
- * "last_buffer_nr()" function.
- */
+/// "last_buffer_nr()" function.
static void f_last_buffer_nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int n = 0;
@@ -5817,9 +5608,7 @@ static void f_last_buffer_nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = n;
}
-/*
- * "len()" function
- */
+/// "len()" function
static void f_len(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
switch (argvars[0].v_type) {
@@ -5892,23 +5681,19 @@ static void libcall_common(typval_T *argvars, typval_T *rettv, int out_type)
}
}
-/*
- * "libcall()" function
- */
+/// "libcall()" function
static void f_libcall(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
libcall_common(argvars, rettv, VAR_STRING);
}
-/*
- * "libcallnr()" function
- */
+/// "libcallnr()" function
static void f_libcallnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
libcall_common(argvars, rettv, VAR_NUMBER);
}
-// "line(string, [winid])" function
+/// "line(string, [winid])" function
static void f_line(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
linenr_T lnum = 0;
@@ -5916,10 +5701,10 @@ static void f_line(typval_T *argvars, typval_T *rettv, FunPtr fptr)
int fnum;
if (argvars[1].v_type != VAR_UNKNOWN) {
- tabpage_T *tp;
-
// use window specified in the second argument
- win_T *wp = win_id2wp_tp(&argvars[1], &tp);
+ int id = (int)tv_get_number(&argvars[1]);
+ tabpage_T *tp;
+ win_T *wp = win_id2wp_tp(id, &tp);
if (wp != NULL && tp != NULL) {
switchwin_T switchwin;
if (switch_win_noblock(&switchwin, wp, tp, true) == OK) {
@@ -5939,9 +5724,7 @@ static void f_line(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = lnum;
}
-/*
- * "line2byte(lnum)" function
- */
+/// "line2byte(lnum)" function
static void f_line2byte(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const linenr_T lnum = tv_get_lnum(argvars);
@@ -5955,9 +5738,7 @@ static void f_line2byte(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "lispindent(lnum)" function
- */
+/// "lispindent(lnum)" function
static void f_lispindent(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const pos_T pos = curwin->w_cursor;
@@ -5971,7 +5752,7 @@ static void f_lispindent(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "list2str()" function
+/// "list2str()" function
static void f_list2str(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
garray_T ga;
@@ -6000,9 +5781,7 @@ static void f_list2str(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = ga.ga_data;
}
-/*
- * "localtime()" function
- */
+/// "localtime()" function
static void f_localtime(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = (varnumber_T)time(NULL);
@@ -6088,25 +5867,19 @@ static void f_luaeval(typval_T *argvars, typval_T *rettv, FunPtr fptr)
nlua_typval_eval(cstr_as_string((char *)str), &argvars[1], rettv);
}
-/*
- * "map()" function
- */
+/// "map()" function
static void f_map(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
filter_map(argvars, rettv, TRUE);
}
-/*
- * "maparg()" function
- */
+/// "maparg()" function
static void f_maparg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
get_maparg(argvars, rettv, TRUE);
}
-/*
- * "mapcheck()" function
- */
+/// "mapcheck()" function
static void f_mapcheck(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
get_maparg(argvars, rettv, FALSE);
@@ -6328,17 +6101,13 @@ theend:
p_cpo = save_cpo;
}
-/*
- * "match()" function
- */
+/// "match()" function
static void f_match(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
find_some_match(argvars, rettv, kSomeMatch);
}
-/*
- * "matchadd()" function
- */
+/// "matchadd()" function
static void f_matchadd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char grpbuf[NUMBUFLEN];
@@ -6430,9 +6199,7 @@ static void f_matchaddpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = match_add(win, group, NULL, prio, id, l, conceal_char);
}
-/*
- * "matcharg()" function
- */
+/// "matcharg()" function
static void f_matcharg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const int id = tv_get_number(&argvars[0]);
@@ -6455,9 +6222,7 @@ static void f_matcharg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "matchdelete()" function
- */
+/// "matchdelete()" function
static void f_matchdelete(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
win_T *win = get_optional_window(argvars, 1);
@@ -6469,25 +6234,19 @@ static void f_matchdelete(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "matchend()" function
- */
+/// "matchend()" function
static void f_matchend(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
find_some_match(argvars, rettv, kSomeMatchEnd);
}
-/*
- * "matchlist()" function
- */
+/// "matchlist()" function
static void f_matchlist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
find_some_match(argvars, rettv, kSomeMatchList);
}
-/*
- * "matchstr()" function
- */
+/// "matchstr()" function
static void f_matchstr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
find_some_match(argvars, rettv, kSomeMatchStr);
@@ -6548,25 +6307,19 @@ static void max_min(const typval_T *const tv, typval_T *const rettv, const bool
rettv->vval.v_number = n;
}
-/*
- * "max()" function
- */
+/// "max()" function
static void f_max(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
max_min(argvars, rettv, TRUE);
}
-/*
- * "min()" function
- */
+/// "min()" function
static void f_min(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
max_min(argvars, rettv, FALSE);
}
-/*
- * "mkdir()" function
- */
+/// "mkdir()" function
static void f_mkdir(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int prot = 0755; // -V536
@@ -6781,9 +6534,7 @@ static void f_msgpackparse(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "nextnonblank()" function
- */
+/// "nextnonblank()" function
static void f_nextnonblank(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
linenr_T lnum;
@@ -6800,9 +6551,7 @@ static void f_nextnonblank(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = lnum;
}
-/*
- * "nr2char()" function
- */
+/// "nr2char()" function
static void f_nr2char(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (argvars[1].v_type != VAR_UNKNOWN) {
@@ -6833,18 +6582,14 @@ static void f_nr2char(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = xmemdupz(buf, (size_t)len);
}
-/*
- * "or(expr, expr)" function
- */
+/// "or(expr, expr)" function
static void f_or(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL)
| tv_get_number_chk(&argvars[1], NULL);
}
-/*
- * "pathshorten()" function
- */
+/// "pathshorten()" function
static void f_pathshorten(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int trim_len = 1;
@@ -6866,9 +6611,7 @@ static void f_pathshorten(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "pow()" function
- */
+/// "pow()" function
static void f_pow(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
float_T fx;
@@ -6882,9 +6625,7 @@ static void f_pow(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "prevnonblank()" function
- */
+/// "prevnonblank()" function
static void f_prevnonblank(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
linenr_T lnum = tv_get_lnum(argvars);
@@ -6898,9 +6639,7 @@ static void f_prevnonblank(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = lnum;
}
-/*
- * "printf()" function
- */
+/// "printf()" function
static void f_printf(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
@@ -6923,7 +6662,7 @@ static void f_printf(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "prompt_setcallback({buffer}, {callback})" function
+/// "prompt_setcallback({buffer}, {callback})" function
static void f_prompt_setcallback(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
buf_T *buf;
@@ -6947,7 +6686,7 @@ static void f_prompt_setcallback(typval_T *argvars, typval_T *rettv, FunPtr fptr
buf->b_prompt_callback = prompt_callback;
}
-// "prompt_setinterrupt({buffer}, {callback})" function
+/// "prompt_setinterrupt({buffer}, {callback})" function
static void f_prompt_setinterrupt(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
buf_T *buf;
@@ -6991,7 +6730,7 @@ static void f_prompt_getprompt(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = vim_strsave(buf_prompt_text(buf));
}
-// "prompt_setprompt({buffer}, {text})" function
+/// "prompt_setprompt({buffer}, {text})" function
static void f_prompt_setprompt(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
buf_T *buf;
@@ -7010,16 +6749,14 @@ static void f_prompt_setprompt(typval_T *argvars, typval_T *rettv, FunPtr fptr)
buf->b_prompt_text = vim_strsave(text);
}
-// "pum_getpos()" function
+/// "pum_getpos()" function
static void f_pum_getpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_dict_alloc_ret(rettv);
pum_set_event_info(rettv->vval.v_dict);
}
-/*
- * "pumvisible()" function
- */
+/// "pumvisible()" function
static void f_pumvisible(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (pum_visible()) {
@@ -7065,10 +6802,12 @@ static void init_srand(uint32_t *const x)
if (dev_urandom_state != OK) {
// Reading /dev/urandom doesn't work, fall back to time().
#endif
+ // uncrustify:off
*x = time(NULL);
#ifndef MSWIN
}
#endif
+ // uncrustify:on
}
static inline uint32_t splitmix32(uint32_t *const x)
@@ -7195,15 +6934,13 @@ static void f_perleval(typval_T *argvars, typval_T *rettv, FunPtr fptr)
script_host_eval("perl", argvars, rettv);
}
-// "rubyeval()" function
+/// "rubyeval()" function
static void f_rubyeval(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
script_host_eval("ruby", argvars, rettv);
}
-/*
- * "range()" function
- */
+/// "range()" function
static void f_range(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
varnumber_T start;
@@ -7238,7 +6975,7 @@ static void f_range(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// Evaluate "expr" for readdir().
+/// Evaluate "expr" for readdir().
static varnumber_T readdir_checkitem(typval_T *expr, const char *name)
{
typval_T save_val;
@@ -7269,7 +7006,7 @@ theend:
return retval;
}
-// "readdir()" function
+/// "readdir()" function
static void f_readdir(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
typval_T *expr;
@@ -7325,9 +7062,7 @@ static void f_readdir(typval_T *argvars, typval_T *rettv, FunPtr fptr)
ga_clear_strings(&ga);
}
-/*
- * "readfile()" function
- */
+/// "readfile()" function
static void f_readfile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
bool binary = false;
@@ -7561,13 +7296,13 @@ static void f_getreginfo(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "reg_executing()" function
+/// "reg_executing()" function
static void f_reg_executing(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
return_register(reg_executing, rettv);
}
-// "reg_recording()" function
+/// "reg_recording()" function
static void f_reg_recording(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
return_register(reg_recording, rettv);
@@ -7669,9 +7404,7 @@ static void f_reltimestr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "remove()" function
- */
+/// "remove()" function
static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
list_T *l;
@@ -7805,9 +7538,7 @@ static void f_remove(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "rename({from}, {to})" function
- */
+/// "rename({from}, {to})" function
static void f_rename(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (check_secure()) {
@@ -7819,9 +7550,7 @@ static void f_rename(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "repeat()" function
- */
+/// "repeat()" function
static void f_repeat(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
varnumber_T n = tv_get_number(&argvars[1]);
@@ -7858,9 +7587,7 @@ static void f_repeat(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "resolve()" function
- */
+/// "resolve()" function
static void f_resolve(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
@@ -8029,9 +7756,7 @@ static void f_resolve(typval_T *argvars, typval_T *rettv, FunPtr fptr)
simplify_filename(rettv->vval.v_string);
}
-/*
- * "reverse({list})" function
- */
+/// "reverse({list})" function
static void f_reverse(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (argvars[0].v_type == VAR_BLOB) {
@@ -8056,7 +7781,7 @@ static void f_reverse(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/// "reduce(list, { accumlator, element -> value } [, initial])" function
+/// "reduce(list, { accumulator, element -> value } [, initial])" function
static void f_reduce(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (argvars[0].v_type != VAR_LIST && argvars[0].v_type != VAR_BLOB) {
@@ -8161,11 +7886,10 @@ static void f_reduce(typval_T *argvars, typval_T *rettv, FunPtr fptr)
#define SP_END 0x40 ///< leave cursor at end of match
#define SP_COLUMN 0x80 ///< start at cursor column
-/*
- * Get flags for a search function.
- * Possibly sets "p_ws".
- * Returns BACKWARD, FORWARD or zero (for an error).
- */
+/// Get flags for a search function.
+/// Possibly sets "p_ws".
+///
+/// @return BACKWARD, FORWARD or zero (for an error).
static int get_search_arg(typval_T *varp, int *flagsp)
{
int dir = FORWARD;
@@ -8223,7 +7947,7 @@ static int get_search_arg(typval_T *varp, int *flagsp)
return dir;
}
-// Shared by search() and searchpos() functions.
+/// Shared by search() and searchpos() functions.
static int search_cmn(typval_T *argvars, pos_T *match_pos, int *flagsp)
{
int flags;
@@ -8295,7 +8019,7 @@ static int search_cmn(typval_T *argvars, pos_T *match_pos, int *flagsp)
// Repeat until {skip} returns false.
for (;;) {
subpatnum
- = searchit(curwin, curbuf, &pos, NULL, dir, (char_u *)pat, 1, options, RE_SEARCH, &sia);
+ = searchit(curwin, curbuf, &pos, NULL, dir, (char_u *)pat, 1, options, RE_SEARCH, &sia);
// finding the first match again means there is no match where {skip}
// evaluates to zero.
if (firstpos.lnum != 0 && equalpos(pos, firstpos)) {
@@ -8359,7 +8083,7 @@ theend:
return retval;
}
-// "rpcnotify()" function
+/// "rpcnotify()" function
static void f_rpcnotify(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -8394,7 +8118,7 @@ static void f_rpcnotify(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = 1;
}
-// "rpcrequest()" function
+/// "rpcrequest()" function
static void f_rpcrequest(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -8492,7 +8216,7 @@ end:
api_clear_error(&err);
}
-// "rpcstart()" function (DEPRECATED)
+/// "rpcstart()" function (DEPRECATED)
static void f_rpcstart(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -8559,7 +8283,7 @@ static void f_rpcstart(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "rpcstop()" function
+/// "rpcstop()" function
static void f_rpcstop(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_NUMBER;
@@ -8589,7 +8313,7 @@ static void f_rpcstop(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "screenattr()" function
+/// "screenattr()" function
static void f_screenattr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int c;
@@ -8607,7 +8331,7 @@ static void f_screenattr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = c;
}
-// "screenchar()" function
+/// "screenchar()" function
static void f_screenchar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int c;
@@ -8625,7 +8349,7 @@ static void f_screenchar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = c;
}
-// "screenchars()" function
+/// "screenchars()" function
static void f_screenchars(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int row = tv_get_number_chk(&argvars[0], NULL) - 1;
@@ -8650,9 +8374,9 @@ static void f_screenchars(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "screencol()" function
-//
-// First column is 1 to be consistent with virtcol().
+/// "screencol()" function
+///
+/// First column is 1 to be consistent with virtcol().
static void f_screencol(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = ui_current_col() + 1;
@@ -8684,13 +8408,13 @@ static void f_screenpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
tv_dict_add_nr(dict, S_LEN("endcol"), ecol);
}
-// "screenrow()" function
+/// "screenrow()" function
static void f_screenrow(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = ui_current_row() + 1;
}
-// "screenstring()" function
+/// "screenstring()" function
static void f_screenstring(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_string = NULL;
@@ -8706,7 +8430,7 @@ static void f_screenstring(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = vim_strsave(grid->chars[grid->line_offset[row] + col]);
}
-// "search()" function
+/// "search()" function
static void f_search(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int flags = 0;
@@ -8714,9 +8438,7 @@ static void f_search(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
}
-/*
- * "searchdecl()" function
- */
+/// "searchdecl()" function
static void f_searchdecl(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int locally = 1;
@@ -8738,9 +8460,7 @@ static void f_searchdecl(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * Used by searchpair() and searchpairpos()
- */
+/// Used by searchpair() and searchpairpos()
static int searchpair_cmn(typval_T *argvars, pos_T *match_pos)
{
bool save_p_ws = p_ws;
@@ -8814,17 +8534,13 @@ theend:
return retval;
}
-/*
- * "searchpair()" function
- */
+/// "searchpair()" function
static void f_searchpair(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = searchpair_cmn(argvars, NULL);
}
-/*
- * "searchpairpos()" function
- */
+/// "searchpairpos()" function
static void f_searchpairpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
pos_T match_pos;
@@ -9010,9 +8726,7 @@ long do_searchpair(const char *spat, const char *mpat, const char *epat, int dir
return retval;
}
-/*
- * "searchpos()" function
- */
+/// "searchpos()" function
static void f_searchpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
pos_T match_pos;
@@ -9126,9 +8840,7 @@ static void f_setbufline(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "setbufvar()" function
- */
+/// "setbufvar()" function
static void f_setbufvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (check_secure()
@@ -9173,7 +8885,7 @@ static void f_setbufvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
/// Set the cursor or mark position.
-/// If 'charpos' is TRUE, then use the column number as a character offet.
+/// If 'charpos' is TRUE, then use the column number as a character offset.
/// Otherwise use the column number as a byte offset.
static void set_position(typval_T *argvars, typval_T *rettv, bool charpos)
{
@@ -9245,9 +8957,7 @@ static void f_setcharsearch(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "setcmdpos()" function
- */
+/// "setcmdpos()" function
static void f_setcmdpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const int pos = (int)tv_get_number(&argvars[0]) - 1;
@@ -9309,9 +9019,7 @@ static void f_setfperm(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = os_setperm(fname, mode) == OK;
}
-/*
- * "setline()" function
- */
+/// "setline()" function
static void f_setline(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
linenr_T lnum = tv_get_lnum(&argvars[0]);
@@ -9338,7 +9046,7 @@ static void set_qf_ll_list(win_T *wp, typval_T *args, typval_T *rettv)
{
static char *e_invact = N_("E927: Invalid action: '%s'");
const char *title = NULL;
- int action = ' ';
+ char action = ' ';
static int recursive = 0;
rettv->vval.v_number = -1;
dict_T *what = NULL;
@@ -9399,9 +9107,7 @@ skip_args:
recursive--;
}
-/*
- * "setloclist()" function
- */
+/// "setloclist()" function
static void f_setloclist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
win_T *win;
@@ -9414,9 +9120,7 @@ static void f_setloclist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "setmatches()" function
- */
+/// "setmatches()" function
static void f_setmatches(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
dict_T *d;
@@ -9525,9 +9229,7 @@ static void f_setpos(typval_T *argvars, typval_T *rettv, FunPtr fptr)
set_position(argvars, rettv, false);
}
-/*
- * "setqflist()" function
- */
+/// "setqflist()" function
static void f_setqflist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
set_qf_ll_list(NULL, argvars, rettv);
@@ -9563,12 +9265,9 @@ static int get_yank_type(char_u **const pp, MotionType *const yank_type, long *c
return OK;
}
-/*
- * "setreg()" function
- */
+/// "setreg()" function
static void f_setreg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
- int regname;
bool append = false;
MotionType yank_type;
long block_len;
@@ -9582,13 +9281,13 @@ static void f_setreg(typval_T *argvars, typval_T *rettv, FunPtr fptr)
if (strregname == NULL) {
return; // Type error; errmsg already given.
}
- regname = (uint8_t)(*strregname);
+ char regname = (uint8_t)(*strregname);
if (regname == 0 || regname == '@') {
regname = '"';
}
const typval_T *regcontents = NULL;
- int pointreg = 0;
+ char pointreg = 0;
if (argvars[1].v_type == VAR_DICT) {
dict_T *const d = argvars[1].vval.v_dict;
@@ -9706,14 +9405,11 @@ free_lstval:
if (set_unnamed) {
// Discard the result. We already handle the error case.
- if (op_reg_set_previous(regname)) {
- }
+ op_reg_set_previous(regname);
}
}
-/*
- * "settabvar()" function
- */
+/// "settabvar()" function
static void f_settabvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = 0;
@@ -9744,21 +9440,19 @@ static void f_settabvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "settabwinvar()" function
- */
+/// "settabwinvar()" function
static void f_settabwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
setwinvar(argvars, rettv, 1);
}
-// "settagstack()" function
+/// "settagstack()" function
static void f_settagstack(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
static char *e_invact2 = N_("E962: Invalid action: '%s'");
win_T *wp;
dict_T *d;
- int action = 'r';
+ char action = 'r';
rettv->vval.v_number = -1;
@@ -9805,9 +9499,7 @@ static void f_settagstack(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "setwinvar()" function
- */
+/// "setwinvar()" function
static void f_setwinvar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
setwinvar(argvars, rettv, 0);
@@ -9824,9 +9516,7 @@ static void f_sha256(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->v_type = VAR_STRING;
}
-/*
- * "shellescape({string})" function
- */
+/// "shellescape({string})" function
static void f_shellescape(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const bool do_special = non_zero_arg(&argvars[1]);
@@ -9837,9 +9527,7 @@ static void f_shellescape(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->v_type = VAR_STRING;
}
-/*
- * shiftwidth() function
- */
+/// shiftwidth() function
static void f_shiftwidth(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = 0;
@@ -10123,9 +9811,7 @@ static void f_sign_unplacelist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
});
}
-/*
- * "simplify()" function
- */
+/// "simplify()" function
static void f_simplify(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *const p = tv_get_string(&argvars[0]);
@@ -10202,9 +9888,7 @@ static sortinfo_T *sortinfo = NULL;
#define ITEM_COMPARE_FAIL 999
-/*
- * Compare functions for f_sort() and f_uniq() below.
- */
+/// Compare functions for f_sort() and f_uniq() below.
static int item_compare(const void *s1, const void *s2, bool keep_zero)
{
ListSortItem *const si1 = (ListSortItem *)s1;
@@ -10368,9 +10052,7 @@ static int item_compare2_not_keeping_zero(const void *s1, const void *s2)
return item_compare2(s1, s2, false);
}
-/*
- * "sort({list})" function
- */
+/// "sort({list})" function
static void do_sort_uniq(typval_T *argvars, typval_T *rettv, bool sort)
{
ListSortItem *ptrs;
@@ -10563,7 +10245,7 @@ static void f_uniq(typval_T *argvars, typval_T *rettv, FunPtr fptr)
do_sort_uniq(argvars, rettv, false);
}
-// "reltimefloat()" function
+/// "reltimefloat()" function
static void f_reltimefloat(typval_T *argvars, typval_T *rettv, FunPtr fptr)
FUNC_ATTR_NONNULL_ALL
{
@@ -10576,9 +10258,7 @@ static void f_reltimefloat(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "soundfold({word})" function
- */
+/// "soundfold({word})" function
static void f_soundfold(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
@@ -10586,9 +10266,7 @@ static void f_soundfold(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = (char_u *)eval_soundfold(s);
}
-/*
- * "spellbadword()" function
- */
+/// "spellbadword()" function
static void f_spellbadword(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *word = "";
@@ -10647,9 +10325,7 @@ static void f_spellbadword(typval_T *argvars, typval_T *rettv, FunPtr fptr)
NULL), -1);
}
-/*
- * "spellsuggest()" function
- */
+/// "spellsuggest()" function
static void f_spellsuggest(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
bool typeerr = false;
@@ -10804,9 +10480,7 @@ static void f_stdpath(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "str2float()" function
- */
+/// "str2float()" function
static void f_str2float(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char_u *p = skipwhite((const char_u *)tv_get_string(&argvars[0]));
@@ -10822,7 +10496,7 @@ static void f_str2float(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->v_type = VAR_FLOAT;
}
-// "str2list()" function
+/// "str2list()" function
static void f_str2list(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_list_alloc_ret(rettv, kListLenUnknown);
@@ -10833,7 +10507,7 @@ static void f_str2list(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "str2nr()" function
+/// "str2nr()" function
static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int base = 10;
@@ -10876,9 +10550,7 @@ static void f_str2nr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "strftime({format}[, {time}])" function
- */
+/// "strftime({format}[, {time}])" function
static void f_strftime(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
time_t seconds;
@@ -10930,7 +10602,7 @@ static void f_strftime(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "strgetchar()" function
+/// "strgetchar()" function
static void f_strgetchar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = -1;
@@ -10958,9 +10630,7 @@ static void f_strgetchar(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "stridx()" function
- */
+/// "stridx()" function
static void f_stridx(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = -1;
@@ -10992,26 +10662,20 @@ static void f_stridx(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "string()" function
- */
+/// "string()" function
static void f_string(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
rettv->vval.v_string = (char_u *)encode_tv2string(&argvars[0], NULL);
}
-/*
- * "strlen()" function
- */
+/// "strlen()" function
static void f_strlen(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = (varnumber_T)strlen(tv_get_string(&argvars[0]));
}
-/*
- * "strchars()" function
- */
+/// "strchars()" function
static void f_strchars(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *s = tv_get_string(&argvars[0]);
@@ -11034,9 +10698,7 @@ static void f_strchars(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "strdisplaywidth()" function
- */
+/// "strdisplaywidth()" function
static void f_strdisplaywidth(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *const s = tv_get_string(&argvars[0]);
@@ -11049,9 +10711,7 @@ static void f_strdisplaywidth(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = (varnumber_T)(linetabsize_col(col, (char_u *)s) - col);
}
-/*
- * "strwidth()" function
- */
+/// "strwidth()" function
static void f_strwidth(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *const s = tv_get_string(&argvars[0]);
@@ -11059,7 +10719,7 @@ static void f_strwidth(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = (varnumber_T)mb_string2cells((const char_u *)s);
}
-// "strcharpart()" function
+/// "strcharpart()" function
static void f_strcharpart(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *const p = tv_get_string(&argvars[0]);
@@ -11113,9 +10773,7 @@ static void f_strcharpart(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = (char_u *)xstrndup(p + nbyte, (size_t)len);
}
-/*
- * "strpart()" function
- */
+/// "strpart()" function
static void f_strpart(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
bool error = false;
@@ -11161,7 +10819,7 @@ static void f_strpart(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = (char_u *)xmemdupz(p + n, (size_t)len);
}
-// "strptime({format}, {timestring})" function
+/// "strptime({format}, {timestring})" function
static void f_strptime(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char fmt_buf[NUMBUFLEN];
@@ -11193,9 +10851,7 @@ static void f_strptime(typval_T *argvars, typval_T *rettv, FunPtr fptr)
xfree(enc);
}
-/*
- * "strridx()" function
- */
+/// "strridx()" function
static void f_strridx(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char buf[NUMBUFLEN];
@@ -11238,18 +10894,14 @@ static void f_strridx(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "strtrans()" function
- */
+/// "strtrans()" function
static void f_strtrans(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
rettv->vval.v_string = (char_u *)transstr(tv_get_string(&argvars[0]), true);
}
-/*
- * "submatch()" function
- */
+/// "submatch()" function
static void f_submatch(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
bool error = false;
@@ -11280,9 +10932,7 @@ static void f_submatch(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "substitute()" function
- */
+/// "substitute()" function
static void f_substitute(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char patbuf[NUMBUFLEN];
@@ -11351,9 +11001,7 @@ static void f_synID(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = id;
}
-/*
- * "synIDattr(id, what [, mode])" function
- */
+/// "synIDattr(id, what [, mode])" function
static void f_synIDattr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const int id = (int)tv_get_number(&argvars[0]);
@@ -11408,22 +11056,28 @@ static void f_synIDattr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
p = highlight_has_attr(id, HL_STANDOUT, modec);
}
break;
- case 'u':
- if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c') { // underline
+ case 'u': {
+ const size_t len = STRLEN(what);
+ if (len <= 5 || (TOLOWER_ASC(what[5]) == 'l' && len <= 9)) { // underline
p = highlight_has_attr(id, HL_UNDERLINE, modec);
- } else { // undercurl
+ } else if (TOLOWER_ASC(what[5]) == 'c') { // undercurl
p = highlight_has_attr(id, HL_UNDERCURL, modec);
+ } else if (len > 9 && TOLOWER_ASC(what[9]) == 'l') { // underlineline
+ p = highlight_has_attr(id, HL_UNDERLINELINE, modec);
+ } else if (len > 6 && TOLOWER_ASC(what[6]) == 'o') { // underdot
+ p = highlight_has_attr(id, HL_UNDERDOT, modec);
+ } else { // underdash
+ p = highlight_has_attr(id, HL_UNDERDASH, modec);
}
break;
}
+ }
rettv->v_type = VAR_STRING;
rettv->vval.v_string = (char_u *)(p == NULL ? p : xstrdup(p));
}
-/*
- * "synIDtrans(id)" function
- */
+/// "synIDtrans(id)" function
static void f_synIDtrans(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int id = tv_get_number(&argvars[0]);
@@ -11437,9 +11091,7 @@ static void f_synIDtrans(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = id;
}
-/*
- * "synconcealed(lnum, col)" function
- */
+/// "synconcealed(lnum, col)" function
static void f_synconcealed(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int syntax_flags = 0;
@@ -11481,9 +11133,7 @@ static void f_synconcealed(typval_T *argvars, typval_T *rettv, FunPtr fptr)
tv_list_append_number(rettv->vval.v_list, matchid);
}
-/*
- * "synstack(lnum, col)" function
- */
+/// "synstack(lnum, col)" function
static void f_synstack(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_list_set_ret(rettv, NULL);
@@ -11519,9 +11169,7 @@ static void f_systemlist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
-/*
- * "tabpagebuflist()" function
- */
+/// "tabpagebuflist()" function
static void f_tabpagebuflist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
win_T *wp = NULL;
@@ -11543,9 +11191,7 @@ static void f_tabpagebuflist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "tabpagenr()" function
- */
+/// "tabpagenr()" function
static void f_tabpagenr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int nr = 1;
@@ -11557,9 +11203,7 @@ static void f_tabpagenr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
if (strcmp(arg, "$") == 0) {
nr = tabpage_index(NULL) - 1;
} else if (strcmp(arg, "#") == 0) {
- nr = valid_tabpage(lastused_tabpage)
- ? tabpage_index(lastused_tabpage)
- : nr;
+ nr = valid_tabpage(lastused_tabpage) ? tabpage_index(lastused_tabpage) : 0;
} else {
semsg(_(e_invexpr2), arg);
}
@@ -11571,9 +11215,7 @@ static void f_tabpagenr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
-/*
- * Common code for tabpagewinnr() and winnr().
- */
+/// Common code for tabpagewinnr() and winnr().
static int get_winnr(tabpage_T *tp, typval_T *argvar)
{
win_T *twin;
@@ -11638,9 +11280,7 @@ static int get_winnr(tabpage_T *tp, typval_T *argvar)
return nr;
}
-/*
- * "tabpagewinnr()" function
- */
+/// "tabpagewinnr()" function
static void f_tabpagewinnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int nr = 1;
@@ -11653,9 +11293,7 @@ static void f_tabpagewinnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = nr;
}
-/*
- * "tagfiles()" function
- */
+/// "tagfiles()" function
static void f_tagfiles(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char *fname;
@@ -11674,9 +11312,7 @@ static void f_tagfiles(typval_T *argvars, typval_T *rettv, FunPtr fptr)
xfree(fname);
}
-/*
- * "taglist()" function
- */
+/// "taglist()" function
static void f_taglist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
const char *const tag_pattern = tv_get_string(&argvars[0]);
@@ -11694,16 +11330,14 @@ static void f_taglist(typval_T *argvars, typval_T *rettv, FunPtr fptr)
(char_u *)tag_pattern, (char_u *)fname);
}
-/*
- * "tempname()" function
- */
+/// "tempname()" function
static void f_tempname(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
rettv->vval.v_string = vim_tempname();
}
-// "termopen(cmd[, cwd])" function
+/// "termopen(cmd[, cwd])" function
static void f_termopen(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (check_secure()) {
@@ -11816,7 +11450,7 @@ static void f_termopen(typval_T *argvars, typval_T *rettv, FunPtr fptr)
channel_create_event(chan, NULL);
}
-// "test_garbagecollect_now()" function
+/// "test_garbagecollect_now()" function
static void f_test_garbagecollect_now(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
// This is dangerous, any Lists and Dicts used internally may be freed
@@ -11824,7 +11458,7 @@ static void f_test_garbagecollect_now(typval_T *argvars, typval_T *rettv, FunPtr
garbage_collect(true);
}
-// "test_write_list_log()" function
+/// "test_write_list_log()" function
static void f_test_write_list_log(typval_T *const argvars, typval_T *const rettv, FunPtr fptr)
{
const char *const fname = tv_get_string_chk(&argvars[0]);
@@ -11907,7 +11541,7 @@ static void f_timer_start(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
-// "timer_stop(timerid)" function
+/// "timer_stop(timerid)" function
static void f_timer_stop(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (argvars[0].v_type != VAR_NUMBER) {
@@ -11928,9 +11562,7 @@ static void f_timer_stopall(typval_T *argvars, typval_T *unused, FunPtr fptr)
timer_stop_all();
}
-/*
- * "tolower(string)" function
- */
+/// "tolower(string)" function
static void f_tolower(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
@@ -11938,9 +11570,7 @@ static void f_tolower(typval_T *argvars, typval_T *rettv, FunPtr fptr)
false);
}
-/*
- * "toupper(string)" function
- */
+/// "toupper(string)" function
static void f_toupper(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
@@ -11948,9 +11578,7 @@ static void f_toupper(typval_T *argvars, typval_T *rettv, FunPtr fptr)
true);
}
-/*
- * "tr(string, fromstr, tostr)" function
- */
+/// "tr(string, fromstr, tostr)" function
static void f_tr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char buf[NUMBUFLEN];
@@ -12030,7 +11658,7 @@ error:
return;
}
-// "trim({expr})" function
+/// "trim({expr})" function
static void f_trim(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char buf1[NUMBUFLEN];
@@ -12113,9 +11741,7 @@ static void f_trim(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_string = vim_strnsave(head, tail - head);
}
-/*
- * "type(expr)" function
- */
+/// "type(expr)" function
static void f_type(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int n = -1;
@@ -12147,9 +11773,7 @@ static void f_type(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = n;
}
-/*
- * "undofile(name)" function
- */
+/// "undofile(name)" function
static void f_undofile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
@@ -12168,9 +11792,7 @@ static void f_undofile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "undotree()" function
- */
+/// "undotree()" function
static void f_undotree(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tv_dict_alloc_ret(rettv);
@@ -12188,17 +11810,13 @@ static void f_undotree(typval_T *argvars, typval_T *rettv, FunPtr fptr)
tv_dict_add_list(dict, S_LEN("entries"), u_eval_tree(curbuf->b_u_oldhead));
}
-/*
- * "values(dict)" function
- */
+/// "values(dict)" function
static void f_values(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
dict_list(argvars, rettv, 1);
}
-/*
- * "virtcol(string)" function
- */
+/// "virtcol(string)" function
static void f_virtcol(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
colnr_T vcol = 0;
@@ -12224,9 +11842,7 @@ static void f_virtcol(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = vcol;
}
-/*
- * "visualmode()" function
- */
+/// "visualmode()" function
static void f_visualmode(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
char_u str[2];
@@ -12242,9 +11858,7 @@ static void f_visualmode(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "wildmenumode()" function
- */
+/// "wildmenumode()" function
static void f_wildmenumode(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
if (wild_menu_showing || ((State & CMDLINE) && pum_visible())) {
@@ -12358,9 +11972,7 @@ static void f_winbufnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "wincol()" function
- */
+/// "wincol()" function
static void f_wincol(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
validate_cursor();
@@ -12378,7 +11990,7 @@ static void f_winheight(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "winlayout()" function
+/// "winlayout()" function
static void f_winlayout(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
tabpage_T *tp;
@@ -12397,18 +12009,14 @@ static void f_winlayout(typval_T *argvars, typval_T *rettv, FunPtr fptr)
get_framelayout(tp->tp_topframe, rettv->vval.v_list, true);
}
-/*
- * "winline()" function
- */
+/// "winline()" function
static void f_winline(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
validate_cursor();
rettv->vval.v_number = curwin->w_wrow + 1;
}
-/*
- * "winnr()" function
- */
+/// "winnr()" function
static void f_winnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
int nr = 1;
@@ -12417,9 +12025,7 @@ static void f_winnr(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->vval.v_number = nr;
}
-/*
- * "winrestcmd()" function
- */
+/// "winrestcmd()" function
static void f_winrestcmd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
garray_T ga;
@@ -12446,9 +12052,7 @@ static void f_winrestcmd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
rettv->v_type = VAR_STRING;
}
-/*
- * "winrestview()" function
- */
+/// "winrestview()" function
static void f_winrestview(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
dict_T *dict;
@@ -12499,9 +12103,7 @@ static void f_winrestview(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-/*
- * "winsaveview()" function
- */
+/// "winsaveview()" function
static void f_winsaveview(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
dict_T *dict;
@@ -12532,7 +12134,7 @@ static void f_winwidth(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
-// "windowsversion()" function
+/// "windowsversion()" function
static void f_windowsversion(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->v_type = VAR_STRING;
@@ -12623,9 +12225,8 @@ static void f_writefile(typval_T *argvars, typval_T *rettv, FunPtr fptr)
}
}
}
-/*
- * "xor(expr, expr)" function
- */
+
+/// "xor(expr, expr)" function
static void f_xor(typval_T *argvars, typval_T *rettv, FunPtr fptr)
{
rettv->vval.v_number = tv_get_number_chk(&argvars[0], NULL)
diff --git a/src/nvim/eval/typval.c b/src/nvim/eval/typval.c
index 6f8b032d41..2a432ecb47 100644
--- a/src/nvim/eval/typval.c
+++ b/src/nvim/eval/typval.c
@@ -8,6 +8,7 @@
#include <stdlib.h>
#include <string.h>
+#include "lauxlib.h"
#include "nvim/ascii.h"
#include "nvim/assert.h"
#include "nvim/charset.h"
@@ -28,11 +29,11 @@
#include "nvim/mbyte.h"
#include "nvim/memory.h"
#include "nvim/message.h"
+#include "nvim/os/fileio.h"
#include "nvim/os/input.h"
#include "nvim/pos.h"
#include "nvim/types.h"
#include "nvim/vim.h"
-#include "nvim/os/fileio.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "eval/typval.c.generated.h"
@@ -1123,6 +1124,8 @@ bool tv_callback_equal(const Callback *cb1, const Callback *cb2)
// FIXME: this is inconsistent with tv_equal but is needed for precision
// maybe change dictwatcheradd to return a watcher id instead?
return cb1->data.partial == cb2->data.partial;
+ case kCallbackLua:
+ return cb1->data.luaref == cb2->data.luaref;
case kCallbackNone:
return true;
}
@@ -1142,6 +1145,9 @@ void callback_free(Callback *callback)
case kCallbackPartial:
partial_unref(callback->data.partial);
break;
+ case kCallbackLua:
+ NLUA_CLEAR_REF(callback->data.luaref);
+ break;
case kCallbackNone:
break;
}
@@ -1164,6 +1170,11 @@ void callback_put(Callback *cb, typval_T *tv)
tv->vval.v_string = vim_strsave(cb->data.funcref);
func_ref(cb->data.funcref);
break;
+ case kCallbackLua:
+ // TODO(tjdevries): Unified Callback.
+ // At this point this isn't possible, but it'd be nice to put
+ // these handled more neatly in one place.
+ // So instead, we just do the default and put nil
default:
tv->v_type = VAR_SPECIAL;
tv->vval.v_special = kSpecialVarNull;
@@ -1185,6 +1196,9 @@ void callback_copy(Callback *dest, Callback *src)
dest->data.funcref = vim_strsave(src->data.funcref);
func_ref(src->data.funcref);
break;
+ case kCallbackLua:
+ dest->data.luaref = api_new_luaref(src->data.luaref);
+ break;
default:
dest->data.funcref = NULL;
break;
diff --git a/src/nvim/eval/typval.h b/src/nvim/eval/typval.h
index ad01c01499..40dc819754 100644
--- a/src/nvim/eval/typval.h
+++ b/src/nvim/eval/typval.h
@@ -72,15 +72,18 @@ typedef enum {
kCallbackNone = 0,
kCallbackFuncref,
kCallbackPartial,
+ kCallbackLua,
} CallbackType;
typedef struct {
union {
char_u *funcref;
partial_T *partial;
+ LuaRef luaref;
} data;
CallbackType type;
} Callback;
+
#define CALLBACK_INIT { .type = kCallbackNone }
#define CALLBACK_NONE ((Callback)CALLBACK_INIT)
diff --git a/src/nvim/eval/userfunc.c b/src/nvim/eval/userfunc.c
index eb241eb8ae..471c4092fe 100644
--- a/src/nvim/eval/userfunc.c
+++ b/src/nvim/eval/userfunc.c
@@ -516,7 +516,7 @@ static char_u *fname_trans_sid(const char_u *const name, char_u *const fname_buf
if (llen > 0) {
fname_buf[0] = K_SPECIAL;
fname_buf[1] = KS_EXTRA;
- fname_buf[2] = (int)KE_SNR;
+ fname_buf[2] = KE_SNR;
int i = 3;
if (eval_fname_sid((const char *)name)) { // "<SID>" or "s:"
if (current_sctx.sc_sid <= 0) {
@@ -1713,7 +1713,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp,
// Check for hard coded <SNR>: already translated function ID (from a user
// command).
if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
- && (*pp)[2] == (int)KE_SNR) {
+ && (*pp)[2] == KE_SNR) {
*pp += 3;
len = get_id_len((const char **)pp) + 3;
return (char_u *)xmemdupz(start, len);
@@ -1821,7 +1821,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp,
// Change "<SNR>" to the byte sequence.
name[0] = K_SPECIAL;
name[1] = KS_EXTRA;
- name[2] = (int)KE_SNR;
+ name[2] = KE_SNR;
memmove(name + 3, name + 5, strlen((char *)name + 5) + 1);
}
goto theend;
@@ -1888,7 +1888,7 @@ char_u *trans_function_name(char_u **pp, bool skip, int flags, funcdict_T *fdp,
if (!skip && lead > 0) {
name[0] = K_SPECIAL;
name[1] = KS_EXTRA;
- name[2] = (int)KE_SNR;
+ name[2] = KE_SNR;
if (sid_buf_len > 0) { // If it's "<SID>"
memcpy(name + 3, sid_buf, sid_buf_len);
}
@@ -2573,6 +2573,7 @@ void ex_function(exarg_T *eap)
fp->uf_calls = 0;
fp->uf_script_ctx = current_sctx;
fp->uf_script_ctx.sc_lnum += sourcing_lnum_top;
+ nlua_set_sctx(&fp->uf_script_ctx);
goto ret_free;
diff --git a/src/nvim/event/rstream.c b/src/nvim/event/rstream.c
index 3c43d1f98d..e51689543f 100644
--- a/src/nvim/event/rstream.c
+++ b/src/nvim/event/rstream.c
@@ -11,8 +11,8 @@
#include "nvim/event/loop.h"
#include "nvim/event/rstream.h"
#include "nvim/log.h"
-#include "nvim/memory.h"
#include "nvim/main.h"
+#include "nvim/memory.h"
#include "nvim/vim.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
diff --git a/src/nvim/event/socket.c b/src/nvim/event/socket.c
index 7948a7be83..c20716496f 100644
--- a/src/nvim/event/socket.c
+++ b/src/nvim/event/socket.c
@@ -53,10 +53,8 @@ int socket_watcher_init(Loop *loop, SocketWatcher *watcher, const char *endpoint
uv_getaddrinfo_t request;
int retval = uv_getaddrinfo(&loop->uv, &request, NULL, addr, port,
- &(struct addrinfo){
- .ai_family = AF_UNSPEC,
- .ai_socktype = SOCK_STREAM,
- });
+ &(struct addrinfo){ .ai_family = AF_UNSPEC,
+ .ai_socktype = SOCK_STREAM, });
if (retval != 0) {
ELOG("Host lookup failed: %s", endpoint);
return retval;
@@ -103,10 +101,9 @@ int socket_watcher_start(SocketWatcher *watcher, int backlog, socket_cb cb)
// contain 0 in this case, unless uv_tcp_getsockname() is used first.
uv_tcp_getsockname(&watcher->uv.tcp.handle, (struct sockaddr *)&sas,
&(int){ sizeof(sas) });
- uint16_t port = (uint16_t)(
- (sas.ss_family == AF_INET)
- ? (STRUCT_CAST(struct sockaddr_in, &sas))->sin_port
- : (STRUCT_CAST(struct sockaddr_in6, &sas))->sin6_port);
+ uint16_t port = (uint16_t)((sas.ss_family == AF_INET)
+ ? (STRUCT_CAST(struct sockaddr_in, &sas))->sin_port
+ : (STRUCT_CAST(struct sockaddr_in6, &sas))->sin6_port);
// v:servername uses the string from watcher->addr
size_t len = strlen(watcher->addr);
snprintf(watcher->addr+len, sizeof(watcher->addr)-len, ":%" PRIu16,
diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c
index 49bf9972b1..1b2a9579e4 100644
--- a/src/nvim/ex_cmds.c
+++ b/src/nvim/ex_cmds.c
@@ -225,9 +225,7 @@ void do_ascii(const exarg_T *const eap)
msg((char *)IObuff);
}
-/*
- * ":left", ":center" and ":right": align text.
- */
+/// ":left", ":center" and ":right": align text.
void ex_align(exarg_T *eap)
{
pos_T save_curpos;
@@ -324,9 +322,7 @@ void ex_align(exarg_T *eap)
beginline(BL_WHITE | BL_FIX);
}
-/*
- * Get the length of the current line, excluding trailing white space.
- */
+/// @return the length of the current line, excluding trailing white space.
static int linelen(int *has_tab)
{
char_u *line;
@@ -452,7 +448,7 @@ static int sort_compare(const void *s1, const void *s2)
return result;
}
-// ":sort".
+/// ":sort".
void ex_sort(exarg_T *eap)
{
regmatch_T regmatch;
@@ -723,9 +719,7 @@ sortend:
}
}
-/*
- * ":retab".
- */
+/// ":retab".
void ex_retab(exarg_T *eap)
{
linenr_T lnum;
@@ -907,11 +901,9 @@ void ex_retab(exarg_T *eap)
u_clearline();
}
-/*
- * :move command - move lines line1-line2 to line dest
- *
- * return FAIL for failure, OK otherwise
- */
+/// :move command - move lines line1-line2 to line dest
+///
+/// @return FAIL for failure, OK otherwise
int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
{
char_u *str;
@@ -1062,9 +1054,7 @@ int do_move(linenr_T line1, linenr_T line2, linenr_T dest)
return OK;
}
-/*
- * ":copy"
- */
+/// ":copy"
void ex_copy(linenr_T line1, linenr_T line2, linenr_T n)
{
linenr_T count;
@@ -1132,11 +1122,9 @@ void free_prev_shellcmd(void)
#endif
-/*
- * Handle the ":!cmd" command. Also for ":r !cmd" and ":w !cmd"
- * Bangs in the argument are replaced with the previously entered command.
- * Remember the argument.
- */
+/// Handle the ":!cmd" command. Also for ":r !cmd" and ":w !cmd"
+/// Bangs in the argument are replaced with the previously entered command.
+/// Remember the argument.
void do_bang(int addr_count, exarg_T *eap, bool forceit, bool do_in, bool do_out)
FUNC_ATTR_NONNULL_ALL
{
@@ -1684,9 +1672,7 @@ void print_line_no_prefix(linenr_T lnum, int use_number, int list)
msg_prt_line(ml_get(lnum), list);
}
-/*
- * Print a text line. Also in silent mode ("ex -s").
- */
+/// Print a text line. Also in silent mode ("ex -s").
void print_line(linenr_T lnum, int use_number, int list)
{
int save_silent = silent_mode;
@@ -1754,9 +1740,7 @@ int rename_buffer(char_u *new_fname)
return OK;
}
-/*
- * ":file[!] [fname]".
- */
+/// ":file[!] [fname]".
void ex_file(exarg_T *eap)
{
// ":0file" removes the file name. Check for illegal uses ":3file",
@@ -1782,9 +1766,7 @@ void ex_file(exarg_T *eap)
}
}
-/*
- * ":update".
- */
+/// ":update".
void ex_update(exarg_T *eap)
{
if (curbufIsChanged()) {
@@ -1792,9 +1774,7 @@ void ex_update(exarg_T *eap)
}
}
-/*
- * ":write" and ":saveas".
- */
+/// ":write" and ":saveas".
void ex_write(exarg_T *eap)
{
if (eap->cmdidx == CMD_saveas) {
@@ -1810,14 +1790,12 @@ void ex_write(exarg_T *eap)
}
}
-/*
- * write current buffer to file 'eap->arg'
- * if 'eap->append' is TRUE, append to the file
- *
- * if *eap->arg == NUL write to current file
- *
- * return FAIL for failure, OK otherwise
- */
+/// write current buffer to file 'eap->arg'
+/// if 'eap->append' is TRUE, append to the file
+///
+/// if *eap->arg == NUL write to current file
+///
+/// @return FAIL for failure, OK otherwise
int do_write(exarg_T *eap)
{
int other;
@@ -1943,7 +1921,7 @@ int do_write(exarg_T *eap)
// If 'filetype' was empty try detecting it now.
if (*curbuf->b_p_ft == NUL) {
- if (au_has_group((char_u *)"filetypedetect")) {
+ if (augroup_exists("filetypedetect")) {
(void)do_doautocmd((char_u *)"filetypedetect BufRead", true, NULL);
}
do_modelines(0);
@@ -2070,9 +2048,7 @@ int check_overwrite(exarg_T *eap, buf_T *buf, char_u *fname, char_u *ffname, int
return OK;
}
-/*
- * Handle ":wnext", ":wNext" and ":wprevious" commands.
- */
+/// Handle ":wnext", ":wNext" and ":wprevious" commands.
void ex_wnext(exarg_T *eap)
{
int i;
@@ -2089,9 +2065,7 @@ void ex_wnext(exarg_T *eap)
}
}
-/*
- * ":wall", ":wqall" and ":xall": Write all changed files (and exit).
- */
+/// ":wall", ":wqall" and ":xall": Write all changed files (and exit).
void do_wqall(exarg_T *eap)
{
int error = 0;
@@ -2149,8 +2123,9 @@ void do_wqall(exarg_T *eap)
}
}
-// Check the 'write' option.
-// Return true and give a message when it's not st.
+/// Check the 'write' option.
+///
+/// @return true and give a message when it's not st.
bool not_writing(void)
{
if (p_write) {
@@ -2160,11 +2135,9 @@ bool not_writing(void)
return true;
}
-/*
- * Check if a buffer is read-only (either 'readonly' option is set or file is
- * read-only). Ask for overruling in a dialog. Return TRUE and give an error
- * message when the buffer is readonly.
- */
+/// Check if a buffer is read-only (either 'readonly' option is set or file is
+/// read-only). Ask for overruling in a dialog. Return TRUE and give an error
+/// message when the buffer is readonly.
static int check_readonly(int *forceit, buf_T *buf)
{
// Handle a file being readonly when the 'readonly' option is set or when
@@ -2205,15 +2178,16 @@ static int check_readonly(int *forceit, buf_T *buf)
return FALSE;
}
-// Try to abandon the current file and edit a new or existing file.
-// "fnum" is the number of the file, if zero use "ffname_arg"/"sfname_arg".
-// "lnum" is the line number for the cursor in the new file (if non-zero).
-//
-// Return:
-// GETFILE_ERROR for "normal" error,
-// GETFILE_NOT_WRITTEN for "not written" error,
-// GETFILE_SAME_FILE for success
-// GETFILE_OPEN_OTHER for successfully opening another file.
+/// Try to abandon the current file and edit a new or existing file.
+///
+/// @param fnum the number of the file, if zero use "ffname_arg"/"sfname_arg".
+/// @param lnum the line number for the cursor in the new file (if non-zero).
+///
+/// @return:
+/// GETFILE_ERROR for "normal" error,
+/// GETFILE_NOT_WRITTEN for "not written" error,
+/// GETFILE_SAME_FILE for success
+/// GETFILE_OPEN_OTHER for successfully opening another file.
int getfile(int fnum, char_u *ffname_arg, char_u *sfname_arg, int setpm, linenr_T lnum, int forceit)
{
char_u *ffname = ffname_arg;
@@ -2934,9 +2908,7 @@ static void delbuf_msg(char_u *name)
static int append_indent = 0; // autoindent for first line
-/*
- * ":insert" and ":append", also used by ":change"
- */
+/// ":insert" and ":append", also used by ":change"
void ex_append(exarg_T *eap)
{
char_u *theline;
@@ -3078,9 +3050,7 @@ void ex_append(exarg_T *eap)
ex_no_reprint = true;
}
-/*
- * ":change"
- */
+/// ":change"
void ex_change(exarg_T *eap)
{
linenr_T lnum;
@@ -3247,9 +3217,9 @@ void ex_z(exarg_T *eap)
ex_no_reprint = true;
}
-// Check if the secure flag is set (.exrc or .vimrc in current directory).
-// If so, give an error message and return true.
-// Otherwise, return false.
+/// @return true if the secure flag is set (.exrc or .vimrc in current directory)
+/// and also give an error message.
+/// Otherwise, return false.
bool check_secure(void)
{
if (secure) {
@@ -4533,22 +4503,20 @@ static void global_exe_one(char_u *const cmd, const linenr_T lnum)
}
}
-/*
- * Execute a global command of the form:
- *
- * g/pattern/X : execute X on all lines where pattern matches
- * v/pattern/X : execute X on all lines where pattern does not match
- *
- * where 'X' is an EX command
- *
- * The command character (as well as the trailing slash) is optional, and
- * is assumed to be 'p' if missing.
- *
- * This is implemented in two passes: first we scan the file for the pattern and
- * set a mark for each line that (not) matches. Secondly we execute the command
- * for each line that has a mark. This is required because after deleting
- * lines we do not know where to search for the next match.
- */
+/// Execute a global command of the form:
+///
+/// g/pattern/X : execute X on all lines where pattern matches
+/// v/pattern/X : execute X on all lines where pattern does not match
+///
+/// where 'X' is an EX command
+///
+/// The command character (as well as the trailing slash) is optional, and
+/// is assumed to be 'p' if missing.
+///
+/// This is implemented in two passes: first we scan the file for the pattern and
+/// set a mark for each line that (not) matches. Secondly we execute the command
+/// for each line that has a mark. This is required because after deleting
+/// lines we do not know where to search for the next match.
void ex_global(exarg_T *eap)
{
linenr_T lnum; // line number according to old situation
@@ -4764,9 +4732,7 @@ bool prepare_tagpreview(bool undo_sync)
}
-/*
- * ":help": open a read-only window on a help file
- */
+/// ":help": open a read-only window on a help file
void ex_help(exarg_T *eap)
{
char_u *arg;
@@ -4949,11 +4915,10 @@ erret:
}
-/*
- * In an argument search for a language specifiers in the form "@xx".
- * Changes the "@" to NUL if found, and returns a pointer to "xx".
- * Returns NULL if not found.
- */
+/// In an argument search for a language specifiers in the form "@xx".
+/// Changes the "@" to NUL if found, and returns a pointer to "xx".
+///
+/// @return NULL if not found.
char_u *check_help_lang(char_u *arg)
{
int len = (int)STRLEN(arg);
@@ -5019,10 +4984,8 @@ int help_heuristic(char_u *matched_string, int offset, int wrong_case)
return (int)(100 * num_letters + STRLEN(matched_string) + offset);
}
-/*
- * Compare functions for qsort() below, that checks the help heuristics number
- * that has been put after the tagname by find_tags().
- */
+/// Compare functions for qsort() below, that checks the help heuristics number
+/// that has been put after the tagname by find_tags().
static int help_compare(const void *s1, const void *s2)
{
char *p1;
@@ -5033,10 +4996,10 @@ static int help_compare(const void *s1, const void *s2)
return strcmp(p1, p2);
}
-// Find all help tags matching "arg", sort them and return in matches[], with
-// the number of matches in num_matches.
-// The matches will be sorted with a "best" match algorithm.
-// When "keep_lang" is true try keeping the language of the current buffer.
+/// Find all help tags matching "arg", sort them and return in matches[], with
+/// the number of matches in num_matches.
+/// The matches will be sorted with a "best" match algorithm.
+/// When "keep_lang" is true try keeping the language of the current buffer.
int find_help_tags(const char_u *arg, int *num_matches, char_u ***matches, bool keep_lang)
{
int i;
@@ -5308,10 +5271,8 @@ static void prepare_help_buffer(void)
set_buflisted(FALSE);
}
-/*
- * After reading a help file: May cleanup a help buffer when syntax
- * highlighting is not used.
- */
+/// After reading a help file: May cleanup a help buffer when syntax
+/// highlighting is not used.
void fix_help_buffer(void)
{
linenr_T lnum;
@@ -5507,17 +5468,13 @@ void fix_help_buffer(void)
}
}
-/*
- * ":exusage"
- */
+/// ":exusage"
void ex_exusage(exarg_T *eap)
{
do_cmdline_cmd("help ex-cmd-index");
}
-/*
- * ":viusage"
- */
+/// ":viusage"
void ex_viusage(exarg_T *eap)
{
do_cmdline_cmd("help normal-index");
@@ -5826,9 +5783,7 @@ static void helptags_cb(char_u *fname, void *cookie)
do_helptags(fname, *(bool *)cookie, true);
}
-/*
- * ":helptags"
- */
+/// ":helptags"
void ex_helptags(exarg_T *eap)
{
expand_T xpc;
@@ -5857,9 +5812,7 @@ void ex_helptags(exarg_T *eap)
}
}
-/*
- * ":helpclose": Close one help window
- */
+/// ":helpclose": Close one help window
void ex_helpclose(exarg_T *eap)
{
FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
@@ -5873,7 +5826,7 @@ void ex_helpclose(exarg_T *eap)
/// Tries to enter to an existing window of given buffer. If no existing buffer
/// is found, creates a new split.
///
-/// Returns OK/FAIL.
+/// @return OK/FAIL.
int sub_preview_win(buf_T *preview_buf)
{
if (preview_buf != NULL) {
@@ -6115,9 +6068,11 @@ void ex_substitute(exarg_T *eap)
/// Skip over the pattern argument of ":vimgrep /pat/[g][j]".
/// Put the start of the pattern in "*s", unless "s" is NULL.
-/// If "flags" is not NULL put the flags in it: VGR_GLOBAL, VGR_NOJUMP.
-/// If "s" is not NULL terminate the pattern with a NUL.
-/// Return a pointer to the char just past the pattern plus flags.
+///
+/// @param flags if not NULL, put the flags in it: VGR_GLOBAL, VGR_NOJUMP.
+/// @param s if not NULL, terminate the pattern with a NUL.
+///
+/// @return a pointer to the char just past the pattern plus flags.
char_u *skip_vimgrep_pat(char_u *p, char_u **s, int *flags)
{
int c;
diff --git a/src/nvim/ex_cmds2.c b/src/nvim/ex_cmds2.c
index 090422088a..fe1dec7298 100644
--- a/src/nvim/ex_cmds2.c
+++ b/src/nvim/ex_cmds2.c
@@ -436,8 +436,8 @@ static void script_dump_profile(FILE *fd)
}
}
-/// Return true when a function defined in the current script should be
-/// profiled.
+/// @return true when a function defined in the current script should be
+/// profiled.
bool prof_def_func(void)
{
if (current_sctx.sc_sid > 0) {
@@ -492,7 +492,7 @@ void autowrite_all(void)
}
}
-/// Return true if buffer was changed and cannot be abandoned.
+/// @return true if buffer was changed and cannot be abandoned.
/// For flags use the CCGD_ values.
bool check_changed(buf_T *buf, int flags)
{
@@ -616,7 +616,7 @@ bool dialog_close_terminal(buf_T *buf)
return ret == VIM_YES;
}
-/// Return true if the buffer "buf" can be abandoned, either by making it
+/// @return true if the buffer "buf" can be abandoned, either by making it
/// hidden, autowriting it or unloading it.
bool can_abandon(buf_T *buf, int forceit)
{
@@ -771,8 +771,8 @@ theend:
return ret;
}
-/// Return FAIL if there is no file name, OK if there is one.
-/// Give error message for FAIL.
+/// @return FAIL if there is no file name, OK if there is one.
+/// Give error message for FAIL.
int check_fname(void)
{
if (curbuf->b_ffname == NULL) {
@@ -784,7 +784,7 @@ int check_fname(void)
/// Flush the contents of a buffer, unless it has no file name.
///
-/// @return FAIL for failure, OK otherwise
+/// @return FAIL for failure, OK otherwise
int buf_write_all(buf_T *buf, int forceit)
{
int retval;
@@ -808,7 +808,8 @@ int buf_write_all(buf_T *buf, int forceit)
/// Isolate one argument, taking backticks.
/// Changes the argument in-place, puts a NUL after it. Backticks remain.
-/// Return a pointer to the start of the next argument.
+///
+/// @return a pointer to the start of the next argument.
static char_u *do_one_arg(char_u *str)
{
char_u *p;
@@ -859,7 +860,7 @@ static void get_arglist(garray_T *gap, char_u *str, int escaped)
/// Parse a list of arguments (file names), expand them and return in
/// "fnames[fcountp]". When "wig" is true, removes files matching 'wildignore'.
///
-/// @return FAIL or OK.
+/// @return FAIL or OK.
int get_arglist_exp(char_u *str, int *fcountp, char_u ***fnamesp, bool wig)
{
garray_T ga;
@@ -889,7 +890,7 @@ int get_arglist_exp(char_u *str, int *fcountp, char_u ***fnamesp, bool wig)
/// 0 means before first one
/// @param will_edit will edit added argument
///
-/// @return FAIL for failure, OK otherwise.
+/// @return FAIL for failure, OK otherwise.
static int do_arglist(char_u *str, int what, int after, bool will_edit)
FUNC_ATTR_NONNULL_ALL
{
@@ -988,8 +989,8 @@ static void alist_check_arg_idx(void)
}
}
-/// Return true if window "win" is editing the file at the current argument
-/// index.
+/// @return true if window "win" is editing the file at the current argument
+/// index.
static bool editing_arg_idx(win_T *win)
{
return !(win->w_arg_idx >= WARGCOUNT(win)
@@ -1698,7 +1699,7 @@ static bool concat_continued_line(garray_T *const ga, const int init_growsize,
return false;
}
if (ga->ga_len > init_growsize) {
- ga_set_growsize(ga, MAX(ga->ga_len, 8000));
+ ga_set_growsize(ga, MIN(ga->ga_len, 8000));
}
ga_concat_len(ga, (const char *)line + 1, len - 1);
return true;
@@ -1717,13 +1718,13 @@ linenr_T *source_breakpoint(void *cookie)
return &((struct source_cookie *)cookie)->breakpoint;
}
-/// Return the address holding the debug tick for a source cookie.
+/// @return the address holding the debug tick for a source cookie.
int *source_dbg_tick(void *cookie)
{
return &((struct source_cookie *)cookie)->dbg_tick;
}
-/// Return the nesting level for a source cookie.
+/// @return the nesting level for a source cookie.
int source_level(void *cookie)
{
return ((struct source_cookie *)cookie)->level;
@@ -1788,7 +1789,8 @@ static char_u *get_str_line(int c, void *cookie, int indent, bool do_concat)
///
/// @param name File name of the script. NULL for anonymous :source.
/// @param[out] sid_out SID of the new item.
-/// @return pointer to the created script item.
+///
+/// @return pointer to the created script item.
scriptitem_T *new_script_item(char_u *const name, scid_T *const sid_out)
{
static scid_T last_current_SID = 0;
@@ -1796,7 +1798,7 @@ scriptitem_T *new_script_item(char_u *const name, scid_T *const sid_out)
if (sid_out != NULL) {
*sid_out = sid;
}
- ga_grow(&script_items, (int)(sid - script_items.ga_len));
+ ga_grow(&script_items, sid - script_items.ga_len);
while (script_items.ga_len < sid) {
script_items.ga_len++;
SCRIPT_ITEM(script_items.ga_len).sn_name = NULL;
@@ -1823,7 +1825,9 @@ static int source_using_linegetter(void *cookie, LineGetter fgetline, const char
sourcing_lnum = 0;
const sctx_T save_current_sctx = current_sctx;
- current_sctx.sc_sid = SID_STR;
+ if (current_sctx.sc_sid != SID_LUA) {
+ current_sctx.sc_sid = SID_STR;
+ }
current_sctx.sc_seq = 0;
current_sctx.sc_lnum = save_sourcing_lnum;
funccal_entry_T entry;
@@ -1850,7 +1854,7 @@ static void cmd_source_buffer(const exarg_T *const eap)
for (linenr_T curr_lnum = eap->line1; curr_lnum <= final_lnum; curr_lnum++) {
// Adjust growsize to current length to speed up concatenating many lines.
if (ga.ga_len > 400) {
- ga_set_growsize(&ga, MAX(ga.ga_len, 8000));
+ ga_set_growsize(&ga, MIN(ga.ga_len, 8000));
}
ga_concat(&ga, (char *)ml_get(curr_lnum));
ga_append(&ga, NL);
@@ -1894,7 +1898,7 @@ int do_source_str(const char *cmd, const char *traceback_name)
/// @param check_other check for .vimrc and _vimrc
/// @param is_vimrc DOSO_ value
///
-/// @return FAIL if file could not be opened, OK otherwise
+/// @return FAIL if file could not be opened, OK otherwise
int do_source(char *fname, int check_other, int is_vimrc)
{
struct source_cookie cookie;
@@ -1904,7 +1908,6 @@ int do_source(char *fname, int check_other, int is_vimrc)
char_u *fname_exp;
char_u *firstline = NULL;
int retval = FAIL;
- static int last_current_SID_seq = 0;
int save_debug_break_level = debug_break_level;
scriptitem_T *si = NULL;
proftime_T wait_start;
@@ -1952,7 +1955,7 @@ int do_source(char *fname, int check_other, int is_vimrc)
}
if (cookie.fp == NULL) {
- if (p_verbose > 0) {
+ if (p_verbose > 1) {
verbose_enter();
if (sourcing_name == NULL) {
smsg(_("could not source \"%s\""), fname);
@@ -2028,37 +2031,8 @@ 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 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;
- current_sctx.sc_seq = ++last_current_SID_seq;
- current_sctx.sc_lnum = 0;
- FileID file_id;
- bool file_id_ok = os_fileid((char *)fname_exp, &file_id);
- assert(script_items.ga_len >= 0);
- for (current_sctx.sc_sid = script_items.ga_len; current_sctx.sc_sid > 0;
- current_sctx.sc_sid--) {
- si = &SCRIPT_ITEM(current_sctx.sc_sid);
- // Compare dev/ino when possible, it catches symbolic links.
- // Also compare file names, the inode may change when the file was edited.
- bool file_id_equal = file_id_ok && si->file_id_valid
- && os_fileid_equal(&(si->file_id), &file_id);
- if (si->sn_name != NULL
- && (file_id_equal || fnamecmp(si->sn_name, fname_exp) == 0)) {
- break;
- }
- }
- if (current_sctx.sc_sid == 0) {
- si = new_script_item(fname_exp, &current_sctx.sc_sid);
- fname_exp = vim_strsave(si->sn_name); // used for autocmd
- if (file_id_ok) {
- si->file_id_valid = true;
- si->file_id = file_id;
- } else {
- si->file_id_valid = false;
- }
- }
+ si = get_current_script_id(fname_exp, &current_sctx);
if (l_do_profiling == PROF_YES) {
bool forceit = false;
@@ -2091,16 +2065,14 @@ int do_source(char *fname, int check_other, int is_vimrc)
firstline = p;
}
- if (path_with_extension((const char *)fname, "lua")) {
- // TODO(shadmansaleh): Properly handle :verbose for lua
- // For now change currennt_sctx before sourcing lua files
- // So verbose doesn't say everything was done in line 1 since we don't know
+ if (path_with_extension((const char *)fname_exp, "lua")) {
const sctx_T current_sctx_backup = current_sctx;
const linenr_T sourcing_lnum_backup = sourcing_lnum;
+ current_sctx.sc_sid = SID_LUA;
current_sctx.sc_lnum = 0;
sourcing_lnum = 0;
// Source the file as lua
- nlua_exec_file((const char *)fname);
+ nlua_exec_file((const char *)fname_exp);
current_sctx = current_sctx_backup;
sourcing_lnum = sourcing_lnum_backup;
} else {
@@ -2173,6 +2145,52 @@ theend:
}
+/// Check if fname was sourced before to finds its SID.
+/// If it's new, generate a new SID.
+///
+/// @param[in] fname file path of script
+/// @param[out] ret_sctx sctx of this script
+scriptitem_T *get_current_script_id(char_u *fname, sctx_T *ret_sctx)
+{
+ static int last_current_SID_seq = 0;
+
+ sctx_T script_sctx = { .sc_seq = ++last_current_SID_seq,
+ .sc_lnum = 0,
+ .sc_sid = 0 };
+ FileID file_id;
+ scriptitem_T *si = NULL;
+
+ bool file_id_ok = os_fileid((char *)fname, &file_id);
+ assert(script_items.ga_len >= 0);
+ for (script_sctx.sc_sid = script_items.ga_len; script_sctx.sc_sid > 0;
+ script_sctx.sc_sid--) {
+ si = &SCRIPT_ITEM(script_sctx.sc_sid);
+ // Compare dev/ino when possible, it catches symbolic links.
+ // Also compare file names, the inode may change when the file was edited.
+ bool file_id_equal = file_id_ok && si->file_id_valid
+ && os_fileid_equal(&(si->file_id), &file_id);
+ if (si->sn_name != NULL
+ && (file_id_equal || fnamecmp(si->sn_name, fname) == 0)) {
+ break;
+ }
+ }
+ if (script_sctx.sc_sid == 0) {
+ si = new_script_item(vim_strsave(fname), &script_sctx.sc_sid);
+ if (file_id_ok) {
+ si->file_id_valid = true;
+ si->file_id = file_id;
+ } else {
+ si->file_id_valid = false;
+ }
+ }
+ if (ret_sctx != NULL) {
+ *ret_sctx = script_sctx;
+ }
+
+ return si;
+}
+
+
/// ":scriptnames"
void ex_scriptnames(exarg_T *eap)
{
@@ -2599,9 +2617,9 @@ void do_finish(exarg_T *eap, int reanimate)
}
-/// Return true when a sourced file had the ":finish" command: Don't give error
-/// message for missing ":endif".
-/// Return false when not sourcing a file.
+/// @return true when a sourced file had the ":finish" command: Don't give error
+/// message for missing ":endif".
+/// false when not sourcing a file.
bool source_finished(LineGetter fgetline, void *cookie)
{
return getline_equal(fgetline, cookie, getsourceline)
@@ -2638,8 +2656,8 @@ static char *get_locale_val(int what)
}
#endif
-// Return true when "lang" starts with a valid language name.
-// Rejects NULL, empty string, "C", "C.UTF-8" and others.
+/// @return true when "lang" starts with a valid language name.
+/// Rejects NULL, empty string, "C", "C.UTF-8" and others.
static bool is_valid_mess_lang(char *lang)
{
return lang != NULL && ASCII_ISALPHA(lang[0]) && ASCII_ISALPHA(lang[1]);
@@ -2742,11 +2760,10 @@ void set_lang_var(void)
}
#ifdef HAVE_WORKING_LIBINTL
-///
+
/// ":language": Set the language (locale).
///
/// @param eap
-///
void ex_language(exarg_T *eap)
{
char *loc;
@@ -2855,8 +2872,9 @@ static char_u **locales = NULL; // Array of all available locales
# ifndef WIN32
static bool did_init_locales = false;
-/// Return an array of strings for all available locales + NULL for the
-/// last element. Return NULL in case of error.
+/// @return an array of strings for all available locales + NULL for the
+/// last element or,
+/// NULL in case of error.
static char_u **find_locales(void)
{
garray_T locales_ga;
diff --git a/src/nvim/ex_cmds_defs.h b/src/nvim/ex_cmds_defs.h
index eaf5f627b6..92675499be 100644
--- a/src/nvim/ex_cmds_defs.h
+++ b/src/nvim/ex_cmds_defs.h
@@ -4,6 +4,7 @@
#include <stdbool.h>
#include <stdint.h>
+#include "nvim/eval/typval.h"
#include "nvim/normal.h"
#include "nvim/pos.h" // for linenr_T
#include "nvim/regexp_defs.h"
@@ -91,6 +92,35 @@ typedef struct exarg exarg_T;
typedef void (*ex_func_T)(exarg_T *eap);
+// NOTE: These possible could be removed and changed so that
+// Callback could take a "command" style string, and simply
+// execute that (instead of it being a function).
+//
+// But it's still a bit weird to do that.
+//
+// Another option would be that we just make a callback reference to
+// "execute($INPUT)" or something like that, so whatever the user
+// sends in via autocmds is just executed via this.
+//
+// However, that would probably have some performance cost (probably
+// very marginal, but still some cost either way).
+typedef enum {
+ CALLABLE_NONE,
+ CALLABLE_EX,
+ CALLABLE_CB,
+} AucmdExecutableType;
+
+typedef struct aucmd_executable_t AucmdExecutable;
+struct aucmd_executable_t {
+ AucmdExecutableType type;
+ union {
+ char_u *cmd;
+ Callback cb;
+ } callable;
+};
+
+#define AUCMD_EXECUTABLE_INIT { .type = CALLABLE_NONE }
+
typedef char_u *(*LineGetter)(int, void *, int, bool);
/// Structure for command definition.
diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c
index e8b8dc799c..14d0c58cd1 100644
--- a/src/nvim/ex_docmd.c
+++ b/src/nvim/ex_docmd.c
@@ -80,7 +80,7 @@
static char *e_no_such_user_defined_command_str = N_("E184: No such user-defined command: %s");
static char *e_no_such_user_defined_command_in_current_buffer_str
- = N_("E1237: No such user-defined command in current buffer: %s");
+ = N_("E1237: No such user-defined command in current buffer: %s");
static int quitmore = 0;
static bool ex_pressedreturn = false;
@@ -2036,6 +2036,18 @@ doend:
return ea.nextcmd;
}
+static char ex_error_buf[MSG_BUF_LEN];
+
+/// @return an error message with argument included.
+/// Uses a static buffer, only the last error will be kept.
+/// "msg" will be translated, caller should use N_().
+char *ex_errmsg(const char *const msg, const char_u *const arg)
+ FUNC_ATTR_NONNULL_ALL
+{
+ vim_snprintf(ex_error_buf, MSG_BUF_LEN, _(msg), arg);
+ return ex_error_buf;
+}
+
// Parse and skip over command modifiers:
// - update eap->cmd
// - store flags in "cmdmod".
@@ -2704,7 +2716,7 @@ static char_u *find_ucmd(exarg_T *eap, char_u *p, int *full, expand_T *xp, int *
// only full match global is accepted.
// Look for buffer-local user commands first, then global ones.
- gap = is_in_cmdwin() ? &prevwin->w_buffer->b_ucmds : &curbuf->b_ucmds;
+ gap = &prevwin_curwin()->w_buffer->b_ucmds;
for (;;) {
for (j = 0; j < gap->ga_len; j++) {
uc = USER_CMD_GA(gap, j);
@@ -2835,7 +2847,7 @@ int modifier_len(char_u *cmd)
for (int i = 0; i < (int)ARRAY_SIZE(cmdmods); i++) {
int j;
for (j = 0; p[j] != NUL; j++) {
- if (p[j] != cmdmods[i].name[j]) {
+ if (p[j] != (char_u)cmdmods[i].name[j]) {
break;
}
}
@@ -4861,7 +4873,13 @@ static int get_tabpage_arg(exarg_T *eap)
if (STRCMP(p, "$") == 0) {
tab_number = LAST_TAB_NR;
} else if (STRCMP(p, "#") == 0) {
- tab_number = tabpage_index(lastused_tabpage);
+ if (valid_tabpage(lastused_tabpage)) {
+ tab_number = tabpage_index(lastused_tabpage);
+ } else {
+ eap->errmsg = ex_errmsg(e_invargval, eap->arg);
+ tab_number = 0;
+ goto theend;
+ }
} else if (p == p_save || *p_save == '-' || *p != NUL
|| tab_number > LAST_TAB_NR) {
// No numbers as argument.
@@ -5277,6 +5295,7 @@ int uc_add_command(char_u *name, size_t name_len, char_u *rep, uint32_t argt, lo
cmd->uc_compl = compl;
cmd->uc_script_ctx = current_sctx;
cmd->uc_script_ctx.sc_lnum += sourcing_lnum;
+ nlua_set_sctx(&cmd->uc_script_ctx);
cmd->uc_compl_arg = compl_arg;
cmd->uc_compl_luaref = compl_luaref;
cmd->uc_addr_type = addr_type;
@@ -5377,7 +5396,7 @@ static void uc_list(char_u *name, size_t name_len)
uint32_t a;
// In cmdwin, the alternative buffer should be used.
- garray_T *gap = is_in_cmdwin() ? &prevwin->w_buffer->b_ucmds : &curbuf->b_ucmds;
+ const garray_T *gap = &prevwin_curwin()->w_buffer->b_ucmds;
for (;;) {
for (i = 0; i < gap->ga_len; i++) {
cmd = USER_CMD_GA(gap, i);
@@ -5802,6 +5821,30 @@ static void ex_delcommand(exarg_T *eap)
}
}
+/// Split a string by unescaped whitespace (space & tab), used for f-args on Lua commands callback.
+/// Similar to uc_split_args(), but does not allocate, add quotes, add commas and is an iterator.
+///
+/// @note If no separator is found start = 0 and end = length - 1
+/// @param[in] arg String to split
+/// @param[in] iter Iteration counter
+/// @param[out] start Start of the split
+/// @param[out] end End of the split
+/// @param[in] length Length of the string
+/// @return false if it's the last split (don't call again), true otherwise (call again).
+bool uc_split_args_iter(const char_u *arg, int iter, int *start, int *end, int length)
+{
+ int pos;
+ *start = *end + (iter > 1 ? 2 : 0); // Skip whitespace after the first split
+ for (pos = *start; pos < length - 2; pos++) {
+ if (arg[pos] != '\\' && ascii_iswhite(arg[pos + 1])) {
+ *end = pos;
+ return true;
+ }
+ }
+ *end = length - 1;
+ return false;
+}
+
/*
* split and quote args for <f-args>
*/
@@ -6205,7 +6248,6 @@ static void do_ucmd(exarg_T *eap)
size_t split_len = 0;
char_u *split_buf = NULL;
ucmd_T *cmd;
- const sctx_T save_current_sctx = current_sctx;
if (eap->cmdidx == CMD_USER) {
cmd = USER_CMD(eap->useridx);
@@ -6295,12 +6337,19 @@ static void do_ucmd(exarg_T *eap)
buf = xmalloc(totlen + 1);
}
+ sctx_T save_current_sctx;
+ bool restore_current_sctx = false;
if ((cmd->uc_argt & EX_KEEPSCRIPT) == 0) {
+ restore_current_sctx = true;
+ save_current_sctx = current_sctx;
current_sctx.sc_sid = cmd->uc_script_ctx.sc_sid;
}
(void)do_cmdline(buf, eap->getline, eap->cookie,
DOCMD_VERBOSE|DOCMD_NOWAIT|DOCMD_KEYTYPED);
- if ((cmd->uc_argt & EX_KEEPSCRIPT) == 0) {
+
+ // Careful: Do not use "cmd" here, it may have become invalid if a user
+ // command was added.
+ if (restore_current_sctx) {
current_sctx = save_current_sctx;
}
xfree(buf);
@@ -6326,7 +6375,7 @@ char_u *get_user_commands(expand_T *xp FUNC_ATTR_UNUSED, int idx)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
// In cmdwin, the alternative buffer should be used.
- const buf_T *const buf = is_in_cmdwin() ? prevwin->w_buffer : curbuf;
+ const buf_T *const buf = prevwin_curwin()->w_buffer;
if (idx < buf->b_ucmds.ga_len) {
return USER_CMD_GA(&buf->b_ucmds, idx)->uc_name;
@@ -6348,7 +6397,8 @@ static char_u *get_user_command_name(int idx, int cmdidx)
}
if (cmdidx == CMD_USER_BUF) {
// In cmdwin, the alternative buffer should be used.
- buf_T *buf = is_in_cmdwin() ? prevwin->w_buffer : curbuf;
+ const buf_T *const buf = prevwin_curwin()->w_buffer;
+
if (idx < buf->b_ucmds.ga_len) {
return USER_CMD_GA(&buf->b_ucmds, idx)->uc_name;
}
@@ -7506,7 +7556,7 @@ static void ex_edit(exarg_T *eap)
do_exedit(eap, NULL);
}
-/// ":edit <file>" command and alikes.
+/// ":edit <file>" command and alike.
///
/// @param old_curwin curwin before doing a split or NULL
void do_exedit(exarg_T *eap, win_T *old_curwin)
@@ -8135,7 +8185,7 @@ static void ex_operators(exarg_T *eap)
case CMD_yank:
oa.op_type = OP_YANK;
- (void)op_yank(&oa, true, false);
+ (void)op_yank(&oa, true);
break;
default: // CMD_rshift or CMD_lshift
@@ -9605,7 +9655,7 @@ static void ex_filetype(exarg_T *eap)
/// 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
+/// autocommands will always fire first (and thus can be overridden) while still
/// allowing general filetype detection to be disabled in the user's init file.
void filetype_plugin_enable(void)
{
diff --git a/src/nvim/ex_docmd.h b/src/nvim/ex_docmd.h
index abf6ec347b..be9f97e27d 100644
--- a/src/nvim/ex_docmd.h
+++ b/src/nvim/ex_docmd.h
@@ -1,8 +1,8 @@
#ifndef NVIM_EX_DOCMD_H
#define NVIM_EX_DOCMD_H
-#include "nvim/ex_cmds_defs.h"
#include "nvim/eval/funcs.h"
+#include "nvim/ex_cmds_defs.h"
#include "nvim/globals.h"
// flags for do_cmdline()
diff --git a/src/nvim/ex_eval.c b/src/nvim/ex_eval.c
index 851828afcf..3c7c635d98 100644
--- a/src/nvim/ex_eval.c
+++ b/src/nvim/ex_eval.c
@@ -88,27 +88,26 @@
*/
static int cause_abort = FALSE;
-// Return true when immediately aborting on error, or when an interrupt
-// occurred or an exception was thrown but not caught. Use for ":{range}call"
-// to check whether an aborted function that does not handle a range itself
-// should be called again for the next line in the range. Also used for
-// cancelling expression evaluation after a function call caused an immediate
-// abort. Note that the first emsg() call temporarily resets "force_abort"
-// until the throw point for error messages has been reached. That is, during
-// cancellation of an expression evaluation after an aborting function call or
-// due to a parsing error, aborting() always returns the same value.
-// "got_int" is also set by calling interrupt().
+/// @return true when immediately aborting on error, or when an interrupt
+/// occurred or an exception was thrown but not caught.
+///
+/// Use for ":{range}call" to check whether an aborted function that does not
+/// handle a range itself should be called again for the next line in the range.
+/// Also used for cancelling expression evaluation after a function call caused
+/// an immediate abort. Note that the first emsg() call temporarily resets
+/// "force_abort" until the throw point for error messages has been reached.
+/// That is, during cancellation of an expression evaluation after an aborting
+/// function call or due to a parsing error, aborting() always returns the same
+/// value. "got_int" is also set by calling interrupt().
int aborting(void)
{
return (did_emsg && force_abort) || got_int || current_exception;
}
-/*
- * The value of "force_abort" is temporarily reset by the first emsg() call
- * during an expression evaluation, and "cause_abort" is used instead. It might
- * be necessary to restore "force_abort" even before the throw point for the
- * error message has been reached. update_force_abort() should be called then.
- */
+/// The value of "force_abort" is temporarily reset by the first emsg() call
+/// during an expression evaluation, and "cause_abort" is used instead. It might
+/// be necessary to restore "force_abort" even before the throw point for the
+/// error message has been reached. update_force_abort() should be called then.
void update_force_abort(void)
{
if (cause_abort) {
@@ -116,23 +115,19 @@ void update_force_abort(void)
}
}
-/*
- * Return TRUE if a command with a subcommand resulting in "retcode" should
- * abort the script processing. Can be used to suppress an autocommand after
- * execution of a failing subcommand as long as the error message has not been
- * displayed and actually caused the abortion.
- */
+/// @return TRUE if a command with a subcommand resulting in "retcode" should
+/// abort the script processing. Can be used to suppress an autocommand after
+/// execution of a failing subcommand as long as the error message has not been
+/// displayed and actually caused the abortion.
int should_abort(int retcode)
{
return (retcode == FAIL && trylevel != 0 && !emsg_silent) || aborting();
}
-/*
- * Return TRUE if a function with the "abort" flag should not be considered
- * ended on an error. This means that parsing commands is continued in order
- * to find finally clauses to be executed, and that some errors in skipped
- * commands are still reported.
- */
+/// @return TRUE if a function with the "abort" flag should not be considered
+/// ended on an error. This means that parsing commands is continued in order
+/// to find finally clauses to be executed, and that some errors in skipped
+/// commands are still reported.
int aborted_in_try(void)
{
// This function is only called after an error. In this case, "force_abort"
@@ -140,13 +135,15 @@ int aborted_in_try(void)
return force_abort;
}
-// cause_errthrow(): Cause a throw of an error exception if appropriate.
-// Return true if the error message should not be displayed by emsg().
-// Sets "ignore", if the emsg() call should be ignored completely.
-//
-// When several messages appear in the same command, the first is usually the
-// most specific one and used as the exception value. The "severe" flag can be
-// set to true, if a later but severer message should be used instead.
+/// cause_errthrow(): Cause a throw of an error exception if appropriate.
+///
+/// @return true if the error message should not be displayed by emsg().
+///
+/// Sets "ignore", if the emsg() call should be ignored completely.
+///
+/// When several messages appear in the same command, the first is usually the
+/// most specific one and used as the exception value. The "severe" flag can be
+/// set to true, if a later but severer message should be used instead.
bool cause_errthrow(const char_u *mesg, bool severe, bool *ignore)
FUNC_ATTR_NONNULL_ALL
{
@@ -279,9 +276,7 @@ bool cause_errthrow(const char_u *mesg, bool severe, bool *ignore)
}
}
-/*
- * Free a "msg_list" and the messages it contains.
- */
+/// Free a "msg_list" and the messages it contains.
static void free_msglist(struct msglist *l)
{
struct msglist *messages, *next;
@@ -295,21 +290,17 @@ static void free_msglist(struct msglist *l)
}
}
-/*
- * Free global "*msg_list" and the messages it contains, then set "*msg_list"
- * to NULL.
- */
+/// Free global "*msg_list" and the messages it contains, then set "*msg_list"
+/// to NULL.
void free_global_msglist(void)
{
free_msglist(*msg_list);
*msg_list = NULL;
}
-/*
- * Throw the message specified in the call to cause_errthrow() above as an
- * error exception. If cstack is NULL, postpone the throw until do_cmdline()
- * has returned (see do_one_cmd()).
- */
+/// Throw the message specified in the call to cause_errthrow() above as an
+/// error exception. If cstack is NULL, postpone the throw until do_cmdline()
+/// has returned (see do_one_cmd()).
void do_errthrow(cstack_T *cstack, char_u *cmdname)
{
/*
@@ -339,11 +330,11 @@ void do_errthrow(cstack_T *cstack, char_u *cmdname)
*msg_list = NULL;
}
-/*
- * do_intthrow(): Replace the current exception by an interrupt or interrupt
- * exception if appropriate. Return TRUE if the current exception is discarded,
- * FALSE otherwise.
- */
+/// do_intthrow(): Replace the current exception by an interrupt or interrupt
+/// exception if appropriate.
+///
+/// @return TRUE if the current exception is discarded or,
+/// FALSE otherwise.
int do_intthrow(cstack_T *cstack)
{
// If no interrupt occurred or no try conditional is active and no exception
@@ -386,7 +377,7 @@ int do_intthrow(cstack_T *cstack)
return true;
}
-// Get an exception message that is to be stored in current_exception->value.
+/// Get an exception message that is to be stored in current_exception->value.
char *get_exception_string(void *value, except_type_T type, char_u *cmdname, int *should_free)
{
char *ret, *mesg;
@@ -430,7 +421,7 @@ char *get_exception_string(void *value, except_type_T type, char_u *cmdname, int
STRCAT(val, p);
p[-2] = NUL;
- sprintf((char *)(val + STRLEN(p)), " (%s)", &mesg[1]);
+ snprintf(val + STRLEN(p), strlen(" (%s)"), " (%s)", &mesg[1]);
p[-2] = '"';
}
break;
@@ -445,10 +436,12 @@ char *get_exception_string(void *value, except_type_T type, char_u *cmdname, int
}
-// Throw a new exception. Return FAIL when out of memory or it was tried to
-// throw an illegal user exception. "value" is the exception string for a
-// user or interrupt exception, or points to a message list in case of an
-// error exception.
+/// Throw a new exception. "value" is the exception string for a
+/// user or interrupt exception, or points to a message list in case of an
+/// error exception.
+///
+/// @return FAIL when out of memory or it was tried to throw an illegal user
+/// exception.
static int throw_exception(void *value, except_type_T type, char_u *cmdname)
{
except_T *excp;
@@ -524,10 +517,8 @@ fail:
return FAIL;
}
-/*
- * Discard an exception. "was_finished" is set when the exception has been
- * caught and the catch clause has been ended normally.
- */
+/// Discard an exception. "was_finished" is set when the exception has been
+/// caught and the catch clause has been ended normally.
static void discard_exception(except_T *excp, bool was_finished)
{
char_u *saved_IObuff;
@@ -579,9 +570,7 @@ static void discard_exception(except_T *excp, bool was_finished)
xfree(excp);
}
-/*
- * Discard the exception currently being thrown.
- */
+/// Discard the exception currently being thrown.
void discard_current_exception(void)
{
if (current_exception != NULL) {
@@ -592,9 +581,7 @@ void discard_current_exception(void)
need_rethrow = false;
}
-/*
- * Put an exception on the caught stack.
- */
+/// Put an exception on the caught stack.
static void catch_exception(except_T *excp)
{
excp->caught = caught_stack;
@@ -640,9 +627,7 @@ static void catch_exception(except_T *excp)
}
}
-/*
- * Remove an exception from the caught stack.
- */
+/// Remove an exception from the caught stack.
static void finish_exception(except_T *excp)
{
if (excp != caught_stack) {
@@ -682,13 +667,11 @@ static void finish_exception(except_T *excp)
#define RP_RESUME 1
#define RP_DISCARD 2
-/*
- * Report information about something pending in a finally clause if required by
- * the 'verbose' option or when debugging. "action" tells whether something is
- * made pending or something pending is resumed or discarded. "pending" tells
- * what is pending. "value" specifies the return value for a pending ":return"
- * or the exception value for a pending exception.
- */
+/// Report information about something pending in a finally clause if required by
+/// the 'verbose' option or when debugging. "action" tells whether something is
+/// made pending or something pending is resumed or discarded. "pending" tells
+/// what is pending. "value" specifies the return value for a pending ":return"
+/// or the exception value for a pending exception.
static void report_pending(int action, int pending, void *value)
{
char *mesg;
@@ -764,10 +747,8 @@ static void report_pending(int action, int pending, void *value)
}
}
-/*
- * If something is made pending in a finally clause, report it if required by
- * the 'verbose' option or when debugging.
- */
+/// If something is made pending in a finally clause, report it if required by
+/// the 'verbose' option or when debugging.
void report_make_pending(int pending, void *value)
{
if (p_verbose >= 14 || debug_break_level > 0) {
@@ -781,10 +762,8 @@ void report_make_pending(int pending, void *value)
}
}
-/*
- * If something pending in a finally clause is resumed at the ":endtry", report
- * it if required by the 'verbose' option or when debugging.
- */
+/// If something pending in a finally clause is resumed at the ":endtry", report
+/// it if required by the 'verbose' option or when debugging.
void report_resume_pending(int pending, void *value)
{
if (p_verbose >= 14 || debug_break_level > 0) {
@@ -798,10 +777,8 @@ void report_resume_pending(int pending, void *value)
}
}
-/*
- * If something pending in a finally clause is discarded, report it if required
- * by the 'verbose' option or when debugging.
- */
+/// If something pending in a finally clause is discarded, report it if required
+/// by the 'verbose' option or when debugging.
void report_discard_pending(int pending, void *value)
{
if (p_verbose >= 14 || debug_break_level > 0) {
@@ -815,7 +792,7 @@ void report_discard_pending(int pending, void *value)
}
}
-// ":eval".
+/// Handle ":eval".
void ex_eval(exarg_T *eap)
{
typval_T tv;
@@ -825,9 +802,7 @@ void ex_eval(exarg_T *eap)
}
}
-/*
- * ":if".
- */
+/// Handle ":if".
void ex_if(exarg_T *eap)
{
int skip;
@@ -856,9 +831,7 @@ void ex_if(exarg_T *eap)
}
}
-/*
- * ":endif".
- */
+/// Handle ":endif".
void ex_endif(exarg_T *eap)
{
did_endif = true;
@@ -883,9 +856,7 @@ void ex_endif(exarg_T *eap)
}
}
-/*
- * ":else" and ":elseif".
- */
+/// Handle ":else" and ":elseif".
void ex_else(exarg_T *eap)
{
int result;
@@ -958,9 +929,7 @@ void ex_else(exarg_T *eap)
}
}
-/*
- * Handle ":while" and ":for".
- */
+/// Handle ":while" and ":for".
void ex_while(exarg_T *eap)
{
bool error;
@@ -1041,9 +1010,7 @@ void ex_while(exarg_T *eap)
}
}
-/*
- * ":continue"
- */
+/// Handle ":continue"
void ex_continue(exarg_T *eap)
{
int idx;
@@ -1075,9 +1042,7 @@ void ex_continue(exarg_T *eap)
}
}
-/*
- * ":break"
- */
+/// Handle ":break"
void ex_break(exarg_T *eap)
{
int idx;
@@ -1098,9 +1063,7 @@ void ex_break(exarg_T *eap)
}
}
-/*
- * ":endwhile" and ":endfor"
- */
+/// Handle ":endwhile" and ":endfor"
void ex_endwhile(exarg_T *eap)
{
cstack_T *const cstack = eap->cstack;
@@ -1175,9 +1138,7 @@ void ex_endwhile(exarg_T *eap)
}
-/*
- * ":throw expr"
- */
+/// Handle ":throw expr"
void ex_throw(exarg_T *eap)
{
const char *arg = (const char *)eap->arg;
@@ -1202,11 +1163,9 @@ void ex_throw(exarg_T *eap)
}
}
-/*
- * Throw the current exception through the specified cstack. Common routine
- * for ":throw" (user exception) and error and interrupt exceptions. Also
- * used for rethrowing an uncaught exception.
- */
+/// Throw the current exception through the specified cstack. Common routine
+/// for ":throw" (user exception) and error and interrupt exceptions. Also
+/// used for rethrowing an uncaught exception.
void do_throw(cstack_T *cstack)
{
int idx;
@@ -1263,9 +1222,7 @@ void do_throw(cstack_T *cstack)
}
}
-/*
- * ":try"
- */
+/// Handle ":try"
void ex_try(exarg_T *eap)
{
int skip;
@@ -1315,9 +1272,7 @@ void ex_try(exarg_T *eap)
}
}
-/*
- * ":catch /{pattern}/" and ":catch"
- */
+/// Handle ":catch /{pattern}/" and ":catch"
void ex_catch(exarg_T *eap)
{
int idx = 0;
@@ -1471,9 +1426,7 @@ void ex_catch(exarg_T *eap)
}
}
-/*
- * ":finally"
- */
+/// Handle ":finally"
void ex_finally(exarg_T *eap)
{
int idx;
@@ -1595,14 +1548,12 @@ void ex_finally(exarg_T *eap)
}
}
-/*
- * ":endtry"
- */
+/// Handle ":endtry"
void ex_endtry(exarg_T *eap)
{
int idx;
bool rethrow = false;
- int pending = CSTP_NONE;
+ char pending = CSTP_NONE;
void *rettv = NULL;
cstack_T *const cstack = eap->cstack;
@@ -1784,14 +1735,12 @@ void ex_endtry(exarg_T *eap)
* error/interrupt/exception state.
*/
-/*
- * This function works a bit like ex_finally() except that there was not
- * actually an extra try block around the part that failed and an error or
- * interrupt has not (yet) been converted to an exception. This function
- * saves the error/interrupt/ exception state and prepares for the call to
- * do_cmdline() that is going to be made for the cleanup autocommand
- * execution.
- */
+/// This function works a bit like ex_finally() except that there was not
+/// actually an extra try block around the part that failed and an error or
+/// interrupt has not (yet) been converted to an exception. This function
+/// saves the error/interrupt/ exception state and prepares for the call to
+/// do_cmdline() that is going to be made for the cleanup autocommand
+/// execution.
void enter_cleanup(cleanup_T *csp)
{
int pending = CSTP_NONE;
@@ -1834,21 +1783,19 @@ void enter_cleanup(cleanup_T *csp)
}
}
-/*
- * See comment above enter_cleanup() for how this function is used.
- *
- * This function is a bit like ex_endtry() except that there was not actually
- * an extra try block around the part that failed and an error or interrupt
- * had not (yet) been converted to an exception when the cleanup autocommand
- * sequence was invoked.
- *
- * This function has to be called with the address of the cleanup_T structure
- * filled by enter_cleanup() as an argument; it restores the error/interrupt/
- * exception state saved by that function - except there was an aborting
- * error, an interrupt or an uncaught exception during execution of the
- * cleanup autocommands. In the latter case, the saved error/interrupt/
- * exception state is discarded.
- */
+/// This function is a bit like ex_endtry() except that there was not actually
+/// an extra try block around the part that failed and an error or interrupt
+/// had not (yet) been converted to an exception when the cleanup autocommand
+/// sequence was invoked.
+///
+/// See comment above enter_cleanup() for how this function is used.
+///
+/// This function has to be called with the address of the cleanup_T structure
+/// filled by enter_cleanup() as an argument; it restores the error/interrupt/
+/// exception state saved by that function - except there was an aborting
+/// error, an interrupt or an uncaught exception during execution of the
+/// cleanup autocommands. In the latter case, the saved error/interrupt/
+/// exception state is discarded.
void leave_cleanup(cleanup_T *csp)
{
int pending = csp->pending;
@@ -1913,22 +1860,25 @@ void leave_cleanup(cleanup_T *csp)
}
-/*
- * Make conditionals inactive and discard what's pending in finally clauses
- * until the conditional type searched for or a try conditional not in its
- * finally clause is reached. If this is in an active catch clause, finish
- * the caught exception.
- * Return the cstack index where the search stopped.
- * Values used for "searched_cond" are (CSF_WHILE | CSF_FOR) or CSF_TRY or 0,
- * the latter meaning the innermost try conditional not in its finally clause.
- * "inclusive" tells whether the conditional searched for should be made
- * inactive itself (a try conditional not in its finally clause possibly find
- * before is always made inactive). If "inclusive" is TRUE and
- * "searched_cond" is CSF_TRY|CSF_SILENT, the saved former value of
- * "emsg_silent", if reset when the try conditional finally reached was
- * entered, is restored (used by ex_endtry()). This is normally done only
- * when such a try conditional is left.
- */
+/// Make conditionals inactive and discard what's pending in finally clauses
+/// until the conditional type searched for or a try conditional not in its
+/// finally clause is reached. If this is in an active catch clause, finish
+/// the caught exception.
+///
+///
+/// @param searched_cond Possible values are (CSF_WHILE | CSF_FOR) or CSF_TRY or 0,
+/// the latter meaning the innermost try conditional not
+/// in its finally clause.
+/// @param inclusive tells whether the conditional searched for should be made
+/// inactive itself (a try conditional not in its finally
+/// clause possibly find before is always made inactive).
+///
+/// If "inclusive" is TRUE and "searched_cond" is CSF_TRY|CSF_SILENT, the saved
+/// former value of "emsg_silent", if reset when the try conditional finally
+/// reached was entered, is restored (used by ex_endtry()). This is normally
+/// done only when such a try conditional is left.
+///
+/// @return the cstack index where the search stopped.
int cleanup_conditionals(cstack_T *cstack, int searched_cond, int inclusive)
{
int idx;
@@ -2037,9 +1987,7 @@ int cleanup_conditionals(cstack_T *cstack, int searched_cond, int inclusive)
return idx;
}
-/*
- * Return an appropriate error message for a missing endwhile/endfor/endif.
- */
+/// @return an appropriate error message for a missing endwhile/endfor/endif.
static char *get_end_emsg(cstack_T *cstack)
{
if (cstack->cs_flags[cstack->cs_idx] & CSF_WHILE) {
@@ -2052,13 +2000,11 @@ static char *get_end_emsg(cstack_T *cstack)
}
-/*
- * Rewind conditionals until index "idx" is reached. "cond_type" and
- * "cond_level" specify a conditional type and the address of a level variable
- * which is to be decremented with each skipped conditional of the specified
- * type.
- * Also free "for info" structures where needed.
- */
+/// Rewind conditionals until index "idx" is reached. "cond_type" and
+/// "cond_level" specify a conditional type and the address of a level variable
+/// which is to be decremented with each skipped conditional of the specified
+/// type.
+/// Also free "for info" structures where needed.
void rewind_conditionals(cstack_T *cstack, int idx, int cond_type, int *cond_level)
{
while (cstack->cs_idx > idx) {
@@ -2072,17 +2018,13 @@ void rewind_conditionals(cstack_T *cstack, int idx, int cond_type, int *cond_lev
}
}
-/*
- * ":endfunction" when not after a ":function"
- */
+/// Handle ":endfunction" when not after a ":function"
void ex_endfunction(exarg_T *eap)
{
emsg(_("E193: :endfunction not inside a function"));
}
-/*
- * Return TRUE if the string "p" looks like a ":while" or ":for" command.
- */
+/// @return TRUE if the string "p" looks like a ":while" or ":for" command.
int has_loop_cmd(char_u *p)
{
int len;
@@ -2104,4 +2046,3 @@ int has_loop_cmd(char_u *p)
}
return FALSE;
}
-
diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c
index ed4475eb1a..c7a6309958 100644
--- a/src/nvim/ex_getln.c
+++ b/src/nvim/ex_getln.c
@@ -231,7 +231,7 @@ static int compl_selected;
/// |:checkhealth| completion items
///
-/// Regenerates on every new command line prompt, to accomodate changes on the
+/// Regenerates on every new command line prompt, to accommodate changes on the
/// runtime files.
typedef struct {
garray_T names; // healthcheck names
@@ -632,7 +632,7 @@ static void may_do_incsearch_highlighting(int firstc, long count, incsearch_stat
validate_cursor();
// May redraw the status line to show the cursor position.
- if (p_ru && curwin->w_status_height > 0) {
+ if (p_ru && (curwin->w_status_height > 0 || global_stl_height() > 0)) {
curwin->w_redr_status = true;
}
@@ -3631,7 +3631,7 @@ void compute_cmdrow(void)
} else {
win_T *wp = lastwin_nofloating();
cmdline_row = wp->w_winrow + wp->w_height
- + wp->w_status_height;
+ + wp->w_hsep_height + wp->w_status_height + global_stl_height();
}
lines_left = cmdline_row;
}
@@ -5049,8 +5049,8 @@ static int ExpandFromContext(expand_T *xp, char_u *pat, int *num_file, char_u **
{ EXPAND_SYNTAX, get_syntax_name, true, true },
{ EXPAND_SYNTIME, get_syntime_arg, true, true },
{ EXPAND_HIGHLIGHT, (ExpandFunc)get_highlight_name, true, true },
- { EXPAND_EVENTS, get_event_name, true, true },
- { EXPAND_AUGROUP, get_augroup_name, true, true },
+ { EXPAND_EVENTS, expand_get_event_name, true, true },
+ { EXPAND_AUGROUP, expand_get_augroup_name, true, true },
{ EXPAND_CSCOPE, get_cscope_name, true, true },
{ EXPAND_SIGN, get_sign_name, true, true },
{ EXPAND_PROFILE, get_profile_name, true, true },
@@ -6589,7 +6589,7 @@ static int open_cmdwin(void)
/// @return true if in the cmdwin, not editing the command line.
bool is_in_cmdwin(void)
- FUNC_ATTR_PURE
+ FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
return cmdwin_type != 0 && get_cmdline_type() == NUL;
}
diff --git a/src/nvim/ex_session.c b/src/nvim/ex_session.c
index ca07174543..0e2b7c0ece 100644
--- a/src/nvim/ex_session.c
+++ b/src/nvim/ex_session.c
@@ -72,7 +72,7 @@ static int ses_winsizes(FILE *fd, int restore_size, win_T *tab_firstwin)
n++;
// restore height when not full height
- if (wp->w_height + wp->w_status_height < topframe->fr_height
+ if (wp->w_height + wp->w_hsep_height + wp->w_status_height < topframe->fr_height
&& (fprintf(fd,
"exe '%dresize ' . ((&lines * %" PRId64
" + %" PRId64 ") / %" PRId64 ")\n",
@@ -365,7 +365,7 @@ static int put_view(FILE *fd, win_T *wp, int add_edit, unsigned *flagp, int curr
// edit that buffer, to not lose folding information (:edit resets
// folds in other buffers)
if (fprintf(fd,
- "if bufexists(\"%s\") | buffer %s | else | edit %s | endif\n"
+ "if bufexists(fnamemodify(\"%s\", \":p\")) | buffer %s | else | edit %s | endif\n"
// Fixup :terminal buffer name. #7836
"if &buftype ==# 'terminal'\n"
" silent file %s\n"
diff --git a/src/nvim/extmark.c b/src/nvim/extmark.c
index 48e57e20e1..6b879f5139 100644
--- a/src/nvim/extmark.c
+++ b/src/nvim/extmark.c
@@ -67,7 +67,9 @@ void extmark_set(buf_T *buf, uint32_t ns_id, uint32_t *idp, int row, colnr_T col
uint8_t decor_level = kDecorLevelNone; // no decor
if (decor) {
- if (kv_size(decor->virt_text) || kv_size(decor->virt_lines)) {
+ if (kv_size(decor->virt_text)
+ || kv_size(decor->virt_lines)
+ || decor_has_sign(decor)) {
decor_full = true;
decor = xmemdup(decor, sizeof *decor);
}
@@ -116,7 +118,7 @@ void extmark_set(buf_T *buf, uint32_t ns_id, uint32_t *idp, int row, colnr_T col
}
mtkey_t mark = { { row, col }, ns_id, id, 0,
- mt_flags(right_gravity, decor_level), 0, NULL };
+ mt_flags(right_gravity, decor_level), 0, NULL };
if (decor_full) {
mark.decor_full = decor;
} else if (decor) {
@@ -142,6 +144,13 @@ revised:
if (kv_size(decor->virt_lines)) {
buf->b_virt_line_blocks++;
}
+ if (decor_has_sign(decor)) {
+ buf->b_signs++;
+ }
+ if (decor->sign_text) {
+ // TODO(lewis6991): smarter invalidation
+ buf_signcols_add_check(buf, NULL);
+ }
decor_redraw(buf, row, end_row > -1 ? end_row : row, decor);
}
diff --git a/src/nvim/extmark.h b/src/nvim/extmark.h
index af9526cd43..b856a1148f 100644
--- a/src/nvim/extmark.h
+++ b/src/nvim/extmark.h
@@ -2,8 +2,8 @@
#define NVIM_EXTMARK_H
#include "nvim/buffer_defs.h"
-#include "nvim/extmark_defs.h"
#include "nvim/decoration.h"
+#include "nvim/extmark_defs.h"
#include "nvim/marktree.h"
#include "nvim/pos.h"
diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c
index f5824d83be..41e67e5b3b 100644
--- a/src/nvim/fileio.c
+++ b/src/nvim/fileio.c
@@ -3,6 +3,8 @@
// fileio.c: read from and write to a file
+// uncrustify:off
+
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
@@ -3796,7 +3798,7 @@ static int set_rw_fname(char_u *fname, char_u *sfname)
// Do filetype detection now if 'filetype' is empty.
if (*curbuf->b_p_ft == NUL) {
- if (au_has_group((char_u *)"filetypedetect")) {
+ if (augroup_exists("filetypedetect")) {
(void)do_doautocmd((char_u *)"filetypedetect BufRead", false, NULL);
}
do_modelines(0);
@@ -3911,13 +3913,13 @@ static int check_mtime(buf_T *buf, FileInfo *file_info)
static bool time_differs(const FileInfo *file_info, long mtime, long mtime_ns) FUNC_ATTR_CONST
{
- return (long)file_info->stat.st_mtim.tv_nsec != mtime_ns
+ return file_info->stat.st_mtim.tv_nsec != mtime_ns
#if defined(__linux__) || defined(MSWIN)
// On a FAT filesystem, esp. under Linux, there are only 5 bits to store
// the seconds. Since the roundoff is done when flushing the inode, the
// time may change unexpectedly by one second!!!
- || (long)file_info->stat.st_mtim.tv_sec - mtime > 1
- || mtime - (long)file_info->stat.st_mtim.tv_sec > 1;
+ || file_info->stat.st_mtim.tv_sec - mtime > 1
+ || mtime - file_info->stat.st_mtim.tv_sec > 1;
#else
|| (long)file_info->stat.st_mtim.tv_sec != mtime;
#endif
@@ -4961,9 +4963,8 @@ int buf_check_timestamp(buf_T *buf)
buf_store_file_info(buf, &file_info);
}
- // Don't do anything for a directory. Might contain the file
- // explorer.
if (os_isdir(buf->b_fname)) {
+ // Don't do anything for a directory. Might contain the file explorer.
} else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
&& !bufIsChanged(buf) && file_info_ok) {
// If 'autoread' is set, the buffer has no changes and the file still
diff --git a/src/nvim/fold.c b/src/nvim/fold.c
index 546345eeac..54430d46af 100644
--- a/src/nvim/fold.c
+++ b/src/nvim/fold.c
@@ -121,9 +121,7 @@ static size_t foldendmarkerlen;
// Exported folding functions. {{{1
// copyFoldingState() {{{2
-/*
- * Copy that folding state from window "wp_from" to window "wp_to".
- */
+/// Copy that folding state from window "wp_from" to window "wp_to".
void copyFoldingState(win_T *wp_from, win_T *wp_to)
{
wp_to->w_fold_manual = wp_from->w_fold_manual;
@@ -132,9 +130,7 @@ void copyFoldingState(win_T *wp_from, win_T *wp_to)
}
// hasAnyFolding() {{{2
-/*
- * Return TRUE if there may be folded lines in the current window.
- */
+/// @return TRUE if there may be folded lines in the current window.
int hasAnyFolding(win_T *win)
{
// very simple now, but can become more complex later
@@ -259,9 +255,7 @@ bool hasFoldingWin(win_T *const win, const linenr_T lnum, linenr_T *const firstp
}
// foldLevel() {{{2
-/*
- * Return fold level at line number "lnum" in the current window.
- */
+/// @return fold level at line number "lnum" in the current window.
int foldLevel(linenr_T lnum)
{
// While updating the folds lines between invalid_top and invalid_bot have
@@ -283,15 +277,16 @@ int foldLevel(linenr_T lnum)
}
// lineFolded() {{{2
-// Low level function to check if a line is folded. Doesn't use any caching.
-// Return true if line is folded.
-// Return false if line is not folded.
+/// Low level function to check if a line is folded. Doesn't use any caching.
+///
+/// @return true if line is folded or,
+/// false if line is not folded.
bool lineFolded(win_T *const win, const linenr_T lnum)
{
return fold_info(win, lnum).fi_lines != 0;
}
-/// fold_info() {{{2
+// fold_info() {{{2
///
/// Count the number of lines that are folded at line number "lnum".
/// Normally "lnum" is the first line of a possible fold, and the returned
@@ -316,61 +311,49 @@ foldinfo_T fold_info(win_T *win, linenr_T lnum)
}
// foldmethodIsManual() {{{2
-/*
- * Return TRUE if 'foldmethod' is "manual"
- */
+/// @return TRUE if 'foldmethod' is "manual"
int foldmethodIsManual(win_T *wp)
{
return wp->w_p_fdm[3] == 'u';
}
// foldmethodIsIndent() {{{2
-/*
- * Return TRUE if 'foldmethod' is "indent"
- */
+/// @return TRUE if 'foldmethod' is "indent"
int foldmethodIsIndent(win_T *wp)
{
return wp->w_p_fdm[0] == 'i';
}
// foldmethodIsExpr() {{{2
-/*
- * Return TRUE if 'foldmethod' is "expr"
- */
+/// @return TRUE if 'foldmethod' is "expr"
int foldmethodIsExpr(win_T *wp)
{
return wp->w_p_fdm[1] == 'x';
}
// foldmethodIsMarker() {{{2
-/*
- * Return TRUE if 'foldmethod' is "marker"
- */
+/// @return TRUE if 'foldmethod' is "marker"
int foldmethodIsMarker(win_T *wp)
{
return wp->w_p_fdm[2] == 'r';
}
// foldmethodIsSyntax() {{{2
-/*
- * Return TRUE if 'foldmethod' is "syntax"
- */
+/// @return TRUE if 'foldmethod' is "syntax"
int foldmethodIsSyntax(win_T *wp)
{
return wp->w_p_fdm[0] == 's';
}
// foldmethodIsDiff() {{{2
-/*
- * Return TRUE if 'foldmethod' is "diff"
- */
+/// @return TRUE if 'foldmethod' is "diff"
int foldmethodIsDiff(win_T *wp)
{
return wp->w_p_fdm[0] == 'd';
}
// closeFold() {{{2
-/// Close fold for current window at line "lnum".
+/// Close fold for current window at position "pos".
/// Repeat "count" times.
void closeFold(pos_T pos, long count)
{
@@ -378,9 +361,7 @@ void closeFold(pos_T pos, long count)
}
// closeFoldRecurse() {{{2
-/*
- * Close fold for current window at line "lnum" recursively.
- */
+/// Close fold for current window at position `pos` recursively.
void closeFoldRecurse(pos_T pos)
{
(void)setManualFold(pos, false, true, NULL);
@@ -427,28 +408,22 @@ void opFoldRange(pos_T firstpos, pos_T lastpos, int opening, int recurse, int ha
}
// openFold() {{{2
-/*
- * Open fold for current window at line "lnum".
- * Repeat "count" times.
- */
+/// Open fold for current window at position "pos".
+/// Repeat "count" times.
void openFold(pos_T pos, long count)
{
setFoldRepeat(pos, count, true);
}
// openFoldRecurse() {{{2
-/*
- * Open fold for current window at line "lnum" recursively.
- */
+/// Open fold for current window at position `pos` recursively.
void openFoldRecurse(pos_T pos)
{
(void)setManualFold(pos, true, true, NULL);
}
// foldOpenCursor() {{{2
-/*
- * Open folds until the cursor line is not in a closed fold.
- */
+/// Open folds until the cursor line is not in a closed fold.
void foldOpenCursor(void)
{
int done;
@@ -466,9 +441,7 @@ void foldOpenCursor(void)
}
// newFoldLevel() {{{2
-/*
- * Set new foldlevel for current window.
- */
+/// Set new foldlevel for current window.
void newFoldLevel(void)
{
newFoldLevelWin(curwin);
@@ -505,9 +478,7 @@ static void newFoldLevelWin(win_T *wp)
}
// foldCheckClose() {{{2
-/*
- * Apply 'foldlevel' to all folds that don't contain the cursor.
- */
+/// Apply 'foldlevel' to all folds that don't contain the cursor.
void foldCheckClose(void)
{
if (*p_fcl != NUL) { // can only be "all" right now
@@ -543,8 +514,8 @@ static int checkCloseRec(garray_T *gap, linenr_T lnum, int level)
}
// foldCreateAllowed() {{{2
-/// Return TRUE if it's allowed to manually create or delete a fold.
-/// Give an error message and return FALSE if not.
+/// @return TRUE if it's allowed to manually create or delete a fold or,
+/// give an error message and return FALSE if not.
int foldManualAllowed(bool create)
{
if (foldmethodIsManual(curwin) || foldmethodIsMarker(curwin)) {
@@ -790,9 +761,7 @@ void deleteFold(win_T *const wp, const linenr_T start, const linenr_T end, const
}
// clearFolding() {{{2
-/*
- * Remove all folding for window "win".
- */
+/// Remove all folding for window "win".
void clearFolding(win_T *win)
{
deleteFoldRecurse(win->w_buffer, &win->w_folds);
@@ -800,12 +769,10 @@ void clearFolding(win_T *win)
}
// foldUpdate() {{{2
-/*
- * Update folds for changes in the buffer of a window.
- * Note that inserted/deleted lines must have already been taken care of by
- * calling foldMarkAdjust().
- * The changes in lines from top to bot (inclusive).
- */
+/// Update folds for changes in the buffer of a window.
+/// Note that inserted/deleted lines must have already been taken care of by
+/// calling foldMarkAdjust().
+/// The changes in lines from top to bot (inclusive).
void foldUpdate(win_T *wp, linenr_T top, linenr_T bot)
{
if (compl_busy || State & INSERT) {
@@ -856,12 +823,10 @@ void foldUpdateAfterInsert(void)
}
// foldUpdateAll() {{{2
-/*
- * Update all lines in a window for folding.
- * Used when a fold setting changes or after reloading the buffer.
- * The actual updating is postponed until fold info is used, to avoid doing
- * every time a setting is changed or a syntax item is added.
- */
+/// Update all lines in a window for folding.
+/// Used when a fold setting changes or after reloading the buffer.
+/// The actual updating is postponed until fold info is used, to avoid doing
+/// every time a setting is changed or a syntax item is added.
void foldUpdateAll(win_T *win)
{
win->w_foldinvalid = true;
@@ -992,21 +957,18 @@ int foldMoveTo(const bool updown, const int dir, const long count)
}
// foldInitWin() {{{2
-/*
- * Init the fold info in a new window.
- */
+/// Init the fold info in a new window.
void foldInitWin(win_T *new_win)
{
ga_init(&new_win->w_folds, (int)sizeof(fold_T), 10);
}
// find_wl_entry() {{{2
-/*
- * Find an entry in the win->w_lines[] array for buffer line "lnum".
- * Only valid entries are considered (for entries where wl_valid is FALSE the
- * line number can be wrong).
- * Returns index of entry or -1 if not found.
- */
+/// Find an entry in the win->w_lines[] array for buffer line "lnum".
+/// Only valid entries are considered (for entries where wl_valid is FALSE the
+/// line number can be wrong).
+///
+/// @return index of entry or -1 if not found.
int find_wl_entry(win_T *win, linenr_T lnum)
{
int i;
@@ -1025,9 +987,7 @@ int find_wl_entry(win_T *win, linenr_T lnum)
}
// foldAdjustVisual() {{{2
-/*
- * Adjust the Visual area to include any fold at the start or end completely.
- */
+/// Adjust the Visual area to include any fold at the start or end completely.
void foldAdjustVisual(void)
{
pos_T *start, *end;
@@ -1059,9 +1019,7 @@ void foldAdjustVisual(void)
}
// cursor_foldstart() {{{2
-/*
- * Move the cursor to the first line of a closed fold.
- */
+/// Move the cursor to the first line of a closed fold.
void foldAdjustCursor(void)
{
(void)hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL);
@@ -1069,9 +1027,7 @@ void foldAdjustCursor(void)
// Internal functions for "fold_T" {{{1
// cloneFoldGrowArray() {{{2
-/*
- * Will "clone" (i.e deep copy) a garray_T of folds.
- */
+/// Will "clone" (i.e deep copy) a garray_T of folds.
void cloneFoldGrowArray(garray_T *from, garray_T *to)
{
fold_T *from_p;
@@ -1143,9 +1099,7 @@ static bool foldFind(const garray_T *gap, linenr_T lnum, fold_T **fpp)
}
// foldLevelWin() {{{2
-/*
- * Return fold level at line number "lnum" in window "wp".
- */
+/// @return fold level at line number "lnum" in window "wp".
static int foldLevelWin(win_T *wp, linenr_T lnum)
{
fold_T *fp;
@@ -1169,9 +1123,7 @@ static int foldLevelWin(win_T *wp, linenr_T lnum)
}
// checkupdate() {{{2
-/*
- * Check if the folds in window "wp" are invalid and update them if needed.
- */
+/// Check if the folds in window "wp" are invalid and update them if needed.
static void checkupdate(win_T *wp)
{
if (wp->w_foldinvalid) {
@@ -1181,10 +1133,8 @@ static void checkupdate(win_T *wp)
}
// setFoldRepeat() {{{2
-/*
- * Open or close fold for current window at line "lnum".
- * Repeat "count" times.
- */
+/// Open or close fold for current window at position `pos`.
+/// Repeat "count" times.
static void setFoldRepeat(pos_T pos, long count, int do_open)
{
int done;
@@ -1204,7 +1154,6 @@ static void setFoldRepeat(pos_T pos, long count, int do_open)
}
// setManualFold() {{{2
-///
/// Open or close the fold in the current window which contains "lnum".
/// Also does this for other windows in diff mode when needed.
///
@@ -1344,9 +1293,7 @@ static linenr_T setManualFoldWin(win_T *wp, linenr_T lnum, int opening, int recu
}
// foldOpenNested() {{{2
-/*
- * Open all nested folds in fold "fpr" recursively.
- */
+/// Open all nested folds in fold "fpr" recursively.
static void foldOpenNested(fold_T *fpr)
{
fold_T *fp;
@@ -1359,9 +1306,10 @@ static void foldOpenNested(fold_T *fpr)
}
// deleteFoldEntry() {{{2
-// Delete fold "idx" from growarray "gap".
-// When "recursive" is true also delete all the folds contained in it.
-// When "recursive" is false contained folds are moved one level up.
+/// Delete fold "idx" from growarray "gap".
+///
+/// @param recursive when true, also delete all the folds contained in it.
+/// when false, contained folds are moved one level up.
static void deleteFoldEntry(win_T *const wp, garray_T *const gap, const int idx,
const bool recursive)
{
@@ -1408,9 +1356,7 @@ static void deleteFoldEntry(win_T *const wp, garray_T *const gap, const int idx,
}
// deleteFoldRecurse() {{{2
-/*
- * Delete nested folds in a fold.
- */
+/// Delete nested folds in a fold.
void deleteFoldRecurse(buf_T *bp, garray_T *gap)
{
#define DELETE_FOLD_NESTED(fd) deleteFoldRecurse(bp, &((fd)->fd_nested))
@@ -1418,9 +1364,7 @@ void deleteFoldRecurse(buf_T *bp, garray_T *gap)
}
// foldMarkAdjust() {{{2
-/*
- * Update line numbers of folds for inserted/deleted lines.
- */
+/// Update line numbers of folds for inserted/deleted lines.
void foldMarkAdjust(win_T *wp, linenr_T line1, linenr_T line2, long amount, long amount_after)
{
// If deleting marks from line1 to line2, but not deleting all those
@@ -1538,10 +1482,8 @@ static void foldMarkAdjustRecurse(win_T *wp, garray_T *gap, linenr_T line1, line
}
// getDeepestNesting() {{{2
-/*
- * Get the lowest 'foldlevel' value that makes the deepest nested fold in the
- * current window open.
- */
+/// Get the lowest 'foldlevel' value that makes the deepest nested fold in
+/// window `wp`.
int getDeepestNesting(win_T *wp)
{
checkupdate(wp);
@@ -1633,7 +1575,7 @@ static void checkSmall(win_T *const wp, fold_T *const fp, const linenr_T lnum_of
}
// setSmallMaybe() {{{2
-// Set small flags in "gap" to kNone.
+/// Set small flags in "gap" to kNone.
static void setSmallMaybe(garray_T *gap)
{
fold_T *fp = (fold_T *)gap->ga_data;
@@ -1643,10 +1585,8 @@ static void setSmallMaybe(garray_T *gap)
}
// foldCreateMarkers() {{{2
-/*
- * Create a fold from line "start" to line "end" (inclusive) in the current
- * window by adding markers.
- */
+/// Create a fold from line "start" to line "end" (inclusive) in window `wp`
+/// by adding markers.
static void foldCreateMarkers(win_T *wp, pos_T start, pos_T end)
{
buf_T *buf = wp->w_buffer;
@@ -1672,9 +1612,7 @@ static void foldCreateMarkers(win_T *wp, pos_T start, pos_T end)
}
// foldAddMarker() {{{2
-/*
- * Add "marker[markerlen]" in 'commentstring' to line "lnum".
- */
+/// Add "marker[markerlen]" in 'commentstring' to position `pos`.
static void foldAddMarker(buf_T *buf, pos_T pos, const char_u *marker, size_t markerlen)
{
char_u *cms = buf->b_p_cms;
@@ -1731,11 +1669,10 @@ static void deleteFoldMarkers(win_T *wp, fold_T *fp, int recursive, linenr_T lnu
}
// foldDelMarker() {{{2
-//
-// Delete marker "marker[markerlen]" at the end of line "lnum".
-// Delete 'commentstring' if it matches.
-// If the marker is not found, there is no error message. Could be a missing
-// close-marker.
+/// Delete marker "marker[markerlen]" at the end of line "lnum".
+/// Delete 'commentstring' if it matches.
+/// If the marker is not found, there is no error message. Could be a missing
+/// close-marker.
static void foldDelMarker(buf_T *buf, linenr_T lnum, char_u *marker, size_t markerlen)
{
char_u *newline;
@@ -1892,9 +1829,7 @@ char_u *get_foldtext(win_T *wp, linenr_T lnum, linenr_T lnume, foldinfo_T foldin
}
// foldtext_cleanup() {{{2
-/*
- * Remove 'foldmarker' and 'commentstring' from "str" (in-place).
- */
+/// Remove 'foldmarker' and 'commentstring' from "str" (in-place).
void foldtext_cleanup(char_u *str)
{
char_u *s;
@@ -1974,10 +1909,8 @@ void foldtext_cleanup(char_u *str)
// Function declarations. {{{2
// foldUpdateIEMS() {{{2
-/*
- * Update the folding for window "wp", at least from lines "top" to "bot".
- * IEMS = "Indent Expr Marker Syntax"
- */
+/// Update the folding for window "wp", at least from lines "top" to "bot".
+/// IEMS = "Indent Expr Marker Syntax"
static void foldUpdateIEMS(win_T *const wp, linenr_T top, linenr_T bot)
{
fline_T fline;
@@ -2640,9 +2573,7 @@ static linenr_T foldUpdateIEMSRecurse(garray_T *const gap, const int level,
}
// foldInsert() {{{2
-/*
- * Insert a new fold in "gap" at position "i".
- */
+/// Insert a new fold in "gap" at position "i".
static void foldInsert(garray_T *gap, int i)
{
fold_T *fp;
@@ -2658,13 +2589,11 @@ static void foldInsert(garray_T *gap, int i)
}
// foldSplit() {{{2
-/*
- * Split the "i"th fold in "gap", which starts before "top" and ends below
- * "bot" in two pieces, one ending above "top" and the other starting below
- * "bot".
- * The caller must first have taken care of any nested folds from "top" to
- * "bot"!
- */
+/// Split the "i"th fold in "gap", which starts before "top" and ends below
+/// "bot" in two pieces, one ending above "top" and the other starting below
+/// "bot".
+/// The caller must first have taken care of any nested folds from "top" to
+/// "bot"!
static void foldSplit(buf_T *buf, garray_T *const gap, const int i, const linenr_T top,
const linenr_T bot)
{
@@ -2704,24 +2633,22 @@ static void foldSplit(buf_T *buf, garray_T *const gap, const int i, const linenr
}
// foldRemove() {{{2
-/*
- * Remove folds within the range "top" to and including "bot".
- * Check for these situations:
- * 1 2 3
- * 1 2 3
- * top 2 3 4 5
- * 2 3 4 5
- * bot 2 3 4 5
- * 3 5 6
- * 3 5 6
- *
- * 1: not changed
- * 2: truncate to stop above "top"
- * 3: split in two parts, one stops above "top", other starts below "bot".
- * 4: deleted
- * 5: made to start below "bot".
- * 6: not changed
- */
+/// Remove folds within the range "top" to and including "bot".
+/// Check for these situations:
+/// 1 2 3
+/// 1 2 3
+/// top 2 3 4 5
+/// 2 3 4 5
+/// bot 2 3 4 5
+/// 3 5 6
+/// 3 5 6
+///
+/// 1: not changed
+/// 2: truncate to stop above "top"
+/// 3: split in two parts, one stops above "top", other starts below "bot".
+/// 4: deleted
+/// 5: made to start below "bot".
+/// 6: not changed
static void foldRemove(win_T *const wp, garray_T *gap, linenr_T top, linenr_T bot)
{
fold_T *fp = NULL;
@@ -2786,35 +2713,35 @@ static void foldReverseOrder(garray_T *gap, const linenr_T start_arg, const line
}
// foldMoveRange() {{{2
-// Move folds within the inclusive range "line1" to "line2" to after "dest"
-// require "line1" <= "line2" <= "dest"
-//
-// There are the following situations for the first fold at or below line1 - 1.
-// 1 2 3 4
-// 1 2 3 4
-// line1 2 3 4
-// 2 3 4 5 6 7
-// line2 3 4 5 6 7
-// 3 4 6 7 8 9
-// dest 4 7 8 9
-// 4 7 8 10
-// 4 7 8 10
-//
-// In the following descriptions, "moved" means moving in the buffer, *and* in
-// the fold array.
-// Meanwhile, "shifted" just means moving in the buffer.
-// 1. not changed
-// 2. truncated above line1
-// 3. length reduced by line2 - line1, folds starting between the end of 3 and
-// dest are truncated and shifted up
-// 4. internal folds moved (from [line1, line2] to dest)
-// 5. moved to dest.
-// 6. truncated below line2 and moved.
-// 7. length reduced by line2 - dest, folds starting between line2 and dest are
-// removed, top is moved down by move_len.
-// 8. truncated below dest and shifted up.
-// 9. shifted up
-// 10. not changed
+/// Move folds within the inclusive range "line1" to "line2" to after "dest"
+/// require "line1" <= "line2" <= "dest"
+///
+/// There are the following situations for the first fold at or below line1 - 1.
+/// 1 2 3 4
+/// 1 2 3 4
+/// line1 2 3 4
+/// 2 3 4 5 6 7
+/// line2 3 4 5 6 7
+/// 3 4 6 7 8 9
+/// dest 4 7 8 9
+/// 4 7 8 10
+/// 4 7 8 10
+///
+/// In the following descriptions, "moved" means moving in the buffer, *and* in
+/// the fold array.
+/// Meanwhile, "shifted" just means moving in the buffer.
+/// 1. not changed
+/// 2. truncated above line1
+/// 3. length reduced by line2 - line1, folds starting between the end of 3 and
+/// dest are truncated and shifted up
+/// 4. internal folds moved (from [line1, line2] to dest)
+/// 5. moved to dest.
+/// 6. truncated below line2 and moved.
+/// 7. length reduced by line2 - dest, folds starting between line2 and dest are
+/// removed, top is moved down by move_len.
+/// 8. truncated below dest and shifted up.
+/// 9. shifted up
+/// 10. not changed
static void truncate_fold(win_T *const wp, fold_T *fp, linenr_T end)
{
// I want to stop *at here*, foldRemove() stops *above* top
@@ -2929,13 +2856,11 @@ void foldMoveRange(win_T *const wp, garray_T *gap, const linenr_T line1, const l
#undef FOLD_INDEX
// foldMerge() {{{2
-/*
- * Merge two adjacent folds (and the nested ones in them).
- * This only works correctly when the folds are really adjacent! Thus "fp1"
- * must end just above "fp2".
- * The resulting fold is "fp1", nested folds are moved from "fp2" to "fp1".
- * Fold entry "fp2" in "gap" is deleted.
- */
+/// Merge two adjacent folds (and the nested ones in them).
+/// This only works correctly when the folds are really adjacent! Thus "fp1"
+/// must end just above "fp2".
+/// The resulting fold is "fp1", nested folds are moved from "fp2" to "fp1".
+/// Fold entry "fp2" in "gap" is deleted.
static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2)
{
fold_T *fp3;
@@ -2968,11 +2893,10 @@ static void foldMerge(win_T *const wp, fold_T *fp1, garray_T *gap, fold_T *fp2)
}
// foldlevelIndent() {{{2
-/*
- * Low level function to get the foldlevel for the "indent" method.
- * Doesn't use any caching.
- * Returns a level of -1 if the foldlevel depends on surrounding lines.
- */
+/// Low level function to get the foldlevel for the "indent" method.
+/// Doesn't use any caching.
+///
+/// @return a level of -1 if the foldlevel depends on surrounding lines.
static void foldlevelIndent(fline_T *flp)
{
char_u *s;
@@ -3000,10 +2924,8 @@ static void foldlevelIndent(fline_T *flp)
}
// foldlevelDiff() {{{2
-/*
- * Low level function to get the foldlevel for the "diff" method.
- * Doesn't use any caching.
- */
+/// Low level function to get the foldlevel for the "diff" method.
+/// Doesn't use any caching.
static void foldlevelDiff(fline_T *flp)
{
if (diff_infold(flp->wp, flp->lnum + flp->off)) {
@@ -3014,11 +2936,10 @@ static void foldlevelDiff(fline_T *flp)
}
// foldlevelExpr() {{{2
-/*
- * Low level function to get the foldlevel for the "expr" method.
- * Doesn't use any caching.
- * Returns a level of -1 if the foldlevel depends on surrounding lines.
- */
+/// Low level function to get the foldlevel for the "expr" method.
+/// Doesn't use any caching.
+///
+/// @return a level of -1 if the foldlevel depends on surrounding lines.
static void foldlevelExpr(fline_T *flp)
{
win_T *win;
@@ -3113,11 +3034,9 @@ static void foldlevelExpr(fline_T *flp)
}
// parseMarker() {{{2
-/*
- * Parse 'foldmarker' and set "foldendmarker", "foldstartmarkerlen" and
- * "foldendmarkerlen".
- * Relies on the option value to have been checked for correctness already.
- */
+/// Parse 'foldmarker' and set "foldendmarker", "foldstartmarkerlen" and
+/// "foldendmarkerlen".
+/// Relies on the option value to have been checked for correctness already.
static void parseMarker(win_T *wp)
{
foldendmarker = vim_strchr(wp->w_p_fmr, ',');
@@ -3126,15 +3045,13 @@ static void parseMarker(win_T *wp)
}
// foldlevelMarker() {{{2
-/*
- * Low level function to get the foldlevel for the "marker" method.
- * "foldendmarker", "foldstartmarkerlen" and "foldendmarkerlen" must have been
- * set before calling this.
- * Requires that flp->lvl is set to the fold level of the previous line!
- * Careful: This means you can't call this function twice on the same line.
- * Doesn't use any caching.
- * Sets flp->start when a start marker was found.
- */
+/// Low level function to get the foldlevel for the "marker" method.
+/// "foldendmarker", "foldstartmarkerlen" and "foldendmarkerlen" must have been
+/// set before calling this.
+/// Requires that flp->lvl is set to the fold level of the previous line!
+/// Careful: This means you can't call this function twice on the same line.
+/// Doesn't use any caching.
+/// Sets flp->start when a start marker was found.
static void foldlevelMarker(fline_T *flp)
{
char_u *startmarker;
@@ -3205,10 +3122,8 @@ static void foldlevelMarker(fline_T *flp)
}
// foldlevelSyntax() {{{2
-/*
- * Low level function to get the foldlevel for the "syntax" method.
- * Doesn't use any caching.
- */
+/// Low level function to get the foldlevel for the "syntax" method.
+/// Doesn't use any caching.
static void foldlevelSyntax(fline_T *flp)
{
linenr_T lnum = flp->lnum + flp->off;
@@ -3228,11 +3143,9 @@ static void foldlevelSyntax(fline_T *flp)
// functions for storing the fold state in a View {{{1
// put_folds() {{{2
-
-/*
- * Write commands to "fd" to restore the manual folds in window "wp".
- * Return FAIL if writing fails.
- */
+/// Write commands to "fd" to restore the manual folds in window "wp".
+///
+/// @return FAIL if writing fails.
int put_folds(FILE *fd, win_T *wp)
{
if (foldmethodIsManual(wp)) {
@@ -3252,10 +3165,9 @@ int put_folds(FILE *fd, win_T *wp)
}
// put_folds_recurse() {{{2
-/*
- * Write commands to "fd" to recreate manually created folds.
- * Returns FAIL when writing failed.
- */
+/// Write commands to "fd" to recreate manually created folds.
+///
+/// @return FAIL when writing failed.
static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off)
{
fold_T *fp = (fold_T *)gap->ga_data;
@@ -3276,10 +3188,9 @@ static int put_folds_recurse(FILE *fd, garray_T *gap, linenr_T off)
}
// put_foldopen_recurse() {{{2
-/*
- * Write commands to "fd" to open and close manually opened/closed folds.
- * Returns FAIL when writing failed.
- */
+/// Write commands to "fd" to open and close manually opened/closed folds.
+///
+/// @return FAIL when writing failed.
static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off)
{
int level;
@@ -3325,10 +3236,9 @@ static int put_foldopen_recurse(FILE *fd, win_T *wp, garray_T *gap, linenr_T off
}
// put_fold_open_close() {{{2
-/*
- * Write the open or close command to "fd".
- * Returns FAIL when writing failed.
- */
+/// Write the open or close command to "fd".
+///
+/// @return FAIL when writing failed.
static int put_fold_open_close(FILE *fd, fold_T *fp, linenr_T off)
{
if (fprintf(fd, "%" PRId64, (int64_t)(fp->fd_top + off)) < 0
diff --git a/src/nvim/generators/c_grammar.lua b/src/nvim/generators/c_grammar.lua
index f35817c466..70a7be86b5 100644
--- a/src/nvim/generators/c_grammar.lua
+++ b/src/nvim/generators/c_grammar.lua
@@ -49,6 +49,7 @@ local c_proto = Ct(
(fill * Cg((P('FUNC_API_REMOTE_IMPL') * Cc(true)), 'remote_impl') ^ -1) *
(fill * Cg((P('FUNC_API_BRIDGE_IMPL') * Cc(true)), 'bridge_impl') ^ -1) *
(fill * Cg((P('FUNC_API_COMPOSITOR_IMPL') * Cc(true)), 'compositor_impl') ^ -1) *
+ (fill * Cg((P('FUNC_API_CLIENT_IMPL') * Cc(true)), 'client_impl') ^ -1) *
fill * P(';')
)
diff --git a/src/nvim/generators/gen_api_ui_events.lua b/src/nvim/generators/gen_api_ui_events.lua
index 3cb117d8b5..5e70442dce 100644..100755
--- a/src/nvim/generators/gen_api_ui_events.lua
+++ b/src/nvim/generators/gen_api_ui_events.lua
@@ -3,13 +3,14 @@ local mpack = require('mpack')
local nvimdir = arg[1]
package.path = nvimdir .. '/?.lua;' .. package.path
-assert(#arg == 7)
+assert(#arg == 8)
local input = io.open(arg[2], 'rb')
local proto_output = io.open(arg[3], 'wb')
local call_output = io.open(arg[4], 'wb')
local remote_output = io.open(arg[5], 'wb')
local bridge_output = io.open(arg[6], 'wb')
local metadata_output = io.open(arg[7], 'wb')
+local client_output = io.open(arg[8], 'wb')
local c_grammar = require('generators.c_grammar')
local events = c_grammar.grammar:match(input:read('*all'))
@@ -50,6 +51,52 @@ local function write_arglist(output, ev, need_copy)
end
end
+local function call_ui_event_method(output, ev)
+ output:write('void ui_client_event_'..ev.name..'(Array args)\n{\n')
+
+ local hlattrs_args_count = 0
+ if #ev.parameters > 0 then
+ output:write(' if (args.size < '..(#ev.parameters))
+ for j = 1, #ev.parameters do
+ local kind = ev.parameters[j][1]
+ if kind ~= "Object" then
+ if kind == 'HlAttrs' then kind = 'Dictionary' end
+ output:write('\n || args.items['..(j-1)..'].type != kObjectType'..kind..'')
+ end
+ end
+ output:write(') {\n')
+ output:write(' ELOG("Error handling ui event \''..ev.name..'\'");\n')
+ output:write(' return;\n')
+ output:write(' }\n')
+ end
+
+ for j = 1, #ev.parameters do
+ local param = ev.parameters[j]
+ local kind = param[1]
+ output:write(' '..kind..' arg_'..j..' = ')
+ if kind == 'HlAttrs' then
+ -- The first HlAttrs argument is rgb_attrs and second is cterm_attrs
+ output:write('ui_client_dict2hlattrs(args.items['..(j-1)..'].data.dictionary, '..(hlattrs_args_count == 0 and 'true' or 'false')..');\n')
+ hlattrs_args_count = hlattrs_args_count + 1
+ elseif kind == 'Object' then
+ output:write('args.items['..(j-1)..'];\n')
+ else
+ output:write('args.items['..(j-1)..'].data.'..string.lower(kind)..';\n')
+ end
+ end
+
+ output:write(' ui_call_'..ev.name..'(')
+ for j = 1, #ev.parameters do
+ output:write('arg_'..j)
+ if j ~= #ev.parameters then
+ output:write(', ')
+ end
+ end
+ output:write(');\n')
+
+ output:write('}\n\n')
+end
+
for i = 1, #events do
local ev = events[i]
assert(ev.return_type == 'void')
@@ -160,12 +207,35 @@ for i = 1, #events do
call_output:write(";\n")
call_output:write("}\n\n")
end
+
+ if (not ev.remote_only) and (not ev.noexport) and (not ev.client_impl) then
+ call_ui_event_method(client_output, ev)
+ end
end
+-- Generate the map_init method for client handlers
+client_output:write([[
+void ui_client_methods_table_init(void)
+{
+
+]])
+
+for i = 1, #events do
+ local fn = events[i]
+ if (not fn.noexport) and ((not fn.remote_only) or fn.client_impl) then
+ client_output:write(' add_ui_client_event_handler('..
+ '(String) {.data = "'..fn.name..'", '..
+ '.size = sizeof("'..fn.name..'") - 1}, '..
+ '(UIClientHandler) ui_client_event_'..fn.name..');\n')
+ end
+end
+
+client_output:write('\n}\n\n')
+
proto_output:close()
call_output:close()
remote_output:close()
-bridge_output:close()
+client_output:close()
-- don't expose internal attributes like "impl_name" in public metadata
local exported_attributes = {'name', 'parameters',
diff --git a/src/nvim/generators/gen_char_blob.lua b/src/nvim/generators/gen_char_blob.lua
index 3ec1ff2caf..11f6cbcc13 100644
--- a/src/nvim/generators/gen_char_blob.lua
+++ b/src/nvim/generators/gen_char_blob.lua
@@ -28,16 +28,19 @@ local target = io.open(target_file, 'w')
target:write('#include <stdint.h>\n\n')
+local index_items = {}
+
local warn_on_missing_compiler = true
-local varnames = {}
+local modnames = {}
for argi = 2, #arg, 2 do
local source_file = arg[argi]
- local varname = arg[argi + 1]
- if varnames[varname] then
- error(string.format("varname %q is already specified for file %q", varname, varnames[varname]))
+ local modname = arg[argi + 1]
+ if modnames[modname] then
+ error(string.format("modname %q is already specified for file %q", modname, modnames[modname]))
end
- varnames[varname] = source_file
+ modnames[modname] = source_file
+ local varname = string.gsub(modname,'%.','_dot_').."_module"
target:write(('static const uint8_t %s[] = {\n'):format(varname))
local output
@@ -78,6 +81,13 @@ for argi = 2, #arg, 2 do
end
target:write(' 0};\n')
+ if modname ~= "_" then
+ table.insert(index_items, ' { "'..modname..'", '..varname..', sizeof '..varname..' },\n\n')
+ end
end
+target:write('static ModuleDef builtin_modules[] = {\n')
+target:write(table.concat(index_items))
+target:write('};\n')
+
target:close()
diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c
index 741fc6d803..3ec5d24753 100644
--- a/src/nvim/getchar.c
+++ b/src/nvim/getchar.c
@@ -842,7 +842,10 @@ static void init_typebuf(void)
void init_default_mappings(void)
{
add_map((char_u *)"Y y$", NORMAL, true);
- add_map((char_u *)"<C-L> <Cmd>nohlsearch<Bar>diffupdate<CR><C-L>", NORMAL, true);
+
+ // Use normal! <C-L> to prevent inserting raw <C-L> when using i_<C-O>
+ // See https://github.com/neovim/neovim/issues/17473
+ add_map((char_u *)"<C-L> <Cmd>nohlsearch<Bar>diffupdate<Bar>normal! <C-L><CR>", NORMAL, true);
add_map((char_u *)"<C-U> <C-G>u<C-U>", INSERT, true);
add_map((char_u *)"<C-W> <C-G>u<C-W>", INSERT, true);
}
@@ -1710,6 +1713,14 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
int keylen = *keylenp;
int i;
int local_State = get_real_state();
+ bool is_plug_map = false;
+
+ // If typehead starts with <Plug> then remap, even for a "noremap" mapping.
+ if (typebuf.tb_buf[typebuf.tb_off] == K_SPECIAL
+ && typebuf.tb_buf[typebuf.tb_off + 1] == KS_EXTRA
+ && typebuf.tb_buf[typebuf.tb_off + 2] == KE_PLUG) {
+ is_plug_map = true;
+ }
// Check for a mappable key sequence.
// Walk through one maphash[] list until we find an entry that matches.
@@ -1725,7 +1736,7 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
tb_c1 = typebuf.tb_buf[typebuf.tb_off];
if (no_mapping == 0 && maphash_valid
&& (no_zero_mapping == 0 || tb_c1 != '0')
- && (typebuf.tb_maplen == 0
+ && (typebuf.tb_maplen == 0 || is_plug_map
|| (p_remap
&& !(typebuf.tb_noremap[typebuf.tb_off] & (RM_NONE|RM_ABBR))))
&& !(p_paste && (State & (INSERT + CMDLINE)))
@@ -1813,7 +1824,7 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
break;
}
}
- if (n >= 0) {
+ if (!is_plug_map && n >= 0) {
continue;
}
@@ -1899,9 +1910,6 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
// complete match
if (keylen >= 0 && keylen <= typebuf.tb_len) {
char_u *map_str = NULL;
- int save_m_expr;
- int save_m_noremap;
- int save_m_silent;
// Write chars to script file(s).
// Note: :lmap mappings are written *after* being applied. #5658
@@ -1938,9 +1946,9 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
// Copy the values from *mp that are used, because evaluating the
// expression may invoke a function that redefines the mapping, thereby
// making *mp invalid.
- save_m_expr = mp->m_expr;
- save_m_noremap = mp->m_noremap;
- save_m_silent = mp->m_silent;
+ char save_m_expr = mp->m_expr;
+ int save_m_noremap = mp->m_noremap;
+ char 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;
@@ -1949,8 +1957,11 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
// expression. Also save and restore the command line
// for "normal :".
if (mp->m_expr) {
- int save_vgetc_busy = vgetc_busy;
+ const int save_vgetc_busy = vgetc_busy;
const bool save_may_garbage_collect = may_garbage_collect;
+ const int save_cursor_row = ui_current_row();
+ const int save_cursor_col = ui_current_col();
+ const int prev_did_emsg = did_emsg;
vgetc_busy = 0;
may_garbage_collect = false;
@@ -1960,6 +1971,32 @@ static int handle_mapping(int *keylenp, bool *timedout, int *mapdepth)
save_m_str = vim_strsave(mp->m_str);
}
map_str = eval_map_expr(mp, NUL);
+
+ // The mapping may do anything, but we expect it to take care of
+ // redrawing. Do put the cursor back where it was.
+ ui_cursor_goto(save_cursor_row, save_cursor_col);
+ ui_flush();
+
+ // If an error was displayed and the expression returns an empty
+ // string, generate a <Nop> to allow for a redraw.
+ if (prev_did_emsg != did_emsg && (map_str == NULL || *map_str == NUL)) {
+ char_u buf[4];
+ xfree(map_str);
+ buf[0] = K_SPECIAL;
+ buf[1] = KS_EXTRA;
+ buf[2] = KE_IGNORE;
+ buf[3] = NUL;
+ map_str = vim_strsave(buf);
+ if (State & CMDLINE) {
+ // redraw the command below the error
+ msg_didout = true;
+ if (msg_row < cmdline_row) {
+ msg_row = cmdline_row;
+ }
+ redrawcmd();
+ }
+ }
+
vgetc_busy = save_vgetc_busy;
may_garbage_collect = save_may_garbage_collect;
} else {
@@ -2455,7 +2492,7 @@ static int vgetorpeek(bool advance)
/// 1. a scriptfile
/// 2. the keyboard
///
-/// As much characters as we can get (up to 'maxlen') are put in "buf" and
+/// As many characters as we can get (up to 'maxlen') are put in "buf" and
/// NUL terminated (buffer length must be 'maxlen' + 1).
/// Minimum for "maxlen" is 3!!!!
///
@@ -2624,9 +2661,9 @@ int fix_input_buffer(char_u *buf, int len)
/// @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,
- LuaRef rhs_lua, 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;
@@ -3048,6 +3085,7 @@ 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;
+ nlua_set_sctx(&mp->m_script_ctx);
if (args->desc != NULL) {
mp->m_desc = xstrdup(args->desc);
}
@@ -3128,6 +3166,7 @@ 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;
+ nlua_set_sctx(&mp->m_script_ctx);
mp->m_desc = NULL;
if (args->desc != NULL) {
mp->m_desc = xstrdup(args->desc);
@@ -3490,6 +3529,7 @@ static void showmap(mapblock_T *mp, bool local)
if (p_verbose > 0) {
last_set_msg(mp->m_script_ctx);
}
+ msg_clr_eos();
ui_flush(); // show one line at a time
}
@@ -3948,7 +3988,7 @@ 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(mapblock_T *mp, int c)
+static char_u *eval_map_expr(mapblock_T *mp, int c)
{
char_u *res;
char_u *p = NULL;
@@ -4103,7 +4143,7 @@ int makemap(FILE *fd, buf_T *buf)
}
for (p = mp->m_str; *p != NUL; p++) {
if (p[0] == K_SPECIAL && p[1] == KS_EXTRA
- && p[2] == (int)KE_SNR) {
+ && p[2] == KE_SNR) {
break;
}
}
diff --git a/src/nvim/globals.h b/src/nvim/globals.h
index 5aa564623f..cbd67afb09 100644
--- a/src/nvim/globals.h
+++ b/src/nvim/globals.h
@@ -326,22 +326,25 @@ EXTERN int want_garbage_collect INIT(= false);
EXTERN int garbage_collect_at_exit INIT(= false);
// Special values for current_SID.
-#define SID_MODELINE -1 // when using a modeline
-#define SID_CMDARG -2 // for "--cmd" argument
-#define SID_CARG -3 // for "-c" argument
-#define SID_ENV -4 // for sourcing environment variable
-#define SID_ERROR -5 // option was reset because of an error
-#define SID_NONE -6 // don't set scriptID
-#define SID_WINLAYOUT -7 // changing window size
-#define SID_LUA -8 // for Lua scripts/chunks
-#define SID_API_CLIENT -9 // for API clients
-#define SID_STR -10 // for sourcing a string with no script item
+#define SID_MODELINE (-1) // when using a modeline
+#define SID_CMDARG (-2) // for "--cmd" argument
+#define SID_CARG (-3) // for "-c" argument
+#define SID_ENV (-4) // for sourcing environment variable
+#define SID_ERROR (-5) // option was reset because of an error
+#define SID_NONE (-6) // don't set scriptID
+#define SID_WINLAYOUT (-7) // changing window size
+#define SID_LUA (-8) // for Lua scripts/chunks
+#define SID_API_CLIENT (-9) // for API clients
+#define SID_STR (-10) // for sourcing a string with no script item
// Script CTX being sourced or was sourced to define the current function.
EXTERN sctx_T current_sctx INIT(= { 0 COMMA 0 COMMA 0 });
// ID of the current channel making a client API call
EXTERN uint64_t current_channel_id INIT(= 0);
+// ID of the client channel. Used by ui client
+EXTERN uint64_t ui_client_channel_id INIT(= 0);
+
EXTERN bool did_source_packages INIT(= false);
// Scope information for the code that indirectly triggered the current
@@ -445,10 +448,11 @@ EXTERN int aucmd_win_used INIT(= false); // aucmd_win is being used
EXTERN frame_T *topframe; // top of the window frame tree
// Tab pages are alternative topframes. "first_tabpage" points to the first
-// one in the list, "curtab" is the current one.
+// one in the list, "curtab" is the current one. "lastused_tabpage" is the
+// last used one.
EXTERN tabpage_T *first_tabpage;
-EXTERN tabpage_T *lastused_tabpage;
EXTERN tabpage_T *curtab;
+EXTERN tabpage_T *lastused_tabpage;
EXTERN bool redraw_tabline INIT(= false); // need to redraw tabline
// Iterates over all tabs in the tab list
diff --git a/src/nvim/hardcopy.c b/src/nvim/hardcopy.c
index 6fc70144ac..93c8c53e33 100644
--- a/src/nvim/hardcopy.c
+++ b/src/nvim/hardcopy.c
@@ -386,30 +386,46 @@ static uint32_t prt_get_term_color(int colorindex)
return cterm_color_8[colorindex % 8];
}
-static void prt_get_attr(int hl_id, prt_text_attr_T *pattr, int modec)
+static uint32_t prt_get_color(int hl_id, int modec)
{
int colorindex;
uint32_t fg_color;
+ const char *color = highlight_color(hl_id, "fg#", 'g');
+ if (color != NULL) {
+ RgbValue rgb = name_to_color(color);
+ if (rgb != -1) {
+ return (uint32_t)rgb;
+ }
+ }
+
+ color = highlight_color(hl_id, "fg", modec);
+ if (color == NULL) {
+ colorindex = 0;
+ } else {
+ colorindex = atoi(color);
+ }
+
+ if (colorindex >= 0 && colorindex < t_colors) {
+ fg_color = prt_get_term_color(colorindex);
+ } else {
+ fg_color = PRCOLOR_BLACK;
+ }
+
+ return fg_color;
+}
+
+static void prt_get_attr(int hl_id, prt_text_attr_T *pattr, int modec)
+{
pattr->bold = (highlight_has_attr(hl_id, HL_BOLD, modec) != NULL);
pattr->italic = (highlight_has_attr(hl_id, HL_ITALIC, modec) != NULL);
pattr->underline = (highlight_has_attr(hl_id, HL_UNDERLINE, modec) != NULL);
+ pattr->underlineline = (highlight_has_attr(hl_id, HL_UNDERLINELINE, modec) != NULL);
pattr->undercurl = (highlight_has_attr(hl_id, HL_UNDERCURL, modec) != NULL);
+ pattr->underdot = (highlight_has_attr(hl_id, HL_UNDERDOT, modec) != NULL);
+ pattr->underdash = (highlight_has_attr(hl_id, HL_UNDERDASH, modec) != NULL);
- {
- const char *color = highlight_color(hl_id, "fg", modec);
- if (color == NULL) {
- colorindex = 0;
- } else {
- colorindex = atoi(color);
- }
-
- if (colorindex >= 0 && colorindex < t_colors) {
- fg_color = prt_get_term_color(colorindex);
- } else {
- fg_color = PRCOLOR_BLACK;
- }
- }
+ uint32_t fg_color = prt_get_color(hl_id, modec);
if (fg_color == PRCOLOR_WHITE) {
fg_color = PRCOLOR_BLACK;
diff --git a/src/nvim/hardcopy.h b/src/nvim/hardcopy.h
index eba769d342..16119c5d2d 100644
--- a/src/nvim/hardcopy.h
+++ b/src/nvim/hardcopy.h
@@ -18,6 +18,9 @@ typedef struct {
TriState italic;
TriState underline;
int undercurl;
+ int underlineline;
+ int underdot;
+ int underdash;
} prt_text_attr_T;
/*
diff --git a/src/nvim/highlight.c b/src/nvim/highlight.c
index 8b998ff62e..abbda1e9fa 100644
--- a/src/nvim/highlight.c
+++ b/src/nvim/highlight.c
@@ -5,6 +5,7 @@
#include "nvim/api/private/defs.h"
#include "nvim/api/private/helpers.h"
+#include "nvim/decoration_provider.h"
#include "nvim/highlight.h"
#include "nvim/highlight_defs.h"
#include "nvim/lua/executor.h"
@@ -327,7 +328,7 @@ void update_window_hl(win_T *wp, bool invalid)
wp->w_hl_attr_normal);
}
- for (int hlf = 0; hlf < (int)HLF_COUNT; hlf++) {
+ for (int hlf = 0; hlf < HLF_COUNT; hlf++) {
int attr;
if (wp->w_hl_ids[hlf] != 0) {
attr = hl_get_ui_attr(hlf, wp->w_hl_ids[hlf], false);
@@ -558,7 +559,7 @@ int hl_blend_attrs(int back_attr, int front_attr, bool *through)
cattrs = battrs;
cattrs.rgb_fg_color = rgb_blend(ratio, battrs.rgb_fg_color,
fattrs.rgb_bg_color);
- if (cattrs.rgb_ae_attr & (HL_UNDERLINE|HL_UNDERCURL)) {
+ if (cattrs.rgb_ae_attr & (HL_ANY_UNDERLINE)) {
cattrs.rgb_sp_color = rgb_blend(ratio, battrs.rgb_sp_color,
fattrs.rgb_bg_color);
} else {
@@ -576,7 +577,7 @@ int hl_blend_attrs(int back_attr, int front_attr, bool *through)
}
cattrs.rgb_fg_color = rgb_blend(ratio/2, battrs.rgb_fg_color,
fattrs.rgb_fg_color);
- if (cattrs.rgb_ae_attr & (HL_UNDERLINE|HL_UNDERCURL)) {
+ if (cattrs.rgb_ae_attr & (HL_ANY_UNDERLINE)) {
cattrs.rgb_sp_color = rgb_blend(ratio/2, battrs.rgb_bg_color,
fattrs.rgb_sp_color);
} else {
@@ -743,10 +744,23 @@ Dictionary hlattrs2dict(HlAttrs ae, bool use_rgb)
PUT(hl, "underline", BOOLEAN_OBJ(true));
}
+ if (mask & HL_UNDERLINELINE) {
+ PUT(hl, "underlineline", BOOLEAN_OBJ(true));
+ }
+
if (mask & HL_UNDERCURL) {
PUT(hl, "undercurl", BOOLEAN_OBJ(true));
}
+ if (mask & HL_UNDERDOT) {
+ PUT(hl, "underdot", BOOLEAN_OBJ(true));
+ }
+
+ if (mask & HL_UNDERDASH) {
+ PUT(hl, "underdash", BOOLEAN_OBJ(true));
+ }
+
+
if (mask & HL_ITALIC) {
PUT(hl, "italic", BOOLEAN_OBJ(true));
}
@@ -800,19 +814,23 @@ HlAttrs dict2hlattrs(Dict(highlight) *dict, bool use_rgb, int *link_id, Error *e
{
HlAttrs hlattrs = HLATTRS_INIT;
int32_t fg = -1, bg = -1, ctermfg = -1, ctermbg = -1, sp = -1;
+ int blend = -1;
int16_t mask = 0;
int16_t cterm_mask = 0;
bool cterm_mask_provided = false;
#define CHECK_FLAG(d, m, name, extra, flag) \
- if (api_object_to_bool(d->name ## extra, #name, false, err)) { \
- m = m | flag; \
- }
+ if (api_object_to_bool(d->name##extra, #name, false, err)) { \
+ m = m | flag; \
+ }
CHECK_FLAG(dict, mask, bold, , HL_BOLD);
CHECK_FLAG(dict, mask, standout, , HL_STANDOUT);
CHECK_FLAG(dict, mask, underline, , HL_UNDERLINE);
+ CHECK_FLAG(dict, mask, underlineline, , HL_UNDERLINELINE);
CHECK_FLAG(dict, mask, undercurl, , HL_UNDERCURL);
+ CHECK_FLAG(dict, mask, underdot, , HL_UNDERDOT);
+ CHECK_FLAG(dict, mask, underdash, , HL_UNDERDASH);
CHECK_FLAG(dict, mask, italic, , HL_ITALIC);
CHECK_FLAG(dict, mask, reverse, , HL_INVERSE);
CHECK_FLAG(dict, mask, strikethrough, , HL_STRIKETHROUGH);
@@ -847,6 +865,20 @@ HlAttrs dict2hlattrs(Dict(highlight) *dict, bool use_rgb, int *link_id, Error *e
return hlattrs;
}
+ if (dict->blend.type == kObjectTypeInteger) {
+ Integer blend0 = dict->blend.data.integer;
+ if (blend0 < 0 || blend0 > 100) {
+ api_set_error(err, kErrorTypeValidation, "'blend' is not between 0 to 100");
+ } else {
+ blend = (int)blend0;
+ }
+ } else if (HAS_KEY(dict->blend)) {
+ api_set_error(err, kErrorTypeValidation, "'blend' must be an integer");
+ }
+ if (ERROR_SET(err)) {
+ return hlattrs;
+ }
+
if (HAS_KEY(dict->link)) {
if (link_id) {
*link_id = object_to_hl_id(dict->link, "link", err);
@@ -875,7 +907,6 @@ HlAttrs dict2hlattrs(Dict(highlight) *dict, bool use_rgb, int *link_id, Error *e
CHECK_FLAG(cterm, cterm_mask, reverse, , HL_INVERSE);
CHECK_FLAG(cterm, cterm_mask, strikethrough, , HL_STRIKETHROUGH);
CHECK_FLAG(cterm, cterm_mask, nocombine, , HL_NOCOMBINE);
-
} else if (dict->cterm.type == kObjectTypeArray && dict->cterm.data.array.size == 0) {
// empty list from Lua API should clear all cterm attributes
// TODO(clason): handle via gen_api_dispatch
@@ -908,6 +939,7 @@ HlAttrs dict2hlattrs(Dict(highlight) *dict, bool use_rgb, int *link_id, Error *e
hlattrs.rgb_bg_color = bg;
hlattrs.rgb_fg_color = fg;
hlattrs.rgb_sp_color = sp;
+ hlattrs.hl_blend = blend;
hlattrs.cterm_bg_color = ctermbg == -1 ? 0 : ctermbg + 1;
hlattrs.cterm_fg_color = ctermfg == -1 ? 0 : ctermfg + 1;
hlattrs.cterm_ae_attr = cterm_mask;
@@ -927,10 +959,11 @@ int object_to_color(Object val, char *key, bool rgb, Error *err)
} else if (val.type == kObjectTypeString) {
String str = val.data.string;
// TODO(bfredl): be more fancy with "bg", "fg" etc
+ if (!str.size || STRICMP(str.data, "NONE") == 0) {
+ return -1;
+ }
int color;
- if (!str.size) {
- color = 0;
- } else if (rgb) {
+ if (rgb) {
color = name_to_color(str.data);
} else {
color = name_to_ctermcolor(str.data);
diff --git a/src/nvim/highlight_defs.h b/src/nvim/highlight_defs.h
index 50a03e0c02..e0ee649013 100644
--- a/src/nvim/highlight_defs.h
+++ b/src/nvim/highlight_defs.h
@@ -24,6 +24,10 @@ typedef enum {
HL_FG_INDEXED = 0x0200,
HL_DEFAULT = 0x0400,
HL_GLOBAL = 0x0800,
+ HL_UNDERLINELINE = 0x1000,
+ HL_UNDERDOT = 0x2000,
+ HL_UNDERDASH = 0x4000,
+ HL_ANY_UNDERLINE = HL_UNDERLINE | HL_UNDERLINELINE | HL_UNDERCURL | HL_UNDERDOT | HL_UNDERDASH,
} HlAttrFlags;
/// Stores a complete highlighting entry, including colors and attributes
@@ -70,7 +74,8 @@ typedef enum {
HLF_R, // return to continue message and yes/no questions
HLF_S, // status lines
HLF_SNC, // status lines of not-current windows
- HLF_C, // column to separate vertically split windows
+ HLF_C, // window split separators
+ HLF_VSP, // VertSplit
HLF_T, // Titles for output from ":set all", ":autocmd" etc.
HLF_V, // Visual mode
HLF_VNC, // Visual mode, autoselecting and not clipboard owner
@@ -129,10 +134,11 @@ EXTERN const char *hlf_names[] INIT(= {
[HLF_R] = "Question",
[HLF_S] = "StatusLine",
[HLF_SNC] = "StatusLineNC",
- [HLF_C] = "VertSplit",
+ [HLF_C] = "WinSeparator",
[HLF_T] = "Title",
[HLF_V] = "Visual",
[HLF_VNC] = "VisualNC",
+ [HLF_VSP] = "VertSplit",
[HLF_W] = "WarningMsg",
[HLF_WM] = "WildMenu",
[HLF_FL] = "Folded",
diff --git a/src/nvim/indent.c b/src/nvim/indent.c
index 8cc5bc2436..59ba2c92f7 100644
--- a/src/nvim/indent.c
+++ b/src/nvim/indent.c
@@ -70,7 +70,7 @@ int get_indent_str(const char_u *ptr, int ts, bool list)
{
int count = 0;
- for (; *ptr; ++ptr) {
+ for (; *ptr; ptr++) {
// Count a tab for what it is worth.
if (*ptr == TAB) {
if (!list || curwin->w_p_lcs_chars.tab1) {
@@ -442,10 +442,9 @@ int get_breakindent_win(win_T *wp, char_u *line)
static long *prev_vts = NULL; // Cached vartabs values.
int bri = 0;
// window width minus window margin space, i.e. what rests for text
- const int eff_wwidth = wp->w_width_inner
- - ((wp->w_p_nu || wp->w_p_rnu)
- && (vim_strchr(p_cpo, CPO_NUMCOL) == NULL)
- ? number_width(wp) + 1 : 0);
+ const int eff_wwidth = wp->w_width_inner -
+ ((wp->w_p_nu || wp->w_p_rnu)
+ && (vim_strchr(p_cpo, CPO_NUMCOL) == NULL) ? number_width(wp) + 1 : 0);
// used cached indent, unless pointer or 'tabstop' changed
if (prev_line != line || prev_ts != wp->w_buffer->b_p_ts
@@ -512,7 +511,7 @@ int inindent(int extra)
char_u *ptr;
colnr_T col;
- for (col = 0, ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr); ++col) {
+ for (col = 0, ptr = get_cursor_line_ptr(); ascii_iswhite(*ptr); col++) {
ptr++;
}
@@ -630,7 +629,7 @@ int get_lisp_indent(void)
continue;
}
- for (that = get_cursor_line_ptr(); *that != NUL; ++that) {
+ for (that = get_cursor_line_ptr(); *that != NUL; that++) {
if (*that == ';') {
while (*(that + 1) != NUL) {
that++;
diff --git a/src/nvim/input.c b/src/nvim/input.c
index 5fa9b8b343..ff6b559710 100644
--- a/src/nvim/input.c
+++ b/src/nvim/input.c
@@ -9,9 +9,9 @@
#include "nvim/func_attr.h"
#include "nvim/getchar.h"
+#include "nvim/input.h"
#include "nvim/mbyte.h"
#include "nvim/memory.h"
-#include "nvim/input.h"
#include "nvim/mouse.h"
#include "nvim/os/input.h"
#include "nvim/ui.h"
diff --git a/src/nvim/lua/converter.c b/src/nvim/lua/converter.c
index 0fbd56ed53..0bb224c729 100644
--- a/src/nvim/lua/converter.c
+++ b/src/nvim/lua/converter.c
@@ -156,7 +156,7 @@ static LuaTableProps nlua_traverse_table(lua_State *const lstate)
&& ret.string_keys_num == 0)) {
ret.type = kObjectTypeArray;
if (tsize == 0 && lua_getmetatable(lstate, -1)) {
- nlua_pushref(lstate, nlua_empty_dict_ref);
+ nlua_pushref(lstate, nlua_global_refs->empty_dict_ref);
if (lua_rawequal(lstate, -2, -1)) {
ret.type = kObjectTypeDictionary;
}
@@ -286,9 +286,7 @@ bool nlua_pop_typval(lua_State *lstate, typval_T *ret_tv)
break;
case LUA_TBOOLEAN:
cur.tv->v_type = VAR_BOOL;
- cur.tv->vval.v_bool = (lua_toboolean(lstate, -1)
- ? kBoolVarTrue
- : kBoolVarFalse);
+ cur.tv->vval.v_bool = (lua_toboolean(lstate, -1) ? kBoolVarTrue : kBoolVarFalse);
break;
case LUA_TSTRING: {
size_t len;
@@ -316,7 +314,7 @@ bool nlua_pop_typval(lua_State *lstate, typval_T *ret_tv)
LuaRef table_ref = LUA_NOREF;
if (lua_getmetatable(lstate, -1)) {
lua_pop(lstate, 1);
- table_ref = nlua_ref(lstate, -1);
+ table_ref = nlua_ref_global(lstate, -1);
}
const LuaTableProps table_props = nlua_traverse_table(lstate);
@@ -389,7 +387,7 @@ nlua_pop_typval_table_processing_end:
}
case LUA_TFUNCTION: {
LuaCFunctionState *state = xmalloc(sizeof(LuaCFunctionState));
- state->lua_callable.func_ref = nlua_ref(lstate, -1);
+ state->lua_callable.func_ref = nlua_ref_global(lstate, -1);
char_u *name = register_cfunc(&nlua_CFunction_func_call,
&nlua_CFunction_func_free,
@@ -401,7 +399,7 @@ nlua_pop_typval_table_processing_end:
}
case LUA_TUSERDATA: {
// TODO(bfredl): check mt.__call and convert to function?
- nlua_pushref(lstate, nlua_nil_ref);
+ nlua_pushref(lstate, nlua_global_refs->nil_ref);
bool is_nil = lua_rawequal(lstate, -2, -1);
lua_pop(lstate, 1);
if (is_nil) {
@@ -445,7 +443,7 @@ static bool typval_conv_special = false;
if (typval_conv_special) { \
lua_pushnil(lstate); \
} else { \
- nlua_pushref(lstate, nlua_nil_ref); \
+ nlua_pushref(lstate, nlua_global_refs->nil_ref); \
} \
} while (0)
@@ -478,7 +476,13 @@ static bool typval_conv_special = false;
#define TYPVAL_ENCODE_CONV_FUNC_START(tv, fun) \
do { \
- TYPVAL_ENCODE_CONV_NIL(tv); \
+ ufunc_T *fp = find_func(fun); \
+ assert(fp != NULL); \
+ if (fp->uf_cb == nlua_CFunction_func_call) { \
+ nlua_pushref(lstate, ((LuaCFunctionState *)fp->uf_cb_state)->lua_callable.func_ref); \
+ } else { \
+ TYPVAL_ENCODE_CONV_NIL(tv); \
+ } \
goto typval_encode_stop_converting_one_item; \
} while (0)
@@ -495,7 +499,7 @@ static bool typval_conv_special = false;
nlua_create_typed_table(lstate, 0, 0, kObjectTypeDictionary); \
} else { \
lua_createtable(lstate, 0, 0); \
- nlua_pushref(lstate, nlua_empty_dict_ref); \
+ nlua_pushref(lstate, nlua_global_refs->empty_dict_ref); \
lua_setmetatable(lstate, -2); \
} \
} while (0)
@@ -551,8 +555,8 @@ static bool typval_conv_special = false;
const MPConvStackVal mpval = kv_A(*mpstack, backref - 1); \
if (mpval.type == conv_type) { \
if (conv_type == kMPConvDict \
- ? (void *)mpval.data.d.dict == (void *)(val) \
- : (void *)mpval.data.l.list == (void *)(val)) { \
+ ? (void *)mpval.data.d.dict == (void *)(val) \
+ : (void *)mpval.data.l.list == (void *)(val)) { \
lua_pushvalue(lstate, \
-((int)((kv_size(*mpstack) - backref + 1) * 2))); \
break; \
@@ -617,14 +621,6 @@ 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;
}
@@ -734,7 +730,7 @@ void nlua_push_Dictionary(lua_State *lstate, const Dictionary dict, bool special
} else {
lua_createtable(lstate, 0, (int)dict.size);
if (dict.size == 0 && !special) {
- nlua_pushref(lstate, nlua_empty_dict_ref);
+ nlua_pushref(lstate, nlua_global_refs->empty_dict_ref);
lua_setmetatable(lstate, -2);
}
}
@@ -782,7 +778,7 @@ void nlua_push_Object(lua_State *lstate, const Object obj, bool special)
if (special) {
lua_pushnil(lstate);
} else {
- nlua_pushref(lstate, nlua_nil_ref);
+ nlua_pushref(lstate, nlua_global_refs->nil_ref);
}
break;
case kObjectTypeLuaRef: {
@@ -1133,10 +1129,7 @@ Object nlua_pop_Object(lua_State *const lstate, bool ref, Error *const err)
case LUA_TSTRING: {
size_t len;
const char *s = lua_tolstring(lstate, -1, &len);
- *cur.obj = STRING_OBJ(((String) {
- .data = xmemdupz(s, len),
- .size = len,
- }));
+ *cur.obj = STRING_OBJ(((String) { .data = xmemdupz(s, len), .size = len }));
break;
}
case LUA_TNUMBER: {
@@ -1154,11 +1147,7 @@ Object nlua_pop_Object(lua_State *const lstate, bool ref, Error *const err)
switch (table_props.type) {
case kObjectTypeArray:
- *cur.obj = ARRAY_OBJ(((Array) {
- .items = NULL,
- .size = 0,
- .capacity = 0,
- }));
+ *cur.obj = ARRAY_OBJ(((Array) { .items = NULL, .size = 0, .capacity = 0 }));
if (table_props.maxidx != 0) {
cur.obj->data.array.items =
xcalloc(table_props.maxidx,
@@ -1169,11 +1158,7 @@ Object nlua_pop_Object(lua_State *const lstate, bool ref, Error *const err)
}
break;
case kObjectTypeDictionary:
- *cur.obj = DICTIONARY_OBJ(((Dictionary) {
- .items = NULL,
- .size = 0,
- .capacity = 0,
- }));
+ *cur.obj = DICTIONARY_OBJ(((Dictionary) { .items = NULL, .size = 0, .capacity = 0 }));
if (table_props.string_keys_num != 0) {
cur.obj->data.dictionary.items =
xcalloc(table_props.string_keys_num,
@@ -1199,14 +1184,14 @@ Object nlua_pop_Object(lua_State *const lstate, bool ref, Error *const err)
case LUA_TFUNCTION:
if (ref) {
- *cur.obj = LUAREF_OBJ(nlua_ref(lstate, -1));
+ *cur.obj = LUAREF_OBJ(nlua_ref_global(lstate, -1));
} else {
goto type_error;
}
break;
case LUA_TUSERDATA: {
- nlua_pushref(lstate, nlua_nil_ref);
+ nlua_pushref(lstate, nlua_global_refs->nil_ref);
bool is_nil = lua_rawequal(lstate, -2, -1);
lua_pop(lstate, 1);
if (is_nil) {
@@ -1240,7 +1225,7 @@ type_error:
LuaRef nlua_pop_LuaRef(lua_State *const lstate, Error *err)
{
- LuaRef rv = nlua_ref(lstate, -1);
+ LuaRef rv = nlua_ref_global(lstate, -1);
lua_pop(lstate, 1);
return rv;
}
diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c
index a61273084c..21625854fb 100644
--- a/src/nvim/lua/executor.c
+++ b/src/nvim/lua/executor.c
@@ -15,6 +15,7 @@
#include "nvim/buffer_defs.h"
#include "nvim/change.h"
#include "nvim/cursor.h"
+#include "nvim/eval/typval.h"
#include "nvim/eval/userfunc.h"
#include "nvim/event/loop.h"
#include "nvim/event/time.h"
@@ -45,11 +46,19 @@ static int in_fast_callback = 0;
// Initialized in nlua_init().
static lua_State *global_lstate = NULL;
+static uv_thread_t main_thread;
+
typedef struct {
Error err;
String lua_err_str;
} LuaError;
+typedef struct {
+ char *name;
+ const uint8_t *data;
+ size_t size;
+} ModuleDef;
+
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "lua/executor.c.generated.h"
# include "lua/vim_module.generated.h"
@@ -65,11 +74,16 @@ typedef struct {
}
#if __has_feature(address_sanitizer)
-static PMap(handle_T) nlua_ref_markers = MAP_INIT;
static bool nlua_track_refs = false;
# define NLUA_TRACK_REFS
#endif
+typedef enum luv_err_type {
+ kCallback,
+ kThread,
+ kThreadCallback,
+} luv_err_t;
+
/// Convert lua error into a Vim error message
///
/// @param lstate Lua interpreter state.
@@ -137,8 +151,21 @@ static int nlua_nvim_version(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL
static void nlua_luv_error_event(void **argv)
{
char *error = (char *)argv[0];
+ luv_err_t type = (luv_err_t)(intptr_t)argv[1];
msg_ext_set_kind("lua_error");
- semsg_multiline("Error executing luv callback:\n%s", error);
+ switch (type) {
+ case kCallback:
+ semsg_multiline("Error executing luv callback:\n%s", error);
+ break;
+ case kThread:
+ semsg_multiline("Error in luv thread:\n%s", error);
+ break;
+ case kThreadCallback:
+ semsg_multiline("Error in luv callback, thread:\n%s", error);
+ break;
+ default:
+ break;
+ }
xfree(error);
}
@@ -163,7 +190,7 @@ static int nlua_luv_cfpcall(lua_State *lstate, int nargs, int nresult, int flags
const char *error = lua_tostring(lstate, -1);
multiqueue_put(main_loop.events, nlua_luv_error_event,
- 1, xstrdup(error));
+ 2, xstrdup(error), (intptr_t)kCallback);
lua_pop(lstate, 1); // error message
retval = -status;
} else { // LUA_OK
@@ -177,12 +204,109 @@ static int nlua_luv_cfpcall(lua_State *lstate, int nargs, int nresult, int flags
return retval;
}
+static int nlua_luv_thread_cb_cfpcall(lua_State *lstate, int nargs, int nresult, int flags)
+{
+ return nlua_luv_thread_common_cfpcall(lstate, nargs, nresult, flags, true);
+}
+
+static int nlua_luv_thread_cfpcall(lua_State *lstate, int nargs, int nresult, int flags)
+ FUNC_ATTR_NONNULL_ALL
+{
+ return nlua_luv_thread_common_cfpcall(lstate, nargs, nresult, flags, false);
+}
+
+static int nlua_luv_thread_cfcpcall(lua_State *lstate, lua_CFunction func, void *ud, int flags)
+ FUNC_ATTR_NONNULL_ARG(1, 2)
+{
+ lua_pushcfunction(lstate, func);
+ lua_pushlightuserdata(lstate, ud);
+ int retval = nlua_luv_thread_cfpcall(lstate, 1, 0, flags);
+ return retval;
+}
+
+static int nlua_luv_thread_common_cfpcall(lua_State *lstate, int nargs, int nresult, int flags,
+ bool is_callback)
+ FUNC_ATTR_NONNULL_ALL
+{
+ int retval;
+
+ int top = lua_gettop(lstate);
+ int status = lua_pcall(lstate, nargs, nresult, 0);
+ if (status) {
+ if (status == LUA_ERRMEM && !(flags & LUVF_CALLBACK_NOEXIT)) {
+ // Terminate this thread, as the main thread may be able to continue
+ // execution.
+ mch_errmsg(e_outofmem);
+ mch_errmsg("\n");
+ lua_close(lstate);
+#ifdef WIN32
+ ExitThread(0);
+#else
+ pthread_exit(0);
+#endif
+ }
+ const char *error = lua_tostring(lstate, -1);
+
+ loop_schedule_deferred(&main_loop,
+ event_create(nlua_luv_error_event, 2,
+ xstrdup(error),
+ is_callback
+ ? (intptr_t)kThreadCallback
+ : (intptr_t)kThread));
+ lua_pop(lstate, 1); // error message
+ retval = -status;
+ } else { // LUA_OK
+ if (nresult == LUA_MULTRET) {
+ nresult = lua_gettop(lstate) - top + nargs + 1;
+ }
+ retval = nresult;
+ }
+
+ return retval;
+}
+
+static int nlua_thr_api_nvim__get_runtime(lua_State *lstate)
+{
+ if (lua_gettop(lstate) != 3) {
+ return luaL_error(lstate, "Expected 3 arguments");
+ }
+
+ luaL_checktype(lstate, -1, LUA_TTABLE);
+ lua_getfield(lstate, -1, "is_lua");
+ if (!lua_isboolean(lstate, -1)) {
+ return luaL_error(lstate, "is_lua is not a boolean");
+ }
+ bool is_lua = lua_toboolean(lstate, -1);
+ lua_pop(lstate, 2);
+
+ luaL_checktype(lstate, -1, LUA_TBOOLEAN);
+ bool all = lua_toboolean(lstate, -1);
+ lua_pop(lstate, 1);
+
+ Error err = ERROR_INIT;
+ const Array pat = nlua_pop_Array(lstate, &err);
+ if (ERROR_SET(&err)) {
+ luaL_where(lstate, 1);
+ lua_pushstring(lstate, err.msg);
+ api_clear_error(&err);
+ lua_concat(lstate, 2);
+ return lua_error(lstate);
+ }
+
+ ArrayOf(String) ret = runtime_get_named_thread(is_lua, pat, all);
+ nlua_push_Array(lstate, ret, true);
+ api_free_array(ret);
+ api_free_array(pat);
+
+ return 1;
+}
+
static void nlua_schedule_event(void **argv)
{
LuaRef cb = (LuaRef)(ptrdiff_t)argv[0];
lua_State *const lstate = global_lstate;
nlua_pushref(lstate, cb);
- nlua_unref(lstate, cb);
+ nlua_unref_global(lstate, cb);
if (nlua_pcall(lstate, 0, 0)) {
nlua_error(lstate, _("Error executing vim.schedule lua callback: %.*s"));
}
@@ -199,7 +323,7 @@ static int nlua_schedule(lua_State *const lstate)
return lua_error(lstate);
}
- LuaRef cb = nlua_ref(lstate, 1);
+ LuaRef cb = nlua_ref_global(lstate, 1);
multiqueue_put(main_loop.events, nlua_schedule_event,
1, (void *)(ptrdiff_t)cb);
@@ -317,10 +441,154 @@ static int nlua_wait(lua_State *lstate)
return 2;
}
+static nlua_ref_state_t *nlua_new_ref_state(lua_State *lstate, bool is_thread)
+ FUNC_ATTR_NONNULL_ALL
+{
+ nlua_ref_state_t *ref_state = lua_newuserdata(lstate, sizeof(*ref_state));
+ memset(ref_state, 0, sizeof(*ref_state));
+ ref_state->nil_ref = LUA_NOREF;
+ ref_state->empty_dict_ref = LUA_NOREF;
+ if (!is_thread) {
+ nlua_global_refs = ref_state;
+ }
+ return ref_state;
+}
+
+static nlua_ref_state_t *nlua_get_ref_state(lua_State *lstate)
+ FUNC_ATTR_NONNULL_ALL
+{
+ lua_getfield(lstate, LUA_REGISTRYINDEX, "nlua.ref_state");
+ nlua_ref_state_t *ref_state = lua_touserdata(lstate, -1);
+ lua_pop(lstate, 1);
+
+ return ref_state;
+}
+
+LuaRef nlua_get_nil_ref(lua_State *lstate)
+ FUNC_ATTR_NONNULL_ALL
+{
+ nlua_ref_state_t *ref_state = nlua_get_ref_state(lstate);
+ return ref_state->nil_ref;
+}
+
+LuaRef nlua_get_empty_dict_ref(lua_State *lstate)
+ FUNC_ATTR_NONNULL_ALL
+{
+ nlua_ref_state_t *ref_state = nlua_get_ref_state(lstate);
+ return ref_state->empty_dict_ref;
+}
+
+int nlua_get_global_ref_count(void)
+{
+ return nlua_global_refs->ref_count;
+}
+
+static void nlua_common_vim_init(lua_State *lstate, bool is_thread)
+ FUNC_ATTR_NONNULL_ARG(1)
+{
+ nlua_ref_state_t *ref_state = nlua_new_ref_state(lstate, is_thread);
+ lua_setfield(lstate, LUA_REGISTRYINDEX, "nlua.ref_state");
+
+ // vim.is_thread
+ lua_pushboolean(lstate, is_thread);
+ lua_setfield(lstate, LUA_REGISTRYINDEX, "nvim.thread");
+ lua_pushcfunction(lstate, &nlua_is_thread);
+ lua_setfield(lstate, -2, "is_thread");
+
+ // vim.NIL
+ lua_newuserdata(lstate, 0);
+ lua_createtable(lstate, 0, 0);
+ lua_pushcfunction(lstate, &nlua_nil_tostring);
+ lua_setfield(lstate, -2, "__tostring");
+ lua_setmetatable(lstate, -2);
+ ref_state->nil_ref = nlua_ref(lstate, ref_state, -1);
+ lua_pushvalue(lstate, -1);
+ lua_setfield(lstate, LUA_REGISTRYINDEX, "mpack.NIL");
+ lua_setfield(lstate, -2, "NIL");
+
+ // vim._empty_dict_mt
+ lua_createtable(lstate, 0, 0);
+ lua_pushcfunction(lstate, &nlua_empty_dict_tostring);
+ lua_setfield(lstate, -2, "__tostring");
+ ref_state->empty_dict_ref = nlua_ref(lstate, ref_state, -1);
+ lua_pushvalue(lstate, -1);
+ lua_setfield(lstate, LUA_REGISTRYINDEX, "mpack.empty_dict");
+ lua_setfield(lstate, -2, "_empty_dict_mt");
+
+ // vim.loop
+ if (is_thread) {
+ luv_set_callback(lstate, nlua_luv_thread_cb_cfpcall);
+ luv_set_thread(lstate, nlua_luv_thread_cfpcall);
+ luv_set_cthread(lstate, nlua_luv_thread_cfcpcall);
+ } else {
+ luv_set_loop(lstate, &main_loop.uv);
+ luv_set_callback(lstate, nlua_luv_cfpcall);
+ }
+ luaopen_luv(lstate);
+ lua_pushvalue(lstate, -1);
+ lua_setfield(lstate, -3, "loop");
+
+ // package.loaded.luv = vim.loop
+ // otherwise luv will be reinitialized when require'luv'
+ lua_getglobal(lstate, "package");
+ lua_getfield(lstate, -1, "loaded");
+ lua_pushvalue(lstate, -3);
+ lua_setfield(lstate, -2, "luv");
+ lua_pop(lstate, 3);
+}
+
+static int nlua_module_preloader(lua_State *lstate)
+{
+ size_t i = (size_t)lua_tointeger(lstate, lua_upvalueindex(1));
+ ModuleDef def = builtin_modules[i];
+ char name[256];
+ name[0] = '@';
+ size_t off = xstrlcpy(name+1, def.name, (sizeof name) - 2);
+ strchrsub(name+1, '.', '/');
+ xstrlcpy(name+1+off, ".lua", (sizeof name)-2-off);
+
+ if (luaL_loadbuffer(lstate, (const char *)def.data, def.size - 1, name)) {
+ return lua_error(lstate);
+ }
+
+ lua_call(lstate, 0, 1); // propagates error to caller
+ return 1;
+}
+
+static bool nlua_init_packages(lua_State *lstate)
+ FUNC_ATTR_NONNULL_ALL
+{
+ // put builtin packages in preload
+ lua_getglobal(lstate, "package"); // [package]
+ lua_getfield(lstate, -1, "preload"); // [package, preload]
+ for (size_t i = 0; i < ARRAY_SIZE(builtin_modules); i++) {
+ ModuleDef def = builtin_modules[i];
+ lua_pushinteger(lstate, (long)i); // [package, preload, i]
+ lua_pushcclosure(lstate, nlua_module_preloader, 1); // [package, preload, cclosure]
+ lua_setfield(lstate, -2, def.name); // [package, preload]
+
+ if (nlua_disable_preload && strequal(def.name, "vim.inspect")) {
+ break;
+ }
+ }
+
+ lua_pop(lstate, 2); // []
+
+ lua_getglobal(lstate, "require");
+ lua_pushstring(lstate, "vim._init_packages");
+ if (nlua_pcall(lstate, 1, 0)) {
+ mch_errmsg(lua_tostring(lstate, -1));
+ mch_errmsg("\n");
+ return false;
+ }
+
+ return true;
+}
+
/// Initialize lua interpreter state
///
/// Called by lua interpreter itself to initialize state.
-static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL
+static bool nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL
{
// print
lua_pushcfunction(lstate, &nlua_print);
@@ -377,117 +645,20 @@ static int nlua_state_init(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL
lua_pushcfunction(lstate, &nlua_wait);
lua_setfield(lstate, -2, "wait");
- // vim.NIL
- lua_newuserdata(lstate, 0);
- lua_createtable(lstate, 0, 0);
- lua_pushcfunction(lstate, &nlua_nil_tostring);
- lua_setfield(lstate, -2, "__tostring");
- lua_setmetatable(lstate, -2);
- nlua_nil_ref = nlua_ref(lstate, -1);
- lua_pushvalue(lstate, -1);
- lua_setfield(lstate, LUA_REGISTRYINDEX, "mpack.NIL");
- lua_setfield(lstate, -2, "NIL");
-
- // vim._empty_dict_mt
- lua_createtable(lstate, 0, 0);
- lua_pushcfunction(lstate, &nlua_empty_dict_tostring);
- lua_setfield(lstate, -2, "__tostring");
- nlua_empty_dict_ref = nlua_ref(lstate, -1);
- lua_pushvalue(lstate, -1);
- lua_setfield(lstate, LUA_REGISTRYINDEX, "mpack.empty_dict");
- lua_setfield(lstate, -2, "_empty_dict_mt");
+ nlua_common_vim_init(lstate, false);
// internal vim._treesitter... API
nlua_add_treesitter(lstate);
- // vim.loop
- luv_set_loop(lstate, &main_loop.uv);
- luv_set_callback(lstate, nlua_luv_cfpcall);
- luaopen_luv(lstate);
- lua_pushvalue(lstate, -1);
- lua_setfield(lstate, -3, "loop");
-
- // package.loaded.luv = vim.loop
- // otherwise luv will be reinitialized when require'luv'
- lua_getglobal(lstate, "package");
- lua_getfield(lstate, -1, "loaded");
- lua_pushvalue(lstate, -3);
- lua_setfield(lstate, -2, "luv");
- lua_pop(lstate, 3);
-
- nlua_state_add_stdlib(lstate);
+ nlua_state_add_stdlib(lstate, false);
lua_setglobal(lstate, "vim");
- {
- const char *code = (char *)&shared_module[0];
- 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\n"));
- return 1;
- }
- }
-
- {
- lua_getglobal(lstate, "package"); // [package]
- lua_getfield(lstate, -1, "loaded"); // [package, loaded]
-
- const char *code = (char *)&inspect_module[0];
- 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\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, sizeof(lua_F_module) - 1, "@vim/F.lua")
- || nlua_pcall(lstate, 0, 1)) {
- 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, sizeof(vim_module) - 1, "@vim.lua")
- || nlua_pcall(lstate, 0, 0)) {
- nlua_error(lstate, _("E5106: Error while creating vim module: %.*s\n"));
- return 1;
- }
- }
-
- {
- lua_getglobal(lstate, "package"); // [package]
- lua_getfield(lstate, -1, "loaded"); // [package, loaded]
-
- const char *code = (char *)&lua_meta_module[0];
- 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\n"));
- return 1;
- }
- // [package, loaded, module]
- lua_setfield(lstate, -2, "vim._meta"); // [package, loaded]
-
- lua_pop(lstate, 2); // []
+ if (!nlua_init_packages(lstate)) {
+ return false;
}
- return 0;
+ return true;
}
/// Initialize global lua interpreter
@@ -504,15 +675,66 @@ void nlua_init(void)
lua_State *lstate = luaL_newstate();
if (lstate == NULL) {
- emsg(_("E970: Failed to initialize lua interpreter"));
- preserve_exit();
+ mch_errmsg(_("E970: Failed to initialize lua interpreter\n"));
+ os_exit(1);
}
luaL_openlibs(lstate);
- nlua_state_init(lstate);
+ if (!nlua_state_init(lstate)) {
+ mch_errmsg(_("E970: Failed to initialize builtin lua modules\n"));
+ os_exit(1);
+ }
+
+ luv_set_thread_cb(nlua_thread_acquire_vm, nlua_common_free_all_mem);
global_lstate = lstate;
+
+ main_thread = uv_thread_self();
}
+static lua_State *nlua_thread_acquire_vm(void)
+{
+ // If it is called from the main thread, it will attempt to rebuild the cache.
+ const uv_thread_t self = uv_thread_self();
+ if (uv_thread_equal(&main_thread, &self)) {
+ runtime_search_path_validate();
+ }
+
+ lua_State *lstate = luaL_newstate();
+
+ // Add in the lua standard libraries
+ luaL_openlibs(lstate);
+
+ // print
+ lua_pushcfunction(lstate, &nlua_print);
+ lua_setglobal(lstate, "print");
+
+ lua_pushinteger(lstate, 0);
+ lua_setfield(lstate, LUA_REGISTRYINDEX, "nlua.refcount");
+
+ // vim
+ lua_newtable(lstate);
+
+ nlua_common_vim_init(lstate, true);
+
+ nlua_state_add_stdlib(lstate, true);
+
+ lua_createtable(lstate, 0, 0);
+ lua_pushcfunction(lstate, nlua_thr_api_nvim__get_runtime);
+ lua_setfield(lstate, -2, "nvim__get_runtime");
+ lua_setfield(lstate, -2, "api");
+
+ lua_setglobal(lstate, "vim");
+
+ nlua_init_packages(lstate);
+
+ lua_getglobal(lstate, "package");
+ lua_getfield(lstate, -1, "loaded");
+ lua_getglobal(lstate, "vim");
+ lua_setfield(lstate, -2, "vim");
+ lua_pop(lstate, 2);
+
+ return lstate;
+}
void nlua_free_all_mem(void)
{
@@ -520,26 +742,30 @@ void nlua_free_all_mem(void)
return;
}
lua_State *lstate = global_lstate;
+ nlua_common_free_all_mem(lstate);
+}
- nlua_unref(lstate, nlua_nil_ref);
- nlua_unref(lstate, nlua_empty_dict_ref);
+static void nlua_common_free_all_mem(lua_State *lstate)
+ FUNC_ATTR_NONNULL_ALL
+{
+ nlua_ref_state_t *ref_state = nlua_get_ref_state(lstate);
+ nlua_unref(lstate, ref_state, ref_state->nil_ref);
+ nlua_unref(lstate, ref_state, ref_state->empty_dict_ref);
#ifdef NLUA_TRACK_REFS
- if (nlua_refcount) {
- fprintf(stderr, "%d lua references were leaked!", nlua_refcount);
+ if (ref_state->ref_count) {
+ fprintf(stderr, "%d lua references were leaked!", ref_state->ref_count);
}
if (nlua_track_refs) {
// in case there are leaked luarefs, leak the associated memory
// to get LeakSanitizer stacktraces on exit
- pmap_destroy(handle_T)(&nlua_ref_markers);
+ pmap_destroy(handle_T)(&ref_state->ref_markers);
}
#endif
- nlua_refcount = 0;
lua_close(lstate);
}
-
static void nlua_print_event(void **argv)
{
char *str = argv[0];
@@ -617,9 +843,18 @@ static int nlua_print(lua_State *const lstate)
#undef PRINT_ERROR
ga_append(&msg_ga, NUL);
- if (in_fast_callback) {
+ lua_getfield(lstate, LUA_REGISTRYINDEX, "nvim.thread");
+ bool is_thread = lua_toboolean(lstate, -1);
+ lua_pop(lstate, 1);
+
+ if (is_thread) {
+ loop_schedule_deferred(&main_loop,
+ event_create(nlua_print_event, 2,
+ msg_ga.ga_data,
+ (intptr_t)msg_ga.ga_len));
+ } else if (in_fast_callback) {
multiqueue_put(main_loop.events, nlua_print_event,
- 2, msg_ga.ga_data, msg_ga.ga_len);
+ 2, msg_ga.ga_data, (intptr_t)msg_ga.ga_len);
} else {
nlua_print_event((void *[]){ msg_ga.ga_data,
(void *)(intptr_t)msg_ga.ga_len });
@@ -628,10 +863,12 @@ static int nlua_print(lua_State *const lstate)
nlua_print_error:
ga_clear(&msg_ga);
+ char *buff = xmalloc(IOSIZE);
const char *fmt = _("E5114: Error while converting print argument #%i: %.*s");
- size_t len = (size_t)vim_snprintf((char *)IObuff, IOSIZE, fmt, curargidx,
+ size_t len = (size_t)vim_snprintf(buff, IOSIZE, fmt, curargidx,
(int)errmsg_len, errmsg);
- lua_pushlstring(lstate, (char *)IObuff, len);
+ lua_pushlstring(lstate, buff, len);
+ xfree(buff);
return lua_error(lstate);
}
@@ -821,40 +1058,53 @@ static int nlua_getenv(lua_State *lstate)
/// add the value to the registry
-LuaRef nlua_ref(lua_State *lstate, int index)
+/// The current implementation does not support calls from threads.
+LuaRef nlua_ref(lua_State *lstate, nlua_ref_state_t *ref_state, int index)
{
lua_pushvalue(lstate, index);
LuaRef ref = luaL_ref(lstate, LUA_REGISTRYINDEX);
if (ref > 0) {
- nlua_refcount++;
+ ref_state->ref_count++;
#ifdef NLUA_TRACK_REFS
if (nlua_track_refs) {
// dummy allocation to make LeakSanitizer track our luarefs
- pmap_put(handle_T)(&nlua_ref_markers, ref, xmalloc(3));
+ pmap_put(handle_T)(&ref_state->ref_markers, ref, xmalloc(3));
}
#endif
}
return ref;
}
+
+LuaRef nlua_ref_global(lua_State *lstate, int index)
+{
+ return nlua_ref(lstate, nlua_global_refs, index);
+}
+
/// remove the value from the registry
-void nlua_unref(lua_State *lstate, LuaRef ref)
+void nlua_unref(lua_State *lstate, nlua_ref_state_t *ref_state, LuaRef ref)
{
if (ref > 0) {
- nlua_refcount--;
+ ref_state->ref_count--;
#ifdef NLUA_TRACK_REFS
// NB: don't remove entry from map to track double-unref
if (nlua_track_refs) {
- xfree(pmap_get(handle_T)(&nlua_ref_markers, ref));
+ xfree(pmap_get(handle_T)(&ref_state->ref_markers, ref));
}
#endif
luaL_unref(lstate, LUA_REGISTRYINDEX, ref);
}
}
+void nlua_unref_global(lua_State *lstate, LuaRef ref)
+{
+ nlua_unref(lstate, nlua_global_refs, ref);
+}
+
+
void api_free_luaref(LuaRef ref)
{
- nlua_unref(global_lstate, ref);
+ nlua_unref_global(global_lstate, ref);
}
/// push a value referenced in the registry
@@ -876,7 +1126,7 @@ LuaRef api_new_luaref(LuaRef original_ref)
lua_State *const lstate = global_lstate;
nlua_pushref(lstate, original_ref);
- LuaRef new_ref = nlua_ref(lstate, -1);
+ LuaRef new_ref = nlua_ref_global(lstate, -1);
lua_pop(lstate, 1);
return new_ref;
}
@@ -1078,6 +1328,19 @@ Object nlua_exec(const String str, const Array args, Error *err)
return nlua_pop_Object(lstate, false, err);
}
+bool nlua_ref_is_function(LuaRef ref)
+{
+ lua_State *const lstate = global_lstate;
+ nlua_pushref(lstate, ref);
+
+ // TODO(tjdevries): This should probably check for callable tables as well.
+ // We should put some work maybe into simplifying how all of that works
+ bool is_function = (lua_type(lstate, -1) == LUA_TFUNCTION);
+ lua_pop(lstate, 1);
+
+ return is_function;
+}
+
/// call a LuaRef as a function (or table with __call metamethod)
///
/// @param ref the reference to call (not consumed)
@@ -1406,6 +1669,13 @@ cleanup:
return ret;
}
+static int nlua_is_thread(lua_State *lstate)
+{
+ lua_getfield(lstate, LUA_REGISTRYINDEX, "nvim.thread");
+
+ return 1;
+}
+
// Required functions for lua c functions as VimL callbacks
int nlua_CFunction_func_call(int argcount, typval_T *argvars, typval_T *rettv, void *state)
@@ -1422,7 +1692,7 @@ void nlua_CFunction_func_free(void *state)
lua_State *const lstate = global_lstate;
LuaCFunctionState *funcstate = (LuaCFunctionState *)state;
- nlua_unref(lstate, funcstate->lua_callable.func_ref);
+ nlua_unref_global(lstate, funcstate->lua_callable.func_ref);
xfree(funcstate);
}
@@ -1472,7 +1742,7 @@ char_u *nlua_register_table_as_callable(typval_T *const arg)
lua_pop(lstate, 2); // [table]
LuaCFunctionState *state = xmalloc(sizeof(LuaCFunctionState));
- state->lua_callable.func_ref = nlua_ref(lstate, -1);
+ state->lua_callable.func_ref = nlua_ref_global(lstate, -1);
char_u *name = register_cfunc(&nlua_CFunction_func_call,
&nlua_CFunction_func_free, state);
@@ -1519,6 +1789,58 @@ void nlua_execute_on_key(int c)
#endif
}
+// Sets the editor "script context" during Lua execution. Used by :verbose.
+// @param[out] current
+void nlua_set_sctx(sctx_T *current)
+{
+ if (p_verbose <= 0 || current->sc_sid != SID_LUA) {
+ return;
+ }
+ lua_State *const lstate = global_lstate;
+ lua_Debug *info = (lua_Debug *)xmalloc(sizeof(lua_Debug));
+
+ // Files where internal wrappers are defined so we can ignore them
+ // like vim.o/opt etc are defined in _meta.lua
+ char *ignorelist[] = {
+ "vim/_meta.lua",
+ "vim/keymap.lua",
+ };
+ int ignorelist_size = sizeof(ignorelist) / sizeof(ignorelist[0]);
+
+ for (int level = 1; true; level++) {
+ if (lua_getstack(lstate, level, info) != 1) {
+ goto cleanup;
+ }
+ if (lua_getinfo(lstate, "nSl", info) == 0) {
+ goto cleanup;
+ }
+
+ bool is_ignored = false;
+ if (info->what[0] == 'C' || info->source[0] != '@') {
+ is_ignored = true;
+ } else {
+ for (int i = 0; i < ignorelist_size; i++) {
+ if (strncmp(ignorelist[i], info->source+1, strlen(ignorelist[i])) == 0) {
+ is_ignored = true;
+ break;
+ }
+ }
+ }
+ if (is_ignored) {
+ continue;
+ }
+ break;
+ }
+ char *source_path = fix_fname(info->source + 1);
+ get_current_script_id((char_u *)source_path, current);
+ xfree(source_path);
+ current->sc_lnum = info->currentline;
+ current->sc_seq = -1;
+
+cleanup:
+ xfree(info);
+}
+
void nlua_do_ucmd(ucmd_T *cmd, exarg_T *eap)
{
lua_State *const lstate = global_lstate;
@@ -1535,8 +1857,31 @@ void nlua_do_ucmd(ucmd_T *cmd, exarg_T *eap)
lua_pushinteger(lstate, eap->line2);
lua_setfield(lstate, -2, "line2");
+ lua_newtable(lstate); // f-args table
lua_pushstring(lstate, (const char *)eap->arg);
- lua_setfield(lstate, -2, "args");
+ lua_pushvalue(lstate, -1); // Reference for potential use on f-args
+ lua_setfield(lstate, -4, "args");
+
+ // Split args by unescaped whitespace |<f-args>| (nargs dependent)
+ if (cmd->uc_argt & EX_NOSPC) {
+ // Commands where nargs = 1 or "?" fargs is the same as args
+ lua_rawseti(lstate, -2, 1);
+ } else {
+ // Commands with more than one possible argument we split
+ lua_pop(lstate, 1); // Pop the reference of opts.args
+ int length = (int)STRLEN(eap->arg);
+ int start = 0;
+ int end = 0;
+ int i = 1;
+ bool res = true;
+ while (res) {
+ res = uc_split_args_iter(eap->arg, i, &start, &end, length);
+ lua_pushlstring(lstate, (const char *)eap->arg + start, (size_t)(end - start + 1));
+ lua_rawseti(lstate, -2, i);
+ i++;
+ }
+ }
+ lua_setfield(lstate, -2, "fargs");
lua_pushstring(lstate, (const char *)&eap->regname);
lua_setfield(lstate, -2, "reg");
diff --git a/src/nvim/lua/executor.h b/src/nvim/lua/executor.h
index bf78f7ec5e..e96494ec5a 100644
--- a/src/nvim/lua/executor.h
+++ b/src/nvim/lua/executor.h
@@ -5,6 +5,7 @@
#include <lua.h>
#include "nvim/api/private/defs.h"
+#include "nvim/assert.h"
#include "nvim/eval/typval.h"
#include "nvim/ex_cmds_defs.h"
#include "nvim/ex_docmd.h"
@@ -14,18 +15,14 @@
// Generated by msgpack-gen.lua
void nlua_add_api_functions(lua_State *lstate) REAL_FATTR_NONNULL_ALL;
-EXTERN LuaRef nlua_nil_ref INIT(= LUA_NOREF);
-EXTERN LuaRef nlua_empty_dict_ref INIT(= LUA_NOREF);
-
-EXTERN int nlua_refcount INIT(= 0);
-
-#define set_api_error(s, err) \
- do { \
- Error *err_ = (err); \
- err_->type = kErrorTypeException; \
- err_->set = true; \
- memcpy(&err_->msg[0], s, sizeof(s)); \
- } while (0)
+typedef struct {
+ LuaRef nil_ref;
+ LuaRef empty_dict_ref;
+ int ref_count;
+#if __has_feature(address_sanitizer)
+ PMap(handle_T) ref_markers;
+#endif
+} nlua_ref_state_t;
#define NLUA_CLEAR_REF(x) \
do { \
@@ -39,4 +36,8 @@ EXTERN int nlua_refcount INIT(= 0);
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "lua/executor.h.generated.h"
#endif
+
+EXTERN nlua_ref_state_t *nlua_global_refs INIT(= NULL);
+EXTERN bool nlua_disable_preload INIT(= false);
+
#endif // NVIM_LUA_EXECUTOR_H
diff --git a/src/nvim/lua/spell.c b/src/nvim/lua/spell.c
index 3a63f61200..31a2b2d19f 100644
--- a/src/nvim/lua/spell.c
+++ b/src/nvim/lua/spell.c
@@ -1,12 +1,12 @@
// 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 <lua.h>
+#include "nvim/lua/spell.h"
#include "nvim/spell.h"
#include "nvim/vim.h"
-#include "nvim/lua/spell.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "lua/spell.c.generated.h"
@@ -45,7 +45,7 @@ int nlua_spell_check(lua_State *lstate)
size_t pos = 0;
int capcol = -1;
int no_res = 0;
- const char * result;
+ const char *result;
lua_createtable(lstate, 0, 0);
@@ -90,7 +90,7 @@ int nlua_spell_check(lua_State *lstate)
static const luaL_Reg spell_functions[] = {
{ "check", nlua_spell_check },
- { NULL , NULL }
+ { NULL, NULL }
};
int luaopen_spell(lua_State *L)
diff --git a/src/nvim/lua/stdlib.c b/src/nvim/lua/stdlib.c
index 55b23cf0c8..e94c61b37c 100644
--- a/src/nvim/lua/stdlib.c
+++ b/src/nvim/lua/stdlib.c
@@ -28,10 +28,10 @@
#include "nvim/globals.h"
#include "nvim/lua/converter.h"
#include "nvim/lua/executor.h"
+#include "nvim/lua/spell.h"
#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"
@@ -411,7 +411,7 @@ int nlua_getvar(lua_State *lstate)
dictitem_T *di = tv_dict_find(dict, name, (ptrdiff_t)len);
if (di == NULL && dict == &globvardict) { // try to autoload script
if (!script_autoload(name, len, false) || aborting()) {
- return 0; // nil
+ return 0; // nil
}
di = tv_dict_find(dict, name, (ptrdiff_t)len);
}
@@ -471,43 +471,52 @@ static int nlua_stricmp(lua_State *const lstate) FUNC_ATTR_NONNULL_ALL
}
-void nlua_state_add_stdlib(lua_State *const lstate)
+void nlua_state_add_stdlib(lua_State *const lstate, bool is_thread)
{
- // stricmp
- lua_pushcfunction(lstate, &nlua_stricmp);
- lua_setfield(lstate, -2, "stricmp");
- // str_utfindex
- lua_pushcfunction(lstate, &nlua_str_utfindex);
- lua_setfield(lstate, -2, "str_utfindex");
- // str_byteindex
- lua_pushcfunction(lstate, &nlua_str_byteindex);
- lua_setfield(lstate, -2, "str_byteindex");
- // str_utf_pos
- lua_pushcfunction(lstate, &nlua_str_utf_pos);
- lua_setfield(lstate, -2, "str_utf_pos");
- // str_utf_start
- lua_pushcfunction(lstate, &nlua_str_utf_start);
- lua_setfield(lstate, -2, "str_utf_start");
- // str_utf_end
- lua_pushcfunction(lstate, &nlua_str_utf_end);
- lua_setfield(lstate, -2, "str_utf_end");
- // regex
- lua_pushcfunction(lstate, &nlua_regex);
- lua_setfield(lstate, -2, "regex");
- luaL_newmetatable(lstate, "nvim_regex");
- luaL_register(lstate, NULL, regex_meta);
-
- lua_pushvalue(lstate, -1); // [meta, meta]
- lua_setfield(lstate, -2, "__index"); // [meta]
- lua_pop(lstate, 1); // don't use metatable now
-
- // _getvar
- lua_pushcfunction(lstate, &nlua_getvar);
- lua_setfield(lstate, -2, "_getvar");
-
- // _setvar
- lua_pushcfunction(lstate, &nlua_setvar);
- lua_setfield(lstate, -2, "_setvar");
+ if (!is_thread) {
+ // TODO(bfredl): some of basic string functions should already be
+ // (or be easy to make) threadsafe
+
+ // stricmp
+ lua_pushcfunction(lstate, &nlua_stricmp);
+ lua_setfield(lstate, -2, "stricmp");
+ // str_utfindex
+ lua_pushcfunction(lstate, &nlua_str_utfindex);
+ lua_setfield(lstate, -2, "str_utfindex");
+ // str_byteindex
+ lua_pushcfunction(lstate, &nlua_str_byteindex);
+ lua_setfield(lstate, -2, "str_byteindex");
+ // str_utf_pos
+ lua_pushcfunction(lstate, &nlua_str_utf_pos);
+ lua_setfield(lstate, -2, "str_utf_pos");
+ // str_utf_start
+ lua_pushcfunction(lstate, &nlua_str_utf_start);
+ lua_setfield(lstate, -2, "str_utf_start");
+ // str_utf_end
+ lua_pushcfunction(lstate, &nlua_str_utf_end);
+ lua_setfield(lstate, -2, "str_utf_end");
+ // regex
+ lua_pushcfunction(lstate, &nlua_regex);
+ lua_setfield(lstate, -2, "regex");
+ luaL_newmetatable(lstate, "nvim_regex");
+ luaL_register(lstate, NULL, regex_meta);
+
+ lua_pushvalue(lstate, -1); // [meta, meta]
+ lua_setfield(lstate, -2, "__index"); // [meta]
+ lua_pop(lstate, 1); // don't use metatable now
+
+ // _getvar
+ lua_pushcfunction(lstate, &nlua_getvar);
+ lua_setfield(lstate, -2, "_getvar");
+
+ // _setvar
+ lua_pushcfunction(lstate, &nlua_setvar);
+ lua_setfield(lstate, -2, "_setvar");
+
+ // vim.spell
+ luaopen_spell(lstate);
+ lua_setfield(lstate, -2, "spell");
+ }
// vim.mpack
luaopen_mpack(lstate);
@@ -526,10 +535,7 @@ 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");
-
+ // vim.json
lua_cjson_new(lstate);
lua_setfield(lstate, -2, "json");
}
diff --git a/src/nvim/lua/xdiff.c b/src/nvim/lua/xdiff.c
index ea7a700e1e..37855630d1 100644
--- a/src/nvim/lua/xdiff.c
+++ b/src/nvim/lua/xdiff.c
@@ -171,6 +171,7 @@ static NluaXdiffMode process_xdl_diff_opts(lua_State *lstate, xdemitconf_t *cfg,
goto exit_1;
}
if (strequal("unified", v->data.string.data)) {
+ // the default
} else if (strequal("indices", v->data.string.data)) {
had_result_type_indices = true;
} else {
diff --git a/src/nvim/main.c b/src/nvim/main.c
index 8991ae7f00..d67b47e82c 100644
--- a/src/nvim/main.c
+++ b/src/nvim/main.c
@@ -9,11 +9,12 @@
#include <string.h>
#include "nvim/ascii.h"
-#include "nvim/aucmd.h"
+#include "nvim/autocmd.h"
#include "nvim/buffer.h"
#include "nvim/channel.h"
#include "nvim/charset.h"
#include "nvim/decoration.h"
+#include "nvim/decoration_provider.h"
#include "nvim/diff.h"
#include "nvim/eval.h"
#include "nvim/ex_cmds.h"
@@ -28,6 +29,7 @@
#include "nvim/if_cscope.h"
#include "nvim/lua/executor.h"
#include "nvim/main.h"
+#include "nvim/ui_client.h"
#include "nvim/vim.h"
#ifdef HAVE_LOCALE_H
# include <locale.h>
@@ -110,7 +112,6 @@ static const char *err_too_many_args = N_("Too many edit arguments");
static const char *err_extra_cmd =
N_("Too many \"+command\", \"-c command\" or \"--cmd command\" arguments");
-
void event_init(void)
{
loop_init(&main_loop, NULL);
@@ -154,10 +155,10 @@ bool event_teardown(void)
void early_init(mparm_T *paramp)
{
env_init();
- fs_init();
eval_init(); // init global variables
init_path(argv0 ? argv0 : "nvim");
init_normal_cmds(); // Init the table of Normal mode commands.
+ runtime_init();
highlight_init();
#ifdef WIN32
@@ -230,6 +231,10 @@ int main(int argc, char **argv)
// `argc` and `argv` are also copied, so that they can be changed.
init_params(&params, argc, argv);
+ // Since os_open is called during the init_startuptime, we need to call
+ // fs_init before it.
+ fs_init();
+
init_startuptime(&params);
// Need to find "--clean" before actually parsing arguments.
@@ -249,12 +254,12 @@ int main(int argc, char **argv)
// Check if we have an interactive window.
check_and_set_isatty(&params);
- nlua_init();
-
// Process the command line arguments. File names are put in the global
// argument list "global_alist".
command_line_scan(&params);
+ nlua_init();
+
if (embedded_mode) {
const char *err;
if (!channel_from_stdio(true, CALLBACK_READER_INIT, &err)) {
@@ -263,6 +268,9 @@ int main(int argc, char **argv)
}
server_init(params.listen_addr);
+ if (params.remote) {
+ remote_request(&params, params.remote, params.server_addr, argc, argv);
+ }
if (GARGCOUNT > 0) {
fname = get_fname(&params, cwd);
@@ -335,6 +343,12 @@ int main(int argc, char **argv)
TIME_MSG("init screen for UI");
}
+ if (ui_client_channel_id) {
+ ui_client_init(ui_client_channel_id);
+ ui_client_execute(ui_client_channel_id);
+ abort(); // unreachable
+ }
+
init_default_mappings(); // Default mappings.
TIME_MSG("init default mappings");
@@ -353,7 +367,7 @@ int main(int argc, char **argv)
// Execute --cmd arguments.
exe_pre_commands(&params);
- if (!vimrc_none) {
+ if (!vimrc_none || params.clean) {
// 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).
@@ -364,7 +378,7 @@ int main(int argc, char **argv)
source_startup_scripts(&params);
// If using the runtime (-u is not NONE), enable syntax & filetype plugins.
- if (!vimrc_none) {
+ if (!vimrc_none || params.clean) {
// Sources filetype.lua and filetype.vim unless the user explicitly disabled it with :filetype
// off.
filetype_maybe_enable();
@@ -798,6 +812,114 @@ static void init_locale(void)
}
#endif
+
+static uint64_t server_connect(char *server_addr, const char **errmsg)
+{
+ if (server_addr == NULL) {
+ *errmsg = "no address specified";
+ return 0;
+ }
+ CallbackReader on_data = CALLBACK_READER_INIT;
+ const char *error = NULL;
+ bool is_tcp = strrchr(server_addr, ':') ? true : false;
+ // connected to channel
+ uint64_t chan = channel_connect(is_tcp, server_addr, true, on_data, 50, &error);
+ if (error) {
+ *errmsg = error;
+ return 0;
+ }
+ return chan;
+}
+
+/// Handle remote subcommands
+static void remote_request(mparm_T *params, int remote_args,
+ char *server_addr, int argc, char **argv)
+{
+ const char *connect_error = NULL;
+ uint64_t chan = server_connect(server_addr, &connect_error);
+ Object rvobj = OBJECT_INIT;
+
+ if (strequal(argv[remote_args], "--remote-ui-test")) {
+ if (!chan) {
+ emsg(connect_error);
+ exit(1);
+ }
+
+ ui_client_channel_id = chan;
+ return;
+ }
+
+ Array args = ARRAY_DICT_INIT;
+ String arg_s;
+ for (int t_argc = remote_args; t_argc < argc; t_argc++) {
+ arg_s = cstr_to_string(argv[t_argc]);
+ ADD(args, STRING_OBJ(arg_s));
+ }
+
+ Error err = ERROR_INIT;
+ Array a = ARRAY_DICT_INIT;
+ ADD(a, INTEGER_OBJ((int)chan));
+ ADD(a, CSTR_TO_OBJ(server_addr));
+ ADD(a, CSTR_TO_OBJ(connect_error));
+ ADD(a, ARRAY_OBJ(args));
+ String s = STATIC_CSTR_AS_STRING("return vim._cs_remote(...)");
+ Object o = nlua_exec(s, a, &err);
+ api_free_array(a);
+ if (ERROR_SET(&err)) {
+ mch_errmsg(err.msg);
+ mch_errmsg("\n");
+ os_exit(2);
+ }
+
+ if (o.type == kObjectTypeDictionary) {
+ rvobj.data.dictionary = o.data.dictionary;
+ } else {
+ mch_errmsg("vim._cs_remote returned unexpected value\n");
+ os_exit(2);
+ }
+
+ TriState should_exit = kNone;
+ TriState tabbed = kNone;
+
+ for (size_t i = 0; i < rvobj.data.dictionary.size ; i++) {
+ if (strcmp(rvobj.data.dictionary.items[i].key.data, "errmsg") == 0) {
+ if (rvobj.data.dictionary.items[i].value.type != kObjectTypeString) {
+ mch_errmsg("vim._cs_remote returned an unexpected type for 'errmsg'\n");
+ os_exit(2);
+ }
+ mch_errmsg(rvobj.data.dictionary.items[i].value.data.string.data);
+ mch_errmsg("\n");
+ os_exit(2);
+ } else if (strcmp(rvobj.data.dictionary.items[i].key.data, "tabbed") == 0) {
+ if (rvobj.data.dictionary.items[i].value.type != kObjectTypeBoolean) {
+ mch_errmsg("vim._cs_remote returned an unexpected type for 'tabbed'\n");
+ os_exit(2);
+ }
+ tabbed = rvobj.data.dictionary.items[i].value.data.boolean ? kTrue : kFalse;
+ } else if (strcmp(rvobj.data.dictionary.items[i].key.data, "should_exit") == 0) {
+ if (rvobj.data.dictionary.items[i].value.type != kObjectTypeBoolean) {
+ mch_errmsg("vim._cs_remote returned an unexpected type for 'should_exit'\n");
+ os_exit(2);
+ }
+ should_exit = rvobj.data.dictionary.items[i].value.data.boolean ? kTrue : kFalse;
+ }
+ }
+ if (should_exit == kNone || tabbed == kNone) {
+ mch_errmsg("vim._cs_remote didn't return a value for should_exit or tabbed, bailing\n");
+ os_exit(2);
+ }
+ api_free_object(o);
+
+ if (should_exit == kTrue) {
+ os_exit(0);
+ }
+ if (tabbed == kTrue) {
+ params->window_count = argc - remote_args - 1;
+ params->window_layout = WIN_TABS;
+ }
+}
+
+
/// Decides whether text (as opposed to commands) will be read from stdin.
/// @see EDIT_STDIN
static bool edit_stdin(bool explicit, mparm_T *parmp)
@@ -819,7 +941,6 @@ static void command_line_scan(mparm_T *parmp)
bool had_stdin_file = false; // found explicit "-" argument
bool had_minmin = false; // found "--" argument
int want_argument; // option argument with argument
- int c;
long n;
argc--;
@@ -841,7 +962,7 @@ static void command_line_scan(mparm_T *parmp)
// Optional argument.
} else if (argv[0][0] == '-' && !had_minmin) {
want_argument = false;
- c = argv[0][argv_idx++];
+ char c = argv[0][argv_idx++];
switch (c) {
case NUL: // "nvim -" read from stdin
if (exmode_active) {
@@ -864,6 +985,8 @@ static void command_line_scan(mparm_T *parmp)
// "--version" give version message
// "--noplugin[s]" skip plugins
// "--cmd <cmd>" execute cmd before vimrc
+ // "--remote" execute commands remotey on a server
+ // "--server" name of vim server to send remote commands to
if (STRICMP(argv[0] + argv_idx, "help") == 0) {
usage();
os_exit(0);
@@ -902,6 +1025,11 @@ static void command_line_scan(mparm_T *parmp)
argv_idx += 6;
} else if (STRNICMP(argv[0] + argv_idx, "literal", 7) == 0) {
// Do nothing: file args are always literal. #7679
+ } else if (STRNICMP(argv[0] + argv_idx, "remote", 6) == 0) {
+ parmp->remote = parmp->argc - argc;
+ } else if (STRNICMP(argv[0] + argv_idx, "server", 6) == 0) {
+ want_argument = true;
+ argv_idx += 6;
} else if (STRNICMP(argv[0] + argv_idx, "noplugin", 8) == 0) {
p_lpl = false;
} else if (STRNICMP(argv[0] + argv_idx, "cmd", 3) == 0) {
@@ -914,6 +1042,8 @@ static void command_line_scan(mparm_T *parmp)
parmp->use_vimrc = "NONE";
parmp->clean = true;
set_option_value("shadafile", 0L, "NONE", 0);
+ } else if (STRNICMP(argv[0] + argv_idx, "luamod-dev", 9) == 0) {
+ nlua_disable_preload = true;
} else {
if (argv[0][argv_idx]) {
mainerr(err_opt_unknown, argv[0]);
@@ -1131,6 +1261,9 @@ static void command_line_scan(mparm_T *parmp)
} else if (strequal(argv[-1], "--listen")) {
// "--listen {address}"
parmp->listen_addr = argv[0];
+ } else if (strequal(argv[-1], "--server")) {
+ // "--server {address}"
+ parmp->server_addr = argv[0];
}
// "--startuptime <file>" already handled
break;
@@ -1285,6 +1418,8 @@ static void init_params(mparm_T *paramp, int argc, char **argv)
paramp->use_debug_break_level = -1;
paramp->window_count = -1;
paramp->listen_addr = NULL;
+ paramp->server_addr = NULL;
+ paramp->remote = 0;
}
/// Initialize global startuptime file if "--startuptime" passed as an argument.
@@ -1986,6 +2121,8 @@ static void mainerr(const char *errstr, const char *str)
/// Prints version information for "nvim -v" or "nvim --version".
static void version(void)
{
+ // TODO(bfred): not like this?
+ nlua_init();
info_message = true; // use mch_msg(), not mch_errmsg()
list_version();
msg_putchar('\n');
@@ -2033,6 +2170,8 @@ static void usage(void)
mch_msg(_(" --headless Don't start a user interface\n"));
mch_msg(_(" --listen <address> Serve RPC API from this address\n"));
mch_msg(_(" --noplugin Don't load plugins\n"));
+ mch_msg(_(" --remote[-subcommand] Execute commands remotely on a server\n"));
+ mch_msg(_(" --server <address> Specify RPC server to send commands to\n"));
mch_msg(_(" --startuptime <file> Write startup timing messages to <file>\n"));
mch_msg(_("\nSee \":help startup-options\" for all options.\n"));
}
diff --git a/src/nvim/main.h b/src/nvim/main.h
index f73af5c288..e55bef6e33 100644
--- a/src/nvim/main.h
+++ b/src/nvim/main.h
@@ -39,6 +39,8 @@ typedef struct {
int diff_mode; // start with 'diff' set
char *listen_addr; // --listen {address}
+ int remote; // --remote-[subcmd] {file1} {file2}
+ char *server_addr; // --server {address}
} mparm_T;
#ifdef INCLUDE_GENERATED_DECLARATIONS
diff --git a/src/nvim/map.c b/src/nvim/map.c
index 77ebc2a387..b3f48ad5d6 100644
--- a/src/nvim/map.c
+++ b/src/nvim/map.c
@@ -177,6 +177,9 @@ MAP_IMPL(handle_T, ptr_t, DEFAULT_INITIALIZER)
MAP_IMPL(String, MsgpackRpcRequestHandler, MSGPACK_HANDLER_INITIALIZER)
MAP_IMPL(HlEntry, int, DEFAULT_INITIALIZER)
MAP_IMPL(String, handle_T, 0)
+MAP_IMPL(String, int, DEFAULT_INITIALIZER)
+MAP_IMPL(int, String, DEFAULT_INITIALIZER)
+MAP_IMPL(String, UIClientHandler, NULL)
MAP_IMPL(ColorKey, ColorItem, COLOR_ITEM_INITIALIZER)
diff --git a/src/nvim/map.h b/src/nvim/map.h
index 5e56f4dd65..693ef50127 100644
--- a/src/nvim/map.h
+++ b/src/nvim/map.h
@@ -8,6 +8,7 @@
#include "nvim/extmark_defs.h"
#include "nvim/highlight_defs.h"
#include "nvim/map_defs.h"
+#include "nvim/ui_client.h"
#if defined(__NetBSD__)
# undef uint64_t
@@ -46,6 +47,9 @@ MAP_DECLS(handle_T, ptr_t)
MAP_DECLS(String, MsgpackRpcRequestHandler)
MAP_DECLS(HlEntry, int)
MAP_DECLS(String, handle_T)
+MAP_DECLS(String, int)
+MAP_DECLS(int, String)
+MAP_DECLS(String, UIClientHandler)
MAP_DECLS(ColorKey, ColorItem)
diff --git a/src/nvim/mark.c b/src/nvim/mark.c
index 8b29aa3676..b770fef05c 100644
--- a/src/nvim/mark.c
+++ b/src/nvim/mark.c
@@ -630,7 +630,7 @@ static char_u *mark_line(pos_T *mp, int lead_len)
if (mp->lnum == 0 || mp->lnum > curbuf->b_ml.ml_line_count) {
return vim_strsave((char_u *)"-invalid-");
}
- assert(Columns >= 0 && (size_t)Columns <= SIZE_MAX);
+ assert(Columns >= 0);
// Allow for up to 5 bytes per character.
s = vim_strnsave(skipwhite(ml_get(mp->lnum)), (size_t)Columns * 5);
diff --git a/src/nvim/marktree.c b/src/nvim/marktree.c
index 918db8b76c..937582572b 100644
--- a/src/nvim/marktree.c
+++ b/src/nvim/marktree.c
@@ -558,8 +558,8 @@ void marktree_revise(MarkTree *b, MarkTreeIter *itr, uint8_t decor_level, mtkey_
{
// 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
+ rawkey(itr).flags = (uint16_t)(rawkey(itr).flags & (uint16_t) ~MT_FLAG_DECOR_MASK);
+ rawkey(itr).flags = (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;
@@ -1111,7 +1111,7 @@ static void marktree_itr_fix_pos(MarkTree *b, MarkTreeIter *itr)
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 };
+ mt_flags(right_gravity, 0), 0, NULL };
marktree_put(b, key, -1, -1, false);
}
@@ -1159,8 +1159,6 @@ static size_t check_node(MarkTree *b, mtnode_t *x, mtpos_t *last, bool *last_rig
if (i > 0) {
unrelative(x->key[i-1].pos, last);
}
- if (x->level) {
- }
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 || mt_right(x->key[i]));
diff --git a/src/nvim/marktree.h b/src/nvim/marktree.h
index 30f5aacebc..ae6da92106 100644
--- a/src/nvim/marktree.h
+++ b/src/nvim/marktree.h
@@ -1,14 +1,14 @@
#ifndef NVIM_MARKTREE_H
#define NVIM_MARKTREE_H
-#include <stdint.h>
#include <assert.h>
+#include <stdint.h>
#include "nvim/assert.h"
#include "nvim/garray.h"
#include "nvim/map.h"
-#include "nvim/types.h"
#include "nvim/pos.h"
+#include "nvim/types.h"
#define MT_MAX_DEPTH 20
#define MT_BRANCH_FACTOR 10
@@ -87,6 +87,11 @@ static inline bool mt_end(mtkey_t key)
return key.flags & MT_FLAG_END;
}
+static inline bool mt_start(mtkey_t key)
+{
+ return mt_paired(key) && !mt_end(key);
+}
+
static inline bool mt_right(mtkey_t key)
{
return key.flags & MT_FLAG_RIGHT_GRAVITY;
diff --git a/src/nvim/mbyte.c b/src/nvim/mbyte.c
index e5fa80a242..f634c7dda8 100644
--- a/src/nvim/mbyte.c
+++ b/src/nvim/mbyte.c
@@ -1317,6 +1317,12 @@ bool mb_isupper(int a)
return mb_tolower(a) != a;
}
+bool mb_isalpha(int a)
+ FUNC_ATTR_WARN_UNUSED_RESULT
+{
+ return mb_islower(a) || mb_isupper(a);
+}
+
static int utf_strnicmp(const char_u *s1, const char_u *s2, size_t n1, size_t n2)
{
int c1, c2, cdiff;
diff --git a/src/nvim/memline.c b/src/nvim/memline.c
index 004ef36b36..59f57aa667 100644
--- a/src/nvim/memline.c
+++ b/src/nvim/memline.c
@@ -303,7 +303,7 @@ int ml_open(buf_T *buf)
b0p->b0_id[0] = BLOCK0_ID0;
b0p->b0_id[1] = BLOCK0_ID1;
- b0p->b0_magic_long = (long)B0_MAGIC_LONG;
+ b0p->b0_magic_long = B0_MAGIC_LONG;
b0p->b0_magic_int = (int)B0_MAGIC_INT;
b0p->b0_magic_short = (short)B0_MAGIC_SHORT;
b0p->b0_magic_char = B0_MAGIC_CHAR;
@@ -3709,7 +3709,7 @@ static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_
static int b0_magic_wrong(ZERO_BL *b0p)
{
- return b0p->b0_magic_long != (long)B0_MAGIC_LONG
+ return b0p->b0_magic_long != B0_MAGIC_LONG
|| b0p->b0_magic_int != (int)B0_MAGIC_INT
|| b0p->b0_magic_short != (short)B0_MAGIC_SHORT
|| b0p->b0_magic_char != B0_MAGIC_CHAR;
diff --git a/src/nvim/memory.c b/src/nvim/memory.c
index 677ff8f522..d68ca6b62e 100644
--- a/src/nvim/memory.c
+++ b/src/nvim/memory.c
@@ -10,7 +10,7 @@
#include "nvim/api/extmark.h"
#include "nvim/context.h"
-#include "nvim/decoration.h"
+#include "nvim/decoration_provider.h"
#include "nvim/eval.h"
#include "nvim/highlight.h"
#include "nvim/lua/executor.h"
diff --git a/src/nvim/message.c b/src/nvim/message.c
index b39450cdc6..b3fefbc0f4 100644
--- a/src/nvim/message.c
+++ b/src/nvim/message.c
@@ -206,11 +206,10 @@ void msg_grid_validate(void)
}
}
-/*
- * msg(s) - displays the string 's' on the status line
- * When terminal not initialized (yet) mch_errmsg(..) is used.
- * return TRUE if wait_return not called
- */
+/// Displays the string 's' on the status line
+/// When terminal not initialized (yet) mch_errmsg(..) is used.
+///
+/// @return TRUE if wait_return not called
int msg(char *s)
{
return msg_attr_keep(s, 0, false, false);
@@ -232,7 +231,7 @@ int msg_attr(const char *s, const int attr)
return msg_attr_keep(s, attr, false, false);
}
-/// similar to msg_outtrans_attr, but support newlines and tabs.
+/// Similar to msg_outtrans_attr, but support newlines and tabs.
void msg_multiline_attr(const char *s, int attr, bool check_int, bool *need_clear)
FUNC_ATTR_NONNULL_ALL
{
@@ -339,7 +338,8 @@ bool msg_attr_keep(const char *s, int attr, bool keep, bool multiline)
}
/// Truncate a string such that it can be printed without causing a scroll.
-/// Returns an allocated string or NULL when no truncating is done.
+///
+/// @return an allocated string or NULL when no truncating is done.
///
/// @param force always truncate
char_u *msg_strtrunc(char_u *s, int force)
@@ -371,10 +371,8 @@ char_u *msg_strtrunc(char_u *s, int force)
return buf;
}
-/*
- * Truncate a string "s" to "buf" with cell width "room".
- * "s" and "buf" may be equal.
- */
+/// Truncate a string "s" to "buf" with cell width "room".
+/// "s" and "buf" may be equal.
void trunc_string(char_u *s, char_u *buf, int room_in, int buflen)
{
size_t room = room_in - 3; // "..." takes 3 chars
@@ -498,19 +496,15 @@ int smsg_attr_keep(int attr, const char *s, ...)
static int last_sourcing_lnum = 0;
static char_u *last_sourcing_name = NULL;
-/*
- * Reset the last used sourcing name/lnum. Makes sure it is displayed again
- * for the next error message;
- */
+/// Reset the last used sourcing name/lnum. Makes sure it is displayed again
+/// for the next error message;
void reset_last_sourcing(void)
{
XFREE_CLEAR(last_sourcing_name);
last_sourcing_lnum = 0;
}
-/*
- * Return TRUE if "sourcing_name" differs from "last_sourcing_name".
- */
+/// @return TRUE if "sourcing_name" differs from "last_sourcing_name".
static int other_sourcing_name(void)
{
if (sourcing_name != NULL) {
@@ -560,11 +554,9 @@ static char *get_emsg_lnum(void)
return NULL;
}
-/*
- * Display name and line number for the source of an error.
- * Remember the file name and line number, so that for the next error the info
- * is only displayed if it changed.
- */
+/// Display name and line number for the source of an error.
+/// Remember the file name and line number, so that for the next error the info
+/// is only displayed if it changed.
void msg_source(int attr)
{
no_wait_return++;
@@ -592,12 +584,10 @@ void msg_source(int attr)
--no_wait_return;
}
-/*
- * Return TRUE if not giving error messages right now:
- * If "emsg_off" is set: no error messages at the moment.
- * If "msg" is in 'debug': do error message but without side effects.
- * If "emsg_skip" is set: never do error messages.
- */
+/// @return TRUE if not giving error messages right now:
+/// If "emsg_off" is set: no error messages at the moment.
+/// If "msg" is in 'debug': do error message but without side effects.
+/// If "emsg_skip" is set: never do error messages.
int emsg_not_now(void)
{
if ((emsg_off > 0 && vim_strchr(p_debug, 'm') == NULL
@@ -840,10 +830,11 @@ void msg_schedule_semsg(const char *const fmt, ...)
multiqueue_put(main_loop.events, msg_semsg_event, 1, s);
}
-// Like msg(), but truncate to a single line if p_shm contains 't', or when
-// "force" is true. This truncates in another way as for normal messages.
-// Careful: The string may be changed by msg_may_trunc()!
-// Returns a pointer to the printed message, if wait_return() not called.
+/// Like msg(), but truncate to a single line if p_shm contains 't', or when
+/// "force" is true. This truncates in another way as for normal messages.
+/// Careful: The string may be changed by msg_may_trunc()!
+///
+/// @return a pointer to the printed message, if wait_return() not called.
char *msg_trunc_attr(char *s, bool force, int attr)
{
int n;
@@ -863,11 +854,11 @@ char *msg_trunc_attr(char *s, bool force, int attr)
return NULL;
}
-/*
- * Check if message "s" should be truncated at the start (for filenames).
- * Return a pointer to where the truncated message starts.
- * Note: May change the message by replacing a character with '<'.
- */
+/// Check if message "s" should be truncated at the start (for filenames).
+///
+/// @return a pointer to where the truncated message starts.
+///
+/// @note: May change the message by replacing a character with '<'.
char_u *msg_may_trunc(bool force, char_u *s)
{
int room;
@@ -967,10 +958,9 @@ static void add_msg_hist(const char *s, int len, int attr, bool multiline)
msg_hist_len++;
}
-/*
- * Delete the first (oldest) message from the history.
- * Returns FAIL if there are no messages.
- */
+/// Delete the first (oldest) message from the history.
+///
+/// @return FAIL if there are no messages.
int delete_first_msg(void)
{
struct msg_hist *p;
@@ -1056,10 +1046,8 @@ void ex_messages(void *const eap_p)
}
}
-/*
- * Call this after prompting the user. This will avoid a hit-return message
- * and a delay.
- */
+/// Call this after prompting the user. This will avoid a hit-return message
+/// and a delay.
void msg_end_prompt(void)
{
msg_ext_clear_later();
@@ -1073,9 +1061,9 @@ void msg_end_prompt(void)
/// Wait for the user to hit a key (normally Enter)
///
-/// If 'redraw' is true, redraw the entire screen NOT_VALID
-/// If 'redraw' is false, do a normal redraw
-/// If 'redraw' is -1, don't redraw at all
+/// @param redraw if true, redraw the entire screen NOT_VALID
+/// if false, do a normal redraw
+/// if -1, don't redraw at all
void wait_return(int redraw)
{
int c;
@@ -1265,9 +1253,7 @@ void wait_return(int redraw)
}
}
-/*
- * Write the hit-return prompt.
- */
+/// Write the hit-return prompt.
static void hit_return_msg(void)
{
int save_p_more = p_more;
@@ -1288,9 +1274,7 @@ static void hit_return_msg(void)
p_more = save_p_more;
}
-/*
- * Set "keep_msg" to "s". Free the old value and check for NULL pointer.
- */
+/// Set "keep_msg" to "s". Free the old value and check for NULL pointer.
void set_keep_msg(char *s, int attr)
{
xfree(keep_msg);
@@ -1357,9 +1341,7 @@ void msg_ext_set_kind(const char *msg_kind)
msg_ext_kind = msg_kind;
}
-/*
- * Prepare for outputting characters in the command line.
- */
+/// Prepare for outputting characters in the command line.
void msg_start(void)
{
int did_return = false;
@@ -1406,9 +1388,7 @@ void msg_start(void)
}
}
-/*
- * Note that the current msg position is where messages start.
- */
+/// Note that the current msg position is where messages start.
void msg_starthere(void)
{
lines_left = cmdline_row;
@@ -1462,12 +1442,11 @@ static void msg_home_replace_attr(char_u *fname, int attr)
xfree(name);
}
-/*
- * Output 'len' characters in 'str' (including NULs) with translation
- * if 'len' is -1, output up to a NUL character.
- * Use attributes 'attr'.
- * Return the number of characters it takes on the screen.
- */
+/// Output 'len' characters in 'str' (including NULs) with translation
+/// if 'len' is -1, output up to a NUL character.
+/// Use attributes 'attr'.
+///
+/// @return the number of characters it takes on the screen.
int msg_outtrans(char_u *str)
{
return msg_outtrans_attr(str, 0);
@@ -1483,10 +1462,10 @@ int msg_outtrans_len(const char_u *str, int len)
return msg_outtrans_len_attr(str, len, 0);
}
-/*
- * Output one character at "p". Return pointer to the next character.
- * Handles multi-byte characters.
- */
+/// Output one character at "p".
+/// Handles multi-byte characters.
+///
+/// @return pointer to the next character.
char_u *msg_outtrans_one(char_u *p, int attr)
{
int l;
@@ -1752,9 +1731,7 @@ void str2specialbuf(const char *sp, char *buf, size_t len)
*buf = NUL;
}
-/*
- * print line for :print or :list command
- */
+/// print line for :print or :list command
void msg_prt_line(char_u *s, int list)
{
int c;
@@ -1903,8 +1880,9 @@ void msg_prt_line(char_u *s, int list)
msg_clr_eos();
}
-// Use grid_puts() to output one multi-byte character.
-// Return the pointer "s" advanced to the next character.
+/// Use grid_puts() to output one multi-byte character.
+///
+/// @return the pointer "s" advanced to the next character.
static char_u *screen_puts_mbyte(char_u *s, int l, int attr)
{
int cw;
@@ -1936,10 +1914,8 @@ static char_u *screen_puts_mbyte(char_u *s, int l, int attr)
return s + l;
}
-/*
- * Output a string to the screen at position msg_row, msg_col.
- * Update msg_row and msg_col for the next message.
- */
+/// Output a string to the screen at position msg_row, msg_col.
+/// Update msg_row and msg_col for the next message.
void msg_puts(const char *s)
{
msg_puts_attr(s, 0);
@@ -1950,11 +1926,9 @@ void msg_puts_title(const char *s)
msg_puts_attr(s, HL_ATTR(HLF_T));
}
-/*
- * Show a message in such a way that it always fits in the line. Cut out a
- * part in the middle and replace it with "..." when necessary.
- * Does not handle multi-byte characters!
- */
+/// Show a message in such a way that it always fits in the line. Cut out a
+/// part in the middle and replace it with "..." when necessary.
+/// Does not handle multi-byte characters!
void msg_outtrans_long_attr(char_u *longstr, int attr)
{
msg_outtrans_long_len_attr(longstr, (int)STRLEN(longstr), attr);
@@ -1974,9 +1948,7 @@ void msg_outtrans_long_len_attr(char_u *longstr, int len, int attr)
msg_outtrans_len_attr(longstr + len - slen, slen, attr);
}
-/*
- * Basic function for writing a message with highlight attributes.
- */
+/// Basic function for writing a message with highlight attributes.
void msg_puts_attr(const char *const s, const int attr)
{
msg_puts_attr_len(s, -1, attr);
@@ -2078,10 +2050,8 @@ static void msg_ext_emit_chunk(void)
ADD(msg_ext_chunks, ARRAY_OBJ(chunk));
}
-/*
- * The display part of msg_puts_attr_len().
- * May be called recursively to display scroll-back text.
- */
+/// The display part of msg_puts_attr_len().
+/// May be called recursively to display scroll-back text.
static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurse)
{
const char_u *s = str;
@@ -2286,8 +2256,8 @@ static void msg_puts_display(const char_u *str, int maxlen, int attr, int recurs
msg_check();
}
-/// Return true when ":filter pattern" was used and "msg" does not match
-/// "pattern".
+/// @return true when ":filter pattern" was used and "msg" does not match
+/// "pattern".
bool message_filtered(char_u *msg)
{
if (cmdmod.filter_regmatch.regprog == NULL) {
@@ -2419,9 +2389,7 @@ void msg_reset_scroll(void)
msg_scrolled_at_flush = 0;
}
-/*
- * Increment "msg_scrolled".
- */
+/// Increment "msg_scrolled".
static void inc_msg_scrolled(void)
{
if (*get_vim_var_str(VV_SCROLLSTART) == NUL) {
@@ -2500,9 +2468,7 @@ static void store_sb_text(char_u **sb_str, char_u *s, int attr, int *sb_col, int
*sb_col = 0;
}
-/*
- * Finished showing messages, clear the scroll-back text on the next message.
- */
+/// Finished showing messages, clear the scroll-back text on the next message.
void may_clear_sb_text(void)
{
do_clear_sb_text = SB_CLEAR_ALL;
@@ -2545,9 +2511,7 @@ void clear_sb_text(int all)
}
}
-/*
- * "g<" command.
- */
+/// "g<" command.
void show_sb_text(void)
{
msgchunk_T *mp;
@@ -2563,9 +2527,7 @@ void show_sb_text(void)
}
}
-/*
- * Move to the start of screen line in already displayed text.
- */
+/// Move to the start of screen line in already displayed text.
static msgchunk_T *msg_sb_start(msgchunk_T *mps)
{
msgchunk_T *mp = mps;
@@ -2576,9 +2538,7 @@ static msgchunk_T *msg_sb_start(msgchunk_T *mps)
return mp;
}
-/*
- * Mark the last message chunk as finishing the line.
- */
+/// Mark the last message chunk as finishing the line.
void msg_sb_eol(void)
{
if (last_msgchunk != NULL) {
@@ -2586,10 +2546,9 @@ void msg_sb_eol(void)
}
}
-/*
- * Display a screen line from previously displayed text at row "row".
- * Returns a pointer to the text for the next line (can be NULL).
- */
+/// Display a screen line from previously displayed text at row "row".
+///
+/// @return a pointer to the text for the next line (can be NULL).
static msgchunk_T *disp_sb_line(int row, msgchunk_T *smp)
{
msgchunk_T *mp = smp;
@@ -2612,9 +2571,7 @@ static msgchunk_T *disp_sb_line(int row, msgchunk_T *smp)
return mp->sb_next;
}
-/*
- * Output any postponed text for msg_puts_attr_len().
- */
+/// Output any postponed text for msg_puts_attr_len().
static void t_puts(int *t_col, const char_u *t_s, const char_u *s, int attr)
{
attr = hl_combine_attr(HL_ATTR(HLF_MSG), attr);
@@ -2635,9 +2592,9 @@ static void t_puts(int *t_col, const char_u *t_s, const char_u *s, int attr)
}
}
-// Returns TRUE when messages should be printed to stdout/stderr:
-// - "batch mode" ("silent mode", -es/-Es)
-// - no UI and not embedded
+/// @return TRUE when messages should be printed to stdout/stderr:
+/// - "batch mode" ("silent mode", -es/-Es)
+/// - no UI and not embedded
int msg_use_printf(void)
{
return !embedded_mode && !ui_active();
@@ -2698,13 +2655,12 @@ static void msg_puts_printf(const char *str, const ptrdiff_t maxlen)
msg_didout = true; // assume that line is not empty
}
-/*
- * Show the more-prompt and handle the user response.
- * This takes care of scrolling back and displaying previously displayed text.
- * When at hit-enter prompt "typed_char" is the already typed character,
- * otherwise it's NUL.
- * Returns TRUE when jumping ahead to "confirm_msg_tail".
- */
+/// Show the more-prompt and handle the user response.
+/// This takes care of scrolling back and displaying previously displayed text.
+/// When at hit-enter prompt "typed_char" is the already typed character,
+/// otherwise it's NUL.
+///
+/// @return TRUE when jumping ahead to "confirm_msg_tail".
static int do_more_prompt(int typed_char)
{
static bool entered = false;
@@ -2962,7 +2918,7 @@ void mch_errmsg(char *str)
}
}
-// Give a message. To be used when the UI is not initialized yet.
+/// Give a message. To be used when the UI is not initialized yet.
void mch_msg(char *str)
{
assert(str != NULL);
@@ -2977,10 +2933,8 @@ void mch_msg(char *str)
}
#endif // WIN32
-/*
- * Put a character on the screen at the current message position and advance
- * to the next position. Only for printable ASCII!
- */
+/// Put a character on the screen at the current message position and advance
+/// to the next position. Only for printable ASCII!
static void msg_screen_putchar(int c, int attr)
{
attr = hl_combine_attr(HL_ATTR(HLF_MSG), attr);
@@ -3013,10 +2967,8 @@ void msg_moremsg(int full)
}
}
-/*
- * Repeat the message for the current mode: ASKMORE, EXTERNCMD, CONFIRM or
- * exmode_active.
- */
+/// Repeat the message for the current mode: ASKMORE, EXTERNCMD, CONFIRM or
+/// exmode_active.
void repeat_message(void)
{
if (State == ASKMORE) {
@@ -3041,10 +2993,8 @@ void repeat_message(void)
}
}
-/*
- * Clear from current message position to end of screen.
- * Skip this when ":silent" was used, no need to clear for redirection.
- */
+/// Clear from current message position to end of screen.
+/// Skip this when ":silent" was used, no need to clear for redirection.
void msg_clr_eos(void)
{
if (msg_silent == 0) {
@@ -3052,11 +3002,9 @@ void msg_clr_eos(void)
}
}
-/*
- * Clear from current message position to end of screen.
- * Note: msg_col is not updated, so we remember the end of the message
- * for msg_check().
- */
+/// Clear from current message position to end of screen.
+/// Note: msg_col is not updated, so we remember the end of the message
+/// for msg_check().
void msg_clr_eos_force(void)
{
if (ui_has(kUIMessages)) {
@@ -3083,9 +3031,7 @@ void msg_clr_eos_force(void)
}
}
-/*
- * Clear the command line.
- */
+/// Clear the command line.
void msg_clr_cmdline(void)
{
msg_row = cmdline_row;
@@ -3093,11 +3039,10 @@ void msg_clr_cmdline(void)
msg_clr_eos_force();
}
-/*
- * end putting a message on the screen
- * call wait_return if the message does not fit in the available space
- * return TRUE if wait_return not called.
- */
+/// end putting a message on the screen
+/// call wait_return if the message does not fit in the available space
+///
+/// @return TRUE if wait_return not called.
int msg_end(void)
{
/*
@@ -3187,10 +3132,8 @@ bool msg_ext_is_visible(void)
return ui_has(kUIMessages) && msg_ext_visible > 0;
}
-/*
- * If the written message runs into the shown command or ruler, we have to
- * wait for hit-return and redraw the window later.
- */
+/// If the written message runs into the shown command or ruler, we have to
+/// wait for hit-return and redraw the window later.
void msg_check(void)
{
if (ui_has(kUIMessages)) {
@@ -3202,10 +3145,9 @@ void msg_check(void)
}
}
-/*
- * May write a string to the redirection file.
- * When "maxlen" is -1 write the whole string, otherwise up to "maxlen" bytes.
- */
+/// May write a string to the redirection file.
+///
+/// @param maxlen if -1, write the whole string, otherwise up to "maxlen" bytes.
static void redir_write(const char *const str, const ptrdiff_t maxlen)
{
const char_u *s = (char_u *)str;
@@ -3290,10 +3232,8 @@ int redirecting(void)
|| redir_reg || redir_vname || capture_ga != NULL;
}
-/*
- * Before giving verbose message.
- * Must always be called paired with verbose_leave()!
- */
+/// Before giving verbose message.
+/// Must always be called paired with verbose_leave()!
void verbose_enter(void)
{
if (*p_vfile != NUL) {
@@ -3301,10 +3241,8 @@ void verbose_enter(void)
}
}
-/*
- * After giving verbose message.
- * Must always be called paired with verbose_enter()!
- */
+/// After giving verbose message.
+/// Must always be called paired with verbose_enter()!
void verbose_leave(void)
{
if (*p_vfile != NUL) {
@@ -3314,9 +3252,7 @@ void verbose_leave(void)
}
}
-/*
- * Like verbose_enter() and set msg_scroll when displaying the message.
- */
+/// Like verbose_enter() and set msg_scroll when displaying the message.
void verbose_enter_scroll(void)
{
if (*p_vfile != NUL) {
@@ -3327,9 +3263,7 @@ void verbose_enter_scroll(void)
}
}
-/*
- * Like verbose_leave() and set cmdline_row when displaying the message.
- */
+/// Like verbose_leave() and set cmdline_row when displaying the message.
void verbose_leave_scroll(void)
{
if (*p_vfile != NUL) {
@@ -3341,9 +3275,7 @@ void verbose_leave_scroll(void)
}
}
-/*
- * Called when 'verbosefile' is set: stop writing to the file.
- */
+/// Called when 'verbosefile' is set: stop writing to the file.
void verbose_stop(void)
{
if (verbose_fd != NULL) {
@@ -3353,10 +3285,9 @@ void verbose_stop(void)
verbose_did_open = FALSE;
}
-/*
- * Open the file 'verbosefile'.
- * Return FAIL or OK.
- */
+/// Open the file 'verbosefile'.
+///
+/// @return FAIL or OK.
int verbose_open(void)
{
if (verbose_fd == NULL && !verbose_did_open) {
@@ -3372,10 +3303,8 @@ int verbose_open(void)
return OK;
}
-/*
- * Give a warning message (for searching).
- * Use 'w' highlighting and may repeat the message after redrawing
- */
+/// Give a warning message (for searching).
+/// Use 'w' highlighting and may repeat the message after redrawing
void give_warning(char_u *message, bool hl) FUNC_ATTR_NONNULL_ARG(1)
{
// Don't do this for ":silent".
@@ -3414,9 +3343,7 @@ void give_warning2(char_u *const message, char_u *const a1, bool hl)
give_warning(IObuff, hl);
}
-/*
- * Advance msg cursor to column "col".
- */
+/// Advance msg cursor to column "col".
void msg_advance(int col)
{
if (msg_silent != 0) { // nothing to advance to
@@ -3626,15 +3553,13 @@ static char_u *console_dialog_alloc(const char_u *message, char_u *buttons, bool
return xmalloc(lenhotkey);
}
-/*
- * Format the dialog string, and display it at the bottom of
- * the screen. Return a string of hotkey chars (if defined) for
- * each 'button'. If a button has no hotkey defined, the first character of
- * the button is used.
- * The hotkeys can be multi-byte characters, but without combining chars.
- *
- * Returns an allocated string with hotkeys.
- */
+/// Format the dialog string, and display it at the bottom of
+/// the screen. Return a string of hotkey chars (if defined) for
+/// each 'button'. If a button has no hotkey defined, the first character of
+/// the button is used.
+/// The hotkeys can be multi-byte characters, but without combining chars.
+///
+/// @return an allocated string with hotkeys.
static char_u *msg_show_console_dialog(char_u *message, char_u *buttons, int dfltbutton)
FUNC_ATTR_NONNULL_RET
{
@@ -3727,9 +3652,7 @@ static void copy_hotkeys_and_msg(const char_u *message, char_u *buttons, int def
*msgp = NUL;
}
-/*
- * Display the ":confirm" message. Also called when screen resized.
- */
+/// Display the ":confirm" message. Also called when screen resized.
void display_confirm_msg(void)
{
// Avoid that 'q' at the more prompt truncates the message here.
diff --git a/src/nvim/mouse.c b/src/nvim/mouse.c
index 5d007fb173..6b27ce9d7b 100644
--- a/src/nvim/mouse.c
+++ b/src/nvim/mouse.c
@@ -535,6 +535,22 @@ static win_T *mouse_find_grid_win(int *gridp, int *rowp, int *colp)
return NULL;
}
+/// Convert a virtual (screen) column to a character column.
+/// The first column is one.
+colnr_T vcol2col(win_T *const wp, const linenr_T lnum, const colnr_T vcol)
+ FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
+{
+ // try to advance to the specified column
+ char_u *ptr = ml_get_buf(wp->w_buffer, lnum, false);
+ char_u *const line = ptr;
+ colnr_T count = 0;
+ while (count < vcol && *ptr != NUL) {
+ count += win_lbr_chartabsize(wp, line, ptr, count, NULL);
+ MB_PTR_ADV(ptr);
+ }
+ return (colnr_T)(ptr - line);
+}
+
/// Set UI mouse depending on current mode and 'mouse'.
///
/// Emits mouse_on/mouse_off UI event (unless 'mouse' is empty).
diff --git a/src/nvim/msgpack_rpc/channel.c b/src/nvim/msgpack_rpc/channel.c
index 299651ee97..48ecd5d0ea 100644
--- a/src/nvim/msgpack_rpc/channel.c
+++ b/src/nvim/msgpack_rpc/channel.c
@@ -547,7 +547,8 @@ void rpc_close(Channel *channel)
channel->rpc.closed = true;
channel_decref(channel);
- if (channel->streamtype == kChannelStreamStdio) {
+ if (channel->streamtype == kChannelStreamStdio
+ || channel->id == ui_client_channel_id) {
multiqueue_put(main_loop.fast_events, exit_event, 0);
}
}
diff --git a/src/nvim/normal.c b/src/nvim/normal.c
index 7fe6469527..f402865d2d 100644
--- a/src/nvim/normal.c
+++ b/src/nvim/normal.c
@@ -2105,10 +2105,9 @@ bool do_mouse(oparg_T *oap, int c, int dir, long count, bool fixindent)
} else { // MOUSE_RIGHT
stuffcharReadbuff('#');
}
- }
- // Handle double clicks, unless on status line
- else if (in_status_line) {
- } else if (in_sep_line) {
+ } else if (in_status_line || in_sep_line) {
+ // Do nothing if on status line or vertical separator
+ // Handle double clicks otherwise
} else if ((mod_mask & MOD_MASK_MULTI_CLICK) && (State & (NORMAL | INSERT))) {
if (is_click || !VIsual_active) {
if (VIsual_active) {
@@ -3569,7 +3568,6 @@ static void nv_zet(cmdarg_T *cap)
bool undo = false;
int l_p_siso = (int)get_sidescrolloff_value(curwin);
- assert(l_p_siso <= INT_MAX);
if (ascii_isdigit(nchar)) {
/*
@@ -5871,7 +5869,7 @@ static void nv_gomark(cmdarg_T *cap)
}
}
-// Handle CTRL-O, CTRL-I, "g;", "g,", and "CTRL-Tab" commands.
+/// Handle CTRL-O, CTRL-I, "g;", "g,", and "CTRL-Tab" commands.
static void nv_pcmark(cmdarg_T *cap)
{
pos_T *pos;
@@ -5880,7 +5878,9 @@ static void nv_pcmark(cmdarg_T *cap)
if (!checkclearopq(cap->oap)) {
if (cap->cmdchar == TAB && mod_mask == MOD_MASK_CTRL) {
- goto_tabpage_lastused();
+ if (!goto_tabpage_lastused()) {
+ clearopbeep(cap->oap);
+ }
return;
}
if (cap->cmdchar == 'g') {
@@ -6644,9 +6644,10 @@ static void nv_g_cmd(cmdarg_T *cap)
goto_tabpage(-(int)cap->count1);
}
break;
+
case TAB:
- if (!checkclearop(oap)) {
- goto_tabpage_lastused();
+ if (!checkclearop(oap) && !goto_tabpage_lastused()) {
+ clearopbeep(oap);
}
break;
diff --git a/src/nvim/ops.c b/src/nvim/ops.c
index b5c7020dee..244a1881aa 100644
--- a/src/nvim/ops.c
+++ b/src/nvim/ops.c
@@ -1023,6 +1023,60 @@ static int stuff_yank(int regname, char_u *p)
static int execreg_lastc = NUL;
+/// When executing a register as a series of ex-commands, if the
+/// line-continuation character is used for a line, then join it with one or
+/// more previous lines. Note that lines are processed backwards starting from
+/// the last line in the register.
+///
+/// @param lines list of lines in the register
+/// @param idx index of the line starting with \ or "\. Join this line with all the immediate
+/// predecessor lines that start with a \ and the first line that doesn't start
+/// with a \. Lines that start with a comment "\ character are ignored.
+/// @returns the concatenated line. The index of the line that should be
+/// processed next is returned in idx.
+static char_u *execreg_line_continuation(char_u **lines, size_t *idx)
+{
+ size_t i = *idx;
+ assert(i > 0);
+ const size_t cmd_end = i;
+
+ garray_T ga;
+ ga_init(&ga, (int)sizeof(char_u), 400);
+
+ char_u *p;
+
+ // search backwards to find the first line of this command.
+ // Any line not starting with \ or "\ is the start of the
+ // command.
+ while (--i > 0) {
+ p = skipwhite(lines[i]);
+ if (*p != '\\' && (p[0] != '"' || p[1] != '\\' || p[2] != ' ')) {
+ break;
+ }
+ }
+ const size_t cmd_start = i;
+
+ // join all the lines
+ ga_concat(&ga, (char *)lines[cmd_start]);
+ for (size_t j = cmd_start + 1; j <= cmd_end; j++) {
+ p = skipwhite(lines[j]);
+ if (*p == '\\') {
+ // Adjust the growsize to the current length to
+ // speed up concatenating many lines.
+ if (ga.ga_len > 400) {
+ ga_set_growsize(&ga, MIN(ga.ga_len, 8000));
+ }
+ ga_concat(&ga, (char *)(p + 1));
+ }
+ }
+ ga_append(&ga, NUL);
+ char_u *str = vim_strsave(ga.ga_data);
+ ga_clear(&ga);
+
+ *idx = i;
+ return str;
+}
+
/// Execute a yank register: copy it into the stuff buffer
///
/// @param colon insert ':' before each line
@@ -1111,7 +1165,21 @@ int do_execreg(int regname, int colon, int addcr, int silent)
return FAIL;
}
}
- escaped = vim_strsave_escape_ks(reg->y_array[i]);
+
+ // Handle line-continuation for :@<register>
+ char_u *str = reg->y_array[i];
+ bool free_str = false;
+ if (colon && i > 0) {
+ p = skipwhite(str);
+ if (*p == '\\' || (p[0] == '"' && p[1] == '\\' && p[2] == ' ')) {
+ str = execreg_line_continuation(reg->y_array, &i);
+ free_str = true;
+ }
+ }
+ escaped = vim_strsave_escape_ks(str);
+ if (free_str) {
+ xfree(str);
+ }
retval = ins_typebuf(escaped, remap, 0, true, silent);
xfree(escaped);
if (retval == FAIL) {
@@ -1504,20 +1572,20 @@ int op_delete(oparg_T *oap)
yankreg_T *reg = NULL;
int did_yank = false;
if (oap->regname != 0) {
- // yank without message
- did_yank = op_yank(oap, false, true);
- if (!did_yank) {
- // op_yank failed, don't do anything
+ // check for read-only register
+ if (!valid_yank_reg(oap->regname, true)) {
+ beep_flush();
return OK;
}
+ reg = get_yank_register(oap->regname, YREG_YANK); // yank into specif'd reg
+ op_yank_reg(oap, false, reg, is_append_register(oap->regname)); // yank without message
+ did_yank = true;
}
- /*
- * Put deleted text into register 1 and shift number registers if the
- * delete contains a line break, or when a regname has been specified.
- */
- if (oap->regname != 0 || oap->motion_type == kMTLineWise
- || oap->line_count > 1 || oap->use_reg_one) {
+ // Put deleted text into register 1 and shift number registers if the
+ // delete contains a line break, or when using a specific operator (Vi
+ // compatible)
+ if (oap->motion_type == kMTLineWise || oap->line_count > 1 || oap->use_reg_one) {
shift_delete_registers(is_append_register(oap->regname));
reg = &y_regs[1];
op_yank_reg(oap, false, reg, false);
@@ -2579,12 +2647,12 @@ void free_register(yankreg_T *reg)
/// Yanks the text between "oap->start" and "oap->end" into a yank register.
/// If we are to append (uppercase register), we first yank into a new yank
/// register and then concatenate the old and the new one.
+/// Do not call this from a delete operation. Use op_yank_reg() instead.
///
/// @param oap operator arguments
/// @param message show message when more than `&report` lines are yanked.
-/// @param deleting whether the function was called from a delete operation.
/// @returns whether the operation register was writable.
-bool op_yank(oparg_T *oap, bool message, int deleting)
+bool op_yank(oparg_T *oap, bool message)
FUNC_ATTR_NONNULL_ALL
{
// check for read-only register
@@ -2598,11 +2666,8 @@ bool op_yank(oparg_T *oap, bool message, int deleting)
yankreg_T *reg = get_yank_register(oap->regname, YREG_YANK);
op_yank_reg(oap, message, reg, is_append_register(oap->regname));
- // op_delete will set_clipboard and do_autocmd
- if (!deleting) {
- set_clipboard(oap->regname, reg);
- do_autocmd_textyankpost(oap, reg);
- }
+ set_clipboard(oap->regname, reg);
+ do_autocmd_textyankpost(oap, reg);
return true;
}
@@ -6630,7 +6695,7 @@ void do_pending_operator(cmdarg_T *cap, int old_col, bool gui_yank)
} else {
curwin->w_p_lbr = lbr_saved;
oap->excl_tr_ws = cap->cmdchar == 'z';
- (void)op_yank(oap, !gui_yank, false);
+ (void)op_yank(oap, !gui_yank);
}
check_cursor_col();
break;
@@ -7314,7 +7379,6 @@ const yankreg_T *op_reg_get(const char name)
///
/// @return true on success, false on failure.
bool op_reg_set_previous(const char name)
- FUNC_ATTR_WARN_UNUSED_RESULT
{
int i = op_reg_index(name);
if (i == -1) {
diff --git a/src/nvim/option.c b/src/nvim/option.c
index c8e50d4494..ef1c2d499c 100644
--- a/src/nvim/option.c
+++ b/src/nvim/option.c
@@ -2910,7 +2910,7 @@ ambw_end:
|| check_opt_strings(curbuf->b_p_bt, p_buftype_values, false) != OK) {
errmsg = e_invarg;
} else {
- if (curwin->w_status_height) {
+ if (curwin->w_status_height || global_stl_height()) {
curwin->w_redr_status = true;
redraw_later(curwin, VALID);
}
@@ -3553,16 +3553,22 @@ static char *set_chars_option(win_T *wp, char_u **varp, bool set)
struct chars_tab *tab;
struct chars_tab fcs_tab[] = {
- { &wp->w_p_fcs_chars.stl, "stl", ' ' },
- { &wp->w_p_fcs_chars.stlnc, "stlnc", ' ' },
- { &wp->w_p_fcs_chars.vert, "vert", 9474 }, // │
- { &wp->w_p_fcs_chars.fold, "fold", 183 }, // ·
- { &wp->w_p_fcs_chars.foldopen, "foldopen", '-' },
- { &wp->w_p_fcs_chars.foldclosed, "foldclose", '+' },
- { &wp->w_p_fcs_chars.foldsep, "foldsep", 9474 }, // │
- { &wp->w_p_fcs_chars.diff, "diff", '-' },
- { &wp->w_p_fcs_chars.msgsep, "msgsep", ' ' },
- { &wp->w_p_fcs_chars.eob, "eob", '~' },
+ { &wp->w_p_fcs_chars.stl, "stl", ' ' },
+ { &wp->w_p_fcs_chars.stlnc, "stlnc", ' ' },
+ { &wp->w_p_fcs_chars.horiz, "horiz", 9472 }, // ─
+ { &wp->w_p_fcs_chars.horizup, "horizup", 9524 }, // ┴
+ { &wp->w_p_fcs_chars.horizdown, "horizdown", 9516 }, // ┬
+ { &wp->w_p_fcs_chars.vert, "vert", 9474 }, // │
+ { &wp->w_p_fcs_chars.vertleft, "vertleft", 9508 }, // ┤
+ { &wp->w_p_fcs_chars.vertright, "vertright", 9500 }, // ├
+ { &wp->w_p_fcs_chars.verthoriz, "verthoriz", 9532 }, // ┼
+ { &wp->w_p_fcs_chars.fold, "fold", 183 }, // ·
+ { &wp->w_p_fcs_chars.foldopen, "foldopen", '-' },
+ { &wp->w_p_fcs_chars.foldclosed, "foldclose", '+' },
+ { &wp->w_p_fcs_chars.foldsep, "foldsep", 9474 }, // │
+ { &wp->w_p_fcs_chars.diff, "diff", '-' },
+ { &wp->w_p_fcs_chars.msgsep, "msgsep", ' ' },
+ { &wp->w_p_fcs_chars.eob, "eob", '~' },
};
struct chars_tab lcs_tab[] = {
{ &wp->w_p_lcs_chars.eol, "eol", NUL },
@@ -3589,15 +3595,17 @@ static char *set_chars_option(win_T *wp, char_u **varp, bool set)
varp = &p_fcs;
}
if (*p_ambw == 'd') {
- // XXX: If ambiwidth=double then "|" and "·" take 2 columns, which is
- // forbidden (TUI limitation?). Set old defaults.
- fcs_tab[2].def = '|';
- fcs_tab[6].def = '|';
- fcs_tab[3].def = '-';
- } else {
- fcs_tab[2].def = 9474; // │
- fcs_tab[6].def = 9474; // │
- fcs_tab[3].def = 183; // ·
+ // XXX: If ambiwidth=double then some characters take 2 columns,
+ // which is forbidden (TUI limitation?). Set old defaults.
+ fcs_tab[2].def = '-';
+ fcs_tab[3].def = '-';
+ fcs_tab[4].def = '-';
+ fcs_tab[5].def = '|';
+ fcs_tab[6].def = '|';
+ fcs_tab[7].def = '|';
+ fcs_tab[8].def = '+';
+ fcs_tab[9].def = '-';
+ fcs_tab[12].def = '|';
}
}
@@ -3851,7 +3859,7 @@ static bool parse_winhl_opt(win_T *wp)
if (strncmp("Normal", p, nlen) == 0) {
w_hl_id_normal = hl_id;
} else {
- for (hlf = 0; hlf < (int)HLF_COUNT; hlf++) {
+ for (hlf = 0; hlf < HLF_COUNT; hlf++) {
if (strlen(hlf_names[hlf]) == nlen
&& strncmp(hlf_names[hlf], p, nlen) == 0) {
w_hl_ids[hlf] = hl_id;
@@ -3878,6 +3886,7 @@ static void set_option_sctx_idx(int opt_idx, int opt_flags, sctx_T script_ctx)
{
int both = (opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0;
int indir = (int)options[opt_idx].indir;
+ nlua_set_sctx(&script_ctx);
const LastSet last_set = {
.script_ctx = {
script_ctx.sc_sid,
@@ -4277,7 +4286,7 @@ static char *set_num_option(int opt_idx, char_u *varp, long value, char *errbuf,
}
// Save the global value before changing anything. This is needed as for
- // a global-only option setting the "local value" infact sets the global
+ // a global-only option setting the "local value" in fact sets the global
// value (since there is only one value).
if ((opt_flags & (OPT_LOCAL | OPT_GLOBAL)) == 0) {
old_global_value = *(long *)get_varp_scope(&(options[opt_idx]), OPT_GLOBAL);
@@ -4474,6 +4483,20 @@ static char *set_num_option(int opt_idx, char_u *varp, long value, char *errbuf,
// 'winminwidth'
win_setminwidth();
} else if (pp == &p_ls) {
+ // When switching to global statusline, decrease topframe height
+ // Also clear the cmdline to remove the ruler if there is one
+ if (value == 3 && old_value != 3) {
+ frame_new_height(topframe, topframe->fr_height - STATUS_HEIGHT, false, false);
+ (void)win_comp_pos();
+ clear_cmdline = true;
+ }
+ // When switching from global statusline, increase height of topframe by STATUS_HEIGHT
+ // in order to to re-add the space that was previously taken by the global statusline
+ if (old_value == 3 && value != 3) {
+ frame_new_height(topframe, topframe->fr_height + STATUS_HEIGHT, false, false);
+ (void)win_comp_pos();
+ }
+
last_status(false); // (re)set last window status line.
} else if (pp == &p_stal) {
// (re)set tab page line
@@ -5266,7 +5289,7 @@ static void showoptions(int all, int opt_flags)
&& Columns + GAP >= INT_MIN + 3
&& (Columns + GAP - 3) / INC >= INT_MIN
&& (Columns + GAP - 3) / INC <= INT_MAX);
- cols = (int)((Columns + GAP - 3) / INC);
+ cols = (Columns + GAP - 3) / INC;
if (cols == 0) {
cols = 1;
}
@@ -5645,7 +5668,7 @@ static int put_setbool(FILE *fd, char *cmd, char *name, int value)
void comp_col(void)
{
- int last_has_status = (p_ls == 2 || (p_ls == 1 && !ONE_WINDOW));
+ int last_has_status = (p_ls > 1 || (p_ls == 1 && !ONE_WINDOW));
sc_col = 0;
ru_col = 0;
@@ -5663,13 +5686,11 @@ void comp_col(void)
}
}
assert(sc_col >= 0
- && INT_MIN + sc_col <= Columns
- && Columns - sc_col <= INT_MAX);
- sc_col = (int)(Columns - sc_col);
+ && INT_MIN + sc_col <= Columns);
+ sc_col = Columns - sc_col;
assert(ru_col >= 0
- && INT_MIN + ru_col <= Columns
- && Columns - ru_col <= INT_MAX);
- ru_col = (int)(Columns - ru_col);
+ && INT_MIN + ru_col <= Columns);
+ ru_col = Columns - ru_col;
if (sc_col <= 0) { // screen too narrow, will become a mess
sc_col = 1;
}
@@ -8165,7 +8186,7 @@ int win_signcol_configured(win_T *wp, int *is_fixed)
}
int needed_signcols = buf_signcols(wp->w_buffer, maximum);
- int ret = MAX(minimum, needed_signcols);
+ int ret = MAX(minimum, MIN(maximum, needed_signcols));
assert(ret <= SIGN_SHOW_MAX);
return ret;
}
diff --git a/src/nvim/os/env.c b/src/nvim/os/env.c
index e9868d6b61..b738d36234 100644
--- a/src/nvim/os/env.c
+++ b/src/nvim/os/env.c
@@ -720,7 +720,7 @@ void expand_env_esc(char_u *restrict srcp, char_u *restrict dst, int dstlen, boo
&& dst[-1] != ':'
#endif
&& vim_ispathsep(*tail)) {
- ++tail;
+ tail++;
}
dst += c;
src = tail;
@@ -738,7 +738,7 @@ void expand_env_esc(char_u *restrict srcp, char_u *restrict dst, int dstlen, boo
at_start = false;
if (src[0] == '\\' && src[1] != NUL) {
*dst++ = *src++;
- --dstlen;
+ dstlen--;
} else if ((src[0] == ' ' || src[0] == ',') && !one) {
at_start = true;
}
diff --git a/src/nvim/os/fs.c b/src/nvim/os/fs.c
index 24c7678633..daf974ee74 100644
--- a/src/nvim/os/fs.c
+++ b/src/nvim/os/fs.c
@@ -40,8 +40,10 @@
bool did_try_to_free = false; \
uv_call_start: {} \
uv_fs_t req; \
+ fs_loop_lock(); \
ret = func(&fs_loop, &req, __VA_ARGS__); \
uv_fs_req_cleanup(&req); \
+ fs_loop_unlock(); \
if (ret == UV_ENOMEM && !did_try_to_free) { \
try_to_free_memory(); \
did_try_to_free = true; \
@@ -52,12 +54,27 @@ uv_call_start: {} \
// Many fs functions from libuv return that value on success.
static const int kLibuvSuccess = 0;
static uv_loop_t fs_loop;
+static uv_mutex_t fs_loop_mutex;
// Initialize the fs module
void fs_init(void)
{
uv_loop_init(&fs_loop);
+ uv_mutex_init_recursive(&fs_loop_mutex);
+}
+
+/// TODO(bfredl): some of these operations should
+/// be possible to do the private libuv loop of the
+/// thread, instead of contending the global fs loop
+void fs_loop_lock(void)
+{
+ uv_mutex_lock(&fs_loop_mutex);
+}
+
+void fs_loop_unlock(void)
+{
+ uv_mutex_unlock(&fs_loop_mutex);
}
@@ -98,9 +115,12 @@ bool os_isrealdir(const char *name)
FUNC_ATTR_NONNULL_ALL
{
uv_fs_t request;
+ fs_loop_lock();
if (uv_fs_lstat(&fs_loop, &request, name, NULL) != kLibuvSuccess) {
+ fs_loop_unlock();
return false;
}
+ fs_loop_unlock();
if (S_ISLNK(request.statbuf.st_mode)) {
return false;
} else {
@@ -738,7 +758,9 @@ static int os_stat(const char *name, uv_stat_t *statbuf)
return UV_EINVAL;
}
uv_fs_t request;
+ fs_loop_lock();
int result = uv_fs_stat(&fs_loop, &request, name, NULL);
+ fs_loop_unlock();
if (result == kLibuvSuccess) {
*statbuf = request.statbuf;
}
@@ -935,9 +957,11 @@ int os_mkdtemp(const char *template, char *path)
FUNC_ATTR_NONNULL_ALL
{
uv_fs_t request;
+ fs_loop_lock();
int result = uv_fs_mkdtemp(&fs_loop, &request, template, NULL);
+ fs_loop_unlock();
if (result == kLibuvSuccess) {
- STRNCPY(path, request.path, TEMP_FILE_PATH_MAXLEN);
+ xstrlcpy(path, request.path, TEMP_FILE_PATH_MAXLEN);
}
uv_fs_req_cleanup(&request);
return result;
@@ -962,7 +986,9 @@ int os_rmdir(const char *path)
bool os_scandir(Directory *dir, const char *path)
FUNC_ATTR_NONNULL_ALL
{
+ fs_loop_lock();
int r = uv_fs_scandir(&fs_loop, &dir->request, path, 0, NULL);
+ fs_loop_unlock();
if (r < 0) {
os_closedir(dir);
}
@@ -1023,7 +1049,9 @@ bool os_fileinfo_link(const char *path, FileInfo *file_info)
return false;
}
uv_fs_t request;
+ fs_loop_lock();
bool ok = uv_fs_lstat(&fs_loop, &request, path, NULL) == kLibuvSuccess;
+ fs_loop_unlock();
if (ok) {
file_info->stat = request.statbuf;
}
@@ -1041,6 +1069,7 @@ bool os_fileinfo_fd(int file_descriptor, FileInfo *file_info)
{
uv_fs_t request;
memset(file_info, 0, sizeof(*file_info));
+ fs_loop_lock();
bool ok = uv_fs_fstat(&fs_loop,
&request,
file_descriptor,
@@ -1049,6 +1078,7 @@ bool os_fileinfo_fd(int file_descriptor, FileInfo *file_info)
file_info->stat = request.statbuf;
}
uv_fs_req_cleanup(&request);
+ fs_loop_unlock();
return ok;
}
@@ -1165,6 +1195,7 @@ char *os_realpath(const char *name, char *buf)
FUNC_ATTR_NONNULL_ARG(1)
{
uv_fs_t request;
+ fs_loop_lock();
int result = uv_fs_realpath(&fs_loop, &request, name, NULL);
if (result == kLibuvSuccess) {
if (buf == NULL) {
@@ -1173,6 +1204,7 @@ char *os_realpath(const char *name, char *buf)
xstrlcpy(buf, request.ptr, MAXPATHL + 1);
}
uv_fs_req_cleanup(&request);
+ fs_loop_unlock();
return result == kLibuvSuccess ? buf : NULL;
}
diff --git a/src/nvim/os/os_defs.h b/src/nvim/os/os_defs.h
index dce4b0c187..a4361859ec 100644
--- a/src/nvim/os/os_defs.h
+++ b/src/nvim/os/os_defs.h
@@ -14,7 +14,7 @@
#endif
#if !defined(NAME_MAX) && defined(_XOPEN_NAME_MAX)
-#define NAME_MAX _XOPEN_NAME_MAX
+# define NAME_MAX _XOPEN_NAME_MAX
#endif
#define BASENAMELEN (NAME_MAX - 5)
diff --git a/src/nvim/os/pty_process_unix.c b/src/nvim/os/pty_process_unix.c
index 3459646bad..4a49c0b162 100644
--- a/src/nvim/os/pty_process_unix.c
+++ b/src/nvim/os/pty_process_unix.c
@@ -16,11 +16,11 @@
#elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
# include <util.h>
#elif defined(__sun)
-# include <sys/stream.h>
-# include <sys/syscall.h>
-# include <fcntl.h>
-# include <unistd.h>
-# include <signal.h>
+# include <fcntl.h>
+# include <signal.h>
+# include <sys/stream.h>
+# include <sys/syscall.h>
+# include <unistd.h>
#else
# include <pty.h>
#endif
@@ -49,10 +49,10 @@
// 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>
+# include <sys/stropts.h>
-static int openpty(int *amaster, int *aslave, char *name,
- struct termios *termp, struct winsize *winp)
+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);
@@ -63,7 +63,7 @@ static int openpty(int *amaster, int *aslave, char *name,
// 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);
+ void (*sig_saved)(int) = signal(SIGCHLD, SIG_DFL);
int res = grantpt(master);
signal(SIGCHLD, sig_saved);
@@ -86,7 +86,7 @@ static int openpty(int *amaster, int *aslave, char *name,
ioctl(slave, I_PUSH, "ptem");
// ldterm provides most of the termio terminal interface
ioctl(slave, I_PUSH, "ldterm");
- // ttcompat compatability with older terminal ioctls
+ // ttcompat compatibility with older terminal ioctls
ioctl(slave, I_PUSH, "ttcompat");
if (termp) {
@@ -129,8 +129,7 @@ static int login_tty(int fd)
return 0;
}
-static pid_t forkpty(int *amaster, char *name,
- struct termios *termp, struct winsize *winp)
+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) {
diff --git a/src/nvim/os/pty_process_win.c b/src/nvim/os/pty_process_win.c
index f78f3e66f5..4fb9e30a96 100644
--- a/src/nvim/os/pty_process_win.c
+++ b/src/nvim/os/pty_process_win.c
@@ -58,8 +58,7 @@ int pty_process_spawn(PtyProcess *ptyproc)
if (os_has_conpty_working()) {
if ((conpty_object =
- os_conpty_init(&in_name, &out_name,
- ptyproc->width, ptyproc->height)) != NULL) {
+ os_conpty_init(&in_name, &out_name, ptyproc->width, ptyproc->height)) != NULL) {
ptyproc->type = kConpty;
}
}
@@ -281,7 +280,7 @@ static void wait_eof_timer_cb(uv_timer_t *wait_eof_timer)
PtyProcess *ptyproc = wait_eof_timer->data;
Process *proc = (Process *)ptyproc;
- if (proc->out.closed || !uv_is_readable(proc->out.uvstream)) {
+ if (proc->out.closed || proc->out.did_eof || !uv_is_readable(proc->out.uvstream)) {
uv_timer_stop(&ptyproc->wait_eof_timer);
pty_process_finish2(ptyproc);
}
@@ -308,7 +307,7 @@ static void pty_process_finish2(PtyProcess *ptyproc)
/// Build the command line to pass to CreateProcessW.
///
/// @param[in] argv Array with string arguments.
-/// @param[out] cmd_line Location where saved builded cmd line.
+/// @param[out] cmd_line Location where saved built cmd line.
///
/// @returns zero on success, or error code of MultiByteToWideChar function.
///
diff --git a/src/nvim/os/shell.c b/src/nvim/os/shell.c
index e618b2788b..5680cdbe42 100644
--- a/src/nvim/os/shell.c
+++ b/src/nvim/os/shell.c
@@ -9,10 +9,10 @@
#include "nvim/ascii.h"
#include "nvim/charset.h"
+#include "nvim/eval.h"
#include "nvim/event/libuv_process.h"
#include "nvim/event/loop.h"
#include "nvim/event/rstream.h"
-#include "nvim/eval.h"
#include "nvim/ex_cmds.h"
#include "nvim/fileio.h"
#include "nvim/lib/kvec.h"
@@ -27,8 +27,8 @@
#include "nvim/path.h"
#include "nvim/screen.h"
#include "nvim/strings.h"
-#include "nvim/types.h"
#include "nvim/tag.h"
+#include "nvim/types.h"
#include "nvim/ui.h"
#include "nvim/vim.h"
@@ -1229,7 +1229,7 @@ static void read_input(DynamicBuffer *buf)
dynamic_buffer_ensure(buf, buf->len + 1);
buf->data[buf->len++] = NL;
}
- ++lnum;
+ lnum++;
if (lnum > curbuf->b_op_end.lnum) {
break;
}
diff --git a/src/nvim/path.c b/src/nvim/path.c
index 7f7f941e26..d3aa5e5bf2 100644
--- a/src/nvim/path.c
+++ b/src/nvim/path.c
@@ -642,8 +642,7 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff,
} else if (path_end >= path + wildoff
&& (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
#ifndef WIN32
- || (!p_fic && (flags & EW_ICASE)
- && isalpha(utf_ptr2char(path_end)))
+ || (!p_fic && (flags & EW_ICASE) && mb_isalpha(utf_ptr2char(path_end)))
#endif
)) {
e = p;
diff --git a/src/nvim/popupmnu.c b/src/nvim/popupmnu.c
index d7726409b5..e354a589a5 100644
--- a/src/nvim/popupmnu.c
+++ b/src/nvim/popupmnu.c
@@ -289,8 +289,7 @@ void pum_display(pumitem_T *array, int size, int selected, bool array_changed, i
if (pum_rl) {
pum_width = pum_col - pum_scrollbar + 1;
} else {
- assert(Columns - pum_col - pum_scrollbar >= INT_MIN
- && Columns - pum_col - pum_scrollbar <= INT_MAX);
+ assert(Columns - pum_col - pum_scrollbar >= 0);
pum_width = Columns - pum_col - pum_scrollbar;
}
@@ -356,7 +355,6 @@ void pum_display(pumitem_T *array, int size, int selected, bool array_changed, i
} else {
pum_col = 0;
}
- assert(Columns - 1 >= INT_MIN);
pum_width = Columns - 1;
} else {
if (max_width > p_pw) {
@@ -367,8 +365,7 @@ void pum_display(pumitem_T *array, int size, int selected, bool array_changed, i
if (pum_rl) {
pum_col = max_width - 1;
} else {
- assert(Columns - max_width >= INT_MIN
- && Columns - max_width <= INT_MAX);
+ assert(Columns - max_width >= 0);
pum_col = Columns - max_width;
}
pum_width = max_width - pum_scrollbar;
diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c
index 7e29aed51b..1a08b22f49 100644
--- a/src/nvim/quickfix.c
+++ b/src/nvim/quickfix.c
@@ -75,6 +75,7 @@ struct qfline_S {
// There is a stack of error lists.
#define LISTCOUNT 10
#define INVALID_QFIDX (-1)
+#define INVALID_QFBUFNR (0)
/// Quickfix list type.
typedef enum
@@ -126,6 +127,7 @@ struct qf_info_S {
int qf_curlist; // current error list
qf_list_T qf_lists[LISTCOUNT];
qfltype_T qfl_type; // type of list
+ int qf_bufnr; // quickfix window buffer number
};
static qf_info_T ql_info; // global quickfix list
@@ -1703,6 +1705,28 @@ static void locstack_queue_delreq(qf_info_T *qi)
qf_delq_head = q;
}
+/// Return the global quickfix stack window buffer number.
+int qf_stack_get_bufnr(void)
+{
+ return ql_info.qf_bufnr;
+}
+
+/// Wipe the quickfix window buffer (if present) for the specified
+/// quickfix/location list.
+static void wipe_qf_buffer(qf_info_T *qi)
+ FUNC_ATTR_NONNULL_ALL
+{
+ if (qi->qf_bufnr != INVALID_QFBUFNR) {
+ buf_T *const qfbuf = buflist_findnr(qi->qf_bufnr);
+ if (qfbuf != NULL && qfbuf->b_nwindows == 0) {
+ // If the quickfix buffer is not loaded in any window, then
+ // wipe the buffer.
+ close_buffer(NULL, qfbuf, DOBUF_WIPE, false);
+ qi->qf_bufnr = INVALID_QFBUFNR;
+ }
+ }
+}
+
/// Free a location list stack
static void ll_free_all(qf_info_T **pqi)
{
@@ -1715,19 +1739,23 @@ static void ll_free_all(qf_info_T **pqi)
}
*pqi = NULL; // Remove reference to this list
+ // If the location list is still in use, then queue the delete request
+ // to be processed later.
+ if (quickfix_busy > 0) {
+ locstack_queue_delreq(qi);
+ return;
+ }
+
qi->qf_refcount--;
if (qi->qf_refcount < 1) {
// No references to this location list.
- // If the location list is still in use, then queue the delete request
- // to be processed later.
- if (quickfix_busy > 0) {
- locstack_queue_delreq(qi);
- } else {
- for (i = 0; i < qi->qf_listcount; i++) {
- qf_free(qf_get_list(qi, i));
- }
- xfree(qi);
+ // If the quickfix window buffer is loaded, then wipe it
+ wipe_qf_buffer(qi);
+
+ for (i = 0; i < qi->qf_listcount; i++) {
+ qf_free(qf_get_list(qi, i));
}
+ xfree(qi);
}
}
@@ -1885,6 +1913,7 @@ static qf_info_T *qf_alloc_stack(qfltype_T qfltype)
qf_info_T *qi = xcalloc(1, sizeof(qf_info_T));
qi->qf_refcount++;
qi->qfl_type = qfltype;
+ qi->qf_bufnr = INVALID_QFBUFNR;
return qi;
}
@@ -2446,7 +2475,7 @@ static qfline_T *qf_get_entry(qf_list_T *qfl, int errornr, int dir, int *new_qfi
return qf_ptr;
}
-// Find a window displaying a Vim help file.
+// Find a window displaying a Vim help file in the current tab page.
static win_T *qf_find_help_win(void)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -2520,8 +2549,9 @@ static int jump_to_help_window(qf_info_T *qi, bool newwin, int *opened_window)
return OK;
}
-// Find a non-quickfix window using the given location list.
-// Returns NULL if a matching window is not found.
+/// Find a non-quickfix window using the given location list stack in the
+/// current tabpage.
+/// Returns NULL if a matching window is not found.
static win_T *qf_find_win_with_loclist(const qf_info_T *ll)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -2533,7 +2563,7 @@ static win_T *qf_find_win_with_loclist(const qf_info_T *ll)
return NULL;
}
-// Find a window containing a normal buffer
+/// Find a window containing a normal buffer in the current tab page.
static win_T *qf_find_win_with_normal_buf(void)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -2589,7 +2619,7 @@ static void qf_goto_win_with_ll_file(win_T *use_win, int qf_fnum, qf_info_T *ll_
win_T *win = use_win;
if (win == NULL) {
- // Find the window showing the selected file
+ // Find the window showing the selected file in the current tab page.
FOR_ALL_WINDOWS_IN_TAB(win2, curtab) {
if (win2->w_buffer->b_fnum == qf_fnum) {
win = win2;
@@ -2721,7 +2751,7 @@ static int qf_jump_to_usable_window(int qf_fnum, bool newwin, int *opened_window
}
/// Edit the selected file or help file.
-static int qf_jump_edit_buffer(qf_info_T *qi, qfline_T *qf_ptr, int forceit, win_T *oldwin,
+static int qf_jump_edit_buffer(qf_info_T *qi, qfline_T *qf_ptr, int forceit, int prev_winid,
int *opened_window)
{
qf_list_T *qfl = qf_get_curlist(qi);
@@ -2740,7 +2770,7 @@ static int qf_jump_edit_buffer(qf_info_T *qi, qfline_T *qf_ptr, int forceit, win
} else {
retval = do_ecmd(qf_ptr->qf_fnum, NULL, NULL, NULL, (linenr_T)1,
ECMD_HIDE + ECMD_SET_HELP,
- oldwin == curwin ? curwin : NULL);
+ prev_winid == curwin->handle ? curwin : NULL);
}
} else {
retval = buflist_getfile(qf_ptr->qf_fnum, (linenr_T)1,
@@ -2748,10 +2778,13 @@ static int qf_jump_edit_buffer(qf_info_T *qi, qfline_T *qf_ptr, int forceit, win
}
// If a location list, check whether the associated window is still
// present.
- if (qfl_type == QFLT_LOCATION && !win_valid_any_tab(oldwin)) {
- emsg(_("E924: Current window was closed"));
- *opened_window = false;
- return NOTDONE;
+ if (qfl_type == QFLT_LOCATION) {
+ win_T *wp = win_id2wp(prev_winid);
+ if (wp == NULL && curwin->w_llist != qi) {
+ emsg(_("E924: Current window was closed"));
+ *opened_window = false;
+ return NOTDONE;
+ }
}
if (qfl_type == QFLT_QUICKFIX && !qflist_valid(NULL, save_qfid)) {
@@ -2906,7 +2939,7 @@ static int qf_jump_open_window(qf_info_T *qi, qfline_T *qf_ptr, bool newwin, int
/// NOTDONE if the quickfix/location list is freed by an autocmd when opening
/// the file.
static int qf_jump_to_buffer(qf_info_T *qi, int qf_index, qfline_T *qf_ptr, int forceit,
- win_T *oldwin, int *opened_window, int openfold, int print_message)
+ int prev_winid, int *opened_window, int openfold, int print_message)
{
buf_T *old_curbuf;
linenr_T old_lnum;
@@ -2918,7 +2951,7 @@ static int qf_jump_to_buffer(qf_info_T *qi, int qf_index, qfline_T *qf_ptr, int
old_lnum = curwin->w_cursor.lnum;
if (qf_ptr->qf_fnum != 0) {
- retval = qf_jump_edit_buffer(qi, qf_ptr, forceit, oldwin,
+ retval = qf_jump_edit_buffer(qi, qf_ptr, forceit, prev_winid,
opened_window);
if (retval != OK) {
return retval;
@@ -2967,8 +3000,8 @@ static void qf_jump_newwin(qf_info_T *qi, int dir, int errornr, int forceit, boo
int old_qf_index;
char_u *old_swb = p_swb;
unsigned old_swb_flags = swb_flags;
+ int prev_winid;
int opened_window = false;
- win_T *oldwin = curwin;
int print_message = true;
const bool old_KeyTyped = KeyTyped; // getting file may reset it
int retval = OK;
@@ -2982,6 +3015,8 @@ static void qf_jump_newwin(qf_info_T *qi, int dir, int errornr, int forceit, boo
return;
}
+ incr_quickfix_busy();
+
qfl = qf_get_curlist(qi);
qf_ptr = qfl->qf_ptr;
@@ -3004,6 +3039,8 @@ static void qf_jump_newwin(qf_info_T *qi, int dir, int errornr, int forceit, boo
print_message = false;
}
+ prev_winid = curwin->handle;
+
retval = qf_jump_open_window(qi, qf_ptr, newwin, &opened_window);
if (retval == FAIL) {
goto failed;
@@ -3012,7 +3049,7 @@ static void qf_jump_newwin(qf_info_T *qi, int dir, int errornr, int forceit, boo
goto theend;
}
- retval = qf_jump_to_buffer(qi, qf_index, qf_ptr, forceit, oldwin,
+ retval = qf_jump_to_buffer(qi, qf_index, qf_ptr, forceit, prev_winid,
&opened_window, old_KeyTyped, print_message);
if (retval == NOTDONE) {
// Quickfix/location list is freed by an autocmd
@@ -3037,12 +3074,13 @@ theend:
qfl->qf_ptr = qf_ptr;
qfl->qf_index = qf_index;
}
- if (p_swb != old_swb && p_swb == empty_option && opened_window) {
+ if (p_swb != old_swb && p_swb == empty_option) {
// Restore old 'switchbuf' value, but not when an autocommand or
// modeline has changed the value.
p_swb = old_swb;
swb_flags = old_swb_flags;
}
+ decr_quickfix_busy();
}
@@ -3597,7 +3635,7 @@ static int qf_goto_cwindow(const qf_info_T *qi, bool resize, int sz, bool vertsp
win_setwidth(sz);
}
} else if (sz != win->w_height
- && (win->w_height + win->w_status_height + tabline_height()
+ && (win->w_height + win->w_hsep_height + win->w_status_height + tabline_height()
< cmdline_row)) {
win_setheight(sz);
}
@@ -3612,7 +3650,7 @@ static void qf_set_cwindow_options(void)
// switch off 'swapfile'
set_option_value("swf", 0L, NULL, OPT_LOCAL);
set_option_value("bt", 0L, "quickfix", OPT_LOCAL);
- set_option_value("bh", 0L, "wipe", OPT_LOCAL);
+ set_option_value("bh", 0L, "hide", OPT_LOCAL);
RESET_BINDING(curwin);
curwin->w_p_diff = false;
set_option_value("fdm", 0L, "manual", OPT_LOCAL);
@@ -3646,22 +3684,13 @@ static int qf_open_new_cwindow(qf_info_T *qi, int height)
if (win_split(height, flags) == FAIL) {
return FAIL; // not enough room for window
}
-
- // User autocommands may have invalidated the previous window after calling
- // win_split, so add a check to ensure that the win is still here
- if (IS_LL_STACK(qi) && !win_valid(win)) {
- // close the window that was supposed to be for the loclist
- win_close(curwin, false, false);
- return FAIL;
- }
-
RESET_BINDING(curwin);
if (IS_LL_STACK(qi)) {
// For the location list window, create a reference to the
- // location list from the window 'win'.
- curwin->w_llist_ref = win->w_llist;
- win->w_llist->qf_refcount++;
+ // location list stack from the window 'win'.
+ curwin->w_llist_ref = qi;
+ qi->qf_refcount++;
}
if (oldwin != curwin) {
@@ -3678,6 +3707,8 @@ static int qf_open_new_cwindow(qf_info_T *qi, int height)
if (do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE + ECMD_NOWINENTER, oldwin) == FAIL) {
return FAIL;
}
+ // save the number of the new buffer
+ qi->qf_bufnr = curbuf->b_fnum;
}
// Set the options for the quickfix buffer/window (if not already done)
@@ -3856,8 +3887,8 @@ static int is_qf_win(const win_T *win, const qf_info_T *qi)
return false;
}
-/// Find a window displaying the quickfix/location stack 'qi'
-/// Only searches in the current tabpage.
+/// Find a window displaying the quickfix/location stack 'qi' in the current tab
+/// page.
static win_T *qf_find_win(const qf_info_T *qi)
FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
{
@@ -3870,11 +3901,20 @@ static win_T *qf_find_win(const qf_info_T *qi)
return NULL;
}
-// Find a quickfix buffer.
-// Searches in windows opened in all the tabs.
+/// Find a quickfix buffer.
+/// Searches in windows opened in all the tab pages.
static buf_T *qf_find_buf(qf_info_T *qi)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
+ if (qi->qf_bufnr != INVALID_QFBUFNR) {
+ buf_T *const qfbuf = buflist_findnr(qi->qf_bufnr);
+ if (qfbuf != NULL) {
+ return qfbuf;
+ }
+ // buffer is no longer present
+ qi->qf_bufnr = INVALID_QFBUFNR;
+ }
+
FOR_ALL_TAB_WINDOWS(tp, win) {
if (is_qf_win(win, qi)) {
return win->w_buffer;
@@ -5421,9 +5461,8 @@ static int vgr_process_args(exarg_T *eap, vgr_args_T *args)
/// Search for a pattern in a list of files and populate the quickfix list with
/// the matches.
-static int vgr_process_files(win_T *wp, qf_info_T *qi, vgr_args_T *cmd_args,
- bool *redraw_for_dummy, buf_T **first_match_buf,
- char_u **target_dir)
+static int vgr_process_files(win_T *wp, qf_info_T *qi, vgr_args_T *cmd_args, bool *redraw_for_dummy,
+ buf_T **first_match_buf, char_u **target_dir)
{
int status = FAIL;
unsigned save_qfid = qf_get_curlist(qi)->qf_id;
@@ -5980,6 +6019,21 @@ static int qf_winid(qf_info_T *qi)
return 0;
}
+/// Returns the number of the buffer displayed in the quickfix/location list
+/// window. If there is no buffer associated with the list or the buffer is
+/// wiped out, then returns 0.
+static int qf_getprop_qfbufnr(const qf_info_T *qi, dict_T *retdict)
+ FUNC_ATTR_NONNULL_ARG(2)
+{
+ int bufnum = 0;
+
+ if (qi != NULL && buflist_findnr(qi->qf_bufnr) != NULL) {
+ bufnum = qi->qf_bufnr;
+ }
+
+ return tv_dict_add_nr(retdict, S_LEN("qfbufnr"), bufnum);
+}
+
/// Convert the keys in 'what' to quickfix list property flags.
static int qf_getprop_keys2flags(const dict_T *what, bool loclist)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
@@ -6023,6 +6077,9 @@ static int qf_getprop_keys2flags(const dict_T *what, bool loclist)
if (loclist && tv_dict_find(what, S_LEN("filewinid")) != NULL) {
flags |= QF_GETLIST_FILEWINID;
}
+ if (tv_dict_find(what, S_LEN("qfbufnr")) != NULL) {
+ flags |= QF_GETLIST_QFBUFNR;
+ }
if (tv_dict_find(what, S_LEN("quickfixtextfunc")) != NULL) {
flags |= QF_GETLIST_QFTF;
}
@@ -6114,6 +6171,9 @@ static int qf_getprop_defaults(qf_info_T *qi, int flags, int locstack, dict_T *r
if ((status == OK) && locstack && (flags & QF_GETLIST_FILEWINID)) {
status = tv_dict_add_nr(retdict, S_LEN("filewinid"), 0);
}
+ if ((status == OK) && (flags & QF_GETLIST_QFBUFNR)) {
+ status = qf_getprop_qfbufnr(qi, retdict);
+ }
if ((status == OK) && (flags & QF_GETLIST_QFTF)) {
status = tv_dict_add_str(retdict, S_LEN("quickfixtextfunc"), "");
}
@@ -6283,6 +6343,9 @@ int qf_get_properties(win_T *wp, dict_T *what, dict_T *retdict)
if ((status == OK) && (wp != NULL) && (flags & QF_GETLIST_FILEWINID)) {
status = qf_getprop_filewinid(wp, qi, retdict);
}
+ if ((status == OK) && (flags & QF_GETLIST_QFBUFNR)) {
+ status = qf_getprop_qfbufnr(qi, retdict);
+ }
if ((status == OK) && (flags & QF_GETLIST_QFTF)) {
status = qf_getprop_qftf(qfl, retdict);
}
@@ -6671,20 +6734,6 @@ static int qf_set_properties(qf_info_T *qi, const dict_T *what, int action, char
return retval;
}
-/// Find the non-location list window with the specified location list stack in
-/// the current tabpage.
-static win_T *find_win_with_ll(const qf_info_T *qi)
- FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
-{
- FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
- if ((wp->w_llist == qi) && !bt_quickfix(wp->w_buffer)) {
- return wp;
- }
- }
-
- return NULL;
-}
-
// Free the entire quickfix/location list stack.
// If the quickfix/location list window is open, then clear it.
static void qf_free_stack(win_T *wp, qf_info_T *qi)
@@ -6699,12 +6748,10 @@ static void qf_free_stack(win_T *wp, qf_info_T *qi)
qf_update_buffer(qi, NULL);
}
- win_T *llwin = NULL;
- win_T *orig_wp = wp;
if (wp != NULL && IS_LL_WINDOW(wp)) {
// If in the location list window, then use the non-location list
// window with this location list (if present)
- llwin = find_win_with_ll(qi);
+ win_T *const llwin = qf_find_win_with_loclist(qi);
if (llwin != NULL) {
wp = llwin;
}
@@ -6715,16 +6762,17 @@ static void qf_free_stack(win_T *wp, qf_info_T *qi)
// quickfix list
qi->qf_curlist = 0;
qi->qf_listcount = 0;
- } else if (IS_LL_WINDOW(orig_wp)) {
+ } else if (qfwin != NULL) {
// If the location list window is open, then create a new empty location
// list
qf_info_T *new_ll = qf_alloc_stack(QFLT_LOCATION);
+ new_ll->qf_bufnr = qfwin->w_buffer->b_fnum;
// first free the list reference in the location list window
- ll_free_all(&orig_wp->w_llist_ref);
+ ll_free_all(&qfwin->w_llist_ref);
- orig_wp->w_llist_ref = new_ll;
- if (llwin != NULL) {
+ qfwin->w_llist_ref = new_ll;
+ if (wp != qfwin) {
win_set_loclist(wp, new_ll);
}
}
diff --git a/src/nvim/rbuffer.h b/src/nvim/rbuffer.h
index cc690050ab..e86765a4ad 100644
--- a/src/nvim/rbuffer.h
+++ b/src/nvim/rbuffer.h
@@ -38,17 +38,15 @@
// create infinite loops
#define RBUFFER_UNTIL_EMPTY(buf, rptr, rcnt) \
for (size_t rcnt = 0, _r = 1; _r; _r = 0) /* NOLINT(readability/braces) */ \
- for ( /* NOLINT(readability/braces) */ \
- char *rptr = rbuffer_read_ptr(buf, &rcnt); \
- buf->size; \
- rptr = rbuffer_read_ptr(buf, &rcnt))
+ for (char *rptr = rbuffer_read_ptr(buf, &rcnt); /* NOLINT(readability/braces) */ \
+ buf->size; \
+ rptr = rbuffer_read_ptr(buf, &rcnt))
#define RBUFFER_UNTIL_FULL(buf, wptr, wcnt) \
for (size_t wcnt = 0, _r = 1; _r; _r = 0) /* NOLINT(readability/braces) */ \
- for ( /* NOLINT(readability/braces) */ \
- char *wptr = rbuffer_write_ptr(buf, &wcnt); \
- rbuffer_space(buf); \
- wptr = rbuffer_write_ptr(buf, &wcnt))
+ for (char *wptr = rbuffer_write_ptr(buf, &wcnt); /* NOLINT(readability/braces) */ \
+ rbuffer_space(buf); \
+ wptr = rbuffer_write_ptr(buf, &wcnt))
// Iteration
diff --git a/src/nvim/regexp.c b/src/nvim/regexp.c
index 6a6c915094..009a26d4e0 100644
--- a/src/nvim/regexp.c
+++ b/src/nvim/regexp.c
@@ -5,41 +5,6 @@
/*
* Handling of regular expressions: vim_regcomp(), vim_regexec(), vim_regsub()
- *
- * NOTICE:
- *
- * This is NOT the original regular expression code as written by Henry
- * Spencer. This code has been modified specifically for use with the VIM
- * editor, and should not be used separately from Vim. If you want a good
- * regular expression library, get the original code. The copyright notice
- * that follows is from the original.
- *
- * END NOTICE
- *
- * Copyright (c) 1986 by University of Toronto.
- * Written by Henry Spencer. Not derived from licensed software.
- *
- * Permission is granted to anyone to use this software for any
- * purpose on any computer system, and to redistribute it freely,
- * subject to the following restrictions:
- *
- * 1. The author is not responsible for the consequences of use of
- * this software, no matter how awful, even if they arise
- * from defects in it.
- *
- * 2. The origin of this software must not be misrepresented, either
- * by explicit claim or by omission.
- *
- * 3. Altered versions must be plainly marked as such, and must not
- * be misrepresented as being the original software.
- *
- * Beware that some of this code is subtly aware of the way operator
- * precedence is structured in regular expressions. Serious changes in
- * regular-expression syntax might require a total rethink.
- *
- * Changes have been made by Tony Andrews, Olaf 'Rhialto' Seibert, Robert
- * Webb, Ciaran McCreesh and Bram Moolenaar.
- * Named character class support added by Walter Briscoe (1998 Jul 01)
*/
// By default: do not create debugging logs or files related to regular
@@ -70,205 +35,15 @@
#include "nvim/strings.h"
#ifdef REGEXP_DEBUG
-/* show/save debugging data when BT engine is used */
+// show/save debugging data when BT engine is used
# define BT_REGEXP_DUMP
-/* save the debugging data to a file instead of displaying it */
+// save the debugging data to a file instead of displaying it
# define BT_REGEXP_LOG
# define BT_REGEXP_DEBUG_LOG
# define BT_REGEXP_DEBUG_LOG_NAME "bt_regexp_debug.log"
#endif
/*
- * The "internal use only" fields in regexp_defs.h are present to pass info from
- * compile to execute that permits the execute phase to run lots faster on
- * simple cases. They are:
- *
- * regstart char that must begin a match; NUL if none obvious; Can be a
- * multi-byte character.
- * reganch is the match anchored (at beginning-of-line only)?
- * regmust string (pointer into program) that match must include, or NULL
- * regmlen length of regmust string
- * regflags RF_ values or'ed together
- *
- * Regstart and reganch permit very fast decisions on suitable starting points
- * for a match, cutting down the work a lot. Regmust permits fast rejection
- * of lines that cannot possibly match. The regmust tests are costly enough
- * that vim_regcomp() supplies a regmust only if the r.e. contains something
- * potentially expensive (at present, the only such thing detected is * or +
- * at the start of the r.e., which can involve a lot of backup). Regmlen is
- * supplied because the test in vim_regexec() needs it and vim_regcomp() is
- * computing it anyway.
- */
-
-/*
- * Structure for regexp "program". This is essentially a linear encoding
- * of a nondeterministic finite-state machine (aka syntax charts or
- * "railroad normal form" in parsing technology). Each node is an opcode
- * plus a "next" pointer, possibly plus an operand. "Next" pointers of
- * all nodes except BRANCH and BRACES_COMPLEX implement concatenation; a "next"
- * pointer with a BRANCH on both ends of it is connecting two alternatives.
- * (Here we have one of the subtle syntax dependencies: an individual BRANCH
- * (as opposed to a collection of them) is never concatenated with anything
- * because of operator precedence). The "next" pointer of a BRACES_COMPLEX
- * node points to the node after the stuff to be repeated.
- * The operand of some types of node is a literal string; for others, it is a
- * node leading into a sub-FSM. In particular, the operand of a BRANCH node
- * is the first node of the branch.
- * (NB this is *not* a tree structure: the tail of the branch connects to the
- * thing following the set of BRANCHes.)
- *
- * pattern is coded like:
- *
- * +-----------------+
- * | V
- * <aa>\|<bb> BRANCH <aa> BRANCH <bb> --> END
- * | ^ | ^
- * +------+ +----------+
- *
- *
- * +------------------+
- * V |
- * <aa>* BRANCH BRANCH <aa> --> BACK BRANCH --> NOTHING --> END
- * | | ^ ^
- * | +---------------+ |
- * +---------------------------------------------+
- *
- *
- * +----------------------+
- * V |
- * <aa>\+ BRANCH <aa> --> BRANCH --> BACK BRANCH --> NOTHING --> END
- * | | ^ ^
- * | +-----------+ |
- * +--------------------------------------------------+
- *
- *
- * +-------------------------+
- * V |
- * <aa>\{} BRANCH BRACE_LIMITS --> BRACE_COMPLEX <aa> --> BACK END
- * | | ^
- * | +----------------+
- * +-----------------------------------------------+
- *
- *
- * <aa>\@!<bb> BRANCH NOMATCH <aa> --> END <bb> --> END
- * | | ^ ^
- * | +----------------+ |
- * +--------------------------------+
- *
- * +---------+
- * | V
- * \z[abc] BRANCH BRANCH a BRANCH b BRANCH c BRANCH NOTHING --> END
- * | | | | ^ ^
- * | | | +-----+ |
- * | | +----------------+ |
- * | +---------------------------+ |
- * +------------------------------------------------------+
- *
- * They all start with a BRANCH for "\|" alternatives, even when there is only
- * one alternative.
- */
-
-/*
- * The opcodes are:
- */
-
-/* definition number opnd? meaning */
-#define END 0 /* End of program or NOMATCH operand. */
-#define BOL 1 /* Match "" at beginning of line. */
-#define EOL 2 /* Match "" at end of line. */
-#define BRANCH 3 /* node Match this alternative, or the
- * next... */
-#define BACK 4 /* Match "", "next" ptr points backward. */
-#define EXACTLY 5 /* str Match this string. */
-#define NOTHING 6 /* Match empty string. */
-#define STAR 7 /* node Match this (simple) thing 0 or more
- * times. */
-#define PLUS 8 /* node Match this (simple) thing 1 or more
- * times. */
-#define MATCH 9 /* node match the operand zero-width */
-#define NOMATCH 10 /* node check for no match with operand */
-#define BEHIND 11 /* node look behind for a match with operand */
-#define NOBEHIND 12 /* node look behind for no match with operand */
-#define SUBPAT 13 /* node match the operand here */
-#define BRACE_SIMPLE 14 /* node Match this (simple) thing between m and
- * n times (\{m,n\}). */
-#define BOW 15 /* Match "" after [^a-zA-Z0-9_] */
-#define EOW 16 /* Match "" at [^a-zA-Z0-9_] */
-#define BRACE_LIMITS 17 /* nr nr define the min & max for BRACE_SIMPLE
- * and BRACE_COMPLEX. */
-#define NEWL 18 /* Match line-break */
-#define BHPOS 19 /* End position for BEHIND or NOBEHIND */
-
-
-/* character classes: 20-48 normal, 50-78 include a line-break */
-#define ADD_NL 30
-#define FIRST_NL ANY + ADD_NL
-#define ANY 20 /* Match any one character. */
-#define ANYOF 21 /* str Match any character in this string. */
-#define ANYBUT 22 /* str Match any character not in this
- * string. */
-#define IDENT 23 /* Match identifier char */
-#define SIDENT 24 /* Match identifier char but no digit */
-#define KWORD 25 /* Match keyword char */
-#define SKWORD 26 /* Match word char but no digit */
-#define FNAME 27 /* Match file name char */
-#define SFNAME 28 /* Match file name char but no digit */
-#define PRINT 29 /* Match printable char */
-#define SPRINT 30 /* Match printable char but no digit */
-#define WHITE 31 /* Match whitespace char */
-#define NWHITE 32 /* Match non-whitespace char */
-#define DIGIT 33 /* Match digit char */
-#define NDIGIT 34 /* Match non-digit char */
-#define HEX 35 /* Match hex char */
-#define NHEX 36 /* Match non-hex char */
-#define OCTAL 37 /* Match octal char */
-#define NOCTAL 38 /* Match non-octal char */
-#define WORD 39 /* Match word char */
-#define NWORD 40 /* Match non-word char */
-#define HEAD 41 /* Match head char */
-#define NHEAD 42 /* Match non-head char */
-#define ALPHA 43 /* Match alpha char */
-#define NALPHA 44 /* Match non-alpha char */
-#define LOWER 45 /* Match lowercase char */
-#define NLOWER 46 /* Match non-lowercase char */
-#define UPPER 47 /* Match uppercase char */
-#define NUPPER 48 /* Match non-uppercase char */
-#define LAST_NL NUPPER + ADD_NL
-// -V:WITH_NL:560
-#define WITH_NL(op) ((op) >= FIRST_NL && (op) <= LAST_NL)
-
-#define MOPEN 80 // -89 Mark this point in input as start of
- // \( … \) subexpr. MOPEN + 0 marks start of
- // match.
-#define MCLOSE 90 // -99 Analogous to MOPEN. MCLOSE + 0 marks
- // end of match.
-#define BACKREF 100 // -109 node Match same string again \1-\9.
-
-# define ZOPEN 110 // -119 Mark this point in input as start of
- // \z( … \) subexpr.
-# define ZCLOSE 120 // -129 Analogous to ZOPEN.
-# define ZREF 130 // -139 node Match external submatch \z1-\z9
-
-#define BRACE_COMPLEX 140 /* -149 node Match nodes between m & n times */
-
-#define NOPEN 150 // Mark this point in input as start of
- // \%( subexpr.
-#define NCLOSE 151 // Analogous to NOPEN.
-
-#define MULTIBYTECODE 200 /* mbc Match one multi-byte character */
-#define RE_BOF 201 /* Match "" at beginning of file. */
-#define RE_EOF 202 /* Match "" at end of file. */
-#define CURSOR 203 /* Match location of cursor. */
-
-#define RE_LNUM 204 /* nr cmp Match line number */
-#define RE_COL 205 /* nr cmp Match column number */
-#define RE_VCOL 206 /* nr cmp Match virtual column number */
-
-#define RE_MARK 207 /* mark cmp Match mark position */
-#define RE_VISUAL 208 /* Match Visual area */
-#define RE_COMPOSING 209 // any composing characters
-
-/*
* Magic characters have a special meaning, they don't match literally.
* Magic characters are negative. This separates them from literal characters
* (possibly multi-byte). Only ASCII characters can be Magic.
@@ -285,107 +60,6 @@
*/
typedef void (*(*fptr_T)(int *, int))(void);
-typedef struct {
- char_u *regparse;
- int prevchr_len;
- int curchr;
- int prevchr;
- int prevprevchr;
- int nextchr;
- int at_start;
- int prev_at_start;
- int regnpar;
-} parse_state_T;
-
-/*
- * Structure used to save the current input state, when it needs to be
- * restored after trying a match. Used by reg_save() and reg_restore().
- * Also stores the length of "backpos".
- */
-typedef struct {
- union {
- char_u *ptr; ///< rex.input pointer, for single-line regexp
- lpos_T pos; ///< rex.input pos, for multi-line regexp
- } rs_u;
- int rs_len;
-} regsave_T;
-
-/* struct to save start/end pointer/position in for \(\) */
-typedef struct {
- union {
- char_u *ptr;
- lpos_T pos;
- } se_u;
-} save_se_T;
-
-/* used for BEHIND and NOBEHIND matching */
-typedef struct regbehind_S {
- regsave_T save_after;
- regsave_T save_behind;
- int save_need_clear_subexpr;
- save_se_T save_start[NSUBEXP];
- save_se_T save_end[NSUBEXP];
-} regbehind_T;
-
-/* Values for rs_state in regitem_T. */
-typedef enum regstate_E {
- RS_NOPEN = 0 /* NOPEN and NCLOSE */
- , RS_MOPEN /* MOPEN + [0-9] */
- , RS_MCLOSE /* MCLOSE + [0-9] */
- , RS_ZOPEN /* ZOPEN + [0-9] */
- , RS_ZCLOSE /* ZCLOSE + [0-9] */
- , RS_BRANCH /* BRANCH */
- , RS_BRCPLX_MORE /* BRACE_COMPLEX and trying one more match */
- , RS_BRCPLX_LONG /* BRACE_COMPLEX and trying longest match */
- , RS_BRCPLX_SHORT /* BRACE_COMPLEX and trying shortest match */
- , RS_NOMATCH /* NOMATCH */
- , RS_BEHIND1 /* BEHIND / NOBEHIND matching rest */
- , RS_BEHIND2 /* BEHIND / NOBEHIND matching behind part */
- , RS_STAR_LONG /* STAR/PLUS/BRACE_SIMPLE longest match */
- , RS_STAR_SHORT /* STAR/PLUS/BRACE_SIMPLE shortest match */
-} regstate_T;
-
-/*
- * When there are alternatives a regstate_T is put on the regstack to remember
- * what we are doing.
- * Before it may be another type of item, depending on rs_state, to remember
- * more things.
- */
-typedef struct regitem_S {
- regstate_T rs_state; // what we are doing, one of RS_ above
- uint16_t rs_no; // submatch nr or BEHIND/NOBEHIND
- char_u *rs_scan; // current node in program
- union {
- save_se_T sesave;
- regsave_T regsave;
- } rs_un; ///< room for saving rex.input
-} regitem_T;
-
-
-/* used for STAR, PLUS and BRACE_SIMPLE matching */
-typedef struct regstar_S {
- int nextb; /* next byte */
- int nextb_ic; /* next byte reverse case */
- long count;
- long minval;
- long maxval;
-} regstar_T;
-
-/* used to store input position when a BACK was encountered, so that we now if
- * we made any progress since the last time. */
-typedef struct backpos_S {
- char_u *bp_scan; /* "scan" where BACK was encountered */
- regsave_T bp_pos; /* last input position */
-} backpos_T;
-
-typedef struct {
- int a, b, c;
-} decomp_T;
-
-
-#ifdef INCLUDE_GENERATED_DECLARATIONS
-# include "regexp.c.generated.h"
-#endif
static int no_Magic(int x)
{
if (is_Magic(x))
@@ -400,66 +74,13 @@ static int toggle_Magic(int x)
return Magic(x);
}
-/*
- * The first byte of the regexp internal "program" is actually this magic
- * number; the start node begins in the second byte. It's used to catch the
- * most severe mutilation of the program by the caller.
- */
-
+// The first byte of the BT regexp internal "program" is actually this magic
+// number; the start node begins in the second byte. It's used to catch the
+// most severe mutilation of the program by the caller.
#define REGMAGIC 0234
-/*
- * Opcode notes:
- *
- * BRANCH The set of branches constituting a single choice are hooked
- * together with their "next" pointers, since precedence prevents
- * anything being concatenated to any individual branch. The
- * "next" pointer of the last BRANCH in a choice points to the
- * thing following the whole choice. This is also where the
- * final "next" pointer of each individual branch points; each
- * branch starts with the operand node of a BRANCH node.
- *
- * BACK Normal "next" pointers all implicitly point forward; BACK
- * exists to make loop structures possible.
- *
- * STAR,PLUS '=', and complex '*' and '+', are implemented as circular
- * BRANCH structures using BACK. Simple cases (one character
- * per match) are implemented with STAR and PLUS for speed
- * and to minimize recursive plunges.
- *
- * BRACE_LIMITS This is always followed by a BRACE_SIMPLE or BRACE_COMPLEX
- * node, and defines the min and max limits to be used for that
- * node.
- *
- * MOPEN,MCLOSE ...are numbered at compile time.
- * ZOPEN,ZCLOSE ...ditto
- */
-
-/*
- * A node is one char of opcode followed by two chars of "next" pointer.
- * "Next" pointers are stored as two 8-bit bytes, high order first. The
- * value is a positive offset from the opcode of the node containing it.
- * An operand, if any, simply follows the node. (Note that much of the
- * code generation knows about this implicit relationship.)
- *
- * Using two bytes for the "next" pointer is vast overkill for most things,
- * but allows patterns to get big without disasters.
- */
-#define OP(p) ((int)*(p))
-#define NEXT(p) (((*((p) + 1) & 0377) << 8) + (*((p) + 2) & 0377))
-#define OPERAND(p) ((p) + 3)
-/* Obtain an operand that was stored as four bytes, MSB first. */
-#define OPERAND_MIN(p) (((long)(p)[3] << 24) + ((long)(p)[4] << 16) \
- + ((long)(p)[5] << 8) + (long)(p)[6])
-/* Obtain a second operand stored as four bytes. */
-#define OPERAND_MAX(p) OPERAND_MIN((p) + 4)
-/* Obtain a second single-byte operand stored after a four bytes operand. */
-#define OPERAND_CMP(p) (p)[7]
-
-/*
- * Utility definitions.
- */
-#define UCHARAT(p) ((int)*(char_u *)(p))
+// Utility definitions.
+#define UCHARAT(p) ((int)(*(char_u *)(p)))
// Used for an error (down from) vim_regcomp(): give the error message, set
// rc_did_emsg and return NULL
@@ -468,6 +89,8 @@ static int toggle_Magic(int x)
#define EMSG_RET_FAIL(m) return (emsg(m), rc_did_emsg = true, FAIL)
#define EMSG2_RET_NULL(m, c) \
return (semsg((m), (c) ? "" : "\\"), rc_did_emsg = true, (void *)NULL)
+#define EMSG3_RET_NULL(m, c, a) \
+ return (semsg((const char *)(m), (c) ? "" : "\\", (a)), rc_did_emsg = true, (void *)NULL)
#define EMSG2_RET_FAIL(m, c) \
return (semsg((m), (c) ? "" : "\\"), rc_did_emsg = true, FAIL)
#define EMSG_ONE_RET_NULL EMSG2_RET_NULL(_( \
@@ -475,14 +98,6 @@ static int toggle_Magic(int x)
#define MAX_LIMIT (32767L << 16L)
-
-#ifdef BT_REGEXP_DUMP
-static void regdump(char_u *, bt_regprog_T *);
-#endif
-#ifdef REGEXP_DEBUG
-static char_u *regprop(char_u *);
-#endif
-
static char_u e_missingbracket[] = N_("E769: Missing ] after %s[");
static char_u e_reverse_range[] = N_("E944: Reverse range in character class");
static char_u e_large_class[] = N_("E945: Range too large in character class");
@@ -498,11 +113,17 @@ static char_u e_recursive[] = N_("E956: Cannot use pattern recursively");
#define NOT_MULTI 0
#define MULTI_ONE 1
#define MULTI_MULT 2
-/*
- * Return NOT_MULTI if c is not a "multi" operator.
- * Return MULTI_ONE if c is a single "multi" operator.
- * Return MULTI_MULT if c is a multi "multi" operator.
- */
+
+// return values for regmatch()
+#define RA_FAIL 1 // something failed, abort
+#define RA_CONT 2 // continue in inner loop
+#define RA_BREAK 3 // break inner loop
+#define RA_MATCH 4 // successful match
+#define RA_NOMATCH 5 // didn't match
+
+/// Return NOT_MULTI if c is not a "multi" operator.
+/// Return MULTI_ONE if c is a single "multi" operator.
+/// Return MULTI_MULT if c is a multi "multi" operator.
static int re_multi_type(int c)
{
if (c == Magic('@') || c == Magic('=') || c == Magic('?'))
@@ -512,22 +133,6 @@ static int re_multi_type(int c)
return NOT_MULTI;
}
-/*
- * Flags to be passed up and down.
- */
-#define HASWIDTH 0x1 /* Known never to match null string. */
-#define SIMPLE 0x2 /* Simple enough to be STAR/PLUS operand. */
-#define SPSTART 0x4 /* Starts with * or +. */
-#define HASNL 0x8 /* Contains some \n. */
-#define HASLOOKBH 0x10 /* Contains "\@<=" or "\@<!". */
-#define WORST 0 /* Worst case. */
-
-/*
- * When regcode is set to this value, code is not emitted and size is computed
- * instead.
- */
-#define JUST_CALC_SIZE ((char_u *) -1)
-
static char_u *reg_prev_sub = NULL;
/*
@@ -682,38 +287,28 @@ static void init_class_tab(void)
# define ri_upper(c) (c < 0x100 && (class_tab[c] & RI_UPPER))
# define ri_white(c) (c < 0x100 && (class_tab[c] & RI_WHITE))
-/* flags for regflags */
-#define RF_ICASE 1 /* ignore case */
-#define RF_NOICASE 2 /* don't ignore case */
-#define RF_HASNL 4 /* can match a NL */
-#define RF_ICOMBINE 8 /* ignore combining characters */
-#define RF_LOOKBH 16 /* uses "\@<=" or "\@<!" */
+// flags for regflags
+#define RF_ICASE 1 // ignore case
+#define RF_NOICASE 2 // don't ignore case
+#define RF_HASNL 4 // can match a NL
+#define RF_ICOMBINE 8 // ignore combining characters
+#define RF_LOOKBH 16 // uses "\@<=" or "\@<!"
// Global work variables for vim_regcomp().
static char_u *regparse; ///< Input-scan pointer.
-static int prevchr_len; ///< byte length of previous char
-static int num_complex_braces; ///< Complex \{...} count
static int regnpar; ///< () count.
static bool wants_nfa; ///< regex should use NFA engine
static int regnzpar; ///< \z() count.
static int re_has_z; ///< \z item detected
-static char_u *regcode; ///< Code-emit pointer, or JUST_CALC_SIZE
-static long regsize; ///< Code size.
-static int reg_toolong; ///< true when offset out of range
-static char_u had_endbrace[NSUBEXP]; ///< flags, true if end of () found
-static unsigned regflags; ///< RF_ flags for prog
-static long brace_min[10]; ///< Minimums for complex brace repeats
-static long brace_max[10]; ///< Maximums for complex brace repeats
-static int brace_count[10]; ///< Current counts for complex brace repeats
-static int had_eol; ///< true when EOL found by vim_regcomp()
-static int one_exactly = false; ///< only do one char for EXACTLY
-
-static int reg_magic; /* magicness of the pattern: */
-#define MAGIC_NONE 1 /* "\V" very unmagic */
-#define MAGIC_OFF 2 /* "\M" or 'magic' off */
-#define MAGIC_ON 3 /* "\m" or 'magic' */
-#define MAGIC_ALL 4 /* "\v" very magic */
+static unsigned regflags; ///< RF_ flags for prog
+static int had_eol; ///< true when EOL found by vim_regcomp()
+
+static int reg_magic; // magicness of the pattern:
+#define MAGIC_NONE 1 // "\V" very unmagic
+#define MAGIC_OFF 2 // "\M" or 'magic' off
+#define MAGIC_ON 3 // "\m" or 'magic'
+#define MAGIC_ALL 4 // "\v" very magic
static int reg_string; // matching with a string instead of a buffer
// line
@@ -723,22 +318,22 @@ static int reg_strict; // "[abc" is illegal
* META contains all characters that may be magic, except '^' and '$'.
*/
-/* META[] is used often enough to justify turning it into a table. */
+// META[] is used often enough to justify turning it into a table.
static char_u META_flags[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- /* % & ( ) * + . */
- 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0,
- /* 1 2 3 4 5 6 7 8 9 < = > ? */
- 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1,
- /* @ A C D F H I K L M O */
- 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1,
- /* P S U V W X Z [ _ */
- 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1,
- /* a c d f h i k l m n o */
- 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1,
- /* p s u v w x z { | ~ */
- 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+// % & ( ) * + .
+ 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0,
+// 1 2 3 4 5 6 7 8 9 < = > ?
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1,
+// @ A C D F H I K L M O
+ 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1,
+// P S U V W X Z [ _
+ 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1,
+// a c d f h i k l m n o
+ 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1,
+// p s u v w x z { | ~
+ 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1
};
static int curchr; // currently parsed character
@@ -746,24 +341,36 @@ static int curchr; // currently parsed character
// start, eg in /[ ^I]^ the pattern was never found even if it existed,
// because ^ was taken to be magic -- webb
static int prevchr;
-static int prevprevchr; /* previous-previous character */
-static int nextchr; /* used for ungetchr() */
+static int prevprevchr; // previous-previous character
+static int nextchr; // used for ungetchr()
-/* arguments for reg() */
-#define REG_NOPAREN 0 /* toplevel reg() */
-#define REG_PAREN 1 /* \(\) */
-#define REG_ZPAREN 2 /* \z(\) */
-#define REG_NPAREN 3 /* \%(\) */
+// arguments for reg()
+#define REG_NOPAREN 0 // toplevel reg()
+#define REG_PAREN 1 // \(\)
+#define REG_ZPAREN 2 // \z(\)
+#define REG_NPAREN 3 // \%(\)
+
+typedef struct {
+ char_u *regparse;
+ int prevchr_len;
+ int curchr;
+ int prevchr;
+ int prevprevchr;
+ int nextchr;
+ int at_start;
+ int prev_at_start;
+ int regnpar;
+} parse_state_T;
-/*
- * Forward declarations for vim_regcomp()'s friends.
- */
-# define REGMBC(x) regmbc(x);
-# define CASEMBC(x) case x:
static regengine_T bt_regengine;
static regengine_T nfa_regengine;
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+# include "regexp.c.generated.h"
+#endif
+
+
// Return true if compiled regular expression "prog" can match a line break.
int re_multiline(const regprog_T *prog)
FUNC_ATTR_NONNULL_ALL
@@ -795,312 +402,6 @@ static int get_equi_class(char_u **pp)
/*
- * Produce the bytes for equivalence class "c".
- * Currently only handles latin1, latin9 and utf-8.
- * NOTE: When changing this function, also change nfa_emit_equi_class()
- */
-static void reg_equi_class(int c)
-{
- {
- switch (c) {
- // Do not use '\300' style, it results in a negative number.
- case 'A': case 0xc0: case 0xc1: case 0xc2:
- case 0xc3: case 0xc4: case 0xc5:
- CASEMBC(0x100) CASEMBC(0x102) CASEMBC(0x104) CASEMBC(0x1cd)
- CASEMBC(0x1de) CASEMBC(0x1e0) CASEMBC(0x1ea2)
- regmbc('A'); regmbc(0xc0); regmbc(0xc1);
- regmbc(0xc2); regmbc(0xc3); regmbc(0xc4);
- regmbc(0xc5);
- REGMBC(0x100) REGMBC(0x102) REGMBC(0x104)
- REGMBC(0x1cd) REGMBC(0x1de) REGMBC(0x1e0)
- REGMBC(0x1ea2)
- return;
- case 'B': CASEMBC(0x1e02) CASEMBC(0x1e06)
- regmbc('B'); REGMBC(0x1e02) REGMBC(0x1e06)
- return;
- case 'C': case 0xc7:
- CASEMBC(0x106) CASEMBC(0x108) CASEMBC(0x10a) CASEMBC(0x10c)
- regmbc('C'); regmbc(0xc7);
- REGMBC(0x106) REGMBC(0x108) REGMBC(0x10a)
- REGMBC(0x10c)
- return;
- case 'D': CASEMBC(0x10e) CASEMBC(0x110) CASEMBC(0x1e0a)
- CASEMBC(0x1e0e) CASEMBC(0x1e10)
- regmbc('D'); REGMBC(0x10e) REGMBC(0x110)
- REGMBC(0x1e0a) REGMBC(0x1e0e) REGMBC(0x1e10)
- return;
- case 'E': case 0xc8: case 0xc9: case 0xca: case 0xcb:
- CASEMBC(0x112) CASEMBC(0x114) CASEMBC(0x116) CASEMBC(0x118)
- CASEMBC(0x11a) CASEMBC(0x1eba) CASEMBC(0x1ebc)
- regmbc('E'); regmbc(0xc8); regmbc(0xc9);
- regmbc(0xca); regmbc(0xcb);
- REGMBC(0x112) REGMBC(0x114) REGMBC(0x116)
- REGMBC(0x118) REGMBC(0x11a) REGMBC(0x1eba)
- REGMBC(0x1ebc)
- return;
- case 'F': CASEMBC(0x1e1e)
- regmbc('F'); REGMBC(0x1e1e)
- return;
- case 'G': CASEMBC(0x11c) CASEMBC(0x11e) CASEMBC(0x120)
- CASEMBC(0x122) CASEMBC(0x1e4) CASEMBC(0x1e6) CASEMBC(0x1f4)
- CASEMBC(0x1e20)
- regmbc('G'); REGMBC(0x11c) REGMBC(0x11e)
- REGMBC(0x120) REGMBC(0x122) REGMBC(0x1e4)
- REGMBC(0x1e6) REGMBC(0x1f4) REGMBC(0x1e20)
- return;
- case 'H': CASEMBC(0x124) CASEMBC(0x126) CASEMBC(0x1e22)
- CASEMBC(0x1e26) CASEMBC(0x1e28)
- regmbc('H'); REGMBC(0x124) REGMBC(0x126)
- REGMBC(0x1e22) REGMBC(0x1e26) REGMBC(0x1e28)
- return;
- case 'I': case 0xcc: case 0xcd: case 0xce: case 0xcf:
- CASEMBC(0x128) CASEMBC(0x12a) CASEMBC(0x12c) CASEMBC(0x12e)
- CASEMBC(0x130) CASEMBC(0x1cf) CASEMBC(0x1ec8)
- regmbc('I'); regmbc(0xcc); regmbc(0xcd);
- regmbc(0xce); regmbc(0xcf);
- REGMBC(0x128) REGMBC(0x12a) REGMBC(0x12c)
- REGMBC(0x12e) REGMBC(0x130) REGMBC(0x1cf)
- REGMBC(0x1ec8)
- return;
- case 'J': CASEMBC(0x134)
- regmbc('J'); REGMBC(0x134)
- return;
- case 'K': CASEMBC(0x136) CASEMBC(0x1e8) CASEMBC(0x1e30)
- CASEMBC(0x1e34)
- regmbc('K'); REGMBC(0x136) REGMBC(0x1e8)
- REGMBC(0x1e30) REGMBC(0x1e34)
- return;
- case 'L': CASEMBC(0x139) CASEMBC(0x13b) CASEMBC(0x13d)
- CASEMBC(0x13f) CASEMBC(0x141) CASEMBC(0x1e3a)
- regmbc('L'); REGMBC(0x139) REGMBC(0x13b)
- REGMBC(0x13d) REGMBC(0x13f) REGMBC(0x141)
- REGMBC(0x1e3a)
- return;
- case 'M': CASEMBC(0x1e3e) CASEMBC(0x1e40)
- regmbc('M'); REGMBC(0x1e3e) REGMBC(0x1e40)
- return;
- case 'N': case 0xd1:
- CASEMBC(0x143) CASEMBC(0x145) CASEMBC(0x147) CASEMBC(0x1e44)
- CASEMBC(0x1e48)
- regmbc('N'); regmbc(0xd1);
- REGMBC(0x143) REGMBC(0x145) REGMBC(0x147)
- REGMBC(0x1e44) REGMBC(0x1e48)
- return;
- case 'O': case 0xd2: case 0xd3: case 0xd4: case 0xd5:
- case 0xd6: case 0xd8:
- CASEMBC(0x14c) CASEMBC(0x14e) CASEMBC(0x150) CASEMBC(0x1a0)
- CASEMBC(0x1d1) CASEMBC(0x1ea) CASEMBC(0x1ec) CASEMBC(0x1ece)
- regmbc('O'); regmbc(0xd2); regmbc(0xd3);
- regmbc(0xd4); regmbc(0xd5); regmbc(0xd6);
- regmbc(0xd8);
- REGMBC(0x14c) REGMBC(0x14e) REGMBC(0x150)
- REGMBC(0x1a0) REGMBC(0x1d1) REGMBC(0x1ea)
- REGMBC(0x1ec) REGMBC(0x1ece)
- return;
- case 'P': case 0x1e54: case 0x1e56:
- regmbc('P'); REGMBC(0x1e54) REGMBC(0x1e56)
- return;
- case 'R': CASEMBC(0x154) CASEMBC(0x156) CASEMBC(0x158)
- CASEMBC(0x1e58) CASEMBC(0x1e5e)
- regmbc('R'); REGMBC(0x154) REGMBC(0x156) REGMBC(0x158)
- REGMBC(0x1e58) REGMBC(0x1e5e)
- return;
- case 'S': CASEMBC(0x15a) CASEMBC(0x15c) CASEMBC(0x15e)
- CASEMBC(0x160) CASEMBC(0x1e60)
- regmbc('S'); REGMBC(0x15a) REGMBC(0x15c)
- REGMBC(0x15e) REGMBC(0x160) REGMBC(0x1e60)
- return;
- case 'T': CASEMBC(0x162) CASEMBC(0x164) CASEMBC(0x166)
- CASEMBC(0x1e6a) CASEMBC(0x1e6e)
- regmbc('T'); REGMBC(0x162) REGMBC(0x164)
- REGMBC(0x166) REGMBC(0x1e6a) REGMBC(0x1e6e)
- return;
- case 'U': case 0xd9: case 0xda: case 0xdb: case 0xdc:
- CASEMBC(0x168) CASEMBC(0x16a) CASEMBC(0x16c) CASEMBC(0x16e)
- CASEMBC(0x170) CASEMBC(0x172) CASEMBC(0x1af) CASEMBC(0x1d3)
- CASEMBC(0x1ee6)
- regmbc('U'); regmbc(0xd9); regmbc(0xda);
- regmbc(0xdb); regmbc(0xdc);
- REGMBC(0x168) REGMBC(0x16a) REGMBC(0x16c)
- REGMBC(0x16e) REGMBC(0x170) REGMBC(0x172)
- REGMBC(0x1af) REGMBC(0x1d3) REGMBC(0x1ee6)
- return;
- case 'V': CASEMBC(0x1e7c)
- regmbc('V'); REGMBC(0x1e7c)
- return;
- case 'W': CASEMBC(0x174) CASEMBC(0x1e80) CASEMBC(0x1e82)
- CASEMBC(0x1e84) CASEMBC(0x1e86)
- regmbc('W'); REGMBC(0x174) REGMBC(0x1e80)
- REGMBC(0x1e82) REGMBC(0x1e84) REGMBC(0x1e86)
- return;
- case 'X': CASEMBC(0x1e8a) CASEMBC(0x1e8c)
- regmbc('X'); REGMBC(0x1e8a) REGMBC(0x1e8c)
- return;
- case 'Y': case 0xdd:
- CASEMBC(0x176) CASEMBC(0x178) CASEMBC(0x1e8e) CASEMBC(0x1ef2)
- CASEMBC(0x1ef6) CASEMBC(0x1ef8)
- regmbc('Y'); regmbc(0xdd);
- REGMBC(0x176) REGMBC(0x178) REGMBC(0x1e8e)
- REGMBC(0x1ef2) REGMBC(0x1ef6) REGMBC(0x1ef8)
- return;
- case 'Z': CASEMBC(0x179) CASEMBC(0x17b) CASEMBC(0x17d)
- CASEMBC(0x1b5) CASEMBC(0x1e90) CASEMBC(0x1e94)
- regmbc('Z'); REGMBC(0x179) REGMBC(0x17b)
- REGMBC(0x17d) REGMBC(0x1b5) REGMBC(0x1e90)
- REGMBC(0x1e94)
- return;
- case 'a': case 0xe0: case 0xe1: case 0xe2:
- case 0xe3: case 0xe4: case 0xe5:
- CASEMBC(0x101) CASEMBC(0x103) CASEMBC(0x105) CASEMBC(0x1ce)
- CASEMBC(0x1df) CASEMBC(0x1e1) CASEMBC(0x1ea3)
- regmbc('a'); regmbc(0xe0); regmbc(0xe1);
- regmbc(0xe2); regmbc(0xe3); regmbc(0xe4);
- regmbc(0xe5);
- REGMBC(0x101) REGMBC(0x103) REGMBC(0x105)
- REGMBC(0x1ce) REGMBC(0x1df) REGMBC(0x1e1)
- REGMBC(0x1ea3)
- return;
- case 'b': CASEMBC(0x1e03) CASEMBC(0x1e07)
- regmbc('b'); REGMBC(0x1e03) REGMBC(0x1e07)
- return;
- case 'c': case 0xe7:
- CASEMBC(0x107) CASEMBC(0x109) CASEMBC(0x10b) CASEMBC(0x10d)
- regmbc('c'); regmbc(0xe7);
- REGMBC(0x107) REGMBC(0x109) REGMBC(0x10b)
- REGMBC(0x10d)
- return;
- case 'd': CASEMBC(0x10f) CASEMBC(0x111) CASEMBC(0x1e0b)
- CASEMBC(0x1e0f) CASEMBC(0x1e11)
- regmbc('d'); REGMBC(0x10f) REGMBC(0x111)
- REGMBC(0x1e0b) REGMBC(0x1e0f) REGMBC(0x1e11)
- return;
- case 'e': case 0xe8: case 0xe9: case 0xea: case 0xeb:
- CASEMBC(0x113) CASEMBC(0x115) CASEMBC(0x117) CASEMBC(0x119)
- CASEMBC(0x11b) CASEMBC(0x1ebb) CASEMBC(0x1ebd)
- regmbc('e'); regmbc(0xe8); regmbc(0xe9);
- regmbc(0xea); regmbc(0xeb);
- REGMBC(0x113) REGMBC(0x115) REGMBC(0x117)
- REGMBC(0x119) REGMBC(0x11b) REGMBC(0x1ebb)
- REGMBC(0x1ebd)
- return;
- case 'f': CASEMBC(0x1e1f)
- regmbc('f'); REGMBC(0x1e1f)
- return;
- case 'g': CASEMBC(0x11d) CASEMBC(0x11f) CASEMBC(0x121)
- CASEMBC(0x123) CASEMBC(0x1e5) CASEMBC(0x1e7) CASEMBC(0x1f5)
- CASEMBC(0x1e21)
- regmbc('g'); REGMBC(0x11d) REGMBC(0x11f)
- REGMBC(0x121) REGMBC(0x123) REGMBC(0x1e5)
- REGMBC(0x1e7) REGMBC(0x1f5) REGMBC(0x1e21)
- return;
- case 'h': CASEMBC(0x125) CASEMBC(0x127) CASEMBC(0x1e23)
- CASEMBC(0x1e27) CASEMBC(0x1e29) CASEMBC(0x1e96)
- regmbc('h'); REGMBC(0x125) REGMBC(0x127)
- REGMBC(0x1e23) REGMBC(0x1e27) REGMBC(0x1e29)
- REGMBC(0x1e96)
- return;
- case 'i': case 0xec: case 0xed: case 0xee: case 0xef:
- CASEMBC(0x129) CASEMBC(0x12b) CASEMBC(0x12d) CASEMBC(0x12f)
- CASEMBC(0x1d0) CASEMBC(0x1ec9)
- regmbc('i'); regmbc(0xec); regmbc(0xed);
- regmbc(0xee); regmbc(0xef);
- REGMBC(0x129) REGMBC(0x12b) REGMBC(0x12d)
- REGMBC(0x12f) REGMBC(0x1d0) REGMBC(0x1ec9)
- return;
- case 'j': CASEMBC(0x135) CASEMBC(0x1f0)
- regmbc('j'); REGMBC(0x135) REGMBC(0x1f0)
- return;
- case 'k': CASEMBC(0x137) CASEMBC(0x1e9) CASEMBC(0x1e31)
- CASEMBC(0x1e35)
- regmbc('k'); REGMBC(0x137) REGMBC(0x1e9)
- REGMBC(0x1e31) REGMBC(0x1e35)
- return;
- case 'l': CASEMBC(0x13a) CASEMBC(0x13c) CASEMBC(0x13e)
- CASEMBC(0x140) CASEMBC(0x142) CASEMBC(0x1e3b)
- regmbc('l'); REGMBC(0x13a) REGMBC(0x13c)
- REGMBC(0x13e) REGMBC(0x140) REGMBC(0x142)
- REGMBC(0x1e3b)
- return;
- case 'm': CASEMBC(0x1e3f) CASEMBC(0x1e41)
- regmbc('m'); REGMBC(0x1e3f) REGMBC(0x1e41)
- return;
- case 'n': case 0xf1:
- CASEMBC(0x144) CASEMBC(0x146) CASEMBC(0x148) CASEMBC(0x149)
- CASEMBC(0x1e45) CASEMBC(0x1e49)
- regmbc('n'); regmbc(0xf1);
- REGMBC(0x144) REGMBC(0x146) REGMBC(0x148)
- REGMBC(0x149) REGMBC(0x1e45) REGMBC(0x1e49)
- return;
- case 'o': case 0xf2: case 0xf3: case 0xf4: case 0xf5:
- case 0xf6: case 0xf8:
- CASEMBC(0x14d) CASEMBC(0x14f) CASEMBC(0x151) CASEMBC(0x1a1)
- CASEMBC(0x1d2) CASEMBC(0x1eb) CASEMBC(0x1ed) CASEMBC(0x1ecf)
- regmbc('o'); regmbc(0xf2); regmbc(0xf3);
- regmbc(0xf4); regmbc(0xf5); regmbc(0xf6);
- regmbc(0xf8);
- REGMBC(0x14d) REGMBC(0x14f) REGMBC(0x151)
- REGMBC(0x1a1) REGMBC(0x1d2) REGMBC(0x1eb)
- REGMBC(0x1ed) REGMBC(0x1ecf)
- return;
- case 'p': CASEMBC(0x1e55) CASEMBC(0x1e57)
- regmbc('p'); REGMBC(0x1e55) REGMBC(0x1e57)
- return;
- case 'r': CASEMBC(0x155) CASEMBC(0x157) CASEMBC(0x159)
- CASEMBC(0x1e59) CASEMBC(0x1e5f)
- regmbc('r'); REGMBC(0x155) REGMBC(0x157) REGMBC(0x159)
- REGMBC(0x1e59) REGMBC(0x1e5f)
- return;
- case 's': CASEMBC(0x15b) CASEMBC(0x15d) CASEMBC(0x15f)
- CASEMBC(0x161) CASEMBC(0x1e61)
- regmbc('s'); REGMBC(0x15b) REGMBC(0x15d)
- REGMBC(0x15f) REGMBC(0x161) REGMBC(0x1e61)
- return;
- case 't': CASEMBC(0x163) CASEMBC(0x165) CASEMBC(0x167)
- CASEMBC(0x1e6b) CASEMBC(0x1e6f) CASEMBC(0x1e97)
- regmbc('t'); REGMBC(0x163) REGMBC(0x165) REGMBC(0x167)
- REGMBC(0x1e6b) REGMBC(0x1e6f) REGMBC(0x1e97)
- return;
- case 'u': case 0xf9: case 0xfa: case 0xfb: case 0xfc:
- CASEMBC(0x169) CASEMBC(0x16b) CASEMBC(0x16d) CASEMBC(0x16f)
- CASEMBC(0x171) CASEMBC(0x173) CASEMBC(0x1b0) CASEMBC(0x1d4)
- CASEMBC(0x1ee7)
- regmbc('u'); regmbc(0xf9); regmbc(0xfa);
- regmbc(0xfb); regmbc(0xfc);
- REGMBC(0x169) REGMBC(0x16b) REGMBC(0x16d)
- REGMBC(0x16f) REGMBC(0x171) REGMBC(0x173)
- REGMBC(0x1b0) REGMBC(0x1d4) REGMBC(0x1ee7)
- return;
- case 'v': CASEMBC(0x1e7d)
- regmbc('v'); REGMBC(0x1e7d)
- return;
- case 'w': CASEMBC(0x175) CASEMBC(0x1e81) CASEMBC(0x1e83)
- CASEMBC(0x1e85) CASEMBC(0x1e87) CASEMBC(0x1e98)
- regmbc('w'); REGMBC(0x175) REGMBC(0x1e81)
- REGMBC(0x1e83) REGMBC(0x1e85) REGMBC(0x1e87)
- REGMBC(0x1e98)
- return;
- case 'x': CASEMBC(0x1e8b) CASEMBC(0x1e8d)
- regmbc('x'); REGMBC(0x1e8b) REGMBC(0x1e8d)
- return;
- case 'y': case 0xfd: case 0xff:
- CASEMBC(0x177) CASEMBC(0x1e8f) CASEMBC(0x1e99)
- CASEMBC(0x1ef3) CASEMBC(0x1ef7) CASEMBC(0x1ef9)
- regmbc('y'); regmbc(0xfd); regmbc(0xff);
- REGMBC(0x177) REGMBC(0x1e8f) REGMBC(0x1e99)
- REGMBC(0x1ef3) REGMBC(0x1ef7) REGMBC(0x1ef9)
- return;
- case 'z': CASEMBC(0x17a) CASEMBC(0x17c) CASEMBC(0x17e)
- CASEMBC(0x1b6) CASEMBC(0x1e91) CASEMBC(0x1e95)
- regmbc('z'); REGMBC(0x17a) REGMBC(0x17c)
- REGMBC(0x17e) REGMBC(0x1b6) REGMBC(0x1e91)
- REGMBC(0x1e95)
- return;
- }
- }
- regmbc(c);
-}
-
-/*
* Check for a collating element "[.a.]". "pp" points to the '['.
* Returns a character. Zero means that no item was recognized. Otherwise
* "pp" is advanced to after the item.
@@ -1123,7 +424,7 @@ static int get_coll_element(char_u **pp)
return 0;
}
-static int reg_cpo_lit; /* 'cpoptions' contains 'l' flag */
+static int reg_cpo_lit; // 'cpoptions' contains 'l' flag
static void get_cpo_flags(void)
{
@@ -1139,10 +440,12 @@ static char_u *skip_anyof(char_u *p)
{
int l;
- if (*p == '^') /* Complement of range. */
- ++p;
- if (*p == ']' || *p == '-')
- ++p;
+ if (*p == '^') { // Complement of range.
+ p++;
+ }
+ if (*p == ']' || *p == '-') {
+ p++;
+ }
while (*p != NUL && *p != ']') {
if ((l = utfc_ptr2len(p)) > 1) {
p += l;
@@ -1202,1550 +505,32 @@ char_u *skip_regexp(char_u *startp, int dirc, int magic, char_u **newp)
break;
} else if (p[0] == '\\' && p[1] != NUL) {
if (dirc == '?' && newp != NULL && p[1] == '?') {
- /* change "\?" to "?", make a copy first. */
+ // change "\?" to "?", make a copy first.
if (*newp == NULL) {
*newp = vim_strsave(startp);
p = *newp + (p - startp);
}
STRMOVE(p, p + 1);
- } else
- ++p; /* skip next character */
- if (*p == 'v')
+ } else {
+ p++; // skip next character
+ }
+ if (*p == 'v') {
mymagic = MAGIC_ALL;
- else if (*p == 'V')
+ } else if (*p == 'V') {
mymagic = MAGIC_NONE;
- }
- }
- return p;
-}
-
-/// Return true if the back reference is legal. We must have seen the close
-/// brace.
-/// TODO(vim): Should also check that we don't refer to something repeated
-/// (+*=): what instance of the repetition should we match?
-static int seen_endbrace(int refnum)
-{
- if (!had_endbrace[refnum]) {
- char_u *p;
-
- // Trick: check if "@<=" or "@<!" follows, in which case
- // the \1 can appear before the referenced match.
- for (p = regparse; *p != NUL; p++) {
- if (p[0] == '@' && p[1] == '<' && (p[2] == '!' || p[2] == '=')) {
- break;
- }
}
-
- if (*p == NUL) {
- emsg(_("E65: Illegal back reference"));
- rc_did_emsg = true;
- return false;
}
}
- return true;
-}
-
-/*
- * bt_regcomp() - compile a regular expression into internal code for the
- * traditional back track matcher.
- * Returns the program in allocated space. Returns NULL for an error.
- *
- * We can't allocate space until we know how big the compiled form will be,
- * but we can't compile it (and thus know how big it is) until we've got a
- * place to put the code. So we cheat: we compile it twice, once with code
- * generation turned off and size counting turned on, and once "for real".
- * This also means that we don't allocate space until we are sure that the
- * thing really will compile successfully, and we never have to move the
- * code and thus invalidate pointers into it. (Note that it has to be in
- * one piece because free() must be able to free it all.)
- *
- * Whether upper/lower case is to be ignored is decided when executing the
- * program, it does not matter here.
- *
- * Beware that the optimization-preparation code in here knows about some
- * of the structure of the compiled regexp.
- * "re_flags": RE_MAGIC and/or RE_STRING.
- */
-static regprog_T *bt_regcomp(char_u *expr, int re_flags)
-{
- char_u *scan;
- char_u *longest;
- int len;
- int flags;
-
- if (expr == NULL) {
- IEMSG_RET_NULL(_(e_null));
- }
-
- init_class_tab();
-
- /*
- * First pass: determine size, legality.
- */
- regcomp_start(expr, re_flags);
- regcode = JUST_CALC_SIZE;
- regc(REGMAGIC);
- if (reg(REG_NOPAREN, &flags) == NULL)
- return NULL;
-
- /* Allocate space. */
- bt_regprog_T *r = xmalloc(sizeof(bt_regprog_T) + regsize);
- r->re_in_use = false;
-
- /*
- * Second pass: emit code.
- */
- regcomp_start(expr, re_flags);
- regcode = r->program;
- regc(REGMAGIC);
- if (reg(REG_NOPAREN, &flags) == NULL || reg_toolong) {
- xfree(r);
- if (reg_toolong)
- EMSG_RET_NULL(_("E339: Pattern too long"));
- return NULL;
- }
-
- /* Dig out information for optimizations. */
- r->regstart = NUL; /* Worst-case defaults. */
- r->reganch = 0;
- r->regmust = NULL;
- r->regmlen = 0;
- r->regflags = regflags;
- if (flags & HASNL)
- r->regflags |= RF_HASNL;
- if (flags & HASLOOKBH)
- r->regflags |= RF_LOOKBH;
- /* Remember whether this pattern has any \z specials in it. */
- r->reghasz = re_has_z;
- scan = r->program + 1; /* First BRANCH. */
- if (OP(regnext(scan)) == END) { /* Only one top-level choice. */
- scan = OPERAND(scan);
-
- /* Starting-point info. */
- if (OP(scan) == BOL || OP(scan) == RE_BOF) {
- r->reganch++;
- scan = regnext(scan);
- }
-
- if (OP(scan) == EXACTLY) {
- r->regstart = utf_ptr2char(OPERAND(scan));
- } else if (OP(scan) == BOW
- || OP(scan) == EOW
- || OP(scan) == NOTHING
- || OP(scan) == MOPEN + 0 || OP(scan) == NOPEN
- || OP(scan) == MCLOSE + 0 || OP(scan) == NCLOSE) {
- char_u *regnext_scan = regnext(scan);
- if (OP(regnext_scan) == EXACTLY) {
- r->regstart = utf_ptr2char(OPERAND(regnext_scan));
- }
- }
-
- /*
- * If there's something expensive in the r.e., find the longest
- * literal string that must appear and make it the regmust. Resolve
- * ties in favor of later strings, since the regstart check works
- * with the beginning of the r.e. and avoiding duplication
- * strengthens checking. Not a strong reason, but sufficient in the
- * absence of others.
- */
- /*
- * When the r.e. starts with BOW, it is faster to look for a regmust
- * first. Used a lot for "#" and "*" commands. (Added by mool).
- */
- if ((flags & SPSTART || OP(scan) == BOW || OP(scan) == EOW)
- && !(flags & HASNL)) {
- longest = NULL;
- len = 0;
- for (; scan != NULL; scan = regnext(scan))
- if (OP(scan) == EXACTLY && STRLEN(OPERAND(scan)) >= (size_t)len) {
- longest = OPERAND(scan);
- len = (int)STRLEN(OPERAND(scan));
- }
- r->regmust = longest;
- r->regmlen = len;
- }
- }
-#ifdef BT_REGEXP_DUMP
- regdump(expr, r);
-#endif
- r->engine = &bt_regengine;
- return (regprog_T *)r;
-}
-
-/*
- * Free a compiled regexp program, returned by bt_regcomp().
- */
-static void bt_regfree(regprog_T *prog)
-{
- xfree(prog);
+ return p;
}
-/*
- * Setup to parse the regexp. Used once to get the length and once to do it.
- */
-static void
-regcomp_start (
- char_u *expr,
- int re_flags /* see vim_regcomp() */
-)
-{
- initchr(expr);
- if (re_flags & RE_MAGIC)
- reg_magic = MAGIC_ON;
- else
- reg_magic = MAGIC_OFF;
- reg_string = (re_flags & RE_STRING);
- reg_strict = (re_flags & RE_STRICT);
- get_cpo_flags();
-
- num_complex_braces = 0;
- regnpar = 1;
- memset(had_endbrace, 0, sizeof(had_endbrace));
- regnzpar = 1;
- re_has_z = 0;
- regsize = 0L;
- reg_toolong = false;
- regflags = 0;
- had_eol = false;
-}
-
-/*
- * Check if during the previous call to vim_regcomp the EOL item "$" has been
- * found. This is messy, but it works fine.
- */
-int vim_regcomp_had_eol(void)
-{
- return had_eol;
-}
// variables used for parsing
+static int prevchr_len; // byte length of previous char
static int at_start; // True when on the first character
static int prev_at_start; // True when on the second character
/*
- * Parse regular expression, i.e. main body or parenthesized thing.
- *
- * Caller must absorb opening parenthesis.
- *
- * Combining parenthesis handling with the base level of regular expression
- * is a trifle forced, but the need to tie the tails of the branches to what
- * follows makes it hard to avoid.
- */
-static char_u *
-reg (
- int paren, /* REG_NOPAREN, REG_PAREN, REG_NPAREN or REG_ZPAREN */
- int *flagp
-)
-{
- char_u *ret;
- char_u *br;
- char_u *ender;
- int parno = 0;
- int flags;
-
- *flagp = HASWIDTH; /* Tentatively. */
-
- if (paren == REG_ZPAREN) {
- /* Make a ZOPEN node. */
- if (regnzpar >= NSUBEXP)
- EMSG_RET_NULL(_("E50: Too many \\z("));
- parno = regnzpar;
- regnzpar++;
- ret = regnode(ZOPEN + parno);
- } else if (paren == REG_PAREN) {
- /* Make a MOPEN node. */
- if (regnpar >= NSUBEXP)
- EMSG2_RET_NULL(_("E51: Too many %s("), reg_magic == MAGIC_ALL);
- parno = regnpar;
- ++regnpar;
- ret = regnode(MOPEN + parno);
- } else if (paren == REG_NPAREN) {
- /* Make a NOPEN node. */
- ret = regnode(NOPEN);
- } else
- ret = NULL;
-
- /* Pick up the branches, linking them together. */
- br = regbranch(&flags);
- if (br == NULL)
- return NULL;
- if (ret != NULL)
- regtail(ret, br); /* [MZ]OPEN -> first. */
- else
- ret = br;
- /* If one of the branches can be zero-width, the whole thing can.
- * If one of the branches has * at start or matches a line-break, the
- * whole thing can. */
- if (!(flags & HASWIDTH))
- *flagp &= ~HASWIDTH;
- *flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
- while (peekchr() == Magic('|')) {
- skipchr();
- br = regbranch(&flags);
- if (br == NULL || reg_toolong)
- return NULL;
- regtail(ret, br); /* BRANCH -> BRANCH. */
- if (!(flags & HASWIDTH))
- *flagp &= ~HASWIDTH;
- *flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
- }
-
- /* Make a closing node, and hook it on the end. */
- ender = regnode(
- paren == REG_ZPAREN ? ZCLOSE + parno :
- paren == REG_PAREN ? MCLOSE + parno :
- paren == REG_NPAREN ? NCLOSE : END);
- regtail(ret, ender);
-
- /* Hook the tails of the branches to the closing node. */
- for (br = ret; br != NULL; br = regnext(br))
- regoptail(br, ender);
-
- /* Check for proper termination. */
- if (paren != REG_NOPAREN && getchr() != Magic(')')) {
- if (paren == REG_ZPAREN)
- EMSG_RET_NULL(_("E52: Unmatched \\z("));
- else if (paren == REG_NPAREN)
- EMSG2_RET_NULL(_(e_unmatchedpp), reg_magic == MAGIC_ALL);
- else
- EMSG2_RET_NULL(_(e_unmatchedp), reg_magic == MAGIC_ALL);
- } else if (paren == REG_NOPAREN && peekchr() != NUL) {
- if (curchr == Magic(')'))
- EMSG2_RET_NULL(_(e_unmatchedpar), reg_magic == MAGIC_ALL);
- else
- EMSG_RET_NULL(_(e_trailing)); /* "Can't happen". */
- /* NOTREACHED */
- }
- // Here we set the flag allowing back references to this set of
- // parentheses.
- if (paren == REG_PAREN) {
- had_endbrace[parno] = true; // have seen the close paren
- }
- return ret;
-}
-
-/*
- * Parse one alternative of an | operator.
- * Implements the & operator.
- */
-static char_u *regbranch(int *flagp)
-{
- char_u *ret;
- char_u *chain = NULL;
- char_u *latest;
- int flags;
-
- *flagp = WORST | HASNL; /* Tentatively. */
-
- ret = regnode(BRANCH);
- for (;; ) {
- latest = regconcat(&flags);
- if (latest == NULL)
- return NULL;
- /* If one of the branches has width, the whole thing has. If one of
- * the branches anchors at start-of-line, the whole thing does.
- * If one of the branches uses look-behind, the whole thing does. */
- *flagp |= flags & (HASWIDTH | SPSTART | HASLOOKBH);
- /* If one of the branches doesn't match a line-break, the whole thing
- * doesn't. */
- *flagp &= ~HASNL | (flags & HASNL);
- if (chain != NULL)
- regtail(chain, latest);
- if (peekchr() != Magic('&'))
- break;
- skipchr();
- regtail(latest, regnode(END)); /* operand ends */
- if (reg_toolong)
- break;
- reginsert(MATCH, latest);
- chain = latest;
- }
-
- return ret;
-}
-
-/*
- * Parse one alternative of an | or & operator.
- * Implements the concatenation operator.
- */
-static char_u *regconcat(int *flagp)
-{
- char_u *first = NULL;
- char_u *chain = NULL;
- char_u *latest;
- int flags;
- int cont = true;
-
- *flagp = WORST; /* Tentatively. */
-
- while (cont) {
- switch (peekchr()) {
- case NUL:
- case Magic('|'):
- case Magic('&'):
- case Magic(')'):
- cont = false;
- break;
- case Magic('Z'):
- regflags |= RF_ICOMBINE;
- skipchr_keepstart();
- break;
- case Magic('c'):
- regflags |= RF_ICASE;
- skipchr_keepstart();
- break;
- case Magic('C'):
- regflags |= RF_NOICASE;
- skipchr_keepstart();
- break;
- case Magic('v'):
- reg_magic = MAGIC_ALL;
- skipchr_keepstart();
- curchr = -1;
- break;
- case Magic('m'):
- reg_magic = MAGIC_ON;
- skipchr_keepstart();
- curchr = -1;
- break;
- case Magic('M'):
- reg_magic = MAGIC_OFF;
- skipchr_keepstart();
- curchr = -1;
- break;
- case Magic('V'):
- reg_magic = MAGIC_NONE;
- skipchr_keepstart();
- curchr = -1;
- break;
- default:
- latest = regpiece(&flags);
- if (latest == NULL || reg_toolong)
- return NULL;
- *flagp |= flags & (HASWIDTH | HASNL | HASLOOKBH);
- if (chain == NULL) /* First piece. */
- *flagp |= flags & SPSTART;
- else
- regtail(chain, latest);
- chain = latest;
- if (first == NULL)
- first = latest;
- break;
- }
- }
- if (first == NULL) /* Loop ran zero times. */
- first = regnode(NOTHING);
- return first;
-}
-
-/*
- * Parse something followed by possible [*+=].
- *
- * Note that the branching code sequences used for = and the general cases
- * of * and + are somewhat optimized: they use the same NOTHING node as
- * both the endmarker for their branch list and the body of the last branch.
- * It might seem that this node could be dispensed with entirely, but the
- * endmarker role is not redundant.
- */
-static char_u *regpiece(int *flagp)
-{
- char_u *ret;
- int op;
- char_u *next;
- int flags;
- long minval;
- long maxval;
-
- ret = regatom(&flags);
- if (ret == NULL)
- return NULL;
-
- op = peekchr();
- if (re_multi_type(op) == NOT_MULTI) {
- *flagp = flags;
- return ret;
- }
- /* default flags */
- *flagp = (WORST | SPSTART | (flags & (HASNL | HASLOOKBH)));
-
- skipchr();
- switch (op) {
- case Magic('*'):
- if (flags & SIMPLE)
- reginsert(STAR, ret);
- else {
- /* Emit x* as (x&|), where & means "self". */
- reginsert(BRANCH, ret); /* Either x */
- regoptail(ret, regnode(BACK)); /* and loop */
- regoptail(ret, ret); /* back */
- regtail(ret, regnode(BRANCH)); /* or */
- regtail(ret, regnode(NOTHING)); /* null. */
- }
- break;
-
- case Magic('+'):
- if (flags & SIMPLE)
- reginsert(PLUS, ret);
- else {
- /* Emit x+ as x(&|), where & means "self". */
- next = regnode(BRANCH); /* Either */
- regtail(ret, next);
- regtail(regnode(BACK), ret); /* loop back */
- regtail(next, regnode(BRANCH)); /* or */
- regtail(ret, regnode(NOTHING)); /* null. */
- }
- *flagp = (WORST | HASWIDTH | (flags & (HASNL | HASLOOKBH)));
- break;
-
- case Magic('@'):
- {
- int lop = END;
- int64_t nr = getdecchrs();
-
- switch (no_Magic(getchr())) {
- case '=': lop = MATCH; break; /* \@= */
- case '!': lop = NOMATCH; break; /* \@! */
- case '>': lop = SUBPAT; break; /* \@> */
- case '<': switch (no_Magic(getchr())) {
- case '=': lop = BEHIND; break; /* \@<= */
- case '!': lop = NOBEHIND; break; /* \@<! */
- }
- }
- if (lop == END)
- EMSG2_RET_NULL(_("E59: invalid character after %s@"),
- reg_magic == MAGIC_ALL);
- /* Look behind must match with behind_pos. */
- if (lop == BEHIND || lop == NOBEHIND) {
- regtail(ret, regnode(BHPOS));
- *flagp |= HASLOOKBH;
- }
- regtail(ret, regnode(END)); /* operand ends */
- if (lop == BEHIND || lop == NOBEHIND) {
- if (nr < 0)
- nr = 0; /* no limit is same as zero limit */
- reginsert_nr(lop, (uint32_t)nr, ret);
- } else
- reginsert(lop, ret);
- break;
- }
-
- case Magic('?'):
- case Magic('='):
- /* Emit x= as (x|) */
- reginsert(BRANCH, ret); /* Either x */
- regtail(ret, regnode(BRANCH)); /* or */
- next = regnode(NOTHING); /* null. */
- regtail(ret, next);
- regoptail(ret, next);
- break;
-
- case Magic('{'):
- if (!read_limits(&minval, &maxval))
- return NULL;
- if (flags & SIMPLE) {
- reginsert(BRACE_SIMPLE, ret);
- reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
- } else {
- if (num_complex_braces >= 10)
- EMSG2_RET_NULL(_("E60: Too many complex %s{...}s"),
- reg_magic == MAGIC_ALL);
- reginsert(BRACE_COMPLEX + num_complex_braces, ret);
- regoptail(ret, regnode(BACK));
- regoptail(ret, ret);
- reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
- ++num_complex_braces;
- }
- if (minval > 0 && maxval > 0)
- *flagp = (HASWIDTH | (flags & (HASNL | HASLOOKBH)));
- break;
- }
- if (re_multi_type(peekchr()) != NOT_MULTI) {
- // Can't have a multi follow a multi.
- if (peekchr() == Magic('*')) {
- snprintf((char *)IObuff, IOSIZE, _("E61: Nested %s*"),
- reg_magic >= MAGIC_ON ? "" : "\\");
- } else {
- snprintf((char *)IObuff, IOSIZE, _("E62: Nested %s%c"),
- reg_magic == MAGIC_ALL ? "" : "\\", no_Magic(peekchr()));
- }
- EMSG_RET_NULL((char *)IObuff);
- }
-
- return ret;
-}
-
-/* When making changes to classchars also change nfa_classcodes. */
-static char_u *classchars = (char_u *)".iIkKfFpPsSdDxXoOwWhHaAlLuU";
-static int classcodes[] = {
- ANY, IDENT, SIDENT, KWORD, SKWORD,
- FNAME, SFNAME, PRINT, SPRINT,
- WHITE, NWHITE, DIGIT, NDIGIT,
- HEX, NHEX, OCTAL, NOCTAL,
- WORD, NWORD, HEAD, NHEAD,
- ALPHA, NALPHA, LOWER, NLOWER,
- UPPER, NUPPER
-};
-
-/*
- * Parse the lowest level.
- *
- * Optimization: gobbles an entire sequence of ordinary characters so that
- * it can turn them into a single node, which is smaller to store and
- * faster to run. Don't do this when one_exactly is set.
- */
-static char_u *regatom(int *flagp)
-{
- char_u *ret;
- int flags;
- int c;
- char_u *p;
- int extra = 0;
- int save_prev_at_start = prev_at_start;
-
- *flagp = WORST; /* Tentatively. */
-
- c = getchr();
- switch (c) {
- case Magic('^'):
- ret = regnode(BOL);
- break;
-
- case Magic('$'):
- ret = regnode(EOL);
- had_eol = true;
- break;
-
- case Magic('<'):
- ret = regnode(BOW);
- break;
-
- case Magic('>'):
- ret = regnode(EOW);
- break;
-
- case Magic('_'):
- c = no_Magic(getchr());
- if (c == '^') { /* "\_^" is start-of-line */
- ret = regnode(BOL);
- break;
- }
- if (c == '$') { /* "\_$" is end-of-line */
- ret = regnode(EOL);
- had_eol = true;
- break;
- }
-
- extra = ADD_NL;
- *flagp |= HASNL;
-
- /* "\_[" is character range plus newline */
- if (c == '[')
- goto collection;
-
- // "\_x" is character class plus newline
- FALLTHROUGH;
-
- /*
- * Character classes.
- */
- case Magic('.'):
- case Magic('i'):
- case Magic('I'):
- case Magic('k'):
- case Magic('K'):
- case Magic('f'):
- case Magic('F'):
- case Magic('p'):
- case Magic('P'):
- case Magic('s'):
- case Magic('S'):
- case Magic('d'):
- case Magic('D'):
- case Magic('x'):
- case Magic('X'):
- case Magic('o'):
- case Magic('O'):
- case Magic('w'):
- case Magic('W'):
- case Magic('h'):
- case Magic('H'):
- case Magic('a'):
- case Magic('A'):
- case Magic('l'):
- case Magic('L'):
- case Magic('u'):
- case Magic('U'):
- p = vim_strchr(classchars, no_Magic(c));
- if (p == NULL)
- EMSG_RET_NULL(_("E63: invalid use of \\_"));
- /* When '.' is followed by a composing char ignore the dot, so that
- * the composing char is matched here. */
- if (c == Magic('.') && utf_iscomposing(peekchr())) {
- c = getchr();
- goto do_multibyte;
- }
- ret = regnode(classcodes[p - classchars] + extra);
- *flagp |= HASWIDTH | SIMPLE;
- break;
-
- case Magic('n'):
- if (reg_string) {
- /* In a string "\n" matches a newline character. */
- ret = regnode(EXACTLY);
- regc(NL);
- regc(NUL);
- *flagp |= HASWIDTH | SIMPLE;
- } else {
- /* In buffer text "\n" matches the end of a line. */
- ret = regnode(NEWL);
- *flagp |= HASWIDTH | HASNL;
- }
- break;
-
- case Magic('('):
- if (one_exactly)
- EMSG_ONE_RET_NULL;
- ret = reg(REG_PAREN, &flags);
- if (ret == NULL)
- return NULL;
- *flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
- break;
-
- case NUL:
- case Magic('|'):
- case Magic('&'):
- case Magic(')'):
- if (one_exactly)
- EMSG_ONE_RET_NULL;
- IEMSG_RET_NULL(_(e_internal)); // Supposed to be caught earlier.
- // NOTREACHED
-
- case Magic('='):
- case Magic('?'):
- case Magic('+'):
- case Magic('@'):
- case Magic('{'):
- case Magic('*'):
- c = no_Magic(c);
- snprintf((char *)IObuff, IOSIZE, _("E64: %s%c follows nothing"),
- (c == '*' ? reg_magic >= MAGIC_ON : reg_magic == MAGIC_ALL)
- ? "" : "\\", c);
- EMSG_RET_NULL((char *)IObuff);
- // NOTREACHED
-
- case Magic('~'): /* previous substitute pattern */
- if (reg_prev_sub != NULL) {
- char_u *lp;
-
- ret = regnode(EXACTLY);
- lp = reg_prev_sub;
- while (*lp != NUL)
- regc(*lp++);
- regc(NUL);
- if (*reg_prev_sub != NUL) {
- *flagp |= HASWIDTH;
- if ((lp - reg_prev_sub) == 1)
- *flagp |= SIMPLE;
- }
- } else
- EMSG_RET_NULL(_(e_nopresub));
- break;
-
- case Magic('1'):
- case Magic('2'):
- case Magic('3'):
- case Magic('4'):
- case Magic('5'):
- case Magic('6'):
- case Magic('7'):
- case Magic('8'):
- case Magic('9'):
- {
- int refnum;
-
- refnum = c - Magic('0');
- if (!seen_endbrace(refnum)) {
- return NULL;
- }
- ret = regnode(BACKREF + refnum);
- }
- break;
-
- case Magic('z'):
- {
- c = no_Magic(getchr());
- switch (c) {
- case '(': if ((reg_do_extmatch & REX_SET) == 0)
- EMSG_RET_NULL(_(e_z_not_allowed));
- if (one_exactly)
- EMSG_ONE_RET_NULL;
- ret = reg(REG_ZPAREN, &flags);
- if (ret == NULL)
- return NULL;
- *flagp |= flags & (HASWIDTH|SPSTART|HASNL|HASLOOKBH);
- re_has_z = REX_SET;
- break;
-
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9': if ((reg_do_extmatch & REX_USE) == 0)
- EMSG_RET_NULL(_(e_z1_not_allowed));
- ret = regnode(ZREF + c - '0');
- re_has_z = REX_USE;
- break;
-
- case 's': ret = regnode(MOPEN + 0);
- if (!re_mult_next("\\zs")) {
- return NULL;
- }
- break;
-
- case 'e': ret = regnode(MCLOSE + 0);
- if (!re_mult_next("\\ze")) {
- return NULL;
- }
- break;
-
- default: EMSG_RET_NULL(_("E68: Invalid character after \\z"));
- }
- }
- break;
-
- case Magic('%'):
- {
- c = no_Magic(getchr());
- switch (c) {
- /* () without a back reference */
- case '(':
- if (one_exactly)
- EMSG_ONE_RET_NULL;
- ret = reg(REG_NPAREN, &flags);
- if (ret == NULL)
- return NULL;
- *flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
- break;
-
- /* Catch \%^ and \%$ regardless of where they appear in the
- * pattern -- regardless of whether or not it makes sense. */
- case '^':
- ret = regnode(RE_BOF);
- break;
-
- case '$':
- ret = regnode(RE_EOF);
- break;
-
- case '#':
- ret = regnode(CURSOR);
- break;
-
- case 'V':
- ret = regnode(RE_VISUAL);
- break;
-
- case 'C':
- ret = regnode(RE_COMPOSING);
- break;
-
- /* \%[abc]: Emit as a list of branches, all ending at the last
- * branch which matches nothing. */
- case '[':
- if (one_exactly) /* doesn't nest */
- EMSG_ONE_RET_NULL;
- {
- char_u *lastbranch;
- char_u *lastnode = NULL;
- char_u *br;
-
- ret = NULL;
- while ((c = getchr()) != ']') {
- if (c == NUL)
- EMSG2_RET_NULL(_(e_missing_sb),
- reg_magic == MAGIC_ALL);
- br = regnode(BRANCH);
- if (ret == NULL) {
- ret = br;
- } else {
- regtail(lastnode, br);
- if (reg_toolong) {
- return NULL;
- }
- }
-
- ungetchr();
- one_exactly = true;
- lastnode = regatom(flagp);
- one_exactly = false;
- if (lastnode == NULL) {
- return NULL;
- }
- }
- if (ret == NULL)
- EMSG2_RET_NULL(_(e_empty_sb),
- reg_magic == MAGIC_ALL);
- lastbranch = regnode(BRANCH);
- br = regnode(NOTHING);
- if (ret != JUST_CALC_SIZE) {
- regtail(lastnode, br);
- regtail(lastbranch, br);
- /* connect all branches to the NOTHING
- * branch at the end */
- for (br = ret; br != lastnode; ) {
- if (OP(br) == BRANCH) {
- regtail(br, lastbranch);
- if (reg_toolong) {
- return NULL;
- }
- br = OPERAND(br);
- } else
- br = regnext(br);
- }
- }
- *flagp &= ~(HASWIDTH | SIMPLE);
- break;
- }
-
- case 'd': /* %d123 decimal */
- case 'o': /* %o123 octal */
- case 'x': /* %xab hex 2 */
- case 'u': /* %uabcd hex 4 */
- case 'U': /* %U1234abcd hex 8 */
- {
- int64_t i;
-
- switch (c) {
- case 'd': i = getdecchrs(); break;
- case 'o': i = getoctchrs(); break;
- case 'x': i = gethexchrs(2); break;
- case 'u': i = gethexchrs(4); break;
- case 'U': i = gethexchrs(8); break;
- default: i = -1; break;
- }
-
- if (i < 0 || i > INT_MAX) {
- EMSG2_RET_NULL(_("E678: Invalid character after %s%%[dxouU]"),
- reg_magic == MAGIC_ALL);
- }
- if (use_multibytecode(i)) {
- ret = regnode(MULTIBYTECODE);
- } else {
- ret = regnode(EXACTLY);
- }
- if (i == 0) {
- regc(0x0a);
- } else {
- regmbc(i);
- }
- regc(NUL);
- *flagp |= HASWIDTH;
- break;
- }
-
- default:
- if (ascii_isdigit(c) || c == '<' || c == '>'
- || c == '\'') {
- uint32_t n = 0;
- int cmp;
-
- cmp = c;
- if (cmp == '<' || cmp == '>')
- c = getchr();
- while (ascii_isdigit(c)) {
- n = n * 10 + (uint32_t)(c - '0');
- c = getchr();
- }
- if (c == '\'' && n == 0) {
- /* "\%'m", "\%<'m" and "\%>'m": Mark */
- c = getchr();
- ret = regnode(RE_MARK);
- if (ret == JUST_CALC_SIZE)
- regsize += 2;
- else {
- *regcode++ = c;
- *regcode++ = cmp;
- }
- break;
- } else if (c == 'l' || c == 'c' || c == 'v') {
- if (c == 'l') {
- ret = regnode(RE_LNUM);
- if (save_prev_at_start) {
- at_start = true;
- }
- } else if (c == 'c') {
- ret = regnode(RE_COL);
- } else {
- ret = regnode(RE_VCOL);
- }
- if (ret == JUST_CALC_SIZE) {
- regsize += 5;
- } else {
- // put the number and the optional
- // comparator after the opcode
- regcode = re_put_uint32(regcode, n);
- *regcode++ = cmp;
- }
- break;
- }
- }
-
- EMSG2_RET_NULL(_("E71: Invalid character after %s%%"),
- reg_magic == MAGIC_ALL);
- }
- }
- break;
-
- case Magic('['):
-collection:
- {
- char_u *lp;
-
- /*
- * If there is no matching ']', we assume the '[' is a normal
- * character. This makes 'incsearch' and ":help [" work.
- */
- lp = skip_anyof(regparse);
- if (*lp == ']') { /* there is a matching ']' */
- int startc = -1; /* > 0 when next '-' is a range */
- int endc;
-
- /*
- * In a character class, different parsing rules apply.
- * Not even \ is special anymore, nothing is.
- */
- if (*regparse == '^') { /* Complement of range. */
- ret = regnode(ANYBUT + extra);
- regparse++;
- } else
- ret = regnode(ANYOF + extra);
-
- /* At the start ']' and '-' mean the literal character. */
- if (*regparse == ']' || *regparse == '-') {
- startc = *regparse;
- regc(*regparse++);
- }
-
- while (*regparse != NUL && *regparse != ']') {
- if (*regparse == '-') {
- ++regparse;
- /* The '-' is not used for a range at the end and
- * after or before a '\n'. */
- if (*regparse == ']' || *regparse == NUL
- || startc == -1
- || (regparse[0] == '\\' && regparse[1] == 'n')) {
- regc('-');
- startc = '-'; /* [--x] is a range */
- } else {
- /* Also accept "a-[.z.]" */
- endc = 0;
- if (*regparse == '[')
- endc = get_coll_element(&regparse);
- if (endc == 0) {
- endc = mb_ptr2char_adv((const char_u **)&regparse);
- }
-
- /* Handle \o40, \x20 and \u20AC style sequences */
- if (endc == '\\' && !reg_cpo_lit)
- endc = coll_get_char();
-
- if (startc > endc) {
- EMSG_RET_NULL(_(e_reverse_range));
- }
- if (utf_char2len(startc) > 1
- || utf_char2len(endc) > 1) {
- // Limit to a range of 256 chars
- if (endc > startc + 256) {
- EMSG_RET_NULL(_(e_large_class));
- }
- while (++startc <= endc) {
- regmbc(startc);
- }
- } else {
- while (++startc <= endc)
- regc(startc);
- }
- startc = -1;
- }
- }
- /*
- * Only "\]", "\^", "\]" and "\\" are special in Vi. Vim
- * accepts "\t", "\e", etc., but only when the 'l' flag in
- * 'cpoptions' is not included.
- */
- else if (*regparse == '\\'
- && (vim_strchr(REGEXP_INRANGE, regparse[1]) != NULL
- || (!reg_cpo_lit
- && vim_strchr(REGEXP_ABBR,
- regparse[1]) != NULL))) {
- regparse++;
- if (*regparse == 'n') {
- /* '\n' in range: also match NL */
- if (ret != JUST_CALC_SIZE) {
- /* Using \n inside [^] does not change what
- * matches. "[^\n]" is the same as ".". */
- if (*ret == ANYOF) {
- *ret = ANYOF + ADD_NL;
- *flagp |= HASNL;
- }
- /* else: must have had a \n already */
- }
- regparse++;
- startc = -1;
- } else if (*regparse == 'd'
- || *regparse == 'o'
- || *regparse == 'x'
- || *regparse == 'u'
- || *regparse == 'U') {
- startc = coll_get_char();
- if (startc == 0)
- regc(0x0a);
- else
- regmbc(startc);
- } else {
- startc = backslash_trans(*regparse++);
- regc(startc);
- }
- } else if (*regparse == '[') {
- int c_class;
- int cu;
-
- c_class = get_char_class(&regparse);
- startc = -1;
- /* Characters assumed to be 8 bits! */
- switch (c_class) {
- case CLASS_NONE:
- c_class = get_equi_class(&regparse);
- if (c_class != 0) {
- /* produce equivalence class */
- reg_equi_class(c_class);
- } else if ((c_class =
- get_coll_element(&regparse)) != 0) {
- /* produce a collating element */
- regmbc(c_class);
- } else {
- /* literal '[', allow [[-x] as a range */
- startc = *regparse++;
- regc(startc);
- }
- break;
- case CLASS_ALNUM:
- for (cu = 1; cu < 128; cu++) {
- if (isalnum(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_ALPHA:
- for (cu = 1; cu < 128; cu++) {
- if (isalpha(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_BLANK:
- regc(' ');
- regc('\t');
- break;
- case CLASS_CNTRL:
- for (cu = 1; cu <= 127; cu++) {
- if (iscntrl(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_DIGIT:
- for (cu = 1; cu <= 127; cu++) {
- if (ascii_isdigit(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_GRAPH:
- for (cu = 1; cu <= 127; cu++) {
- if (isgraph(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_LOWER:
- for (cu = 1; cu <= 255; cu++) {
- if (mb_islower(cu) && cu != 170 && cu != 186) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_PRINT:
- for (cu = 1; cu <= 255; cu++) {
- if (vim_isprintc(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_PUNCT:
- for (cu = 1; cu < 128; cu++) {
- if (ispunct(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_SPACE:
- for (cu = 9; cu <= 13; cu++)
- regc(cu);
- regc(' ');
- break;
- case CLASS_UPPER:
- for (cu = 1; cu <= 255; cu++) {
- if (mb_isupper(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_XDIGIT:
- for (cu = 1; cu <= 255; cu++) {
- if (ascii_isxdigit(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_TAB:
- regc('\t');
- break;
- case CLASS_RETURN:
- regc('\r');
- break;
- case CLASS_BACKSPACE:
- regc('\b');
- break;
- case CLASS_ESCAPE:
- regc(ESC);
- break;
- case CLASS_IDENT:
- for (cu = 1; cu <= 255; cu++) {
- if (vim_isIDc(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_KEYWORD:
- for (cu = 1; cu <= 255; cu++) {
- if (reg_iswordc(cu)) {
- regmbc(cu);
- }
- }
- break;
- case CLASS_FNAME:
- for (cu = 1; cu <= 255; cu++) {
- if (vim_isfilec(cu)) {
- regmbc(cu);
- }
- }
- break;
- }
- } else {
- // produce a multibyte character, including any
- // following composing characters.
- startc = utf_ptr2char(regparse);
- int len = utfc_ptr2len(regparse);
- if (utf_char2len(startc) != len) {
- // composing chars
- startc = -1;
- }
- while (--len >= 0) {
- regc(*regparse++);
- }
- }
- }
- regc(NUL);
- prevchr_len = 1; /* last char was the ']' */
- if (*regparse != ']')
- EMSG_RET_NULL(_(e_toomsbra)); /* Cannot happen? */
- skipchr(); /* let's be friends with the lexer again */
- *flagp |= HASWIDTH | SIMPLE;
- break;
- } else if (reg_strict)
- EMSG2_RET_NULL(_(e_missingbracket), reg_magic > MAGIC_OFF);
- }
- FALLTHROUGH;
-
- default:
- {
- int len;
-
- /* A multi-byte character is handled as a separate atom if it's
- * before a multi and when it's a composing char. */
- if (use_multibytecode(c)) {
-do_multibyte:
- ret = regnode(MULTIBYTECODE);
- regmbc(c);
- *flagp |= HASWIDTH | SIMPLE;
- break;
- }
-
- ret = regnode(EXACTLY);
-
- /*
- * Append characters as long as:
- * - there is no following multi, we then need the character in
- * front of it as a single character operand
- * - not running into a Magic character
- * - "one_exactly" is not set
- * But always emit at least one character. Might be a Multi,
- * e.g., a "[" without matching "]".
- */
- for (len = 0; c != NUL && (len == 0
- || (re_multi_type(peekchr()) == NOT_MULTI
- && !one_exactly
- && !is_Magic(c))); ++len) {
- c = no_Magic(c);
- {
- regmbc(c);
- {
- int l;
-
- /* Need to get composing character too. */
- for (;; ) {
- l = utf_ptr2len(regparse);
- if (!utf_composinglike(regparse, regparse + l)) {
- break;
- }
- regmbc(utf_ptr2char(regparse));
- skipchr();
- }
- }
- }
- c = getchr();
- }
- ungetchr();
-
- regc(NUL);
- *flagp |= HASWIDTH;
- if (len == 1)
- *flagp |= SIMPLE;
- }
- break;
- }
-
- return ret;
-}
-
-/// Used in a place where no * or \+ can follow.
-static bool re_mult_next(char *what)
-{
- if (re_multi_type(peekchr()) == MULTI_MULT) {
- EMSG2_RET_FAIL(_("E888: (NFA regexp) cannot repeat %s"), what);
- }
- return true;
-}
-
-// Return true if MULTIBYTECODE should be used instead of EXACTLY for
-// character "c".
-static bool use_multibytecode(int c)
-{
- return utf_char2len(c) > 1
- && (re_multi_type(peekchr()) != NOT_MULTI
- || utf_iscomposing(c));
-}
-
-/*
- * Emit a node.
- * Return pointer to generated code.
- */
-static char_u *regnode(int op)
-{
- char_u *ret;
-
- ret = regcode;
- if (ret == JUST_CALC_SIZE)
- regsize += 3;
- else {
- *regcode++ = op;
- *regcode++ = NUL; /* Null "next" pointer. */
- *regcode++ = NUL;
- }
- return ret;
-}
-
-/*
- * Emit (if appropriate) a byte of code
- */
-static void regc(int b)
-{
- if (regcode == JUST_CALC_SIZE)
- regsize++;
- else
- *regcode++ = b;
-}
-
-/*
- * Emit (if appropriate) a multi-byte character of code
- */
-static void regmbc(int c)
-{
- if (regcode == JUST_CALC_SIZE) {
- regsize += utf_char2len(c);
- } else {
- regcode += utf_char2bytes(c, regcode);
- }
-}
-
-/*
- * Insert an operator in front of already-emitted operand
- *
- * Means relocating the operand.
- */
-static void reginsert(int op, char_u *opnd)
-{
- char_u *src;
- char_u *dst;
- char_u *place;
-
- if (regcode == JUST_CALC_SIZE) {
- regsize += 3;
- return;
- }
- src = regcode;
- regcode += 3;
- dst = regcode;
- while (src > opnd)
- *--dst = *--src;
-
- place = opnd; /* Op node, where operand used to be. */
- *place++ = op;
- *place++ = NUL;
- *place = NUL;
-}
-
-/*
- * Insert an operator in front of already-emitted operand.
- * Add a number to the operator.
- */
-static void reginsert_nr(int op, long val, char_u *opnd)
-{
- char_u *src;
- char_u *dst;
- char_u *place;
-
- if (regcode == JUST_CALC_SIZE) {
- regsize += 7;
- return;
- }
- src = regcode;
- regcode += 7;
- dst = regcode;
- while (src > opnd)
- *--dst = *--src;
-
- place = opnd; /* Op node, where operand used to be. */
- *place++ = op;
- *place++ = NUL;
- *place++ = NUL;
- assert(val >= 0 && (uintmax_t)val <= UINT32_MAX);
- re_put_uint32(place, (uint32_t)val);
-}
-
-/*
- * Insert an operator in front of already-emitted operand.
- * The operator has the given limit values as operands. Also set next pointer.
- *
- * Means relocating the operand.
- */
-static void reginsert_limits(int op, long minval, long maxval, char_u *opnd)
-{
- char_u *src;
- char_u *dst;
- char_u *place;
-
- if (regcode == JUST_CALC_SIZE) {
- regsize += 11;
- return;
- }
- src = regcode;
- regcode += 11;
- dst = regcode;
- while (src > opnd)
- *--dst = *--src;
-
- place = opnd; /* Op node, where operand used to be. */
- *place++ = op;
- *place++ = NUL;
- *place++ = NUL;
- assert(minval >= 0 && (uintmax_t)minval <= UINT32_MAX);
- place = re_put_uint32(place, (uint32_t)minval);
- assert(maxval >= 0 && (uintmax_t)maxval <= UINT32_MAX);
- place = re_put_uint32(place, (uint32_t)maxval);
- regtail(opnd, place);
-}
-
-/*
- * Write a four bytes number at "p" and return pointer to the next char.
- */
-static char_u *re_put_uint32(char_u *p, uint32_t val)
-{
- *p++ = (char_u) ((val >> 24) & 0377);
- *p++ = (char_u) ((val >> 16) & 0377);
- *p++ = (char_u) ((val >> 8) & 0377);
- *p++ = (char_u) (val & 0377);
- return p;
-}
-
-// Set the next-pointer at the end of a node chain.
-static void regtail(char_u *p, char_u *val)
-{
- int offset;
-
- if (p == JUST_CALC_SIZE) {
- return;
- }
-
- // Find last node.
- char_u *scan = p;
- for (;; ) {
- char_u *temp = regnext(scan);
- if (temp == NULL) {
- break;
- }
- scan = temp;
- }
-
- if (OP(scan) == BACK) {
- offset = (int)(scan - val);
- } else {
- offset = (int)(val - scan);
- }
- // When the offset uses more than 16 bits it can no longer fit in the two
- // bytes available. Use a global flag to avoid having to check return
- // values in too many places.
- if (offset > 0xffff) {
- reg_toolong = true;
- } else {
- *(scan + 1) = (char_u)(((unsigned)offset >> 8) & 0377);
- *(scan + 2) = (char_u)(offset & 0377);
- }
-}
-
-/*
- * Like regtail, on item after a BRANCH; nop if none.
- */
-static void regoptail(char_u *p, char_u *val)
-{
- /* When op is neither BRANCH nor BRACE_COMPLEX0-9, it is "operandless" */
- if (p == NULL || p == JUST_CALC_SIZE
- || (OP(p) != BRANCH
- && (OP(p) < BRACE_COMPLEX || OP(p) > BRACE_COMPLEX + 9)))
- return;
- regtail(OPERAND(p), val);
-}
-
-/*
- * Functions for getting characters from the regexp input.
- */
-
-/*
* Start parsing at "str".
*/
static void initchr(char_u *str)
@@ -2806,9 +591,10 @@ static int peekchr(void)
case '.':
case '[':
case '~':
- /* magic when 'magic' is on */
- if (reg_magic >= MAGIC_ON)
+ // magic when 'magic' is on
+ if (reg_magic >= MAGIC_ON) {
curchr = Magic(curchr);
+ }
break;
case '(':
case ')':
@@ -2823,18 +609,19 @@ static int peekchr(void)
case '|':
case '<':
case '>':
- case '#': /* future ext. */
- case '"': /* future ext. */
- case '\'': /* future ext. */
- case ',': /* future ext. */
- case '-': /* future ext. */
- case ':': /* future ext. */
- case ';': /* future ext. */
- case '`': /* future ext. */
- case '/': /* Can't be used in / command */
- /* magic only after "\v" */
- if (reg_magic == MAGIC_ALL)
+ case '#': // future ext.
+ case '"': // future ext.
+ case '\'': // future ext.
+ case ',': // future ext.
+ case '-': // future ext.
+ case ':': // future ext.
+ case ';': // future ext.
+ case '`': // future ext.
+ case '/': // Can't be used in / command
+ // magic only after "\v"
+ if (reg_magic == MAGIC_ALL) {
curchr = Magic(curchr);
+ }
break;
case '*':
// * is not magic as the very first character, eg "?*ptr", when
@@ -2947,11 +734,12 @@ static int peekchr(void)
*/
static void skipchr(void)
{
- /* peekchr() eats a backslash, do the same here */
- if (*regparse == '\\')
+ // peekchr() eats a backslash, do the same here
+ if (*regparse == '\\') {
prevchr_len = 1;
- else
+ } else {
prevchr_len = 0;
+ }
if (regparse[prevchr_len] != NUL) {
// Exclude composing chars that utfc_ptr2len does include.
prevchr_len += utf_ptr2len(regparse + prevchr_len);
@@ -2961,7 +749,7 @@ static void skipchr(void)
at_start = false;
prevprevchr = prevchr;
prevchr = curchr;
- curchr = nextchr; /* use previously unget char, or -1 */
+ curchr = nextchr; // use previously unget char, or -1
nextchr = -1;
}
@@ -3054,8 +842,8 @@ static int64_t getdecchrs(void)
break;
nr *= 10;
nr += c - '0';
- ++regparse;
- curchr = -1; /* no longer valid */
+ regparse++;
+ curchr = -1; // no longer valid
}
if (i == 0)
@@ -3091,29 +879,6 @@ static int64_t getoctchrs(void)
return nr;
}
-/*
- * Get a number after a backslash that is inside [].
- * When nothing is recognized return a backslash.
- */
-static int coll_get_char(void)
-{
- int64_t nr = -1;
-
- switch (*regparse++) {
- case 'd': nr = getdecchrs(); break;
- case 'o': nr = getoctchrs(); break;
- case 'x': nr = gethexchrs(2); break;
- case 'u': nr = gethexchrs(4); break;
- case 'U': nr = gethexchrs(8); break;
- }
- if (nr < 0 || nr > INT_MAX) {
- // If getting the number fails be backwards compatible: the character
- // is a backslash.
- regparse--;
- nr = '\\';
- }
- return nr;
-}
/*
* read_limits - Read two integers to be taken as a minimum and maximum.
@@ -3149,9 +914,7 @@ static int read_limits(long *minval, long *maxval)
regparse++; // Allow either \{...} or \{...\}
}
if (*regparse != '}') {
- snprintf((char *)IObuff, IOSIZE, _("E554: Syntax error in %s{...}"),
- reg_magic == MAGIC_ALL ? "" : "\\");
- EMSG_RET_FAIL((char *)IObuff);
+ EMSG2_RET_FAIL(_("E554: Syntax error in %s{...}"), reg_magic == MAGIC_ALL);
}
/*
@@ -3163,7 +926,7 @@ static int read_limits(long *minval, long *maxval)
*minval = *maxval;
*maxval = tmp;
}
- skipchr(); /* let's be friends with the lexer again */
+ skipchr(); // let's be friends with the lexer again
return OK;
}
@@ -3175,22 +938,6 @@ static int read_limits(long *minval, long *maxval)
* Global work variables for vim_regexec().
*/
-/* Save the sub-expressions before attempting a match. */
-#define save_se(savep, posp, pp) \
- REG_MULTI ? save_se_multi((savep), (posp)) : save_se_one((savep), (pp))
-
-/* After a failed match restore the sub-expressions. */
-#define restore_se(savep, posp, pp) { \
- if (REG_MULTI) \
- *(posp) = (savep)->se_u.pos; \
- else \
- *(pp) = (savep)->se_u.ptr; }
-
-
-#ifdef REGEXP_DEBUG
-int regnarrate = 0;
-#endif
-
// Sometimes need to save a copy of a line. Since alloc()/free() is very
// slow, we keep one allocated piece of memory and only re-allocate it when
// it's too small. It's freed in bt_regexec_both() when finished.
@@ -3266,41 +1013,6 @@ typedef struct {
static regexec_T rex;
static bool rex_in_use = false;
-/*
- * "regstack" and "backpos" are used by regmatch(). They are kept over calls
- * to avoid invoking malloc() and free() often.
- * "regstack" is a stack with regitem_T items, sometimes preceded by regstar_T
- * or regbehind_T.
- * "backpos_T" is a table with backpos_T for BACK
- */
-static garray_T regstack = GA_EMPTY_INIT_VALUE;
-static garray_T backpos = GA_EMPTY_INIT_VALUE;
-
-/*
- * Both for regstack and backpos tables we use the following strategy of
- * allocation (to reduce malloc/free calls):
- * - Initial size is fairly small.
- * - When needed, the tables are grown bigger (8 times at first, double after
- * that).
- * - After executing the match we free the memory only if the array has grown.
- * Thus the memory is kept allocated when it's at the initial size.
- * This makes it fast while not keeping a lot of memory allocated.
- * A three times speed increase was observed when using many simple patterns.
- */
-#define REGSTACK_INITIAL 2048
-#define BACKPOS_INITIAL 64
-
-#if defined(EXITFREE)
-void free_regexp_stuff(void)
-{
- ga_clear(&regstack);
- ga_clear(&backpos);
- xfree(reg_tofree);
- xfree(reg_prev_sub);
-}
-
-#endif
-
// Return true if character 'c' is included in 'iskeyword' option for
// "reg_buf" buffer.
static bool reg_iswordc(int c)
@@ -3325,312 +1037,15 @@ static char_u *reg_getline(linenr_T lnum)
return ml_get_buf(rex.reg_buf, rex.reg_firstlnum + lnum, false);
}
-static regsave_T behind_pos;
-
-static char_u *reg_startzp[NSUBEXP]; /* Workspace to mark beginning */
-static char_u *reg_endzp[NSUBEXP]; /* and end of \z(...\) matches */
-static lpos_T reg_startzpos[NSUBEXP]; /* idem, beginning pos */
-static lpos_T reg_endzpos[NSUBEXP]; /* idem, end pos */
+static char_u *reg_startzp[NSUBEXP]; // Workspace to mark beginning
+static char_u *reg_endzp[NSUBEXP]; // and end of \z(...\) matches
+static lpos_T reg_startzpos[NSUBEXP]; // idem, beginning pos
+static lpos_T reg_endzpos[NSUBEXP]; // idem, end pos
// true if using multi-line regexp.
#define REG_MULTI (rex.reg_match == NULL)
/*
- * Match a regexp against a string.
- * "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
- * Uses curbuf for line count and 'iskeyword'.
- * If "line_lbr" is true, consider a "\n" in "line" to be a line break.
- *
- * Returns 0 for failure, number of lines contained in the match otherwise.
- */
-static int
-bt_regexec_nl (
- regmatch_T *rmp,
- char_u *line, /* string to match against */
- colnr_T col, /* column to start looking for match */
- bool line_lbr
-)
-{
- rex.reg_match = rmp;
- rex.reg_mmatch = NULL;
- rex.reg_maxline = 0;
- rex.reg_line_lbr = line_lbr;
- rex.reg_buf = curbuf;
- rex.reg_win = NULL;
- rex.reg_ic = rmp->rm_ic;
- rex.reg_icombine = false;
- rex.reg_maxcol = 0;
-
- long r = bt_regexec_both(line, col, NULL, NULL);
- assert(r <= INT_MAX);
- return (int)r;
-}
-
-/// Wrapper around strchr which accounts for case-insensitive searches and
-/// non-ASCII characters.
-///
-/// This function is used a lot for simple searches, keep it fast!
-///
-/// @param s string to search
-/// @param c character to find in @a s
-///
-/// @return NULL if no match, otherwise pointer to the position in @a s
-static inline char_u *cstrchr(const char_u *const s, const int c)
- FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
- FUNC_ATTR_ALWAYS_INLINE
-{
- if (!rex.reg_ic) {
- return vim_strchr(s, c);
- }
-
- // Use folded case for UTF-8, slow! For ASCII use libc strpbrk which is
- // expected to be highly optimized.
- if (c > 0x80) {
- const int folded_c = utf_fold(c);
- for (const char_u *p = s; *p != NUL; p += utfc_ptr2len(p)) {
- if (utf_fold(utf_ptr2char(p)) == folded_c) {
- return (char_u *)p;
- }
- }
- return NULL;
- }
-
- int cc;
- if (ASCII_ISUPPER(c)) {
- cc = TOLOWER_ASC(c);
- } else if (ASCII_ISLOWER(c)) {
- cc = TOUPPER_ASC(c);
- } else {
- return vim_strchr(s, c);
- }
-
- char tofind[] = { (char)c, (char)cc, NUL };
- return (char_u *)strpbrk((const char *)s, tofind);
-}
-
-/// Matches a regexp against multiple lines.
-/// "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
-/// Uses curbuf for line count and 'iskeyword'.
-///
-/// @param win Window in which to search or NULL
-/// @param buf Buffer in which to search
-/// @param lnum Number of line to start looking for match
-/// @param col Column to start looking for match
-/// @param tm Timeout limit or NULL
-///
-/// @return zero if there is no match and number of lines contained in the match
-/// otherwise.
-static long bt_regexec_multi(regmmatch_T *rmp, win_T *win, buf_T *buf,
- linenr_T lnum, colnr_T col,
- proftime_T *tm, int *timed_out)
-{
- rex.reg_match = NULL;
- rex.reg_mmatch = rmp;
- rex.reg_buf = buf;
- rex.reg_win = win;
- rex.reg_firstlnum = lnum;
- rex.reg_maxline = rex.reg_buf->b_ml.ml_line_count - lnum;
- rex.reg_line_lbr = false;
- rex.reg_ic = rmp->rmm_ic;
- rex.reg_icombine = false;
- rex.reg_maxcol = rmp->rmm_maxcol;
-
- return bt_regexec_both(NULL, col, tm, timed_out);
-}
-
-/// Match a regexp against a string ("line" points to the string) or multiple
-/// lines (if "line" is NULL, use reg_getline()).
-/// @return 0 for failure, or number of lines contained in the match.
-static long bt_regexec_both(char_u *line,
- colnr_T col, // column to start search
- proftime_T *tm, // timeout limit or NULL
- int *timed_out) // flag set on timeout or NULL
-{
- bt_regprog_T *prog;
- char_u *s;
- long retval = 0L;
-
- /* Create "regstack" and "backpos" if they are not allocated yet.
- * We allocate *_INITIAL amount of bytes first and then set the grow size
- * to much bigger value to avoid many malloc calls in case of deep regular
- * expressions. */
- if (regstack.ga_data == NULL) {
- /* Use an item size of 1 byte, since we push different things
- * onto the regstack. */
- ga_init(&regstack, 1, REGSTACK_INITIAL);
- ga_grow(&regstack, REGSTACK_INITIAL);
- ga_set_growsize(&regstack, REGSTACK_INITIAL * 8);
- }
-
- if (backpos.ga_data == NULL) {
- ga_init(&backpos, sizeof(backpos_T), BACKPOS_INITIAL);
- ga_grow(&backpos, BACKPOS_INITIAL);
- ga_set_growsize(&backpos, BACKPOS_INITIAL * 8);
- }
-
- if (REG_MULTI) {
- prog = (bt_regprog_T *)rex.reg_mmatch->regprog;
- line = reg_getline((linenr_T)0);
- rex.reg_startpos = rex.reg_mmatch->startpos;
- rex.reg_endpos = rex.reg_mmatch->endpos;
- } else {
- prog = (bt_regprog_T *)rex.reg_match->regprog;
- rex.reg_startp = rex.reg_match->startp;
- rex.reg_endp = rex.reg_match->endp;
- }
-
- /* Be paranoid... */
- if (prog == NULL || line == NULL) {
- iemsg(_(e_null));
- goto theend;
- }
-
- /* Check validity of program. */
- if (prog_magic_wrong())
- goto theend;
-
- // If the start column is past the maximum column: no need to try.
- if (rex.reg_maxcol > 0 && col >= rex.reg_maxcol) {
- goto theend;
- }
-
- // If pattern contains "\c" or "\C": overrule value of rex.reg_ic
- if (prog->regflags & RF_ICASE) {
- rex.reg_ic = true;
- } else if (prog->regflags & RF_NOICASE) {
- rex.reg_ic = false;
- }
-
- // If pattern contains "\Z" overrule value of rex.reg_icombine
- if (prog->regflags & RF_ICOMBINE) {
- rex.reg_icombine = true;
- }
-
- /* If there is a "must appear" string, look for it. */
- if (prog->regmust != NULL) {
- int c = utf_ptr2char(prog->regmust);
- s = line + col;
-
- // This is used very often, esp. for ":global". Use two versions of
- // the loop to avoid overhead of conditions.
- if (!rex.reg_ic) {
- while ((s = vim_strchr(s, c)) != NULL) {
- if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0) {
- break; // Found it.
- }
- MB_PTR_ADV(s);
- }
- } else {
- while ((s = cstrchr(s, c)) != NULL) {
- if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0) {
- break; // Found it.
- }
- MB_PTR_ADV(s);
- }
- }
- if (s == NULL) { // Not present.
- goto theend;
- }
- }
-
- rex.line = line;
- rex.lnum = 0;
- reg_toolong = false;
-
- /* Simplest case: Anchored match need be tried only once. */
- if (prog->reganch) {
- int c = utf_ptr2char(rex.line + col);
- if (prog->regstart == NUL
- || prog->regstart == c
- || (rex.reg_ic
- && (utf_fold(prog->regstart) == utf_fold(c)
- || (c < 255 && prog->regstart < 255
- && mb_tolower(prog->regstart) == mb_tolower(c))))) {
- retval = regtry(prog, col, tm, timed_out);
- } else {
- retval = 0;
- }
- } else {
- int tm_count = 0;
- /* Messy cases: unanchored match. */
- while (!got_int) {
- if (prog->regstart != NUL) {
- // Skip until the char we know it must start with.
- s = cstrchr(rex.line + col, prog->regstart);
- if (s == NULL) {
- retval = 0;
- break;
- }
- col = (int)(s - rex.line);
- }
-
- // Check for maximum column to try.
- if (rex.reg_maxcol > 0 && col >= rex.reg_maxcol) {
- retval = 0;
- break;
- }
-
- retval = regtry(prog, col, tm, timed_out);
- if (retval > 0) {
- break;
- }
-
- // if not currently on the first line, get it again
- if (rex.lnum != 0) {
- rex.lnum = 0;
- rex.line = reg_getline((linenr_T)0);
- }
- if (rex.line[col] == NUL) {
- break;
- }
- col += utfc_ptr2len(rex.line + col);
- // Check for timeout once in a twenty times to avoid overhead.
- if (tm != NULL && ++tm_count == 20) {
- tm_count = 0;
- if (profile_passed_limit(*tm)) {
- if (timed_out != NULL) {
- *timed_out = true;
- }
- break;
- }
- }
- }
- }
-
-theend:
- /* Free "reg_tofree" when it's a bit big.
- * Free regstack and backpos if they are bigger than their initial size. */
- if (reg_tofreelen > 400) {
- XFREE_CLEAR(reg_tofree);
- }
- if (regstack.ga_maxlen > REGSTACK_INITIAL)
- ga_clear(&regstack);
- if (backpos.ga_maxlen > BACKPOS_INITIAL)
- ga_clear(&backpos);
-
- if (retval > 0) {
- // Make sure the end is never before the start. Can happen when \zs
- // and \ze are used.
- if (REG_MULTI) {
- const lpos_T *const start = &rex.reg_mmatch->startpos[0];
- const lpos_T *const end = &rex.reg_mmatch->endpos[0];
-
- if (end->lnum < start->lnum
- || (end->lnum == start->lnum && end->col < start->col)) {
- rex.reg_mmatch->endpos[0] = rex.reg_mmatch->startpos[0];
- }
- } else {
- if (rex.reg_match->endp[0] < rex.reg_match->startp[0]) {
- rex.reg_match->endp[0] = rex.reg_match->startp[0];
- }
- }
- }
-
- return retval;
-}
-
-
-/*
* Create a new extmatch and mark it as referenced once.
*/
static reg_extmatch_T *make_extmatch(void)
@@ -3666,75 +1081,6 @@ void unref_extmatch(reg_extmatch_T *em)
}
}
-/// Try match of "prog" with at rex.line["col"].
-/// @returns 0 for failure, or number of lines contained in the match.
-static long regtry(bt_regprog_T *prog,
- colnr_T col,
- proftime_T *tm, // timeout limit or NULL
- int *timed_out) // flag set on timeout or NULL
-{
- rex.input = rex.line + col;
- rex.need_clear_subexpr = true;
- // Clear the external match subpointers if necessaey.
- rex.need_clear_zsubexpr = (prog->reghasz == REX_SET);
-
- if (regmatch(prog->program + 1, tm, timed_out) == 0) {
- return 0;
- }
-
- cleanup_subexpr();
- if (REG_MULTI) {
- if (rex.reg_startpos[0].lnum < 0) {
- rex.reg_startpos[0].lnum = 0;
- rex.reg_startpos[0].col = col;
- }
- if (rex.reg_endpos[0].lnum < 0) {
- rex.reg_endpos[0].lnum = rex.lnum;
- rex.reg_endpos[0].col = (int)(rex.input - rex.line);
- } else {
- // Use line number of "\ze".
- rex.lnum = rex.reg_endpos[0].lnum;
- }
- } else {
- if (rex.reg_startp[0] == NULL) {
- rex.reg_startp[0] = rex.line + col;
- }
- if (rex.reg_endp[0] == NULL) {
- rex.reg_endp[0] = rex.input;
- }
- }
- /* Package any found \z(...\) matches for export. Default is none. */
- unref_extmatch(re_extmatch_out);
- re_extmatch_out = NULL;
-
- if (prog->reghasz == REX_SET) {
- int i;
-
- cleanup_zsubexpr();
- re_extmatch_out = make_extmatch();
- for (i = 0; i < NSUBEXP; i++) {
- if (REG_MULTI) {
- /* Only accept single line matches. */
- if (reg_startzpos[i].lnum >= 0
- && reg_endzpos[i].lnum == reg_startzpos[i].lnum
- && reg_endzpos[i].col >= reg_startzpos[i].col) {
- re_extmatch_out->matches[i] =
- vim_strnsave(reg_getline(reg_startzpos[i].lnum)
- + reg_startzpos[i].col,
- reg_endzpos[i].col
- - reg_startzpos[i].col);
- }
- } else {
- if (reg_startzp[i] != NULL && reg_endzp[i] != NULL)
- re_extmatch_out->matches[i] =
- vim_strnsave(reg_startzp[i], reg_endzp[i] - reg_startzp[i]);
- }
- }
- }
- return 1 + rex.lnum;
-}
-
-
// Get class of previous character.
static int reg_prev_class(void)
{
@@ -3790,8 +1136,8 @@ static bool reg_match_visual(void)
return false;
}
+ col = (colnr_T)(rex.input - rex.line);
if (mode == 'v') {
- col = (colnr_T)(rex.input - rex.line);
if ((lnum == top.lnum && col < top.col)
|| (lnum == bot.lnum && col >= bot.col + (*p_sel != 'e'))) {
return false;
@@ -3806,8 +1152,12 @@ static bool reg_match_visual(void)
if (top.col == MAXCOL || bot.col == MAXCOL || curswant == MAXCOL) {
end = MAXCOL;
}
- unsigned int cols_u = win_linetabsize(wp, rex.line,
- (colnr_T)(rex.input - rex.line));
+
+ // getvvcol() flushes rex.line, need to get it again
+ rex.line = reg_getline(rex.lnum);
+ rex.input = rex.line + col;
+
+ unsigned int cols_u = win_linetabsize(wp, rex.line, col);
assert(cols_u <= MAXCOL);
colnr_T cols = (colnr_T)cols_u;
if (cols < start || cols > end - (*p_sel == 'e')) {
@@ -3817,1803 +1167,6 @@ static bool reg_match_visual(void)
return true;
}
-#define ADVANCE_REGINPUT() MB_PTR_ADV(rex.input)
-
-/*
- * The arguments from BRACE_LIMITS are stored here. They are actually local
- * to regmatch(), but they are here to reduce the amount of stack space used
- * (it can be called recursively many times).
- */
-static long bl_minval;
-static long bl_maxval;
-
-/// Main matching routine
-///
-/// Conceptually the strategy is simple: Check to see whether the current node
-/// matches, push an item onto the regstack and loop to see whether the rest
-/// matches, and then act accordingly. In practice we make some effort to
-/// avoid using the regstack, in particular by going through "ordinary" nodes
-/// (that don't need to know whether the rest of the match failed) by a nested
-/// loop.
-///
-/// Returns true when there is a match. Leaves rex.input and rex.lnum
-/// just after the last matched character.
-/// Returns false when there is no match. Leaves rex.input and rex.lnum in an
-/// undefined state!
-static bool regmatch(
- char_u *scan, // Current node.
- proftime_T *tm, // timeout limit or NULL
- int *timed_out // flag set on timeout or NULL
-)
-{
- char_u *next; /* Next node. */
- int op;
- int c;
- regitem_T *rp;
- int no;
- int status; // one of the RA_ values:
- int tm_count = 0;
-#define RA_FAIL 1 // something failed, abort
-#define RA_CONT 2 // continue in inner loop
-#define RA_BREAK 3 // break inner loop
-#define RA_MATCH 4 // successful match
-#define RA_NOMATCH 5 // didn't match
-
- // Make "regstack" and "backpos" empty. They are allocated and freed in
- // bt_regexec_both() to reduce malloc()/free() calls.
- regstack.ga_len = 0;
- backpos.ga_len = 0;
-
- /*
- * Repeat until "regstack" is empty.
- */
- for (;; ) {
- /* Some patterns may take a long time to match, e.g., "\([a-z]\+\)\+Q".
- * Allow interrupting them with CTRL-C. */
- fast_breakcheck();
-
-#ifdef REGEXP_DEBUG
- if (scan != NULL && regnarrate) {
- mch_errmsg((char *)regprop(scan));
- mch_errmsg("(\n");
- }
-#endif
-
- /*
- * Repeat for items that can be matched sequentially, without using the
- * regstack.
- */
- for (;; ) {
- if (got_int || scan == NULL) {
- status = RA_FAIL;
- break;
- }
- // Check for timeout once in a 100 times to avoid overhead.
- if (tm != NULL && ++tm_count == 100) {
- tm_count = 0;
- if (profile_passed_limit(*tm)) {
- if (timed_out != NULL) {
- *timed_out = true;
- }
- status = RA_FAIL;
- break;
- }
- }
- status = RA_CONT;
-
-#ifdef REGEXP_DEBUG
- if (regnarrate) {
- mch_errmsg((char *)regprop(scan));
- mch_errmsg("...\n");
- if (re_extmatch_in != NULL) {
- int i;
-
- mch_errmsg(_("External submatches:\n"));
- for (i = 0; i < NSUBEXP; i++) {
- mch_errmsg(" \"");
- if (re_extmatch_in->matches[i] != NULL)
- mch_errmsg((char *)re_extmatch_in->matches[i]);
- mch_errmsg("\"\n");
- }
- }
- }
-#endif
- next = regnext(scan);
-
- op = OP(scan);
- // Check for character class with NL added.
- if (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI
- && *rex.input == NUL && rex.lnum <= rex.reg_maxline) {
- reg_nextline();
- } else if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\n') {
- ADVANCE_REGINPUT();
- } else {
- if (WITH_NL(op)) {
- op -= ADD_NL;
- }
- c = utf_ptr2char(rex.input);
- switch (op) {
- case BOL:
- if (rex.input != rex.line) {
- status = RA_NOMATCH;
- }
- break;
-
- case EOL:
- if (c != NUL) {
- status = RA_NOMATCH;
- }
- break;
-
- case RE_BOF:
- // We're not at the beginning of the file when below the first
- // line where we started, not at the start of the line or we
- // didn't start at the first line of the buffer.
- if (rex.lnum != 0 || rex.input != rex.line
- || (REG_MULTI && rex.reg_firstlnum > 1)) {
- status = RA_NOMATCH;
- }
- break;
-
- case RE_EOF:
- if (rex.lnum != rex.reg_maxline || c != NUL) {
- status = RA_NOMATCH;
- }
- break;
-
- case CURSOR:
- // Check if the buffer is in a window and compare the
- // rex.reg_win->w_cursor position to the match position.
- if (rex.reg_win == NULL
- || (rex.lnum + rex.reg_firstlnum != rex.reg_win->w_cursor.lnum)
- || ((colnr_T)(rex.input - rex.line) !=
- rex.reg_win->w_cursor.col)) {
- status = RA_NOMATCH;
- }
- break;
-
- case RE_MARK:
- /* Compare the mark position to the match position. */
- {
- int mark = OPERAND(scan)[0];
- int cmp = OPERAND(scan)[1];
- pos_T *pos;
-
- pos = getmark_buf(rex.reg_buf, mark, false);
- if (pos == NULL // mark doesn't exist
- || pos->lnum <= 0) { // mark isn't set in reg_buf
- status = RA_NOMATCH;
- } else {
- const colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum
- && pos->col == MAXCOL
- ? (colnr_T)STRLEN(reg_getline(pos->lnum - rex.reg_firstlnum))
- : pos->col;
-
- if (pos->lnum == rex.lnum + rex.reg_firstlnum
- ? (pos_col == (colnr_T)(rex.input - rex.line)
- ? (cmp == '<' || cmp == '>')
- : (pos_col < (colnr_T)(rex.input - rex.line)
- ? cmp != '>'
- : cmp != '<'))
- : (pos->lnum < rex.lnum + rex.reg_firstlnum
- ? cmp != '>'
- : cmp != '<')) {
- status = RA_NOMATCH;
- }
- }
- }
- break;
-
- case RE_VISUAL:
- if (!reg_match_visual())
- status = RA_NOMATCH;
- break;
-
- case RE_LNUM:
- assert(rex.lnum + rex.reg_firstlnum >= 0
- && (uintmax_t)(rex.lnum + rex.reg_firstlnum) <= UINT32_MAX);
- if (!REG_MULTI
- || !re_num_cmp((uint32_t)(rex.lnum + rex.reg_firstlnum), scan)) {
- status = RA_NOMATCH;
- }
- break;
-
- case RE_COL:
- assert(rex.input - rex.line + 1 >= 0
- && (uintmax_t)(rex.input - rex.line + 1) <= UINT32_MAX);
- if (!re_num_cmp((uint32_t)(rex.input - rex.line + 1), scan)) {
- status = RA_NOMATCH;
- }
- break;
-
- case RE_VCOL:
- if (!re_num_cmp(win_linetabsize(rex.reg_win == NULL
- ? curwin : rex.reg_win,
- rex.line,
- (colnr_T)(rex.input - rex.line)) + 1,
- scan)) {
- status = RA_NOMATCH;
- }
- break;
-
- case BOW: // \<word; rex.input points to w
- if (c == NUL) { // Can't match at end of line
- status = RA_NOMATCH;
- } else {
- // Get class of current and previous char (if it exists).
- const int this_class =
- mb_get_class_tab(rex.input, rex.reg_buf->b_chartab);
- if (this_class <= 1) {
- status = RA_NOMATCH; // Not on a word at all.
- } else if (reg_prev_class() == this_class) {
- status = RA_NOMATCH; // Previous char is in same word.
- }
- }
- break;
-
- case EOW: // word\>; rex.input points after d
- if (rex.input == rex.line) { // Can't match at start of line
- status = RA_NOMATCH;
- } else {
- int this_class, prev_class;
-
- // Get class of current and previous char (if it exists).
- this_class = mb_get_class_tab(rex.input, rex.reg_buf->b_chartab);
- prev_class = reg_prev_class();
- if (this_class == prev_class
- || prev_class == 0 || prev_class == 1) {
- status = RA_NOMATCH;
- }
- }
- break; // Matched with EOW
-
- case ANY:
- // ANY does not match new lines.
- if (c == NUL) {
- status = RA_NOMATCH;
- } else {
- ADVANCE_REGINPUT();
- }
- break;
-
- case IDENT:
- if (!vim_isIDc(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case SIDENT:
- if (ascii_isdigit(*rex.input) || !vim_isIDc(c)) {
- status = RA_NOMATCH;
- } else {
- ADVANCE_REGINPUT();
- }
- break;
-
- case KWORD:
- if (!vim_iswordp_buf(rex.input, rex.reg_buf)) {
- status = RA_NOMATCH;
- } else {
- ADVANCE_REGINPUT();
- }
- break;
-
- case SKWORD:
- if (ascii_isdigit(*rex.input)
- || !vim_iswordp_buf(rex.input, rex.reg_buf)) {
- status = RA_NOMATCH;
- } else {
- ADVANCE_REGINPUT();
- }
- break;
-
- case FNAME:
- if (!vim_isfilec(c)) {
- status = RA_NOMATCH;
- } else {
- ADVANCE_REGINPUT();
- }
- break;
-
- case SFNAME:
- if (ascii_isdigit(*rex.input) || !vim_isfilec(c)) {
- status = RA_NOMATCH;
- } else {
- ADVANCE_REGINPUT();
- }
- break;
-
- case PRINT:
- if (!vim_isprintc(utf_ptr2char(rex.input))) {
- status = RA_NOMATCH;
- } else {
- ADVANCE_REGINPUT();
- }
- break;
-
- case SPRINT:
- if (ascii_isdigit(*rex.input) || !vim_isprintc(utf_ptr2char(rex.input))) {
- status = RA_NOMATCH;
- } else {
- ADVANCE_REGINPUT();
- }
- break;
-
- case WHITE:
- if (!ascii_iswhite(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case NWHITE:
- if (c == NUL || ascii_iswhite(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case DIGIT:
- if (!ri_digit(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case NDIGIT:
- if (c == NUL || ri_digit(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case HEX:
- if (!ri_hex(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case NHEX:
- if (c == NUL || ri_hex(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case OCTAL:
- if (!ri_octal(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case NOCTAL:
- if (c == NUL || ri_octal(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case WORD:
- if (!ri_word(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case NWORD:
- if (c == NUL || ri_word(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case HEAD:
- if (!ri_head(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case NHEAD:
- if (c == NUL || ri_head(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case ALPHA:
- if (!ri_alpha(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case NALPHA:
- if (c == NUL || ri_alpha(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case LOWER:
- if (!ri_lower(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case NLOWER:
- if (c == NUL || ri_lower(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case UPPER:
- if (!ri_upper(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case NUPPER:
- if (c == NUL || ri_upper(c))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case EXACTLY:
- {
- int len;
- char_u *opnd;
-
- opnd = OPERAND(scan);
- // Inline the first byte, for speed.
- if (*opnd != *rex.input
- && (!rex.reg_ic)) {
- status = RA_NOMATCH;
- } else if (*opnd == NUL) {
- // match empty string always works; happens when "~" is
- // empty.
- } else {
- if (opnd[1] == NUL && !rex.reg_ic) {
- len = 1; // matched a single byte above
- } else {
- // Need to match first byte again for multi-byte.
- len = (int)STRLEN(opnd);
- if (cstrncmp(opnd, rex.input, &len) != 0) {
- status = RA_NOMATCH;
- }
- }
- // Check for following composing character, unless %C
- // follows (skips over all composing chars).
- if (status != RA_NOMATCH
- && utf_composinglike(rex.input, rex.input + len)
- && !rex.reg_icombine
- && OP(next) != RE_COMPOSING) {
- // raaron: This code makes a composing character get
- // ignored, which is the correct behavior (sometimes)
- // for voweled Hebrew texts.
- status = RA_NOMATCH;
- }
- if (status != RA_NOMATCH) {
- rex.input += len;
- }
- }
- }
- break;
-
- case ANYOF:
- case ANYBUT:
- if (c == NUL)
- status = RA_NOMATCH;
- else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))
- status = RA_NOMATCH;
- else
- ADVANCE_REGINPUT();
- break;
-
- case MULTIBYTECODE:
- {
- int i, len;
-
- const char_u *opnd = OPERAND(scan);
- // Safety check (just in case 'encoding' was changed since
- // compiling the program).
- if ((len = utfc_ptr2len(opnd)) < 2) {
- status = RA_NOMATCH;
- break;
- }
- const int opndc = utf_ptr2char(opnd);
- if (utf_iscomposing(opndc)) {
- // When only a composing char is given match at any
- // position where that composing char appears.
- status = RA_NOMATCH;
- for (i = 0; rex.input[i] != NUL;
- i += utf_ptr2len(rex.input + i)) {
- const int inpc = utf_ptr2char(rex.input + i);
- if (!utf_iscomposing(inpc)) {
- if (i > 0) {
- break;
- }
- } else if (opndc == inpc) {
- // Include all following composing chars.
- len = i + utfc_ptr2len(rex.input + i);
- status = RA_MATCH;
- break;
- }
- }
- } else {
- for (i = 0; i < len; i++) {
- if (opnd[i] != rex.input[i]) {
- status = RA_NOMATCH;
- break;
- }
- }
- }
- rex.input += len;
- }
- break;
-
- case RE_COMPOSING:
- {
- // Skip composing characters.
- while (utf_iscomposing(utf_ptr2char(rex.input))) {
- MB_CPTR_ADV(rex.input);
- }
- }
- break;
-
- case NOTHING:
- break;
-
- case BACK:
- {
- int i;
-
- /*
- * When we run into BACK we need to check if we don't keep
- * looping without matching any input. The second and later
- * times a BACK is encountered it fails if the input is still
- * at the same position as the previous time.
- * The positions are stored in "backpos" and found by the
- * current value of "scan", the position in the RE program.
- */
- backpos_T *bp = (backpos_T *)backpos.ga_data;
- for (i = 0; i < backpos.ga_len; ++i)
- if (bp[i].bp_scan == scan)
- break;
- if (i == backpos.ga_len) {
- backpos_T *p = GA_APPEND_VIA_PTR(backpos_T, &backpos);
- p->bp_scan = scan;
- } else if (reg_save_equal(&bp[i].bp_pos))
- /* Still at same position as last time, fail. */
- status = RA_NOMATCH;
-
- assert(status != RA_FAIL);
- if (status != RA_NOMATCH) {
- reg_save(&bp[i].bp_pos, &backpos);
- }
- }
- break;
-
- case MOPEN + 0: /* Match start: \zs */
- case MOPEN + 1: /* \( */
- case MOPEN + 2:
- case MOPEN + 3:
- case MOPEN + 4:
- case MOPEN + 5:
- case MOPEN + 6:
- case MOPEN + 7:
- case MOPEN + 8:
- case MOPEN + 9:
- {
- no = op - MOPEN;
- cleanup_subexpr();
- rp = regstack_push(RS_MOPEN, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else {
- rp->rs_no = no;
- save_se(&rp->rs_un.sesave, &rex.reg_startpos[no],
- &rex.reg_startp[no]);
- // We simply continue and handle the result when done.
- }
- }
- break;
-
- case NOPEN: /* \%( */
- case NCLOSE: /* \) after \%( */
- if (regstack_push(RS_NOPEN, scan) == NULL)
- status = RA_FAIL;
- /* We simply continue and handle the result when done. */
- break;
-
- case ZOPEN + 1:
- case ZOPEN + 2:
- case ZOPEN + 3:
- case ZOPEN + 4:
- case ZOPEN + 5:
- case ZOPEN + 6:
- case ZOPEN + 7:
- case ZOPEN + 8:
- case ZOPEN + 9:
- {
- no = op - ZOPEN;
- cleanup_zsubexpr();
- rp = regstack_push(RS_ZOPEN, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else {
- rp->rs_no = no;
- save_se(&rp->rs_un.sesave, &reg_startzpos[no],
- &reg_startzp[no]);
- /* We simply continue and handle the result when done. */
- }
- }
- break;
-
- case MCLOSE + 0: /* Match end: \ze */
- case MCLOSE + 1: /* \) */
- case MCLOSE + 2:
- case MCLOSE + 3:
- case MCLOSE + 4:
- case MCLOSE + 5:
- case MCLOSE + 6:
- case MCLOSE + 7:
- case MCLOSE + 8:
- case MCLOSE + 9:
- {
- no = op - MCLOSE;
- cleanup_subexpr();
- rp = regstack_push(RS_MCLOSE, scan);
- if (rp == NULL) {
- status = RA_FAIL;
- } else {
- rp->rs_no = no;
- save_se(&rp->rs_un.sesave, &rex.reg_endpos[no], &rex.reg_endp[no]);
- // We simply continue and handle the result when done.
- }
- }
- break;
-
- case ZCLOSE + 1: /* \) after \z( */
- case ZCLOSE + 2:
- case ZCLOSE + 3:
- case ZCLOSE + 4:
- case ZCLOSE + 5:
- case ZCLOSE + 6:
- case ZCLOSE + 7:
- case ZCLOSE + 8:
- case ZCLOSE + 9:
- {
- no = op - ZCLOSE;
- cleanup_zsubexpr();
- rp = regstack_push(RS_ZCLOSE, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else {
- rp->rs_no = no;
- save_se(&rp->rs_un.sesave, &reg_endzpos[no],
- &reg_endzp[no]);
- /* We simply continue and handle the result when done. */
- }
- }
- break;
-
- case BACKREF + 1:
- case BACKREF + 2:
- case BACKREF + 3:
- case BACKREF + 4:
- case BACKREF + 5:
- case BACKREF + 6:
- case BACKREF + 7:
- case BACKREF + 8:
- case BACKREF + 9:
- {
- int len;
-
- no = op - BACKREF;
- cleanup_subexpr();
- if (!REG_MULTI) { // Single-line regexp
- if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL) {
- // Backref was not set: Match an empty string.
- len = 0;
- } else {
- // Compare current input with back-ref in the same line.
- len = (int)(rex.reg_endp[no] - rex.reg_startp[no]);
- if (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0) {
- status = RA_NOMATCH;
- }
- }
- } else { // Multi-line regexp
- if (rex.reg_startpos[no].lnum < 0 || rex.reg_endpos[no].lnum < 0) {
- // Backref was not set: Match an empty string.
- len = 0;
- } else {
- if (rex.reg_startpos[no].lnum == rex.lnum
- && rex.reg_endpos[no].lnum == rex.lnum) {
- // Compare back-ref within the current line.
- len = rex.reg_endpos[no].col - rex.reg_startpos[no].col;
- if (cstrncmp(rex.line + rex.reg_startpos[no].col,
- rex.input, &len) != 0) {
- status = RA_NOMATCH;
- }
- } else {
- // Messy situation: Need to compare between two lines.
- int r = match_with_backref(rex.reg_startpos[no].lnum,
- rex.reg_startpos[no].col,
- rex.reg_endpos[no].lnum,
- rex.reg_endpos[no].col,
- &len);
- if (r != RA_MATCH) {
- status = r;
- }
- }
- }
- }
-
- // Matched the backref, skip over it.
- rex.input += len;
- }
- break;
-
- case ZREF + 1:
- case ZREF + 2:
- case ZREF + 3:
- case ZREF + 4:
- case ZREF + 5:
- case ZREF + 6:
- case ZREF + 7:
- case ZREF + 8:
- case ZREF + 9:
- {
- cleanup_zsubexpr();
- no = op - ZREF;
- if (re_extmatch_in != NULL
- && re_extmatch_in->matches[no] != NULL) {
- int len = (int)STRLEN(re_extmatch_in->matches[no]);
- if (cstrncmp(re_extmatch_in->matches[no], rex.input, &len) != 0) {
- status = RA_NOMATCH;
- } else {
- rex.input += len;
- }
- } else {
- // Backref was not set: Match an empty string.
- }
- }
- break;
-
- case BRANCH:
- {
- if (OP(next) != BRANCH) /* No choice. */
- next = OPERAND(scan); /* Avoid recursion. */
- else {
- rp = regstack_push(RS_BRANCH, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else
- status = RA_BREAK; /* rest is below */
- }
- }
- break;
-
- case BRACE_LIMITS:
- {
- if (OP(next) == BRACE_SIMPLE) {
- bl_minval = OPERAND_MIN(scan);
- bl_maxval = OPERAND_MAX(scan);
- } else if (OP(next) >= BRACE_COMPLEX
- && OP(next) < BRACE_COMPLEX + 10) {
- no = OP(next) - BRACE_COMPLEX;
- brace_min[no] = OPERAND_MIN(scan);
- brace_max[no] = OPERAND_MAX(scan);
- brace_count[no] = 0;
- } else {
- internal_error("BRACE_LIMITS");
- status = RA_FAIL;
- }
- }
- break;
-
- case BRACE_COMPLEX + 0:
- case BRACE_COMPLEX + 1:
- case BRACE_COMPLEX + 2:
- case BRACE_COMPLEX + 3:
- case BRACE_COMPLEX + 4:
- case BRACE_COMPLEX + 5:
- case BRACE_COMPLEX + 6:
- case BRACE_COMPLEX + 7:
- case BRACE_COMPLEX + 8:
- case BRACE_COMPLEX + 9:
- {
- no = op - BRACE_COMPLEX;
- ++brace_count[no];
-
- /* If not matched enough times yet, try one more */
- if (brace_count[no] <= (brace_min[no] <= brace_max[no]
- ? brace_min[no] : brace_max[no])) {
- rp = regstack_push(RS_BRCPLX_MORE, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else {
- rp->rs_no = no;
- reg_save(&rp->rs_un.regsave, &backpos);
- next = OPERAND(scan);
- /* We continue and handle the result when done. */
- }
- break;
- }
-
- /* If matched enough times, may try matching some more */
- if (brace_min[no] <= brace_max[no]) {
- /* Range is the normal way around, use longest match */
- if (brace_count[no] <= brace_max[no]) {
- rp = regstack_push(RS_BRCPLX_LONG, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else {
- rp->rs_no = no;
- reg_save(&rp->rs_un.regsave, &backpos);
- next = OPERAND(scan);
- /* We continue and handle the result when done. */
- }
- }
- } else {
- /* Range is backwards, use shortest match first */
- if (brace_count[no] <= brace_min[no]) {
- rp = regstack_push(RS_BRCPLX_SHORT, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else {
- reg_save(&rp->rs_un.regsave, &backpos);
- /* We continue and handle the result when done. */
- }
- }
- }
- }
- break;
-
- case BRACE_SIMPLE:
- case STAR:
- case PLUS:
- {
- regstar_T rst;
-
- /*
- * Lookahead to avoid useless match attempts when we know
- * what character comes next.
- */
- if (OP(next) == EXACTLY) {
- rst.nextb = *OPERAND(next);
- if (rex.reg_ic) {
- if (mb_isupper(rst.nextb)) {
- rst.nextb_ic = mb_tolower(rst.nextb);
- } else {
- rst.nextb_ic = mb_toupper(rst.nextb);
- }
- } else {
- rst.nextb_ic = rst.nextb;
- }
- } else {
- rst.nextb = NUL;
- rst.nextb_ic = NUL;
- }
- if (op != BRACE_SIMPLE) {
- rst.minval = (op == STAR) ? 0 : 1;
- rst.maxval = MAX_LIMIT;
- } else {
- rst.minval = bl_minval;
- rst.maxval = bl_maxval;
- }
-
- /*
- * When maxval > minval, try matching as much as possible, up
- * to maxval. When maxval < minval, try matching at least the
- * minimal number (since the range is backwards, that's also
- * maxval!).
- */
- rst.count = regrepeat(OPERAND(scan), rst.maxval);
- if (got_int) {
- status = RA_FAIL;
- break;
- }
- if (rst.minval <= rst.maxval
- ? rst.count >= rst.minval : rst.count >= rst.maxval) {
- /* It could match. Prepare for trying to match what
- * follows. The code is below. Parameters are stored in
- * a regstar_T on the regstack. */
- if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) {
- emsg(_(e_maxmempat));
- status = RA_FAIL;
- } else {
- ga_grow(&regstack, sizeof(regstar_T));
- regstack.ga_len += sizeof(regstar_T);
- rp = regstack_push(rst.minval <= rst.maxval
- ? RS_STAR_LONG : RS_STAR_SHORT, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else {
- *(((regstar_T *)rp) - 1) = rst;
- status = RA_BREAK; /* skip the restore bits */
- }
- }
- } else
- status = RA_NOMATCH;
-
- }
- break;
-
- case NOMATCH:
- case MATCH:
- case SUBPAT:
- rp = regstack_push(RS_NOMATCH, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else {
- rp->rs_no = op;
- reg_save(&rp->rs_un.regsave, &backpos);
- next = OPERAND(scan);
- /* We continue and handle the result when done. */
- }
- break;
-
- case BEHIND:
- case NOBEHIND:
- /* Need a bit of room to store extra positions. */
- if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) {
- emsg(_(e_maxmempat));
- status = RA_FAIL;
- } else {
- ga_grow(&regstack, sizeof(regbehind_T));
- regstack.ga_len += sizeof(regbehind_T);
- rp = regstack_push(RS_BEHIND1, scan);
- if (rp == NULL)
- status = RA_FAIL;
- else {
- /* Need to save the subexpr to be able to restore them
- * when there is a match but we don't use it. */
- save_subexpr(((regbehind_T *)rp) - 1);
-
- rp->rs_no = op;
- reg_save(&rp->rs_un.regsave, &backpos);
- /* First try if what follows matches. If it does then we
- * check the behind match by looping. */
- }
- }
- break;
-
- case BHPOS:
- if (REG_MULTI) {
- if (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line)
- || behind_pos.rs_u.pos.lnum != rex.lnum) {
- status = RA_NOMATCH;
- }
- } else if (behind_pos.rs_u.ptr != rex.input) {
- status = RA_NOMATCH;
- }
- break;
-
- case NEWL:
- if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline
- || rex.reg_line_lbr) && (c != '\n' || !rex.reg_line_lbr)) {
- status = RA_NOMATCH;
- } else if (rex.reg_line_lbr) {
- ADVANCE_REGINPUT();
- } else {
- reg_nextline();
- }
- break;
-
- case END:
- status = RA_MATCH; /* Success! */
- break;
-
- default:
- iemsg(_(e_re_corr));
-#ifdef REGEXP_DEBUG
- printf("Illegal op code %d\n", op);
-#endif
- status = RA_FAIL;
- break;
- }
- }
-
- /* If we can't continue sequentially, break the inner loop. */
- if (status != RA_CONT)
- break;
-
- /* Continue in inner loop, advance to next item. */
- scan = next;
-
- } /* end of inner loop */
-
- /*
- * If there is something on the regstack execute the code for the state.
- * If the state is popped then loop and use the older state.
- */
- while (!GA_EMPTY(&regstack) && status != RA_FAIL) {
- rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
- switch (rp->rs_state) {
- case RS_NOPEN:
- /* Result is passed on as-is, simply pop the state. */
- regstack_pop(&scan);
- break;
-
- case RS_MOPEN:
- // Pop the state. Restore pointers when there is no match.
- if (status == RA_NOMATCH) {
- restore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no],
- &rex.reg_startp[rp->rs_no]);
- }
- regstack_pop(&scan);
- break;
-
- case RS_ZOPEN:
- /* Pop the state. Restore pointers when there is no match. */
- if (status == RA_NOMATCH)
- restore_se(&rp->rs_un.sesave, &reg_startzpos[rp->rs_no],
- &reg_startzp[rp->rs_no]);
- regstack_pop(&scan);
- break;
-
- case RS_MCLOSE:
- // Pop the state. Restore pointers when there is no match.
- if (status == RA_NOMATCH) {
- restore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no],
- &rex.reg_endp[rp->rs_no]);
- }
- regstack_pop(&scan);
- break;
-
- case RS_ZCLOSE:
- /* Pop the state. Restore pointers when there is no match. */
- if (status == RA_NOMATCH)
- restore_se(&rp->rs_un.sesave, &reg_endzpos[rp->rs_no],
- &reg_endzp[rp->rs_no]);
- regstack_pop(&scan);
- break;
-
- case RS_BRANCH:
- if (status == RA_MATCH)
- /* this branch matched, use it */
- regstack_pop(&scan);
- else {
- if (status != RA_BREAK) {
- /* After a non-matching branch: try next one. */
- reg_restore(&rp->rs_un.regsave, &backpos);
- scan = rp->rs_scan;
- }
- if (scan == NULL || OP(scan) != BRANCH) {
- /* no more branches, didn't find a match */
- status = RA_NOMATCH;
- regstack_pop(&scan);
- } else {
- /* Prepare to try a branch. */
- rp->rs_scan = regnext(scan);
- reg_save(&rp->rs_un.regsave, &backpos);
- scan = OPERAND(scan);
- }
- }
- break;
-
- case RS_BRCPLX_MORE:
- /* Pop the state. Restore pointers when there is no match. */
- if (status == RA_NOMATCH) {
- reg_restore(&rp->rs_un.regsave, &backpos);
- --brace_count[rp->rs_no]; /* decrement match count */
- }
- regstack_pop(&scan);
- break;
-
- case RS_BRCPLX_LONG:
- /* Pop the state. Restore pointers when there is no match. */
- if (status == RA_NOMATCH) {
- /* There was no match, but we did find enough matches. */
- reg_restore(&rp->rs_un.regsave, &backpos);
- --brace_count[rp->rs_no];
- /* continue with the items after "\{}" */
- status = RA_CONT;
- }
- regstack_pop(&scan);
- if (status == RA_CONT)
- scan = regnext(scan);
- break;
-
- case RS_BRCPLX_SHORT:
- /* Pop the state. Restore pointers when there is no match. */
- if (status == RA_NOMATCH)
- /* There was no match, try to match one more item. */
- reg_restore(&rp->rs_un.regsave, &backpos);
- regstack_pop(&scan);
- if (status == RA_NOMATCH) {
- scan = OPERAND(scan);
- status = RA_CONT;
- }
- break;
-
- case RS_NOMATCH:
- /* Pop the state. If the operand matches for NOMATCH or
- * doesn't match for MATCH/SUBPAT, we fail. Otherwise backup,
- * except for SUBPAT, and continue with the next item. */
- if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH))
- status = RA_NOMATCH;
- else {
- status = RA_CONT;
- if (rp->rs_no != SUBPAT) /* zero-width */
- reg_restore(&rp->rs_un.regsave, &backpos);
- }
- regstack_pop(&scan);
- if (status == RA_CONT)
- scan = regnext(scan);
- break;
-
- case RS_BEHIND1:
- if (status == RA_NOMATCH) {
- regstack_pop(&scan);
- regstack.ga_len -= sizeof(regbehind_T);
- } else {
- /* The stuff after BEHIND/NOBEHIND matches. Now try if
- * the behind part does (not) match before the current
- * position in the input. This must be done at every
- * position in the input and checking if the match ends at
- * the current position. */
-
- /* save the position after the found match for next */
- reg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos);
-
- /* Start looking for a match with operand at the current
- * position. Go back one character until we find the
- * result, hitting the start of the line or the previous
- * line (for multi-line matching).
- * Set behind_pos to where the match should end, BHPOS
- * will match it. Save the current value. */
- (((regbehind_T *)rp) - 1)->save_behind = behind_pos;
- behind_pos = rp->rs_un.regsave;
-
- rp->rs_state = RS_BEHIND2;
-
- reg_restore(&rp->rs_un.regsave, &backpos);
- scan = OPERAND(rp->rs_scan) + 4;
- }
- break;
-
- case RS_BEHIND2:
- /*
- * Looping for BEHIND / NOBEHIND match.
- */
- if (status == RA_MATCH && reg_save_equal(&behind_pos)) {
- /* found a match that ends where "next" started */
- behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
- if (rp->rs_no == BEHIND)
- reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
- &backpos);
- else {
- /* But we didn't want a match. Need to restore the
- * subexpr, because what follows matched, so they have
- * been set. */
- status = RA_NOMATCH;
- restore_subexpr(((regbehind_T *)rp) - 1);
- }
- regstack_pop(&scan);
- regstack.ga_len -= sizeof(regbehind_T);
- } else {
- long limit;
-
- /* No match or a match that doesn't end where we want it: Go
- * back one character. May go to previous line once. */
- no = OK;
- limit = OPERAND_MIN(rp->rs_scan);
- if (REG_MULTI) {
- if (limit > 0
- && ((rp->rs_un.regsave.rs_u.pos.lnum
- < behind_pos.rs_u.pos.lnum
- ? (colnr_T)STRLEN(rex.line)
- : behind_pos.rs_u.pos.col)
- - rp->rs_un.regsave.rs_u.pos.col >= limit))
- no = FAIL;
- else if (rp->rs_un.regsave.rs_u.pos.col == 0) {
- if (rp->rs_un.regsave.rs_u.pos.lnum
- < behind_pos.rs_u.pos.lnum
- || reg_getline(
- --rp->rs_un.regsave.rs_u.pos.lnum)
- == NULL)
- no = FAIL;
- else {
- reg_restore(&rp->rs_un.regsave, &backpos);
- rp->rs_un.regsave.rs_u.pos.col =
- (colnr_T)STRLEN(rex.line);
- }
- } else {
- const char_u *const line =
- reg_getline(rp->rs_un.regsave.rs_u.pos.lnum);
-
- rp->rs_un.regsave.rs_u.pos.col -=
- utf_head_off(line,
- line + rp->rs_un.regsave.rs_u.pos.col - 1)
- + 1;
- }
- } else {
- if (rp->rs_un.regsave.rs_u.ptr == rex.line) {
- no = FAIL;
- } else {
- MB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr);
- if (limit > 0
- && (long)(behind_pos.rs_u.ptr
- - rp->rs_un.regsave.rs_u.ptr) > limit) {
- no = FAIL;
- }
- }
- }
- if (no == OK) {
- /* Advanced, prepare for finding match again. */
- reg_restore(&rp->rs_un.regsave, &backpos);
- scan = OPERAND(rp->rs_scan) + 4;
- if (status == RA_MATCH) {
- /* We did match, so subexpr may have been changed,
- * need to restore them for the next try. */
- status = RA_NOMATCH;
- restore_subexpr(((regbehind_T *)rp) - 1);
- }
- } else {
- /* Can't advance. For NOBEHIND that's a match. */
- behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
- if (rp->rs_no == NOBEHIND) {
- reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
- &backpos);
- status = RA_MATCH;
- } else {
- /* We do want a proper match. Need to restore the
- * subexpr if we had a match, because they may have
- * been set. */
- if (status == RA_MATCH) {
- status = RA_NOMATCH;
- restore_subexpr(((regbehind_T *)rp) - 1);
- }
- }
- regstack_pop(&scan);
- regstack.ga_len -= sizeof(regbehind_T);
- }
- }
- break;
-
- case RS_STAR_LONG:
- case RS_STAR_SHORT:
- {
- regstar_T *rst = ((regstar_T *)rp) - 1;
-
- if (status == RA_MATCH) {
- regstack_pop(&scan);
- regstack.ga_len -= sizeof(regstar_T);
- break;
- }
-
- /* Tried once already, restore input pointers. */
- if (status != RA_BREAK)
- reg_restore(&rp->rs_un.regsave, &backpos);
-
- /* Repeat until we found a position where it could match. */
- for (;; ) {
- if (status != RA_BREAK) {
- /* Tried first position already, advance. */
- if (rp->rs_state == RS_STAR_LONG) {
- /* Trying for longest match, but couldn't or
- * didn't match -- back up one char. */
- if (--rst->count < rst->minval)
- break;
- if (rex.input == rex.line) {
- // backup to last char of previous line
- rex.lnum--;
- rex.line = reg_getline(rex.lnum);
- // Just in case regrepeat() didn't count right.
- if (rex.line == NULL) {
- break;
- }
- rex.input = rex.line + STRLEN(rex.line);
- fast_breakcheck();
- } else {
- MB_PTR_BACK(rex.line, rex.input);
- }
- } else {
- /* Range is backwards, use shortest match first.
- * Careful: maxval and minval are exchanged!
- * Couldn't or didn't match: try advancing one
- * char. */
- if (rst->count == rst->minval
- || regrepeat(OPERAND(rp->rs_scan), 1L) == 0)
- break;
- ++rst->count;
- }
- if (got_int)
- break;
- } else
- status = RA_NOMATCH;
-
- // If it could match, try it.
- if (rst->nextb == NUL || *rex.input == rst->nextb
- || *rex.input == rst->nextb_ic) {
- reg_save(&rp->rs_un.regsave, &backpos);
- scan = regnext(rp->rs_scan);
- status = RA_CONT;
- break;
- }
- }
- if (status != RA_CONT) {
- /* Failed. */
- regstack_pop(&scan);
- regstack.ga_len -= sizeof(regstar_T);
- status = RA_NOMATCH;
- }
- }
- break;
- }
-
- /* If we want to continue the inner loop or didn't pop a state
- * continue matching loop */
- if (status == RA_CONT || rp == (regitem_T *)
- ((char *)regstack.ga_data + regstack.ga_len) - 1)
- break;
- }
-
- /* May need to continue with the inner loop, starting at "scan". */
- if (status == RA_CONT)
- continue;
-
- /*
- * If the regstack is empty or something failed we are done.
- */
- if (GA_EMPTY(&regstack) || status == RA_FAIL) {
- if (scan == NULL) {
- /*
- * We get here only if there's trouble -- normally "case END" is
- * the terminating point.
- */
- iemsg(_(e_re_corr));
-#ifdef REGEXP_DEBUG
- printf("Premature EOL\n");
-#endif
- }
- return status == RA_MATCH;
- }
-
- } /* End of loop until the regstack is empty. */
-
- /* NOTREACHED */
-}
-
-/*
- * Push an item onto the regstack.
- * Returns pointer to new item. Returns NULL when out of memory.
- */
-static regitem_T *regstack_push(regstate_T state, char_u *scan)
-{
- regitem_T *rp;
-
- if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) {
- emsg(_(e_maxmempat));
- return NULL;
- }
- ga_grow(&regstack, sizeof(regitem_T));
-
- rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len);
- rp->rs_state = state;
- rp->rs_scan = scan;
-
- regstack.ga_len += sizeof(regitem_T);
- return rp;
-}
-
-/*
- * Pop an item from the regstack.
- */
-static void regstack_pop(char_u **scan)
-{
- regitem_T *rp;
-
- rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
- *scan = rp->rs_scan;
-
- regstack.ga_len -= sizeof(regitem_T);
-}
-
-/*
- * regrepeat - repeatedly match something simple, return how many.
- * Advances rex.input (and rex.lnum) to just after the matched chars.
- */
-static int
-regrepeat (
- char_u *p,
- long maxcount /* maximum number of matches allowed */
-)
-{
- long count = 0;
- char_u *opnd;
- int mask;
- int testval = 0;
-
- char_u *scan = rex.input; // Make local copy of rex.input for speed.
- opnd = OPERAND(p);
- switch (OP(p)) {
- case ANY:
- case ANY + ADD_NL:
- while (count < maxcount) {
- /* Matching anything means we continue until end-of-line (or
- * end-of-file for ANY + ADD_NL), only limited by maxcount. */
- while (*scan != NUL && count < maxcount) {
- count++;
- MB_PTR_ADV(scan);
- }
- if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
- || rex.reg_line_lbr || count == maxcount) {
- break;
- }
- count++; // count the line-break
- reg_nextline();
- scan = rex.input;
- if (got_int) {
- break;
- }
- }
- break;
-
- case IDENT:
- case IDENT + ADD_NL:
- testval = 1;
- FALLTHROUGH;
- case SIDENT:
- case SIDENT + ADD_NL:
- while (count < maxcount) {
- if (vim_isIDc(utf_ptr2char(scan)) && (testval || !ascii_isdigit(*scan))) {
- MB_PTR_ADV(scan);
- } else if (*scan == NUL) {
- if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
- || rex.reg_line_lbr) {
- break;
- }
- reg_nextline();
- scan = rex.input;
- if (got_int) {
- break;
- }
- } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
- scan++;
- } else {
- break;
- }
- ++count;
- }
- break;
-
- case KWORD:
- case KWORD + ADD_NL:
- testval = 1;
- FALLTHROUGH;
- case SKWORD:
- case SKWORD + ADD_NL:
- while (count < maxcount) {
- if (vim_iswordp_buf(scan, rex.reg_buf)
- && (testval || !ascii_isdigit(*scan))) {
- MB_PTR_ADV(scan);
- } else if (*scan == NUL) {
- if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
- || rex.reg_line_lbr) {
- break;
- }
- reg_nextline();
- scan = rex.input;
- if (got_int) {
- break;
- }
- } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
- scan++;
- } else {
- break;
- }
- count++;
- }
- break;
-
- case FNAME:
- case FNAME + ADD_NL:
- testval = 1;
- FALLTHROUGH;
- case SFNAME:
- case SFNAME + ADD_NL:
- while (count < maxcount) {
- if (vim_isfilec(utf_ptr2char(scan)) && (testval || !ascii_isdigit(*scan))) {
- MB_PTR_ADV(scan);
- } else if (*scan == NUL) {
- if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
- || rex.reg_line_lbr) {
- break;
- }
- reg_nextline();
- scan = rex.input;
- if (got_int) {
- break;
- }
- } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
- scan++;
- } else {
- break;
- }
- count++;
- }
- break;
-
- case PRINT:
- case PRINT + ADD_NL:
- testval = 1;
- FALLTHROUGH;
- case SPRINT:
- case SPRINT + ADD_NL:
- while (count < maxcount) {
- if (*scan == NUL) {
- if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
- || rex.reg_line_lbr) {
- break;
- }
- reg_nextline();
- scan = rex.input;
- if (got_int) {
- break;
- }
- } else if (vim_isprintc(utf_ptr2char(scan)) == 1
- && (testval || !ascii_isdigit(*scan))) {
- MB_PTR_ADV(scan);
- } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
- scan++;
- } else {
- break;
- }
- count++;
- }
- break;
-
- case WHITE:
- case WHITE + ADD_NL:
- testval = mask = RI_WHITE;
-do_class:
- while (count < maxcount) {
- int l;
- if (*scan == NUL) {
- if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
- || rex.reg_line_lbr) {
- break;
- }
- reg_nextline();
- scan = rex.input;
- if (got_int) {
- break;
- }
- } else if ((l = utfc_ptr2len(scan)) > 1) {
- if (testval != 0) {
- break;
- }
- scan += l;
- } else if ((class_tab[*scan] & mask) == testval) {
- scan++;
- } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
- scan++;
- } else {
- break;
- }
- ++count;
- }
- break;
-
- case NWHITE:
- case NWHITE + ADD_NL:
- mask = RI_WHITE;
- goto do_class;
- case DIGIT:
- case DIGIT + ADD_NL:
- testval = mask = RI_DIGIT;
- goto do_class;
- case NDIGIT:
- case NDIGIT + ADD_NL:
- mask = RI_DIGIT;
- goto do_class;
- case HEX:
- case HEX + ADD_NL:
- testval = mask = RI_HEX;
- goto do_class;
- case NHEX:
- case NHEX + ADD_NL:
- mask = RI_HEX;
- goto do_class;
- case OCTAL:
- case OCTAL + ADD_NL:
- testval = mask = RI_OCTAL;
- goto do_class;
- case NOCTAL:
- case NOCTAL + ADD_NL:
- mask = RI_OCTAL;
- goto do_class;
- case WORD:
- case WORD + ADD_NL:
- testval = mask = RI_WORD;
- goto do_class;
- case NWORD:
- case NWORD + ADD_NL:
- mask = RI_WORD;
- goto do_class;
- case HEAD:
- case HEAD + ADD_NL:
- testval = mask = RI_HEAD;
- goto do_class;
- case NHEAD:
- case NHEAD + ADD_NL:
- mask = RI_HEAD;
- goto do_class;
- case ALPHA:
- case ALPHA + ADD_NL:
- testval = mask = RI_ALPHA;
- goto do_class;
- case NALPHA:
- case NALPHA + ADD_NL:
- mask = RI_ALPHA;
- goto do_class;
- case LOWER:
- case LOWER + ADD_NL:
- testval = mask = RI_LOWER;
- goto do_class;
- case NLOWER:
- case NLOWER + ADD_NL:
- mask = RI_LOWER;
- goto do_class;
- case UPPER:
- case UPPER + ADD_NL:
- testval = mask = RI_UPPER;
- goto do_class;
- case NUPPER:
- case NUPPER + ADD_NL:
- mask = RI_UPPER;
- goto do_class;
-
- case EXACTLY:
- {
- int cu, cl;
-
- // This doesn't do a multi-byte character, because a MULTIBYTECODE
- // would have been used for it. It does handle single-byte
- // characters, such as latin1.
- if (rex.reg_ic) {
- cu = mb_toupper(*opnd);
- cl = mb_tolower(*opnd);
- while (count < maxcount && (*scan == cu || *scan == cl)) {
- count++;
- scan++;
- }
- } else {
- cu = *opnd;
- while (count < maxcount && *scan == cu) {
- count++;
- scan++;
- }
- }
- break;
- }
-
- case MULTIBYTECODE:
- {
- int i, len, cf = 0;
-
- /* Safety check (just in case 'encoding' was changed since
- * compiling the program). */
- if ((len = utfc_ptr2len(opnd)) > 1) {
- if (rex.reg_ic) {
- cf = utf_fold(utf_ptr2char(opnd));
- }
- while (count < maxcount && utfc_ptr2len(scan) >= len) {
- for (i = 0; i < len; i++) {
- if (opnd[i] != scan[i]) {
- break;
- }
- }
- if (i < len && (!rex.reg_ic
- || utf_fold(utf_ptr2char(scan)) != cf)) {
- break;
- }
- scan += len;
- ++count;
- }
- }
- }
- break;
-
- case ANYOF:
- case ANYOF + ADD_NL:
- testval = 1;
- FALLTHROUGH;
-
- case ANYBUT:
- case ANYBUT + ADD_NL:
- while (count < maxcount) {
- int len;
- if (*scan == NUL) {
- if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
- || rex.reg_line_lbr) {
- break;
- }
- reg_nextline();
- scan = rex.input;
- if (got_int) {
- break;
- }
- } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
- scan++;
- } else if ((len = utfc_ptr2len(scan)) > 1) {
- if ((cstrchr(opnd, utf_ptr2char(scan)) == NULL) == testval) {
- break;
- }
- scan += len;
- } else {
- if ((cstrchr(opnd, *scan) == NULL) == testval)
- break;
- ++scan;
- }
- ++count;
- }
- break;
-
- case NEWL:
- while (count < maxcount
- && ((*scan == NUL && rex.lnum <= rex.reg_maxline && !rex.reg_line_lbr
- && REG_MULTI) || (*scan == '\n' && rex.reg_line_lbr))) {
- count++;
- if (rex.reg_line_lbr) {
- ADVANCE_REGINPUT();
- } else {
- reg_nextline();
- }
- scan = rex.input;
- if (got_int) {
- break;
- }
- }
- break;
-
- default: // Oh dear. Called inappropriately.
- iemsg(_(e_re_corr));
-#ifdef REGEXP_DEBUG
- printf("Called regrepeat with op code %d\n", OP(p));
-#endif
- break;
- }
-
- rex.input = scan;
-
- return (int)count;
-}
-
-/*
- * regnext - dig the "next" pointer out of a node
- * Returns NULL when calculating size, when there is no next item and when
- * there is an error.
- */
-static char_u *regnext(char_u *p)
- FUNC_ATTR_NONNULL_ALL
-{
- int offset;
-
- if (p == JUST_CALC_SIZE || reg_toolong)
- return NULL;
-
- offset = NEXT(p);
- if (offset == 0)
- return NULL;
-
- if (OP(p) == BACK)
- return p - offset;
- else
- return p + offset;
-}
-
/*
* Check the regexp program for its magic number.
* Return true if it's wrong.
@@ -5659,7 +1212,7 @@ static void cleanup_zsubexpr(void)
{
if (rex.need_clear_zsubexpr) {
if (REG_MULTI) {
- /* Use 0xff to set lnum to -1 */
+ // Use 0xff to set lnum to -1
memset(reg_startzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
memset(reg_endzpos, 0xff, sizeof(lpos_T) * NSUBEXP);
} else {
@@ -5670,45 +1223,6 @@ static void cleanup_zsubexpr(void)
}
}
-// Save the current subexpr to "bp", so that they can be restored
-// later by restore_subexpr().
-static void save_subexpr(regbehind_T *bp)
- FUNC_ATTR_NONNULL_ALL
-{
- // When "rex.need_clear_subexpr" is set we don't need to save the values, only
- // remember that this flag needs to be set again when restoring.
- bp->save_need_clear_subexpr = rex.need_clear_subexpr;
- if (!rex.need_clear_subexpr) {
- for (int i = 0; i < NSUBEXP; i++) {
- if (REG_MULTI) {
- bp->save_start[i].se_u.pos = rex.reg_startpos[i];
- bp->save_end[i].se_u.pos = rex.reg_endpos[i];
- } else {
- bp->save_start[i].se_u.ptr = rex.reg_startp[i];
- bp->save_end[i].se_u.ptr = rex.reg_endp[i];
- }
- }
- }
-}
-
-// Restore the subexpr from "bp".
-static void restore_subexpr(regbehind_T *bp)
- FUNC_ATTR_NONNULL_ALL
-{
- // Only need to restore saved values when they are not to be cleared.
- rex.need_clear_subexpr = bp->save_need_clear_subexpr;
- if (!rex.need_clear_subexpr) {
- for (int i = 0; i < NSUBEXP; i++) {
- if (REG_MULTI) {
- rex.reg_startpos[i] = bp->save_start[i].se_u.pos;
- rex.reg_endpos[i] = bp->save_end[i].se_u.pos;
- } else {
- rex.reg_startp[i] = bp->save_start[i].se_u.ptr;
- rex.reg_endp[i] = bp->save_end[i].se_u.ptr;
- }
- }
- }
-}
// Advance rex.lnum, rex.line and rex.input to the next line.
static void reg_nextline(void)
@@ -5718,81 +1232,6 @@ static void reg_nextline(void)
fast_breakcheck();
}
-// Save the input line and position in a regsave_T.
-static void reg_save(regsave_T *save, garray_T *gap)
- FUNC_ATTR_NONNULL_ALL
-{
- if (REG_MULTI) {
- save->rs_u.pos.col = (colnr_T)(rex.input - rex.line);
- save->rs_u.pos.lnum = rex.lnum;
- } else {
- save->rs_u.ptr = rex.input;
- }
- save->rs_len = gap->ga_len;
-}
-
-// Restore the input line and position from a regsave_T.
-static void reg_restore(regsave_T *save, garray_T *gap)
- FUNC_ATTR_NONNULL_ALL
-{
- if (REG_MULTI) {
- if (rex.lnum != save->rs_u.pos.lnum) {
- // only call reg_getline() when the line number changed to save
- // a bit of time
- rex.lnum = save->rs_u.pos.lnum;
- rex.line = reg_getline(rex.lnum);
- }
- rex.input = rex.line + save->rs_u.pos.col;
- } else {
- rex.input = save->rs_u.ptr;
- }
- gap->ga_len = save->rs_len;
-}
-
-// Return true if current position is equal to saved position.
-static bool reg_save_equal(const regsave_T *save)
- FUNC_ATTR_NONNULL_ALL
-{
- if (REG_MULTI) {
- return rex.lnum == save->rs_u.pos.lnum
- && rex.input == rex.line + save->rs_u.pos.col;
- }
- return rex.input == save->rs_u.ptr;
-}
-
-/*
- * Tentatively set the sub-expression start to the current position (after
- * calling regmatch() they will have changed). Need to save the existing
- * values for when there is no match.
- * Use se_save() to use pointer (save_se_multi()) or position (save_se_one()),
- * depending on REG_MULTI.
- */
-static void save_se_multi(save_se_T *savep, lpos_T *posp)
-{
- savep->se_u.pos = *posp;
- posp->lnum = rex.lnum;
- posp->col = (colnr_T)(rex.input - rex.line);
-}
-
-static void save_se_one(save_se_T *savep, char_u **pp)
-{
- savep->se_u.ptr = *pp;
- *pp = rex.input;
-}
-
-/*
- * Compare a number with the operand of RE_LNUM, RE_COL or RE_VCOL.
- */
-static int re_num_cmp(uint32_t val, char_u *scan)
-{
- uint32_t n = (uint32_t)OPERAND_MIN(scan);
-
- if (OPERAND_CMP(scan) == '>')
- return val > n;
- if (OPERAND_CMP(scan) == '<')
- return val < n;
- return val == n;
-}
/*
* Check whether a backreference matches.
@@ -5800,7 +1239,12 @@ static int re_num_cmp(uint32_t val, char_u *scan)
* If "bytelen" is not NULL, it is set to the byte length of the match in the
* last line.
*/
-static int match_with_backref(linenr_T start_lnum, colnr_T start_col, linenr_T end_lnum, colnr_T end_col, int *bytelen)
+static int match_with_backref(
+ linenr_T start_lnum,
+ colnr_T start_col,
+ linenr_T end_lnum,
+ colnr_T end_col,
+ int *bytelen)
{
linenr_T clnum = start_lnum;
colnr_T ccol = start_col;
@@ -5815,7 +1259,7 @@ static int match_with_backref(linenr_T start_lnum, colnr_T start_col, linenr_T e
if (rex.line != reg_tofree) {
len = (int)STRLEN(rex.line);
if (reg_tofree == NULL || len >= (int)reg_tofreelen) {
- len += 50; /* get some extra */
+ len += 50; // get some extra
xfree(reg_tofree);
reg_tofree = xmalloc(len);
reg_tofreelen = len;
@@ -5825,7 +1269,7 @@ static int match_with_backref(linenr_T start_lnum, colnr_T start_col, linenr_T e
rex.line = reg_tofree;
}
- /* Get the line to compare with. */
+ // Get the line to compare with.
p = reg_getline(clnum);
assert(p);
@@ -5847,7 +1291,7 @@ static int match_with_backref(linenr_T start_lnum, colnr_T start_col, linenr_T e
return RA_NOMATCH; // text too short
}
- /* Advance to next line. */
+ // Advance to next line.
reg_nextline();
if (bytelen != NULL)
*bytelen = 0;
@@ -5862,520 +1306,72 @@ static int match_with_backref(linenr_T start_lnum, colnr_T start_col, linenr_T e
return RA_MATCH;
}
-#ifdef BT_REGEXP_DUMP
-
-/*
- * regdump - dump a regexp onto stdout in vaguely comprehensible form
- */
-static void regdump(char_u *pattern, bt_regprog_T *r)
-{
- char_u *s;
- int op = EXACTLY; /* Arbitrary non-END op. */
- char_u *next;
- char_u *end = NULL;
- FILE *f;
-
-#ifdef BT_REGEXP_LOG
- f = fopen("bt_regexp_log.log", "a");
-#else
- f = stdout;
-#endif
- if (f == NULL)
- return;
- fprintf(f, "-------------------------------------\n\r\nregcomp(%s):\r\n",
- pattern);
-
- s = r->program + 1;
- /*
- * Loop until we find the END that isn't before a referred next (an END
- * can also appear in a NOMATCH operand).
- */
- while (op != END || s <= end) {
- op = OP(s);
- fprintf(f, "%2d%s", (int)(s - r->program), regprop(s)); /* Where, what. */
- next = regnext(s);
- if (next == NULL) /* Next ptr. */
- fprintf(f, "(0)");
- else
- fprintf(f, "(%d)", (int)((s - r->program) + (next - s)));
- if (end < next)
- end = next;
- if (op == BRACE_LIMITS) {
- /* Two ints */
- fprintf(f, " minval %" PRId64 ", maxval %" PRId64,
- (int64_t)OPERAND_MIN(s), (int64_t)OPERAND_MAX(s));
- s += 8;
- } else if (op == BEHIND || op == NOBEHIND) {
- /* one int */
- fprintf(f, " count %" PRId64, (int64_t)OPERAND_MIN(s));
- s += 4;
- } else if (op == RE_LNUM || op == RE_COL || op == RE_VCOL) {
- // one int plus comparator
- fprintf(f, " count %" PRId64, (int64_t)OPERAND_MIN(s));
- s += 5;
- }
- s += 3;
- if (op == ANYOF || op == ANYOF + ADD_NL
- || op == ANYBUT || op == ANYBUT + ADD_NL
- || op == EXACTLY) {
- /* Literal string, where present. */
- fprintf(f, "\nxxxxxxxxx\n");
- while (*s != NUL)
- fprintf(f, "%c", *s++);
- fprintf(f, "\nxxxxxxxxx\n");
- s++;
- }
- fprintf(f, "\r\n");
- }
-
- /* Header fields of interest. */
- if (r->regstart != NUL)
- fprintf(f, "start `%s' 0x%x; ", r->regstart < 256
- ? (char *)transchar(r->regstart)
- : "multibyte", r->regstart);
- if (r->reganch)
- fprintf(f, "anchored; ");
- if (r->regmust != NULL)
- fprintf(f, "must have \"%s\"", r->regmust);
- fprintf(f, "\r\n");
-
-#ifdef BT_REGEXP_LOG
- fclose(f);
-#endif
-}
-#endif /* BT_REGEXP_DUMP */
-
-#ifdef REGEXP_DEBUG
-/*
- * regprop - printable representation of opcode
- */
-static char_u *regprop(char_u *op)
+/// Used in a place where no * or \+ can follow.
+static bool re_mult_next(char *what)
{
- char *p;
- static char buf[50];
-
- STRCPY(buf, ":");
-
- switch ((int) OP(op)) {
- case BOL:
- p = "BOL";
- break;
- case EOL:
- p = "EOL";
- break;
- case RE_BOF:
- p = "BOF";
- break;
- case RE_EOF:
- p = "EOF";
- break;
- case CURSOR:
- p = "CURSOR";
- break;
- case RE_VISUAL:
- p = "RE_VISUAL";
- break;
- case RE_LNUM:
- p = "RE_LNUM";
- break;
- case RE_MARK:
- p = "RE_MARK";
- break;
- case RE_COL:
- p = "RE_COL";
- break;
- case RE_VCOL:
- p = "RE_VCOL";
- break;
- case BOW:
- p = "BOW";
- break;
- case EOW:
- p = "EOW";
- break;
- case ANY:
- p = "ANY";
- break;
- case ANY + ADD_NL:
- p = "ANY+NL";
- break;
- case ANYOF:
- p = "ANYOF";
- break;
- case ANYOF + ADD_NL:
- p = "ANYOF+NL";
- break;
- case ANYBUT:
- p = "ANYBUT";
- break;
- case ANYBUT + ADD_NL:
- p = "ANYBUT+NL";
- break;
- case IDENT:
- p = "IDENT";
- break;
- case IDENT + ADD_NL:
- p = "IDENT+NL";
- break;
- case SIDENT:
- p = "SIDENT";
- break;
- case SIDENT + ADD_NL:
- p = "SIDENT+NL";
- break;
- case KWORD:
- p = "KWORD";
- break;
- case KWORD + ADD_NL:
- p = "KWORD+NL";
- break;
- case SKWORD:
- p = "SKWORD";
- break;
- case SKWORD + ADD_NL:
- p = "SKWORD+NL";
- break;
- case FNAME:
- p = "FNAME";
- break;
- case FNAME + ADD_NL:
- p = "FNAME+NL";
- break;
- case SFNAME:
- p = "SFNAME";
- break;
- case SFNAME + ADD_NL:
- p = "SFNAME+NL";
- break;
- case PRINT:
- p = "PRINT";
- break;
- case PRINT + ADD_NL:
- p = "PRINT+NL";
- break;
- case SPRINT:
- p = "SPRINT";
- break;
- case SPRINT + ADD_NL:
- p = "SPRINT+NL";
- break;
- case WHITE:
- p = "WHITE";
- break;
- case WHITE + ADD_NL:
- p = "WHITE+NL";
- break;
- case NWHITE:
- p = "NWHITE";
- break;
- case NWHITE + ADD_NL:
- p = "NWHITE+NL";
- break;
- case DIGIT:
- p = "DIGIT";
- break;
- case DIGIT + ADD_NL:
- p = "DIGIT+NL";
- break;
- case NDIGIT:
- p = "NDIGIT";
- break;
- case NDIGIT + ADD_NL:
- p = "NDIGIT+NL";
- break;
- case HEX:
- p = "HEX";
- break;
- case HEX + ADD_NL:
- p = "HEX+NL";
- break;
- case NHEX:
- p = "NHEX";
- break;
- case NHEX + ADD_NL:
- p = "NHEX+NL";
- break;
- case OCTAL:
- p = "OCTAL";
- break;
- case OCTAL + ADD_NL:
- p = "OCTAL+NL";
- break;
- case NOCTAL:
- p = "NOCTAL";
- break;
- case NOCTAL + ADD_NL:
- p = "NOCTAL+NL";
- break;
- case WORD:
- p = "WORD";
- break;
- case WORD + ADD_NL:
- p = "WORD+NL";
- break;
- case NWORD:
- p = "NWORD";
- break;
- case NWORD + ADD_NL:
- p = "NWORD+NL";
- break;
- case HEAD:
- p = "HEAD";
- break;
- case HEAD + ADD_NL:
- p = "HEAD+NL";
- break;
- case NHEAD:
- p = "NHEAD";
- break;
- case NHEAD + ADD_NL:
- p = "NHEAD+NL";
- break;
- case ALPHA:
- p = "ALPHA";
- break;
- case ALPHA + ADD_NL:
- p = "ALPHA+NL";
- break;
- case NALPHA:
- p = "NALPHA";
- break;
- case NALPHA + ADD_NL:
- p = "NALPHA+NL";
- break;
- case LOWER:
- p = "LOWER";
- break;
- case LOWER + ADD_NL:
- p = "LOWER+NL";
- break;
- case NLOWER:
- p = "NLOWER";
- break;
- case NLOWER + ADD_NL:
- p = "NLOWER+NL";
- break;
- case UPPER:
- p = "UPPER";
- break;
- case UPPER + ADD_NL:
- p = "UPPER+NL";
- break;
- case NUPPER:
- p = "NUPPER";
- break;
- case NUPPER + ADD_NL:
- p = "NUPPER+NL";
- break;
- case BRANCH:
- p = "BRANCH";
- break;
- case EXACTLY:
- p = "EXACTLY";
- break;
- case NOTHING:
- p = "NOTHING";
- break;
- case BACK:
- p = "BACK";
- break;
- case END:
- p = "END";
- break;
- case MOPEN + 0:
- p = "MATCH START";
- break;
- case MOPEN + 1:
- case MOPEN + 2:
- case MOPEN + 3:
- case MOPEN + 4:
- case MOPEN + 5:
- case MOPEN + 6:
- case MOPEN + 7:
- case MOPEN + 8:
- case MOPEN + 9:
- sprintf(buf + STRLEN(buf), "MOPEN%d", OP(op) - MOPEN);
- p = NULL;
- break;
- case MCLOSE + 0:
- p = "MATCH END";
- break;
- case MCLOSE + 1:
- case MCLOSE + 2:
- case MCLOSE + 3:
- case MCLOSE + 4:
- case MCLOSE + 5:
- case MCLOSE + 6:
- case MCLOSE + 7:
- case MCLOSE + 8:
- case MCLOSE + 9:
- sprintf(buf + STRLEN(buf), "MCLOSE%d", OP(op) - MCLOSE);
- p = NULL;
- break;
- case BACKREF + 1:
- case BACKREF + 2:
- case BACKREF + 3:
- case BACKREF + 4:
- case BACKREF + 5:
- case BACKREF + 6:
- case BACKREF + 7:
- case BACKREF + 8:
- case BACKREF + 9:
- sprintf(buf + STRLEN(buf), "BACKREF%d", OP(op) - BACKREF);
- p = NULL;
- break;
- case NOPEN:
- p = "NOPEN";
- break;
- case NCLOSE:
- p = "NCLOSE";
- break;
- case ZOPEN + 1:
- case ZOPEN + 2:
- case ZOPEN + 3:
- case ZOPEN + 4:
- case ZOPEN + 5:
- case ZOPEN + 6:
- case ZOPEN + 7:
- case ZOPEN + 8:
- case ZOPEN + 9:
- sprintf(buf + STRLEN(buf), "ZOPEN%d", OP(op) - ZOPEN);
- p = NULL;
- break;
- case ZCLOSE + 1:
- case ZCLOSE + 2:
- case ZCLOSE + 3:
- case ZCLOSE + 4:
- case ZCLOSE + 5:
- case ZCLOSE + 6:
- case ZCLOSE + 7:
- case ZCLOSE + 8:
- case ZCLOSE + 9:
- sprintf(buf + STRLEN(buf), "ZCLOSE%d", OP(op) - ZCLOSE);
- p = NULL;
- break;
- case ZREF + 1:
- case ZREF + 2:
- case ZREF + 3:
- case ZREF + 4:
- case ZREF + 5:
- case ZREF + 6:
- case ZREF + 7:
- case ZREF + 8:
- case ZREF + 9:
- sprintf(buf + STRLEN(buf), "ZREF%d", OP(op) - ZREF);
- p = NULL;
- break;
- case STAR:
- p = "STAR";
- break;
- case PLUS:
- p = "PLUS";
- break;
- case NOMATCH:
- p = "NOMATCH";
- break;
- case MATCH:
- p = "MATCH";
- break;
- case BEHIND:
- p = "BEHIND";
- break;
- case NOBEHIND:
- p = "NOBEHIND";
- break;
- case SUBPAT:
- p = "SUBPAT";
- break;
- case BRACE_LIMITS:
- p = "BRACE_LIMITS";
- break;
- case BRACE_SIMPLE:
- p = "BRACE_SIMPLE";
- break;
- case BRACE_COMPLEX + 0:
- case BRACE_COMPLEX + 1:
- case BRACE_COMPLEX + 2:
- case BRACE_COMPLEX + 3:
- case BRACE_COMPLEX + 4:
- case BRACE_COMPLEX + 5:
- case BRACE_COMPLEX + 6:
- case BRACE_COMPLEX + 7:
- case BRACE_COMPLEX + 8:
- case BRACE_COMPLEX + 9:
- sprintf(buf + STRLEN(buf), "BRACE_COMPLEX%d", OP(op) - BRACE_COMPLEX);
- p = NULL;
- break;
- case MULTIBYTECODE:
- p = "MULTIBYTECODE";
- break;
- case NEWL:
- p = "NEWL";
- break;
- default:
- sprintf(buf + STRLEN(buf), "corrupt %d", OP(op));
- p = NULL;
- break;
+ if (re_multi_type(peekchr()) == MULTI_MULT) {
+ semsg(_("E888: (NFA regexp) cannot repeat %s"), what);
+ rc_did_emsg = true;
+ return false;
}
- if (p != NULL)
- STRCAT(buf, p);
- return (char_u *)buf;
+ return true;
}
-#endif /* REGEXP_DEBUG */
-
+typedef struct {
+ int a, b, c;
+} decomp_T;
-/* 0xfb20 - 0xfb4f */
+// 0xfb20 - 0xfb4f
static decomp_T decomp_table[0xfb4f-0xfb20+1] =
{
- {0x5e2,0,0}, /* 0xfb20 alt ayin */
- {0x5d0,0,0}, /* 0xfb21 alt alef */
- {0x5d3,0,0}, /* 0xfb22 alt dalet */
- {0x5d4,0,0}, /* 0xfb23 alt he */
- {0x5db,0,0}, /* 0xfb24 alt kaf */
- {0x5dc,0,0}, /* 0xfb25 alt lamed */
- {0x5dd,0,0}, /* 0xfb26 alt mem-sofit */
- {0x5e8,0,0}, /* 0xfb27 alt resh */
- {0x5ea,0,0}, /* 0xfb28 alt tav */
- {'+', 0, 0}, /* 0xfb29 alt plus */
- {0x5e9, 0x5c1, 0}, /* 0xfb2a shin+shin-dot */
- {0x5e9, 0x5c2, 0}, /* 0xfb2b shin+sin-dot */
- {0x5e9, 0x5c1, 0x5bc}, /* 0xfb2c shin+shin-dot+dagesh */
- {0x5e9, 0x5c2, 0x5bc}, /* 0xfb2d shin+sin-dot+dagesh */
- {0x5d0, 0x5b7, 0}, /* 0xfb2e alef+patah */
- {0x5d0, 0x5b8, 0}, /* 0xfb2f alef+qamats */
- {0x5d0, 0x5b4, 0}, /* 0xfb30 alef+hiriq */
- {0x5d1, 0x5bc, 0}, /* 0xfb31 bet+dagesh */
- {0x5d2, 0x5bc, 0}, /* 0xfb32 gimel+dagesh */
- {0x5d3, 0x5bc, 0}, /* 0xfb33 dalet+dagesh */
- {0x5d4, 0x5bc, 0}, /* 0xfb34 he+dagesh */
- {0x5d5, 0x5bc, 0}, /* 0xfb35 vav+dagesh */
- {0x5d6, 0x5bc, 0}, /* 0xfb36 zayin+dagesh */
- {0xfb37, 0, 0}, /* 0xfb37 -- */
- {0x5d8, 0x5bc, 0}, /* 0xfb38 tet+dagesh */
- {0x5d9, 0x5bc, 0}, /* 0xfb39 yud+dagesh */
- {0x5da, 0x5bc, 0}, /* 0xfb3a kaf sofit+dagesh */
- {0x5db, 0x5bc, 0}, /* 0xfb3b kaf+dagesh */
- {0x5dc, 0x5bc, 0}, /* 0xfb3c lamed+dagesh */
- {0xfb3d, 0, 0}, /* 0xfb3d -- */
- {0x5de, 0x5bc, 0}, /* 0xfb3e mem+dagesh */
- {0xfb3f, 0, 0}, /* 0xfb3f -- */
- {0x5e0, 0x5bc, 0}, /* 0xfb40 nun+dagesh */
- {0x5e1, 0x5bc, 0}, /* 0xfb41 samech+dagesh */
- {0xfb42, 0, 0}, /* 0xfb42 -- */
- {0x5e3, 0x5bc, 0}, /* 0xfb43 pe sofit+dagesh */
- {0x5e4, 0x5bc,0}, /* 0xfb44 pe+dagesh */
- {0xfb45, 0, 0}, /* 0xfb45 -- */
- {0x5e6, 0x5bc, 0}, /* 0xfb46 tsadi+dagesh */
- {0x5e7, 0x5bc, 0}, /* 0xfb47 qof+dagesh */
- {0x5e8, 0x5bc, 0}, /* 0xfb48 resh+dagesh */
- {0x5e9, 0x5bc, 0}, /* 0xfb49 shin+dagesh */
- {0x5ea, 0x5bc, 0}, /* 0xfb4a tav+dagesh */
- {0x5d5, 0x5b9, 0}, /* 0xfb4b vav+holam */
- {0x5d1, 0x5bf, 0}, /* 0xfb4c bet+rafe */
- {0x5db, 0x5bf, 0}, /* 0xfb4d kaf+rafe */
- {0x5e4, 0x5bf, 0}, /* 0xfb4e pe+rafe */
- {0x5d0, 0x5dc, 0} /* 0xfb4f alef-lamed */
+ { 0x5e2, 0, 0 }, // 0xfb20 alt ayin
+ { 0x5d0, 0, 0 }, // 0xfb21 alt alef
+ { 0x5d3, 0, 0 }, // 0xfb22 alt dalet
+ { 0x5d4, 0, 0 }, // 0xfb23 alt he
+ { 0x5db, 0, 0 }, // 0xfb24 alt kaf
+ { 0x5dc, 0, 0 }, // 0xfb25 alt lamed
+ { 0x5dd, 0, 0 }, // 0xfb26 alt mem-sofit
+ { 0x5e8, 0, 0 }, // 0xfb27 alt resh
+ { 0x5ea, 0, 0 }, // 0xfb28 alt tav
+ { '+', 0, 0 }, // 0xfb29 alt plus
+ { 0x5e9, 0x5c1, 0 }, // 0xfb2a shin+shin-dot
+ { 0x5e9, 0x5c2, 0 }, // 0xfb2b shin+sin-dot
+ { 0x5e9, 0x5c1, 0x5bc }, // 0xfb2c shin+shin-dot+dagesh
+ { 0x5e9, 0x5c2, 0x5bc }, // 0xfb2d shin+sin-dot+dagesh
+ { 0x5d0, 0x5b7, 0 }, // 0xfb2e alef+patah
+ { 0x5d0, 0x5b8, 0 }, // 0xfb2f alef+qamats
+ { 0x5d0, 0x5b4, 0 }, // 0xfb30 alef+hiriq
+ { 0x5d1, 0x5bc, 0 }, // 0xfb31 bet+dagesh
+ { 0x5d2, 0x5bc, 0 }, // 0xfb32 gimel+dagesh
+ { 0x5d3, 0x5bc, 0 }, // 0xfb33 dalet+dagesh
+ { 0x5d4, 0x5bc, 0 }, // 0xfb34 he+dagesh
+ { 0x5d5, 0x5bc, 0 }, // 0xfb35 vav+dagesh
+ { 0x5d6, 0x5bc, 0 }, // 0xfb36 zayin+dagesh
+ { 0xfb37, 0, 0 }, // 0xfb37 -- UNUSED
+ { 0x5d8, 0x5bc, 0 }, // 0xfb38 tet+dagesh
+ { 0x5d9, 0x5bc, 0 }, // 0xfb39 yud+dagesh
+ { 0x5da, 0x5bc, 0 }, // 0xfb3a kaf sofit+dagesh
+ { 0x5db, 0x5bc, 0 }, // 0xfb3b kaf+dagesh
+ { 0x5dc, 0x5bc, 0 }, // 0xfb3c lamed+dagesh
+ { 0xfb3d, 0, 0 }, // 0xfb3d -- UNUSED
+ { 0x5de, 0x5bc, 0 }, // 0xfb3e mem+dagesh
+ { 0xfb3f, 0, 0 }, // 0xfb3f -- UNUSED
+ { 0x5e0, 0x5bc, 0 }, // 0xfb40 nun+dagesh
+ { 0x5e1, 0x5bc, 0 }, // 0xfb41 samech+dagesh
+ { 0xfb42, 0, 0 }, // 0xfb42 -- UNUSED
+ { 0x5e3, 0x5bc, 0 }, // 0xfb43 pe sofit+dagesh
+ { 0x5e4, 0x5bc, 0 }, // 0xfb44 pe+dagesh
+ { 0xfb45, 0, 0 }, // 0xfb45 -- UNUSED
+ { 0x5e6, 0x5bc, 0 }, // 0xfb46 tsadi+dagesh
+ { 0x5e7, 0x5bc, 0 }, // 0xfb47 qof+dagesh
+ { 0x5e8, 0x5bc, 0 }, // 0xfb48 resh+dagesh
+ { 0x5e9, 0x5bc, 0 }, // 0xfb49 shin+dagesh
+ { 0x5ea, 0x5bc, 0 }, // 0xfb4a tav+dagesh
+ { 0x5d5, 0x5b9, 0 }, // 0xfb4b vav+holam
+ { 0x5d1, 0x5bf, 0 }, // 0xfb4c bet+rafe
+ { 0x5db, 0x5bf, 0 }, // 0xfb4d kaf+rafe
+ { 0x5e4, 0x5bf, 0 }, // 0xfb4e pe+rafe
+ { 0x5d0, 0x5dc, 0 } // 0xfb4f alef-lamed
};
static void mb_decompose(int c, int *c1, int *c2, int *c3)
@@ -6444,12 +1440,53 @@ static int cstrncmp(char_u *s1, char_u *s2, int *n)
return result;
}
+/// Wrapper around strchr which accounts for case-insensitive searches and
+/// non-ASCII characters.
+///
+/// This function is used a lot for simple searches, keep it fast!
+///
+/// @param s string to search
+/// @param c character to find in @a s
+///
+/// @return NULL if no match, otherwise pointer to the position in @a s
+static inline char_u *cstrchr(const char_u *const s, const int c)
+ FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
+ FUNC_ATTR_ALWAYS_INLINE
+{
+ if (!rex.reg_ic) {
+ return vim_strchr(s, c);
+ }
+
+ // Use folded case for UTF-8, slow! For ASCII use libc strpbrk which is
+ // expected to be highly optimized.
+ if (c > 0x80) {
+ const int folded_c = utf_fold(c);
+ for (const char_u *p = s; *p != NUL; p += utfc_ptr2len(p)) {
+ if (utf_fold(utf_ptr2char(p)) == folded_c) {
+ return (char_u *)p;
+ }
+ }
+ return NULL;
+ }
+
+ int cc;
+ if (ASCII_ISUPPER(c)) {
+ cc = TOLOWER_ASC(c);
+ } else if (ASCII_ISLOWER(c)) {
+ cc = TOUPPER_ASC(c);
+ } else {
+ return vim_strchr(s, c);
+ }
+
+ char tofind[] = { (char)c, (char)cc, NUL };
+ return (char_u *)strpbrk((const char *)s, tofind);
+}
+
////////////////////////////////////////////////////////////////
// regsub stuff //
////////////////////////////////////////////////////////////////
-/* This stuff below really confuses cc on an SGI -- webb */
-
+// This stuff below really confuses cc on an SGI -- webb
static fptr_T do_upper(int *d, int c)
@@ -6503,13 +1540,13 @@ char_u *regtilde(char_u *source, int magic)
for (p = newsub; *p; ++p) {
if ((*p == '~' && magic) || (*p == '\\' && *(p + 1) == '~' && !magic)) {
if (reg_prev_sub != NULL) {
- /* length = len(newsub) - 1 + len(prev_sub) + 1 */
+ // length = len(newsub) - 1 + len(prev_sub) + 1
prevlen = (int)STRLEN(reg_prev_sub);
tmpsub = xmalloc(STRLEN(newsub) + prevlen);
- /* copy prefix */
- len = (int)(p - newsub); /* not including ~ */
+ // copy prefix
+ len = (int)(p - newsub); // not including ~
memmove(tmpsub, newsub, (size_t)len);
- /* interpret tilde */
+ // interpret tilde
memmove(tmpsub + len, reg_prev_sub, (size_t)prevlen);
// copy postfix
if (!magic) {
@@ -6517,15 +1554,17 @@ char_u *regtilde(char_u *source, int magic)
}
STRCPY(tmpsub + len + prevlen, p + 1);
- if (newsub != source) /* already allocated newsub */
+ if (newsub != source) { // already allocated newsub
xfree(newsub);
+ }
newsub = tmpsub;
p = newsub + len + prevlen;
- } else if (magic)
- STRMOVE(p, p + 1); /* remove '~' */
- else
- STRMOVE(p, p + 2); /* remove '\~' */
- --p;
+ } else if (magic) {
+ STRMOVE(p, p + 1); // remove '~'
+ } else {
+ STRMOVE(p, p + 2); // remove '\~'
+ }
+ p--;
} else {
if (*p == '\\' && p[1]) { // skip escaped characters
p++;
@@ -6644,7 +1683,8 @@ int vim_regsub(regmatch_T *rmp, char_u *source, typval_T *expr, char_u *dest,
return result;
}
-int vim_regsub_multi(regmmatch_T *rmp, linenr_T lnum, char_u *source, char_u *dest, int copy, int magic, int backslash)
+int vim_regsub_multi(regmmatch_T *rmp, linenr_T lnum, char_u *source, char_u *dest,
+ int copy, int magic, int backslash)
{
regexec_T rex_save;
bool rex_in_use_save = rex_in_use;
@@ -6682,8 +1722,8 @@ static int vim_regsub_both(char_u *source, typval_T *expr, char_u *dest,
int no = -1;
fptr_T func_all = (fptr_T)NULL;
fptr_T func_one = (fptr_T)NULL;
- linenr_T clnum = 0; /* init for GCC */
- int len = 0; /* init for GCC */
+ linenr_T clnum = 0; // init for GCC
+ int len = 0; // init for GCC
static char_u *eval_result = NULL;
// We need to keep track of how many backslashes we escape, so that the byte
@@ -6795,7 +1835,7 @@ static int vim_regsub_both(char_u *source, typval_T *expr, char_u *dest,
}
}
if (had_backslash && backslash) {
- /* Backslashes will be consumed, need to double them. */
+ // Backslashes will be consumed, need to double them.
s = vim_strsave_escaped(eval_result, (char_u *)"\\");
xfree(eval_result);
eval_result = s;
@@ -6835,9 +1875,9 @@ static int vim_regsub_both(char_u *source, typval_T *expr, char_u *dest,
}
}
}
- if (no < 0) { /* Ordinary character. */
+ if (no < 0) { // Ordinary character.
if (c == K_SPECIAL && src[0] != NUL && src[1] != NUL) {
- /* Copy a special key as-is. */
+ // Copy a special key as-is.
if (copy) {
*dst++ = c;
*dst++ = *src++;
@@ -6965,14 +2005,15 @@ static int vim_regsub_both(char_u *source, typval_T *expr, char_u *dest,
} else {
c = utf_ptr2char(s);
- if (func_one != (fptr_T)NULL)
- /* Turbo C complains without the typecast */
+ if (func_one != (fptr_T)NULL) {
+ // Turbo C complains without the typecast
func_one = (fptr_T)(func_one(&cc, c));
- else if (func_all != (fptr_T)NULL)
- /* Turbo C complains without the typecast */
+ } else if (func_all != (fptr_T)NULL) {
+ // Turbo C complains without the typecast
func_all = (fptr_T)(func_all(&cc, c));
- else /* just copy */
+ } else { // just copy
cc = c;
+ }
{
int l;
@@ -7167,6 +2208,12 @@ list_T *reg_submatch_list(int no)
return list;
}
+// XXX Do not allow headers generator to catch definitions from regexp_nfa.c
+#ifndef DO_NOT_DEFINE_EMPTY_ATTRIBUTES
+# include "nvim/regexp_bt.c"
+# include "nvim/regexp_nfa.c"
+#endif
+
static regengine_T bt_regengine =
{
bt_regcomp,
@@ -7176,12 +2223,6 @@ static regengine_T bt_regengine =
(char_u *)""
};
-
-// XXX Do not allow headers generator to catch definitions from regexp_nfa.c
-#ifndef DO_NOT_DEFINE_EMPTY_ATTRIBUTES
-# include "nvim/regexp_nfa.c"
-#endif
-
static regengine_T nfa_regengine =
{
nfa_regcomp,
@@ -7217,7 +2258,7 @@ regprog_T *vim_regcomp(char_u *expr_arg, int re_flags)
regexp_engine = p_re;
- /* Check for prefix "\%#=", that sets the regexp engine */
+ // Check for prefix "\%#=", that sets the regexp engine
if (STRNCMP(expr, "\\%#=", 4) == 0) {
int newengine = expr[4] - '0';
@@ -7302,6 +2343,18 @@ void vim_regfree(regprog_T *prog)
prog->engine->regfree(prog);
}
+
+#if defined(EXITFREE)
+void free_regexp_stuff(void)
+{
+ ga_clear(&regstack);
+ ga_clear(&backpos);
+ xfree(reg_tofree);
+ xfree(reg_prev_sub);
+}
+
+#endif
+
static void report_re_switch(char_u *pat)
{
if (p_verbose > 0) {
@@ -7324,8 +2377,7 @@ static void report_re_switch(char_u *pat)
/// @param nl
///
/// @return true if there is a match, false if not.
-static bool vim_regexec_string(regmatch_T *rmp, char_u *line, colnr_T col,
- bool nl)
+static bool vim_regexec_string(regmatch_T *rmp, char_u *line, colnr_T col, bool nl)
{
regexec_T rex_save;
bool rex_in_use_save = rex_in_use;
@@ -7382,8 +2434,7 @@ static bool vim_regexec_string(regmatch_T *rmp, char_u *line, colnr_T col,
// Note: "*prog" may be freed and changed.
// Return true if there is a match, false if not.
-bool vim_regexec_prog(regprog_T **prog, bool ignore_case, char_u *line,
- colnr_T col)
+bool vim_regexec_prog(regprog_T **prog, bool ignore_case, char_u *line, colnr_T col)
{
regmatch_T regmatch = { .regprog = *prog, .rm_ic = ignore_case };
bool r = vim_regexec_string(&regmatch, line, col, false);
@@ -7415,13 +2466,12 @@ bool vim_regexec_nl(regmatch_T *rmp, char_u *line, colnr_T col)
/// match otherwise.
long vim_regexec_multi(
regmmatch_T *rmp,
- win_T *win, // window in which to search or NULL
- buf_T *buf, // buffer in which to search
- linenr_T lnum, // nr of line to start looking for match
- colnr_T col, // column to start looking for match
- proftime_T *tm, // timeout limit or NULL
- int *timed_out // flag is set when timeout limit reached
-)
+ win_T *win, // window in which to search or NULL
+ buf_T *buf, // buffer in which to search
+ linenr_T lnum, // nr of line to start looking for match
+ colnr_T col, // column to start looking for match
+ proftime_T *tm, // timeout limit or NULL
+ int *timed_out) // flag is set when timeout limit reached
FUNC_ATTR_NONNULL_ARG(1)
{
regexec_T rex_save;
diff --git a/src/nvim/regexp.h b/src/nvim/regexp.h
index 9527afed58..6edbcf8a31 100644
--- a/src/nvim/regexp.h
+++ b/src/nvim/regexp.h
@@ -19,6 +19,7 @@
// regexp.c
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "regexp.h.generated.h"
+# include "regexp_bt.h.generated.h"
#endif
#endif // NVIM_REGEXP_H
diff --git a/src/nvim/regexp_bt.c b/src/nvim/regexp_bt.c
new file mode 100644
index 0000000000..1153b8ed33
--- /dev/null
+++ b/src/nvim/regexp_bt.c
@@ -0,0 +1,4955 @@
+// This is an open source non-commercial project. Dear PVS-Studio, please check
+// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
+
+// uncrustify:off
+
+/*
+ *
+ * Backtracking regular expression implementation.
+ *
+ * This file is included in "regexp.c".
+ *
+ * NOTICE:
+ *
+ * This is NOT the original regular expression code as written by Henry
+ * Spencer. This code has been modified specifically for use with the VIM
+ * editor, and should not be used separately from Vim. If you want a good
+ * regular expression library, get the original code. The copyright notice
+ * that follows is from the original.
+ *
+ * END NOTICE
+ *
+ * Copyright (c) 1986 by University of Toronto.
+ * Written by Henry Spencer. Not derived from licensed software.
+ *
+ * Permission is granted to anyone to use this software for any
+ * purpose on any computer system, and to redistribute it freely,
+ * subject to the following restrictions:
+ *
+ * 1. The author is not responsible for the consequences of use of
+ * this software, no matter how awful, even if they arise
+ * from defects in it.
+ *
+ * 2. The origin of this software must not be misrepresented, either
+ * by explicit claim or by omission.
+ *
+ * 3. Altered versions must be plainly marked as such, and must not
+ * be misrepresented as being the original software.
+ *
+ * Beware that some of this code is subtly aware of the way operator
+ * precedence is structured in regular expressions. Serious changes in
+ * regular-expression syntax might require a total rethink.
+ *
+ * Changes have been made by Tony Andrews, Olaf 'Rhialto' Seibert, Robert
+ * Webb, Ciaran McCreesh and Bram Moolenaar.
+ * Named character class support added by Walter Briscoe (1998 Jul 01)
+ */
+
+
+/*
+ * The "internal use only" fields in regexp_defs.h are present to pass info from
+ * compile to execute that permits the execute phase to run lots faster on
+ * simple cases. They are:
+ *
+ * regstart char that must begin a match; NUL if none obvious; Can be a
+ * multi-byte character.
+ * reganch is the match anchored (at beginning-of-line only)?
+ * regmust string (pointer into program) that match must include, or NULL
+ * regmlen length of regmust string
+ * regflags RF_ values or'ed together
+ *
+ * Regstart and reganch permit very fast decisions on suitable starting points
+ * for a match, cutting down the work a lot. Regmust permits fast rejection
+ * of lines that cannot possibly match. The regmust tests are costly enough
+ * that vim_regcomp() supplies a regmust only if the r.e. contains something
+ * potentially expensive (at present, the only such thing detected is * or +
+ * at the start of the r.e., which can involve a lot of backup). Regmlen is
+ * supplied because the test in vim_regexec() needs it and vim_regcomp() is
+ * computing it anyway.
+ */
+
+/*
+ * Structure for regexp "program". This is essentially a linear encoding
+ * of a nondeterministic finite-state machine (aka syntax charts or
+ * "railroad normal form" in parsing technology). Each node is an opcode
+ * plus a "next" pointer, possibly plus an operand. "Next" pointers of
+ * all nodes except BRANCH and BRACES_COMPLEX implement concatenation; a "next"
+ * pointer with a BRANCH on both ends of it is connecting two alternatives.
+ * (Here we have one of the subtle syntax dependencies: an individual BRANCH
+ * (as opposed to a collection of them) is never concatenated with anything
+ * because of operator precedence). The "next" pointer of a BRACES_COMPLEX
+ * node points to the node after the stuff to be repeated.
+ * The operand of some types of node is a literal string; for others, it is a
+ * node leading into a sub-FSM. In particular, the operand of a BRANCH node
+ * is the first node of the branch.
+ * (NB this is *not* a tree structure: the tail of the branch connects to the
+ * thing following the set of BRANCHes.)
+ *
+ * pattern is coded like:
+ *
+ * +-----------------+
+ * | V
+ * <aa>\|<bb> BRANCH <aa> BRANCH <bb> --> END
+ * | ^ | ^
+ * +------+ +----------+
+ *
+ *
+ * +------------------+
+ * V |
+ * <aa>* BRANCH BRANCH <aa> --> BACK BRANCH --> NOTHING --> END
+ * | | ^ ^
+ * | +---------------+ |
+ * +---------------------------------------------+
+ *
+ *
+ * +----------------------+
+ * V |
+ * <aa>\+ BRANCH <aa> --> BRANCH --> BACK BRANCH --> NOTHING --> END
+ * | | ^ ^
+ * | +-----------+ |
+ * +--------------------------------------------------+
+ *
+ *
+ * +-------------------------+
+ * V |
+ * <aa>\{} BRANCH BRACE_LIMITS --> BRACE_COMPLEX <aa> --> BACK END
+ * | | ^
+ * | +----------------+
+ * +-----------------------------------------------+
+ *
+ *
+ * <aa>\@!<bb> BRANCH NOMATCH <aa> --> END <bb> --> END
+ * | | ^ ^
+ * | +----------------+ |
+ * +--------------------------------+
+ *
+ * +---------+
+ * | V
+ * \z[abc] BRANCH BRANCH a BRANCH b BRANCH c BRANCH NOTHING --> END
+ * | | | | ^ ^
+ * | | | +-----+ |
+ * | | +----------------+ |
+ * | +---------------------------+ |
+ * +------------------------------------------------------+
+ *
+ * They all start with a BRANCH for "\|" alternatives, even when there is only
+ * one alternative.
+ */
+
+#include <assert.h>
+#include <inttypes.h>
+#include <stdbool.h>
+#include <string.h>
+
+#include "nvim/regexp.h"
+#include "nvim/garray.h"
+
+/*
+ * The opcodes are:
+ */
+
+// definition number opnd? meaning
+#define END 0 // End of program or NOMATCH operand.
+#define BOL 1 // Match "" at beginning of line.
+#define EOL 2 // Match "" at end of line.
+#define BRANCH 3 // node Match this alternative, or the
+ // next...
+#define BACK 4 // Match "", "next" ptr points backward.
+#define EXACTLY 5 // str Match this string.
+#define NOTHING 6 // Match empty string.
+#define STAR 7 // node Match this (simple) thing 0 or more
+ // times.
+#define PLUS 8 // node Match this (simple) thing 1 or more
+ // times.
+#define MATCH 9 // node match the operand zero-width
+#define NOMATCH 10 // node check for no match with operand
+#define BEHIND 11 // node look behind for a match with operand
+#define NOBEHIND 12 // node look behind for no match with operand
+#define SUBPAT 13 // node match the operand here
+#define BRACE_SIMPLE 14 // node Match this (simple) thing between m and
+ // n times (\{m,n\}).
+#define BOW 15 // Match "" after [^a-zA-Z0-9_]
+#define EOW 16 // Match "" at [^a-zA-Z0-9_]
+#define BRACE_LIMITS 17 // nr nr define the min & max for BRACE_SIMPLE
+ // and BRACE_COMPLEX.
+#define NEWL 18 // Match line-break
+#define BHPOS 19 // End position for BEHIND or NOBEHIND
+
+
+// character classes: 20-48 normal, 50-78 include a line-break
+#define ADD_NL 30
+#define FIRST_NL ANY + ADD_NL
+#define ANY 20 // Match any one character.
+#define ANYOF 21 // str Match any character in this string.
+#define ANYBUT 22 // str Match any character not in this
+ // string.
+#define IDENT 23 // Match identifier char
+#define SIDENT 24 // Match identifier char but no digit
+#define KWORD 25 // Match keyword char
+#define SKWORD 26 // Match word char but no digit
+#define FNAME 27 // Match file name char
+#define SFNAME 28 // Match file name char but no digit
+#define PRINT 29 // Match printable char
+#define SPRINT 30 // Match printable char but no digit
+#define WHITE 31 // Match whitespace char
+#define NWHITE 32 // Match non-whitespace char
+#define DIGIT 33 // Match digit char
+#define NDIGIT 34 // Match non-digit char
+#define HEX 35 // Match hex char
+#define NHEX 36 // Match non-hex char
+#define OCTAL 37 // Match octal char
+#define NOCTAL 38 // Match non-octal char
+#define WORD 39 // Match word char
+#define NWORD 40 // Match non-word char
+#define HEAD 41 // Match head char
+#define NHEAD 42 // Match non-head char
+#define ALPHA 43 // Match alpha char
+#define NALPHA 44 // Match non-alpha char
+#define LOWER 45 // Match lowercase char
+#define NLOWER 46 // Match non-lowercase char
+#define UPPER 47 // Match uppercase char
+#define NUPPER 48 // Match non-uppercase char
+#define LAST_NL NUPPER + ADD_NL
+// -V:WITH_NL:560
+#define WITH_NL(op) ((op) >= FIRST_NL && (op) <= LAST_NL)
+
+#define MOPEN 80 // -89 Mark this point in input as start of
+ // \( … \) subexpr. MOPEN + 0 marks start of
+ // match.
+#define MCLOSE 90 // -99 Analogous to MOPEN. MCLOSE + 0 marks
+ // end of match.
+#define BACKREF 100 // -109 node Match same string again \1-\9.
+
+# define ZOPEN 110 // -119 Mark this point in input as start of
+ // \z( … \) subexpr.
+# define ZCLOSE 120 // -129 Analogous to ZOPEN.
+# define ZREF 130 // -139 node Match external submatch \z1-\z9
+
+#define BRACE_COMPLEX 140 // -149 node Match nodes between m & n times
+
+#define NOPEN 150 // Mark this point in input as start of
+ // \%( subexpr.
+#define NCLOSE 151 // Analogous to NOPEN.
+
+#define MULTIBYTECODE 200 // mbc Match one multi-byte character
+#define RE_BOF 201 // Match "" at beginning of file.
+#define RE_EOF 202 // Match "" at end of file.
+#define CURSOR 203 // Match location of cursor.
+
+#define RE_LNUM 204 // nr cmp Match line number
+#define RE_COL 205 // nr cmp Match column number
+#define RE_VCOL 206 // nr cmp Match virtual column number
+
+#define RE_MARK 207 // mark cmp Match mark position
+#define RE_VISUAL 208 // Match Visual area
+#define RE_COMPOSING 209 // any composing characters
+
+/*
+ * Flags to be passed up and down.
+ */
+#define HASWIDTH 0x1 // Known never to match null string.
+#define SIMPLE 0x2 // Simple enough to be STAR/PLUS operand.
+#define SPSTART 0x4 // Starts with * or +.
+#define HASNL 0x8 // Contains some \n.
+#define HASLOOKBH 0x10 // Contains "\@<=" or "\@<!".
+#define WORST 0 // Worst case.
+
+
+static int prevchr_len; ///< byte length of previous char
+static int num_complex_braces; ///< Complex \{...} count
+static char_u *regcode; ///< Code-emit pointer, or JUST_CALC_SIZE
+static long regsize; ///< Code size.
+static int reg_toolong; ///< true when offset out of range
+static char_u had_endbrace[NSUBEXP]; ///< flags, true if end of () found
+static long brace_min[10]; ///< Minimums for complex brace repeats
+static long brace_max[10]; ///< Maximums for complex brace repeats
+static int brace_count[10]; ///< Current counts for complex brace repeats
+static int one_exactly = false; ///< only do one char for EXACTLY
+
+// When making changes to classchars also change nfa_classcodes.
+static char_u *classchars = (char_u *)".iIkKfFpPsSdDxXoOwWhHaAlLuU";
+static int classcodes[] = {
+ ANY, IDENT, SIDENT, KWORD, SKWORD,
+ FNAME, SFNAME, PRINT, SPRINT,
+ WHITE, NWHITE, DIGIT, NDIGIT,
+ HEX, NHEX, OCTAL, NOCTAL,
+ WORD, NWORD, HEAD, NHEAD,
+ ALPHA, NALPHA, LOWER, NLOWER,
+ UPPER, NUPPER
+};
+
+/*
+ * When regcode is set to this value, code is not emitted and size is computed
+ * instead.
+ */
+#define JUST_CALC_SIZE ((char_u *) -1)
+
+// Values for rs_state in regitem_T.
+typedef enum regstate_E {
+ RS_NOPEN = 0, // NOPEN and NCLOSE
+ RS_MOPEN, // MOPEN + [0-9]
+ RS_MCLOSE, // MCLOSE + [0-9]
+ RS_ZOPEN, // ZOPEN + [0-9]
+ RS_ZCLOSE, // ZCLOSE + [0-9]
+ RS_BRANCH, // BRANCH
+ RS_BRCPLX_MORE, // BRACE_COMPLEX and trying one more match
+ RS_BRCPLX_LONG, // BRACE_COMPLEX and trying longest match
+ RS_BRCPLX_SHORT, // BRACE_COMPLEX and trying shortest match
+ RS_NOMATCH, // NOMATCH
+ RS_BEHIND1, // BEHIND / NOBEHIND matching rest
+ RS_BEHIND2, // BEHIND / NOBEHIND matching behind part
+ RS_STAR_LONG, // STAR/PLUS/BRACE_SIMPLE longest match
+ RS_STAR_SHORT // STAR/PLUS/BRACE_SIMPLE shortest match
+} regstate_T;
+
+/*
+ * Structure used to save the current input state, when it needs to be
+ * restored after trying a match. Used by reg_save() and reg_restore().
+ * Also stores the length of "backpos".
+ */
+typedef struct
+{
+ union
+ {
+ char_u *ptr; // rex.input pointer, for single-line regexp
+ lpos_T pos; // rex.input pos, for multi-line regexp
+ } rs_u;
+ int rs_len;
+} regsave_T;
+
+// struct to save start/end pointer/position in for \(\)
+typedef struct
+{
+ union
+ {
+ char_u *ptr;
+ lpos_T pos;
+ } se_u;
+} save_se_T;
+
+// used for BEHIND and NOBEHIND matching
+typedef struct regbehind_S
+{
+ regsave_T save_after;
+ regsave_T save_behind;
+ int save_need_clear_subexpr;
+ save_se_T save_start[NSUBEXP];
+ save_se_T save_end[NSUBEXP];
+} regbehind_T;
+
+/*
+ * When there are alternatives a regstate_T is put on the regstack to remember
+ * what we are doing.
+ * Before it may be another type of item, depending on rs_state, to remember
+ * more things.
+ */
+typedef struct regitem_S
+{
+ regstate_T rs_state; // what we are doing, one of RS_ above
+ short rs_no; // submatch nr or BEHIND/NOBEHIND
+ char_u *rs_scan; // current node in program
+ union
+ {
+ save_se_T sesave;
+ regsave_T regsave;
+ } rs_un; // room for saving rex.input
+} regitem_T;
+
+
+// used for STAR, PLUS and BRACE_SIMPLE matching
+typedef struct regstar_S
+{
+ int nextb; // next byte
+ int nextb_ic; // next byte reverse case
+ long count;
+ long minval;
+ long maxval;
+} regstar_T;
+
+// used to store input position when a BACK was encountered, so that we now if
+// we made any progress since the last time.
+typedef struct backpos_S
+{
+ char_u *bp_scan; // "scan" where BACK was encountered
+ regsave_T bp_pos; // last input position
+} backpos_T;
+
+/*
+ * "regstack" and "backpos" are used by regmatch(). They are kept over calls
+ * to avoid invoking malloc() and free() often.
+ * "regstack" is a stack with regitem_T items, sometimes preceded by regstar_T
+ * or regbehind_T.
+ * "backpos_T" is a table with backpos_T for BACK
+ */
+static garray_T regstack = GA_EMPTY_INIT_VALUE;
+static garray_T backpos = GA_EMPTY_INIT_VALUE;
+
+static regsave_T behind_pos;
+
+/*
+ * Both for regstack and backpos tables we use the following strategy of
+ * allocation (to reduce malloc/free calls):
+ * - Initial size is fairly small.
+ * - When needed, the tables are grown bigger (8 times at first, double after
+ * that).
+ * - After executing the match we free the memory only if the array has grown.
+ * Thus the memory is kept allocated when it's at the initial size.
+ * This makes it fast while not keeping a lot of memory allocated.
+ * A three times speed increase was observed when using many simple patterns.
+ */
+#define REGSTACK_INITIAL 2048
+#define BACKPOS_INITIAL 64
+
+/*
+ * Opcode notes:
+ *
+ * BRANCH The set of branches constituting a single choice are hooked
+ * together with their "next" pointers, since precedence prevents
+ * anything being concatenated to any individual branch. The
+ * "next" pointer of the last BRANCH in a choice points to the
+ * thing following the whole choice. This is also where the
+ * final "next" pointer of each individual branch points; each
+ * branch starts with the operand node of a BRANCH node.
+ *
+ * BACK Normal "next" pointers all implicitly point forward; BACK
+ * exists to make loop structures possible.
+ *
+ * STAR,PLUS '=', and complex '*' and '+', are implemented as circular
+ * BRANCH structures using BACK. Simple cases (one character
+ * per match) are implemented with STAR and PLUS for speed
+ * and to minimize recursive plunges.
+ *
+ * BRACE_LIMITS This is always followed by a BRACE_SIMPLE or BRACE_COMPLEX
+ * node, and defines the min and max limits to be used for that
+ * node.
+ *
+ * MOPEN,MCLOSE ...are numbered at compile time.
+ * ZOPEN,ZCLOSE ...ditto
+ */
+
+/*
+ * A node is one char of opcode followed by two chars of "next" pointer.
+ * "Next" pointers are stored as two 8-bit bytes, high order first. The
+ * value is a positive offset from the opcode of the node containing it.
+ * An operand, if any, simply follows the node. (Note that much of the
+ * code generation knows about this implicit relationship.)
+ *
+ * Using two bytes for the "next" pointer is vast overkill for most things,
+ * but allows patterns to get big without disasters.
+ */
+#define OP(p) ((int)(*(p)))
+#define NEXT(p) (((*((p) + 1) & 0377) << 8) + (*((p) + 2) & 0377))
+#define OPERAND(p) ((p) + 3)
+// Obtain an operand that was stored as four bytes, MSB first.
+#define OPERAND_MIN(p) (((long)(p)[3] << 24) + ((long)(p)[4] << 16) \
+ + ((long)(p)[5] << 8) + (long)(p)[6])
+// Obtain a second operand stored as four bytes.
+#define OPERAND_MAX(p) OPERAND_MIN((p) + 4)
+// Obtain a second single-byte operand stored after a four bytes operand.
+#define OPERAND_CMP(p) (p)[7]
+
+static char_u *reg(int paren, int *flagp);
+
+#ifdef BT_REGEXP_DUMP
+static void regdump(char_u *, bt_regprog_T *);
+#endif
+
+
+#ifdef REGEXP_DEBUG
+static char_u *regprop(char_u *);
+
+static int regnarrate = 0;
+#endif
+
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+# include "regexp_bt.c.generated.h"
+#endif
+
+
+/*
+ * Setup to parse the regexp. Used once to get the length and once to do it.
+ */
+static void regcomp_start(
+ char_u *expr,
+ int re_flags) // see vim_regcomp()
+{
+ initchr(expr);
+ if (re_flags & RE_MAGIC)
+ reg_magic = MAGIC_ON;
+ else
+ reg_magic = MAGIC_OFF;
+ reg_string = (re_flags & RE_STRING);
+ reg_strict = (re_flags & RE_STRICT);
+ get_cpo_flags();
+
+ num_complex_braces = 0;
+ regnpar = 1;
+ memset(had_endbrace, 0, sizeof(had_endbrace));
+ regnzpar = 1;
+ re_has_z = 0;
+ regsize = 0L;
+ reg_toolong = false;
+ regflags = 0;
+ had_eol = false;
+}
+
+// Return true if MULTIBYTECODE should be used instead of EXACTLY for
+// character "c".
+static bool use_multibytecode(int c)
+{
+ return utf_char2len(c) > 1
+ && (re_multi_type(peekchr()) != NOT_MULTI
+ || utf_iscomposing(c));
+}
+
+
+/*
+ * Emit (if appropriate) a byte of code
+ */
+static void regc(int b)
+{
+ if (regcode == JUST_CALC_SIZE)
+ regsize++;
+ else
+ *regcode++ = b;
+}
+
+/*
+ * Emit (if appropriate) a multi-byte character of code
+ */
+static void regmbc(int c)
+{
+ if (regcode == JUST_CALC_SIZE) {
+ regsize += utf_char2len(c);
+ } else {
+ regcode += utf_char2bytes(c, regcode);
+ }
+}
+
+#define REGMBC(x) regmbc(x);
+#define CASEMBC(x) case x:
+
+/*
+ * Produce the bytes for equivalence class "c".
+ * Currently only handles latin1, latin9 and utf-8.
+ * NOTE: When changing this function, also change nfa_emit_equi_class()
+ */
+static void reg_equi_class(int c)
+{
+ {
+ switch (c) {
+ // Do not use '\300' style, it results in a negative number.
+ case 'A': case 0xc0: case 0xc1: case 0xc2:
+ case 0xc3: case 0xc4: case 0xc5:
+ CASEMBC(0x100) CASEMBC(0x102) CASEMBC(0x104) CASEMBC(0x1cd)
+ CASEMBC(0x1de) CASEMBC(0x1e0) CASEMBC(0x1ea2)
+ regmbc('A'); regmbc(0xc0); regmbc(0xc1);
+ regmbc(0xc2); regmbc(0xc3); regmbc(0xc4);
+ regmbc(0xc5);
+ REGMBC(0x100) REGMBC(0x102) REGMBC(0x104)
+ REGMBC(0x1cd) REGMBC(0x1de) REGMBC(0x1e0)
+ REGMBC(0x1ea2)
+ return;
+ case 'B': CASEMBC(0x1e02) CASEMBC(0x1e06)
+ regmbc('B'); REGMBC(0x1e02) REGMBC(0x1e06)
+ return;
+ case 'C': case 0xc7:
+ CASEMBC(0x106) CASEMBC(0x108) CASEMBC(0x10a) CASEMBC(0x10c)
+ regmbc('C'); regmbc(0xc7);
+ REGMBC(0x106) REGMBC(0x108) REGMBC(0x10a)
+ REGMBC(0x10c)
+ return;
+ case 'D': CASEMBC(0x10e) CASEMBC(0x110) CASEMBC(0x1e0a)
+ CASEMBC(0x1e0e) CASEMBC(0x1e10)
+ regmbc('D'); REGMBC(0x10e) REGMBC(0x110)
+ REGMBC(0x1e0a) REGMBC(0x1e0e) REGMBC(0x1e10)
+ return;
+ case 'E': case 0xc8: case 0xc9: case 0xca: case 0xcb:
+ CASEMBC(0x112) CASEMBC(0x114) CASEMBC(0x116) CASEMBC(0x118)
+ CASEMBC(0x11a) CASEMBC(0x1eba) CASEMBC(0x1ebc)
+ regmbc('E'); regmbc(0xc8); regmbc(0xc9);
+ regmbc(0xca); regmbc(0xcb);
+ REGMBC(0x112) REGMBC(0x114) REGMBC(0x116)
+ REGMBC(0x118) REGMBC(0x11a) REGMBC(0x1eba)
+ REGMBC(0x1ebc)
+ return;
+ case 'F': CASEMBC(0x1e1e)
+ regmbc('F'); REGMBC(0x1e1e)
+ return;
+ case 'G': CASEMBC(0x11c) CASEMBC(0x11e) CASEMBC(0x120)
+ CASEMBC(0x122) CASEMBC(0x1e4) CASEMBC(0x1e6) CASEMBC(0x1f4)
+ CASEMBC(0x1e20)
+ regmbc('G'); REGMBC(0x11c) REGMBC(0x11e)
+ REGMBC(0x120) REGMBC(0x122) REGMBC(0x1e4)
+ REGMBC(0x1e6) REGMBC(0x1f4) REGMBC(0x1e20)
+ return;
+ case 'H': CASEMBC(0x124) CASEMBC(0x126) CASEMBC(0x1e22)
+ CASEMBC(0x1e26) CASEMBC(0x1e28)
+ regmbc('H'); REGMBC(0x124) REGMBC(0x126)
+ REGMBC(0x1e22) REGMBC(0x1e26) REGMBC(0x1e28)
+ return;
+ case 'I': case 0xcc: case 0xcd: case 0xce: case 0xcf:
+ CASEMBC(0x128) CASEMBC(0x12a) CASEMBC(0x12c) CASEMBC(0x12e)
+ CASEMBC(0x130) CASEMBC(0x1cf) CASEMBC(0x1ec8)
+ regmbc('I'); regmbc(0xcc); regmbc(0xcd);
+ regmbc(0xce); regmbc(0xcf);
+ REGMBC(0x128) REGMBC(0x12a) REGMBC(0x12c)
+ REGMBC(0x12e) REGMBC(0x130) REGMBC(0x1cf)
+ REGMBC(0x1ec8)
+ return;
+ case 'J': CASEMBC(0x134)
+ regmbc('J'); REGMBC(0x134)
+ return;
+ case 'K': CASEMBC(0x136) CASEMBC(0x1e8) CASEMBC(0x1e30)
+ CASEMBC(0x1e34)
+ regmbc('K'); REGMBC(0x136) REGMBC(0x1e8)
+ REGMBC(0x1e30) REGMBC(0x1e34)
+ return;
+ case 'L': CASEMBC(0x139) CASEMBC(0x13b) CASEMBC(0x13d)
+ CASEMBC(0x13f) CASEMBC(0x141) CASEMBC(0x1e3a)
+ regmbc('L'); REGMBC(0x139) REGMBC(0x13b)
+ REGMBC(0x13d) REGMBC(0x13f) REGMBC(0x141)
+ REGMBC(0x1e3a)
+ return;
+ case 'M': CASEMBC(0x1e3e) CASEMBC(0x1e40)
+ regmbc('M'); REGMBC(0x1e3e) REGMBC(0x1e40)
+ return;
+ case 'N': case 0xd1:
+ CASEMBC(0x143) CASEMBC(0x145) CASEMBC(0x147) CASEMBC(0x1e44)
+ CASEMBC(0x1e48)
+ regmbc('N'); regmbc(0xd1);
+ REGMBC(0x143) REGMBC(0x145) REGMBC(0x147)
+ REGMBC(0x1e44) REGMBC(0x1e48)
+ return;
+ case 'O': case 0xd2: case 0xd3: case 0xd4: case 0xd5:
+ case 0xd6: case 0xd8:
+ CASEMBC(0x14c) CASEMBC(0x14e) CASEMBC(0x150) CASEMBC(0x1a0)
+ CASEMBC(0x1d1) CASEMBC(0x1ea) CASEMBC(0x1ec) CASEMBC(0x1ece)
+ regmbc('O'); regmbc(0xd2); regmbc(0xd3);
+ regmbc(0xd4); regmbc(0xd5); regmbc(0xd6);
+ regmbc(0xd8);
+ REGMBC(0x14c) REGMBC(0x14e) REGMBC(0x150)
+ REGMBC(0x1a0) REGMBC(0x1d1) REGMBC(0x1ea)
+ REGMBC(0x1ec) REGMBC(0x1ece)
+ return;
+ case 'P': case 0x1e54: case 0x1e56:
+ regmbc('P'); REGMBC(0x1e54) REGMBC(0x1e56)
+ return;
+ case 'R': CASEMBC(0x154) CASEMBC(0x156) CASEMBC(0x158)
+ CASEMBC(0x1e58) CASEMBC(0x1e5e)
+ regmbc('R'); REGMBC(0x154) REGMBC(0x156) REGMBC(0x158)
+ REGMBC(0x1e58) REGMBC(0x1e5e)
+ return;
+ case 'S': CASEMBC(0x15a) CASEMBC(0x15c) CASEMBC(0x15e)
+ CASEMBC(0x160) CASEMBC(0x1e60)
+ regmbc('S'); REGMBC(0x15a) REGMBC(0x15c)
+ REGMBC(0x15e) REGMBC(0x160) REGMBC(0x1e60)
+ return;
+ case 'T': CASEMBC(0x162) CASEMBC(0x164) CASEMBC(0x166)
+ CASEMBC(0x1e6a) CASEMBC(0x1e6e)
+ regmbc('T'); REGMBC(0x162) REGMBC(0x164)
+ REGMBC(0x166) REGMBC(0x1e6a) REGMBC(0x1e6e)
+ return;
+ case 'U': case 0xd9: case 0xda: case 0xdb: case 0xdc:
+ CASEMBC(0x168) CASEMBC(0x16a) CASEMBC(0x16c) CASEMBC(0x16e)
+ CASEMBC(0x170) CASEMBC(0x172) CASEMBC(0x1af) CASEMBC(0x1d3)
+ CASEMBC(0x1ee6)
+ regmbc('U'); regmbc(0xd9); regmbc(0xda);
+ regmbc(0xdb); regmbc(0xdc);
+ REGMBC(0x168) REGMBC(0x16a) REGMBC(0x16c)
+ REGMBC(0x16e) REGMBC(0x170) REGMBC(0x172)
+ REGMBC(0x1af) REGMBC(0x1d3) REGMBC(0x1ee6)
+ return;
+ case 'V': CASEMBC(0x1e7c)
+ regmbc('V'); REGMBC(0x1e7c)
+ return;
+ case 'W': CASEMBC(0x174) CASEMBC(0x1e80) CASEMBC(0x1e82)
+ CASEMBC(0x1e84) CASEMBC(0x1e86)
+ regmbc('W'); REGMBC(0x174) REGMBC(0x1e80)
+ REGMBC(0x1e82) REGMBC(0x1e84) REGMBC(0x1e86)
+ return;
+ case 'X': CASEMBC(0x1e8a) CASEMBC(0x1e8c)
+ regmbc('X'); REGMBC(0x1e8a) REGMBC(0x1e8c)
+ return;
+ case 'Y': case 0xdd:
+ CASEMBC(0x176) CASEMBC(0x178) CASEMBC(0x1e8e) CASEMBC(0x1ef2)
+ CASEMBC(0x1ef6) CASEMBC(0x1ef8)
+ regmbc('Y'); regmbc(0xdd);
+ REGMBC(0x176) REGMBC(0x178) REGMBC(0x1e8e)
+ REGMBC(0x1ef2) REGMBC(0x1ef6) REGMBC(0x1ef8)
+ return;
+ case 'Z': CASEMBC(0x179) CASEMBC(0x17b) CASEMBC(0x17d)
+ CASEMBC(0x1b5) CASEMBC(0x1e90) CASEMBC(0x1e94)
+ regmbc('Z'); REGMBC(0x179) REGMBC(0x17b)
+ REGMBC(0x17d) REGMBC(0x1b5) REGMBC(0x1e90)
+ REGMBC(0x1e94)
+ return;
+ case 'a': case 0xe0: case 0xe1: case 0xe2:
+ case 0xe3: case 0xe4: case 0xe5:
+ CASEMBC(0x101) CASEMBC(0x103) CASEMBC(0x105) CASEMBC(0x1ce)
+ CASEMBC(0x1df) CASEMBC(0x1e1) CASEMBC(0x1ea3)
+ regmbc('a'); regmbc(0xe0); regmbc(0xe1);
+ regmbc(0xe2); regmbc(0xe3); regmbc(0xe4);
+ regmbc(0xe5);
+ REGMBC(0x101) REGMBC(0x103) REGMBC(0x105)
+ REGMBC(0x1ce) REGMBC(0x1df) REGMBC(0x1e1)
+ REGMBC(0x1ea3)
+ return;
+ case 'b': CASEMBC(0x1e03) CASEMBC(0x1e07)
+ regmbc('b'); REGMBC(0x1e03) REGMBC(0x1e07)
+ return;
+ case 'c': case 0xe7:
+ CASEMBC(0x107) CASEMBC(0x109) CASEMBC(0x10b) CASEMBC(0x10d)
+ regmbc('c'); regmbc(0xe7);
+ REGMBC(0x107) REGMBC(0x109) REGMBC(0x10b)
+ REGMBC(0x10d)
+ return;
+ case 'd': CASEMBC(0x10f) CASEMBC(0x111) CASEMBC(0x1e0b)
+ CASEMBC(0x1e0f) CASEMBC(0x1e11)
+ regmbc('d'); REGMBC(0x10f) REGMBC(0x111)
+ REGMBC(0x1e0b) REGMBC(0x1e0f) REGMBC(0x1e11)
+ return;
+ case 'e': case 0xe8: case 0xe9: case 0xea: case 0xeb:
+ CASEMBC(0x113) CASEMBC(0x115) CASEMBC(0x117) CASEMBC(0x119)
+ CASEMBC(0x11b) CASEMBC(0x1ebb) CASEMBC(0x1ebd)
+ regmbc('e'); regmbc(0xe8); regmbc(0xe9);
+ regmbc(0xea); regmbc(0xeb);
+ REGMBC(0x113) REGMBC(0x115) REGMBC(0x117)
+ REGMBC(0x119) REGMBC(0x11b) REGMBC(0x1ebb)
+ REGMBC(0x1ebd)
+ return;
+ case 'f': CASEMBC(0x1e1f)
+ regmbc('f'); REGMBC(0x1e1f)
+ return;
+ case 'g': CASEMBC(0x11d) CASEMBC(0x11f) CASEMBC(0x121)
+ CASEMBC(0x123) CASEMBC(0x1e5) CASEMBC(0x1e7) CASEMBC(0x1f5)
+ CASEMBC(0x1e21)
+ regmbc('g'); REGMBC(0x11d) REGMBC(0x11f)
+ REGMBC(0x121) REGMBC(0x123) REGMBC(0x1e5)
+ REGMBC(0x1e7) REGMBC(0x1f5) REGMBC(0x1e21)
+ return;
+ case 'h': CASEMBC(0x125) CASEMBC(0x127) CASEMBC(0x1e23)
+ CASEMBC(0x1e27) CASEMBC(0x1e29) CASEMBC(0x1e96)
+ regmbc('h'); REGMBC(0x125) REGMBC(0x127)
+ REGMBC(0x1e23) REGMBC(0x1e27) REGMBC(0x1e29)
+ REGMBC(0x1e96)
+ return;
+ case 'i': case 0xec: case 0xed: case 0xee: case 0xef:
+ CASEMBC(0x129) CASEMBC(0x12b) CASEMBC(0x12d) CASEMBC(0x12f)
+ CASEMBC(0x1d0) CASEMBC(0x1ec9)
+ regmbc('i'); regmbc(0xec); regmbc(0xed);
+ regmbc(0xee); regmbc(0xef);
+ REGMBC(0x129) REGMBC(0x12b) REGMBC(0x12d)
+ REGMBC(0x12f) REGMBC(0x1d0) REGMBC(0x1ec9)
+ return;
+ case 'j': CASEMBC(0x135) CASEMBC(0x1f0)
+ regmbc('j'); REGMBC(0x135) REGMBC(0x1f0)
+ return;
+ case 'k': CASEMBC(0x137) CASEMBC(0x1e9) CASEMBC(0x1e31)
+ CASEMBC(0x1e35)
+ regmbc('k'); REGMBC(0x137) REGMBC(0x1e9)
+ REGMBC(0x1e31) REGMBC(0x1e35)
+ return;
+ case 'l': CASEMBC(0x13a) CASEMBC(0x13c) CASEMBC(0x13e)
+ CASEMBC(0x140) CASEMBC(0x142) CASEMBC(0x1e3b)
+ regmbc('l'); REGMBC(0x13a) REGMBC(0x13c)
+ REGMBC(0x13e) REGMBC(0x140) REGMBC(0x142)
+ REGMBC(0x1e3b)
+ return;
+ case 'm': CASEMBC(0x1e3f) CASEMBC(0x1e41)
+ regmbc('m'); REGMBC(0x1e3f) REGMBC(0x1e41)
+ return;
+ case 'n': case 0xf1:
+ CASEMBC(0x144) CASEMBC(0x146) CASEMBC(0x148) CASEMBC(0x149)
+ CASEMBC(0x1e45) CASEMBC(0x1e49)
+ regmbc('n'); regmbc(0xf1);
+ REGMBC(0x144) REGMBC(0x146) REGMBC(0x148)
+ REGMBC(0x149) REGMBC(0x1e45) REGMBC(0x1e49)
+ return;
+ case 'o': case 0xf2: case 0xf3: case 0xf4: case 0xf5:
+ case 0xf6: case 0xf8:
+ CASEMBC(0x14d) CASEMBC(0x14f) CASEMBC(0x151) CASEMBC(0x1a1)
+ CASEMBC(0x1d2) CASEMBC(0x1eb) CASEMBC(0x1ed) CASEMBC(0x1ecf)
+ regmbc('o'); regmbc(0xf2); regmbc(0xf3);
+ regmbc(0xf4); regmbc(0xf5); regmbc(0xf6);
+ regmbc(0xf8);
+ REGMBC(0x14d) REGMBC(0x14f) REGMBC(0x151)
+ REGMBC(0x1a1) REGMBC(0x1d2) REGMBC(0x1eb)
+ REGMBC(0x1ed) REGMBC(0x1ecf)
+ return;
+ case 'p': CASEMBC(0x1e55) CASEMBC(0x1e57)
+ regmbc('p'); REGMBC(0x1e55) REGMBC(0x1e57)
+ return;
+ case 'r': CASEMBC(0x155) CASEMBC(0x157) CASEMBC(0x159)
+ CASEMBC(0x1e59) CASEMBC(0x1e5f)
+ regmbc('r'); REGMBC(0x155) REGMBC(0x157) REGMBC(0x159)
+ REGMBC(0x1e59) REGMBC(0x1e5f)
+ return;
+ case 's': CASEMBC(0x15b) CASEMBC(0x15d) CASEMBC(0x15f)
+ CASEMBC(0x161) CASEMBC(0x1e61)
+ regmbc('s'); REGMBC(0x15b) REGMBC(0x15d)
+ REGMBC(0x15f) REGMBC(0x161) REGMBC(0x1e61)
+ return;
+ case 't': CASEMBC(0x163) CASEMBC(0x165) CASEMBC(0x167)
+ CASEMBC(0x1e6b) CASEMBC(0x1e6f) CASEMBC(0x1e97)
+ regmbc('t'); REGMBC(0x163) REGMBC(0x165) REGMBC(0x167)
+ REGMBC(0x1e6b) REGMBC(0x1e6f) REGMBC(0x1e97)
+ return;
+ case 'u': case 0xf9: case 0xfa: case 0xfb: case 0xfc:
+ CASEMBC(0x169) CASEMBC(0x16b) CASEMBC(0x16d) CASEMBC(0x16f)
+ CASEMBC(0x171) CASEMBC(0x173) CASEMBC(0x1b0) CASEMBC(0x1d4)
+ CASEMBC(0x1ee7)
+ regmbc('u'); regmbc(0xf9); regmbc(0xfa);
+ regmbc(0xfb); regmbc(0xfc);
+ REGMBC(0x169) REGMBC(0x16b) REGMBC(0x16d)
+ REGMBC(0x16f) REGMBC(0x171) REGMBC(0x173)
+ REGMBC(0x1b0) REGMBC(0x1d4) REGMBC(0x1ee7)
+ return;
+ case 'v': CASEMBC(0x1e7d)
+ regmbc('v'); REGMBC(0x1e7d)
+ return;
+ case 'w': CASEMBC(0x175) CASEMBC(0x1e81) CASEMBC(0x1e83)
+ CASEMBC(0x1e85) CASEMBC(0x1e87) CASEMBC(0x1e98)
+ regmbc('w'); REGMBC(0x175) REGMBC(0x1e81)
+ REGMBC(0x1e83) REGMBC(0x1e85) REGMBC(0x1e87)
+ REGMBC(0x1e98)
+ return;
+ case 'x': CASEMBC(0x1e8b) CASEMBC(0x1e8d)
+ regmbc('x'); REGMBC(0x1e8b) REGMBC(0x1e8d)
+ return;
+ case 'y': case 0xfd: case 0xff:
+ CASEMBC(0x177) CASEMBC(0x1e8f) CASEMBC(0x1e99)
+ CASEMBC(0x1ef3) CASEMBC(0x1ef7) CASEMBC(0x1ef9)
+ regmbc('y'); regmbc(0xfd); regmbc(0xff);
+ REGMBC(0x177) REGMBC(0x1e8f) REGMBC(0x1e99)
+ REGMBC(0x1ef3) REGMBC(0x1ef7) REGMBC(0x1ef9)
+ return;
+ case 'z': CASEMBC(0x17a) CASEMBC(0x17c) CASEMBC(0x17e)
+ CASEMBC(0x1b6) CASEMBC(0x1e91) CASEMBC(0x1e95)
+ regmbc('z'); REGMBC(0x17a) REGMBC(0x17c)
+ REGMBC(0x17e) REGMBC(0x1b6) REGMBC(0x1e91)
+ REGMBC(0x1e95)
+ return;
+ }
+ }
+ regmbc(c);
+}
+
+
+
+/*
+ * Emit a node.
+ * Return pointer to generated code.
+ */
+static char_u *regnode(int op)
+{
+ char_u *ret;
+
+ ret = regcode;
+ if (ret == JUST_CALC_SIZE)
+ regsize += 3;
+ else {
+ *regcode++ = op;
+ *regcode++ = NUL; // Null "next" pointer.
+ *regcode++ = NUL;
+ }
+ return ret;
+}
+
+/*
+ * Write a four bytes number at "p" and return pointer to the next char.
+ */
+static char_u *re_put_uint32(char_u *p, uint32_t val)
+{
+ *p++ = (char_u)((val >> 24) & 0377);
+ *p++ = (char_u)((val >> 16) & 0377);
+ *p++ = (char_u)((val >> 8) & 0377);
+ *p++ = (char_u)(val & 0377);
+ return p;
+}
+
+/*
+ * regnext - dig the "next" pointer out of a node
+ * Returns NULL when calculating size, when there is no next item and when
+ * there is an error.
+ */
+static char_u *regnext(char_u *p)
+ FUNC_ATTR_NONNULL_ALL
+{
+ int offset;
+
+ if (p == JUST_CALC_SIZE || reg_toolong)
+ return NULL;
+
+ offset = NEXT(p);
+ if (offset == 0)
+ return NULL;
+
+ if (OP(p) == BACK)
+ return p - offset;
+ else
+ return p + offset;
+}
+
+// Set the next-pointer at the end of a node chain.
+static void regtail(char_u *p, char_u *val)
+{
+ int offset;
+
+ if (p == JUST_CALC_SIZE) {
+ return;
+ }
+
+ // Find last node.
+ char_u *scan = p;
+ for (;; ) {
+ char_u *temp = regnext(scan);
+ if (temp == NULL) {
+ break;
+ }
+ scan = temp;
+ }
+
+ if (OP(scan) == BACK) {
+ offset = (int)(scan - val);
+ } else {
+ offset = (int)(val - scan);
+ }
+ // When the offset uses more than 16 bits it can no longer fit in the two
+ // bytes available. Use a global flag to avoid having to check return
+ // values in too many places.
+ if (offset > 0xffff) {
+ reg_toolong = true;
+ } else {
+ *(scan + 1) = (char_u)(((unsigned)offset >> 8) & 0377);
+ *(scan + 2) = (char_u)(offset & 0377);
+ }
+}
+
+/*
+ * Like regtail, on item after a BRANCH; nop if none.
+ */
+static void regoptail(char_u *p, char_u *val)
+{
+ // When op is neither BRANCH nor BRACE_COMPLEX0-9, it is "operandless"
+ if (p == NULL || p == JUST_CALC_SIZE
+ || (OP(p) != BRANCH
+ && (OP(p) < BRACE_COMPLEX || OP(p) > BRACE_COMPLEX + 9)))
+ return;
+ regtail(OPERAND(p), val);
+}
+
+
+/*
+ * Insert an operator in front of already-emitted operand
+ *
+ * Means relocating the operand.
+ */
+static void reginsert(int op, char_u *opnd)
+{
+ char_u *src;
+ char_u *dst;
+ char_u *place;
+
+ if (regcode == JUST_CALC_SIZE) {
+ regsize += 3;
+ return;
+ }
+ src = regcode;
+ regcode += 3;
+ dst = regcode;
+ while (src > opnd)
+ *--dst = *--src;
+
+ place = opnd; // Op node, where operand used to be.
+ *place++ = op;
+ *place++ = NUL;
+ *place = NUL;
+}
+
+/*
+ * Insert an operator in front of already-emitted operand.
+ * Add a number to the operator.
+ */
+static void reginsert_nr(int op, long val, char_u *opnd)
+{
+ char_u *src;
+ char_u *dst;
+ char_u *place;
+
+ if (regcode == JUST_CALC_SIZE) {
+ regsize += 7;
+ return;
+ }
+ src = regcode;
+ regcode += 7;
+ dst = regcode;
+ while (src > opnd)
+ *--dst = *--src;
+
+ place = opnd; // Op node, where operand used to be.
+ *place++ = op;
+ *place++ = NUL;
+ *place++ = NUL;
+ assert(val >= 0 && (uintmax_t)val <= UINT32_MAX);
+ re_put_uint32(place, (uint32_t)val);
+}
+
+/*
+ * Insert an operator in front of already-emitted operand.
+ * The operator has the given limit values as operands. Also set next pointer.
+ *
+ * Means relocating the operand.
+ */
+static void reginsert_limits(int op, long minval, long maxval, char_u *opnd)
+{
+ char_u *src;
+ char_u *dst;
+ char_u *place;
+
+ if (regcode == JUST_CALC_SIZE) {
+ regsize += 11;
+ return;
+ }
+ src = regcode;
+ regcode += 11;
+ dst = regcode;
+ while (src > opnd)
+ *--dst = *--src;
+
+ place = opnd; // Op node, where operand used to be.
+ *place++ = op;
+ *place++ = NUL;
+ *place++ = NUL;
+ assert(minval >= 0 && (uintmax_t)minval <= UINT32_MAX);
+ place = re_put_uint32(place, (uint32_t)minval);
+ assert(maxval >= 0 && (uintmax_t)maxval <= UINT32_MAX);
+ place = re_put_uint32(place, (uint32_t)maxval);
+ regtail(opnd, place);
+}
+
+/// Return true if the back reference is legal. We must have seen the close
+/// brace.
+/// TODO(vim): Should also check that we don't refer to something repeated
+/// (+*=): what instance of the repetition should we match?
+static int seen_endbrace(int refnum)
+{
+ if (!had_endbrace[refnum]) {
+ char_u *p;
+
+ // Trick: check if "@<=" or "@<!" follows, in which case
+ // the \1 can appear before the referenced match.
+ for (p = regparse; *p != NUL; p++) {
+ if (p[0] == '@' && p[1] == '<' && (p[2] == '!' || p[2] == '=')) {
+ break;
+ }
+ }
+
+ if (*p == NUL) {
+ emsg(_("E65: Illegal back reference"));
+ rc_did_emsg = true;
+ return false;
+ }
+ }
+ return true;
+}
+
+/*
+ * Parse the lowest level.
+ *
+ * Optimization: gobbles an entire sequence of ordinary characters so that
+ * it can turn them into a single node, which is smaller to store and
+ * faster to run. Don't do this when one_exactly is set.
+ */
+static char_u *regatom(int *flagp)
+{
+ char_u *ret;
+ int flags;
+ int c;
+ char_u *p;
+ int extra = 0;
+ int save_prev_at_start = prev_at_start;
+
+ *flagp = WORST; // Tentatively.
+
+ c = getchr();
+ switch (c) {
+ case Magic('^'):
+ ret = regnode(BOL);
+ break;
+
+ case Magic('$'):
+ ret = regnode(EOL);
+ had_eol = true;
+ break;
+
+ case Magic('<'):
+ ret = regnode(BOW);
+ break;
+
+ case Magic('>'):
+ ret = regnode(EOW);
+ break;
+
+ case Magic('_'):
+ c = no_Magic(getchr());
+ if (c == '^') { // "\_^" is start-of-line
+ ret = regnode(BOL);
+ break;
+ }
+ if (c == '$') { // "\_$" is end-of-line
+ ret = regnode(EOL);
+ had_eol = true;
+ break;
+ }
+
+ extra = ADD_NL;
+ *flagp |= HASNL;
+
+ // "\_[" is character range plus newline
+ if (c == '[')
+ goto collection;
+
+ // "\_x" is character class plus newline
+ FALLTHROUGH;
+
+ // Character classes.
+ case Magic('.'):
+ case Magic('i'):
+ case Magic('I'):
+ case Magic('k'):
+ case Magic('K'):
+ case Magic('f'):
+ case Magic('F'):
+ case Magic('p'):
+ case Magic('P'):
+ case Magic('s'):
+ case Magic('S'):
+ case Magic('d'):
+ case Magic('D'):
+ case Magic('x'):
+ case Magic('X'):
+ case Magic('o'):
+ case Magic('O'):
+ case Magic('w'):
+ case Magic('W'):
+ case Magic('h'):
+ case Magic('H'):
+ case Magic('a'):
+ case Magic('A'):
+ case Magic('l'):
+ case Magic('L'):
+ case Magic('u'):
+ case Magic('U'):
+ p = vim_strchr(classchars, no_Magic(c));
+ if (p == NULL)
+ EMSG_RET_NULL(_("E63: invalid use of \\_"));
+ // When '.' is followed by a composing char ignore the dot, so that
+ // the composing char is matched here.
+ if (c == Magic('.') && utf_iscomposing(peekchr())) {
+ c = getchr();
+ goto do_multibyte;
+ }
+ ret = regnode(classcodes[p - classchars] + extra);
+ *flagp |= HASWIDTH | SIMPLE;
+ break;
+
+ case Magic('n'):
+ if (reg_string) {
+ // In a string "\n" matches a newline character.
+ ret = regnode(EXACTLY);
+ regc(NL);
+ regc(NUL);
+ *flagp |= HASWIDTH | SIMPLE;
+ } else {
+ // In buffer text "\n" matches the end of a line.
+ ret = regnode(NEWL);
+ *flagp |= HASWIDTH | HASNL;
+ }
+ break;
+
+ case Magic('('):
+ if (one_exactly)
+ EMSG_ONE_RET_NULL;
+ ret = reg(REG_PAREN, &flags);
+ if (ret == NULL)
+ return NULL;
+ *flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
+ break;
+
+ case NUL:
+ case Magic('|'):
+ case Magic('&'):
+ case Magic(')'):
+ if (one_exactly)
+ EMSG_ONE_RET_NULL;
+ IEMSG_RET_NULL(_(e_internal)); // Supposed to be caught earlier.
+ // NOTREACHED
+
+ case Magic('='):
+ case Magic('?'):
+ case Magic('+'):
+ case Magic('@'):
+ case Magic('{'):
+ case Magic('*'):
+ c = no_Magic(c);
+ EMSG3_RET_NULL(_("E64: %s%c follows nothing"),
+ (c == '*' ? reg_magic >= MAGIC_ON : reg_magic == MAGIC_ALL), c);
+ // NOTREACHED
+
+ case Magic('~'): // previous substitute pattern
+ if (reg_prev_sub != NULL) {
+ char_u *lp;
+
+ ret = regnode(EXACTLY);
+ lp = reg_prev_sub;
+ while (*lp != NUL)
+ regc(*lp++);
+ regc(NUL);
+ if (*reg_prev_sub != NUL) {
+ *flagp |= HASWIDTH;
+ if ((lp - reg_prev_sub) == 1)
+ *flagp |= SIMPLE;
+ }
+ } else
+ EMSG_RET_NULL(_(e_nopresub));
+ break;
+
+ case Magic('1'):
+ case Magic('2'):
+ case Magic('3'):
+ case Magic('4'):
+ case Magic('5'):
+ case Magic('6'):
+ case Magic('7'):
+ case Magic('8'):
+ case Magic('9'):
+ {
+ int refnum;
+
+ refnum = c - Magic('0');
+ if (!seen_endbrace(refnum)) {
+ return NULL;
+ }
+ ret = regnode(BACKREF + refnum);
+ }
+ break;
+
+ case Magic('z'):
+ {
+ c = no_Magic(getchr());
+ switch (c) {
+ case '(': if ((reg_do_extmatch & REX_SET) == 0)
+ EMSG_RET_NULL(_(e_z_not_allowed));
+ if (one_exactly)
+ EMSG_ONE_RET_NULL;
+ ret = reg(REG_ZPAREN, &flags);
+ if (ret == NULL)
+ return NULL;
+ *flagp |= flags & (HASWIDTH|SPSTART|HASNL|HASLOOKBH);
+ re_has_z = REX_SET;
+ break;
+
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': if ((reg_do_extmatch & REX_USE) == 0)
+ EMSG_RET_NULL(_(e_z1_not_allowed));
+ ret = regnode(ZREF + c - '0');
+ re_has_z = REX_USE;
+ break;
+
+ case 's': ret = regnode(MOPEN + 0);
+ if (!re_mult_next("\\zs")) {
+ return NULL;
+ }
+ break;
+
+ case 'e': ret = regnode(MCLOSE + 0);
+ if (!re_mult_next("\\ze")) {
+ return NULL;
+ }
+ break;
+
+ default: EMSG_RET_NULL(_("E68: Invalid character after \\z"));
+ }
+ }
+ break;
+
+ case Magic('%'):
+ {
+ c = no_Magic(getchr());
+ switch (c) {
+ // () without a back reference
+ case '(':
+ if (one_exactly)
+ EMSG_ONE_RET_NULL;
+ ret = reg(REG_NPAREN, &flags);
+ if (ret == NULL)
+ return NULL;
+ *flagp |= flags & (HASWIDTH | SPSTART | HASNL | HASLOOKBH);
+ break;
+
+ // Catch \%^ and \%$ regardless of where they appear in the
+ // pattern -- regardless of whether or not it makes sense.
+ case '^':
+ ret = regnode(RE_BOF);
+ break;
+
+ case '$':
+ ret = regnode(RE_EOF);
+ break;
+
+ case '#':
+ ret = regnode(CURSOR);
+ break;
+
+ case 'V':
+ ret = regnode(RE_VISUAL);
+ break;
+
+ case 'C':
+ ret = regnode(RE_COMPOSING);
+ break;
+
+ // \%[abc]: Emit as a list of branches, all ending at the last
+ // branch which matches nothing.
+ case '[':
+ if (one_exactly) // doesn't nest
+ EMSG_ONE_RET_NULL;
+ {
+ char_u *lastbranch;
+ char_u *lastnode = NULL;
+ char_u *br;
+
+ ret = NULL;
+ while ((c = getchr()) != ']') {
+ if (c == NUL)
+ EMSG2_RET_NULL(_(e_missing_sb),
+ reg_magic == MAGIC_ALL);
+ br = regnode(BRANCH);
+ if (ret == NULL) {
+ ret = br;
+ } else {
+ regtail(lastnode, br);
+ if (reg_toolong) {
+ return NULL;
+ }
+ }
+
+ ungetchr();
+ one_exactly = true;
+ lastnode = regatom(flagp);
+ one_exactly = false;
+ if (lastnode == NULL) {
+ return NULL;
+ }
+ }
+ if (ret == NULL)
+ EMSG2_RET_NULL(_(e_empty_sb),
+ reg_magic == MAGIC_ALL);
+ lastbranch = regnode(BRANCH);
+ br = regnode(NOTHING);
+ if (ret != JUST_CALC_SIZE) {
+ regtail(lastnode, br);
+ regtail(lastbranch, br);
+ // connect all branches to the NOTHING
+ // branch at the end
+ for (br = ret; br != lastnode; ) {
+ if (OP(br) == BRANCH) {
+ regtail(br, lastbranch);
+ if (reg_toolong) {
+ return NULL;
+ }
+ br = OPERAND(br);
+ } else
+ br = regnext(br);
+ }
+ }
+ *flagp &= ~(HASWIDTH | SIMPLE);
+ break;
+ }
+
+ case 'd': // %d123 decimal
+ case 'o': // %o123 octal
+ case 'x': // %xab hex 2
+ case 'u': // %uabcd hex 4
+ case 'U': // %U1234abcd hex 8
+ {
+ int64_t i;
+
+ switch (c) {
+ case 'd': i = getdecchrs(); break;
+ case 'o': i = getoctchrs(); break;
+ case 'x': i = gethexchrs(2); break;
+ case 'u': i = gethexchrs(4); break;
+ case 'U': i = gethexchrs(8); break;
+ default: i = -1; break;
+ }
+
+ if (i < 0 || i > INT_MAX) {
+ EMSG2_RET_NULL(_("E678: Invalid character after %s%%[dxouU]"),
+ reg_magic == MAGIC_ALL);
+ }
+ if (use_multibytecode(i)) {
+ ret = regnode(MULTIBYTECODE);
+ } else {
+ ret = regnode(EXACTLY);
+ }
+ if (i == 0) {
+ regc(0x0a);
+ } else {
+ regmbc(i);
+ }
+ regc(NUL);
+ *flagp |= HASWIDTH;
+ break;
+ }
+
+ default:
+ if (ascii_isdigit(c) || c == '<' || c == '>'
+ || c == '\'') {
+ uint32_t n = 0;
+ int cmp;
+
+ cmp = c;
+ if (cmp == '<' || cmp == '>')
+ c = getchr();
+ while (ascii_isdigit(c)) {
+ n = n * 10 + (uint32_t)(c - '0');
+ c = getchr();
+ }
+ if (c == '\'' && n == 0) {
+ // "\%'m", "\%<'m" and "\%>'m": Mark
+ c = getchr();
+ ret = regnode(RE_MARK);
+ if (ret == JUST_CALC_SIZE)
+ regsize += 2;
+ else {
+ *regcode++ = c;
+ *regcode++ = cmp;
+ }
+ break;
+ } else if (c == 'l' || c == 'c' || c == 'v') {
+ if (c == 'l') {
+ ret = regnode(RE_LNUM);
+ if (save_prev_at_start) {
+ at_start = true;
+ }
+ } else if (c == 'c') {
+ ret = regnode(RE_COL);
+ } else {
+ ret = regnode(RE_VCOL);
+ }
+ if (ret == JUST_CALC_SIZE) {
+ regsize += 5;
+ } else {
+ // put the number and the optional
+ // comparator after the opcode
+ regcode = re_put_uint32(regcode, n);
+ *regcode++ = cmp;
+ }
+ break;
+ }
+ }
+
+ EMSG2_RET_NULL(_("E71: Invalid character after %s%%"),
+ reg_magic == MAGIC_ALL);
+ }
+ }
+ break;
+
+ case Magic('['):
+collection:
+ {
+ char_u *lp;
+
+ // If there is no matching ']', we assume the '[' is a normal
+ // character. This makes 'incsearch' and ":help [" work.
+ lp = skip_anyof(regparse);
+ if (*lp == ']') { // there is a matching ']'
+ int startc = -1; // > 0 when next '-' is a range
+ int endc;
+
+ // In a character class, different parsing rules apply.
+ // Not even \ is special anymore, nothing is.
+ if (*regparse == '^') { // Complement of range.
+ ret = regnode(ANYBUT + extra);
+ regparse++;
+ } else
+ ret = regnode(ANYOF + extra);
+
+ // At the start ']' and '-' mean the literal character.
+ if (*regparse == ']' || *regparse == '-') {
+ startc = *regparse;
+ regc(*regparse++);
+ }
+
+ while (*regparse != NUL && *regparse != ']') {
+ if (*regparse == '-') {
+ ++regparse;
+ // The '-' is not used for a range at the end and
+ // after or before a '\n'.
+ if (*regparse == ']' || *regparse == NUL
+ || startc == -1
+ || (regparse[0] == '\\' && regparse[1] == 'n')) {
+ regc('-');
+ startc = '-'; // [--x] is a range
+ } else {
+ // Also accept "a-[.z.]"
+ endc = 0;
+ if (*regparse == '[')
+ endc = get_coll_element(&regparse);
+ if (endc == 0) {
+ endc = mb_ptr2char_adv((const char_u **)&regparse);
+ }
+
+ // Handle \o40, \x20 and \u20AC style sequences
+ if (endc == '\\' && !reg_cpo_lit)
+ endc = coll_get_char();
+
+ if (startc > endc) {
+ EMSG_RET_NULL(_(e_reverse_range));
+ }
+ if (utf_char2len(startc) > 1
+ || utf_char2len(endc) > 1) {
+ // Limit to a range of 256 chars
+ if (endc > startc + 256) {
+ EMSG_RET_NULL(_(e_large_class));
+ }
+ while (++startc <= endc) {
+ regmbc(startc);
+ }
+ } else {
+ while (++startc <= endc)
+ regc(startc);
+ }
+ startc = -1;
+ }
+ }
+ // Only "\]", "\^", "\]" and "\\" are special in Vi. Vim
+ // accepts "\t", "\e", etc., but only when the 'l' flag in
+ // 'cpoptions' is not included.
+ else if (*regparse == '\\'
+ && (vim_strchr(REGEXP_INRANGE, regparse[1]) != NULL
+ || (!reg_cpo_lit
+ && vim_strchr(REGEXP_ABBR,
+ regparse[1]) != NULL))) {
+ regparse++;
+ if (*regparse == 'n') {
+ // '\n' in range: also match NL
+ if (ret != JUST_CALC_SIZE) {
+ // Using \n inside [^] does not change what
+ // matches. "[^\n]" is the same as ".".
+ if (*ret == ANYOF) {
+ *ret = ANYOF + ADD_NL;
+ *flagp |= HASNL;
+ }
+ // else: must have had a \n already
+ }
+ regparse++;
+ startc = -1;
+ } else if (*regparse == 'd'
+ || *regparse == 'o'
+ || *regparse == 'x'
+ || *regparse == 'u'
+ || *regparse == 'U') {
+ startc = coll_get_char();
+ if (startc == 0)
+ regc(0x0a);
+ else
+ regmbc(startc);
+ } else {
+ startc = backslash_trans(*regparse++);
+ regc(startc);
+ }
+ } else if (*regparse == '[') {
+ int c_class;
+ int cu;
+
+ c_class = get_char_class(&regparse);
+ startc = -1;
+ // Characters assumed to be 8 bits!
+ switch (c_class) {
+ case CLASS_NONE:
+ c_class = get_equi_class(&regparse);
+ if (c_class != 0) {
+ // produce equivalence class
+ reg_equi_class(c_class);
+ } else if ((c_class =
+ get_coll_element(&regparse)) != 0) {
+ // produce a collating element
+ regmbc(c_class);
+ } else {
+ // literal '[', allow [[-x] as a range
+ startc = *regparse++;
+ regc(startc);
+ }
+ break;
+ case CLASS_ALNUM:
+ for (cu = 1; cu < 128; cu++) {
+ if (isalnum(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_ALPHA:
+ for (cu = 1; cu < 128; cu++) {
+ if (isalpha(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_BLANK:
+ regc(' ');
+ regc('\t');
+ break;
+ case CLASS_CNTRL:
+ for (cu = 1; cu <= 127; cu++) {
+ if (iscntrl(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_DIGIT:
+ for (cu = 1; cu <= 127; cu++) {
+ if (ascii_isdigit(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_GRAPH:
+ for (cu = 1; cu <= 127; cu++) {
+ if (isgraph(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_LOWER:
+ for (cu = 1; cu <= 255; cu++) {
+ if (mb_islower(cu) && cu != 170 && cu != 186) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_PRINT:
+ for (cu = 1; cu <= 255; cu++) {
+ if (vim_isprintc(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_PUNCT:
+ for (cu = 1; cu < 128; cu++) {
+ if (ispunct(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_SPACE:
+ for (cu = 9; cu <= 13; cu++)
+ regc(cu);
+ regc(' ');
+ break;
+ case CLASS_UPPER:
+ for (cu = 1; cu <= 255; cu++) {
+ if (mb_isupper(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_XDIGIT:
+ for (cu = 1; cu <= 255; cu++) {
+ if (ascii_isxdigit(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_TAB:
+ regc('\t');
+ break;
+ case CLASS_RETURN:
+ regc('\r');
+ break;
+ case CLASS_BACKSPACE:
+ regc('\b');
+ break;
+ case CLASS_ESCAPE:
+ regc(ESC);
+ break;
+ case CLASS_IDENT:
+ for (cu = 1; cu <= 255; cu++) {
+ if (vim_isIDc(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_KEYWORD:
+ for (cu = 1; cu <= 255; cu++) {
+ if (reg_iswordc(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ case CLASS_FNAME:
+ for (cu = 1; cu <= 255; cu++) {
+ if (vim_isfilec(cu)) {
+ regmbc(cu);
+ }
+ }
+ break;
+ }
+ } else {
+ // produce a multibyte character, including any
+ // following composing characters.
+ startc = utf_ptr2char(regparse);
+ int len = utfc_ptr2len(regparse);
+ if (utf_char2len(startc) != len) {
+ // composing chars
+ startc = -1;
+ }
+ while (--len >= 0) {
+ regc(*regparse++);
+ }
+ }
+ }
+ regc(NUL);
+ prevchr_len = 1; // last char was the ']'
+ if (*regparse != ']')
+ EMSG_RET_NULL(_(e_toomsbra)); // Cannot happen?
+ skipchr(); // let's be friends with the lexer again
+ *flagp |= HASWIDTH | SIMPLE;
+ break;
+ } else if (reg_strict)
+ EMSG2_RET_NULL(_(e_missingbracket), reg_magic > MAGIC_OFF);
+ }
+ FALLTHROUGH;
+
+ default:
+ {
+ int len;
+
+ // A multi-byte character is handled as a separate atom if it's
+ // before a multi and when it's a composing char.
+ if (use_multibytecode(c)) {
+do_multibyte:
+ ret = regnode(MULTIBYTECODE);
+ regmbc(c);
+ *flagp |= HASWIDTH | SIMPLE;
+ break;
+ }
+
+ ret = regnode(EXACTLY);
+
+ // Append characters as long as:
+ // - there is no following multi, we then need the character in
+ // front of it as a single character operand
+ // - not running into a Magic character
+ // - "one_exactly" is not set
+ // But always emit at least one character. Might be a Multi,
+ // e.g., a "[" without matching "]".
+ for (len = 0; c != NUL && (len == 0
+ || (re_multi_type(peekchr()) == NOT_MULTI
+ && !one_exactly
+ && !is_Magic(c))); ++len) {
+ c = no_Magic(c);
+ {
+ regmbc(c);
+ {
+ int l;
+
+ // Need to get composing character too.
+ for (;; ) {
+ l = utf_ptr2len(regparse);
+ if (!utf_composinglike(regparse, regparse + l)) {
+ break;
+ }
+ regmbc(utf_ptr2char(regparse));
+ skipchr();
+ }
+ }
+ }
+ c = getchr();
+ }
+ ungetchr();
+
+ regc(NUL);
+ *flagp |= HASWIDTH;
+ if (len == 1)
+ *flagp |= SIMPLE;
+ }
+ break;
+ }
+
+ return ret;
+}
+
+/*
+ * Parse something followed by possible [*+=].
+ *
+ * Note that the branching code sequences used for = and the general cases
+ * of * and + are somewhat optimized: they use the same NOTHING node as
+ * both the endmarker for their branch list and the body of the last branch.
+ * It might seem that this node could be dispensed with entirely, but the
+ * endmarker role is not redundant.
+ */
+static char_u *regpiece(int *flagp)
+{
+ char_u *ret;
+ int op;
+ char_u *next;
+ int flags;
+ long minval;
+ long maxval;
+
+ ret = regatom(&flags);
+ if (ret == NULL)
+ return NULL;
+
+ op = peekchr();
+ if (re_multi_type(op) == NOT_MULTI) {
+ *flagp = flags;
+ return ret;
+ }
+ // default flags
+ *flagp = (WORST | SPSTART | (flags & (HASNL | HASLOOKBH)));
+
+ skipchr();
+ switch (op) {
+ case Magic('*'):
+ if (flags & SIMPLE)
+ reginsert(STAR, ret);
+ else {
+ // Emit x* as (x&|), where & means "self".
+ reginsert(BRANCH, ret); // Either x
+ regoptail(ret, regnode(BACK)); // and loop
+ regoptail(ret, ret); // back
+ regtail(ret, regnode(BRANCH)); // or
+ regtail(ret, regnode(NOTHING)); // null.
+ }
+ break;
+
+ case Magic('+'):
+ if (flags & SIMPLE)
+ reginsert(PLUS, ret);
+ else {
+ // Emit x+ as x(&|), where & means "self".
+ next = regnode(BRANCH); // Either
+ regtail(ret, next);
+ regtail(regnode(BACK), ret); // loop back
+ regtail(next, regnode(BRANCH)); // or
+ regtail(ret, regnode(NOTHING)); // null.
+ }
+ *flagp = (WORST | HASWIDTH | (flags & (HASNL | HASLOOKBH)));
+ break;
+
+ case Magic('@'):
+ {
+ int lop = END;
+ int64_t nr = getdecchrs();
+
+ switch (no_Magic(getchr())) {
+ case '=': lop = MATCH; break; // \@=
+ case '!': lop = NOMATCH; break; // \@!
+ case '>': lop = SUBPAT; break; // \@>
+ case '<': switch (no_Magic(getchr())) {
+ case '=': lop = BEHIND; break; // \@<=
+ case '!': lop = NOBEHIND; break; // \@<!
+ }
+ }
+ if (lop == END)
+ EMSG2_RET_NULL(_("E59: invalid character after %s@"),
+ reg_magic == MAGIC_ALL);
+ // Look behind must match with behind_pos.
+ if (lop == BEHIND || lop == NOBEHIND) {
+ regtail(ret, regnode(BHPOS));
+ *flagp |= HASLOOKBH;
+ }
+ regtail(ret, regnode(END)); // operand ends
+ if (lop == BEHIND || lop == NOBEHIND) {
+ if (nr < 0)
+ nr = 0; // no limit is same as zero limit
+ reginsert_nr(lop, (uint32_t)nr, ret);
+ } else
+ reginsert(lop, ret);
+ break;
+ }
+
+ case Magic('?'):
+ case Magic('='):
+ // Emit x= as (x|)
+ reginsert(BRANCH, ret); // Either x
+ regtail(ret, regnode(BRANCH)); // or
+ next = regnode(NOTHING); // null.
+ regtail(ret, next);
+ regoptail(ret, next);
+ break;
+
+ case Magic('{'):
+ if (!read_limits(&minval, &maxval))
+ return NULL;
+ if (flags & SIMPLE) {
+ reginsert(BRACE_SIMPLE, ret);
+ reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
+ } else {
+ if (num_complex_braces >= 10)
+ EMSG2_RET_NULL(_("E60: Too many complex %s{...}s"),
+ reg_magic == MAGIC_ALL);
+ reginsert(BRACE_COMPLEX + num_complex_braces, ret);
+ regoptail(ret, regnode(BACK));
+ regoptail(ret, ret);
+ reginsert_limits(BRACE_LIMITS, minval, maxval, ret);
+ ++num_complex_braces;
+ }
+ if (minval > 0 && maxval > 0)
+ *flagp = (HASWIDTH | (flags & (HASNL | HASLOOKBH)));
+ break;
+ }
+ if (re_multi_type(peekchr()) != NOT_MULTI) {
+ // Can't have a multi follow a multi.
+ if (peekchr() == Magic('*')) {
+ EMSG2_RET_NULL(_("E61: Nested %s*"), reg_magic >= MAGIC_ON);
+ }
+ EMSG3_RET_NULL(_("E62: Nested %s%c"), reg_magic == MAGIC_ALL, no_Magic(peekchr()));
+ }
+
+ return ret;
+}
+
+/*
+ * Parse one alternative of an | or & operator.
+ * Implements the concatenation operator.
+ */
+static char_u *regconcat(int *flagp)
+{
+ char_u *first = NULL;
+ char_u *chain = NULL;
+ char_u *latest;
+ int flags;
+ int cont = true;
+
+ *flagp = WORST; // Tentatively.
+
+ while (cont) {
+ switch (peekchr()) {
+ case NUL:
+ case Magic('|'):
+ case Magic('&'):
+ case Magic(')'):
+ cont = false;
+ break;
+ case Magic('Z'):
+ regflags |= RF_ICOMBINE;
+ skipchr_keepstart();
+ break;
+ case Magic('c'):
+ regflags |= RF_ICASE;
+ skipchr_keepstart();
+ break;
+ case Magic('C'):
+ regflags |= RF_NOICASE;
+ skipchr_keepstart();
+ break;
+ case Magic('v'):
+ reg_magic = MAGIC_ALL;
+ skipchr_keepstart();
+ curchr = -1;
+ break;
+ case Magic('m'):
+ reg_magic = MAGIC_ON;
+ skipchr_keepstart();
+ curchr = -1;
+ break;
+ case Magic('M'):
+ reg_magic = MAGIC_OFF;
+ skipchr_keepstart();
+ curchr = -1;
+ break;
+ case Magic('V'):
+ reg_magic = MAGIC_NONE;
+ skipchr_keepstart();
+ curchr = -1;
+ break;
+ default:
+ latest = regpiece(&flags);
+ if (latest == NULL || reg_toolong)
+ return NULL;
+ *flagp |= flags & (HASWIDTH | HASNL | HASLOOKBH);
+ if (chain == NULL) // First piece.
+ *flagp |= flags & SPSTART;
+ else
+ regtail(chain, latest);
+ chain = latest;
+ if (first == NULL)
+ first = latest;
+ break;
+ }
+ }
+ if (first == NULL) // Loop ran zero times.
+ first = regnode(NOTHING);
+ return first;
+}
+
+/*
+ * Parse one alternative of an | operator.
+ * Implements the & operator.
+ */
+static char_u *regbranch(int *flagp)
+{
+ char_u *ret;
+ char_u *chain = NULL;
+ char_u *latest;
+ int flags;
+
+ *flagp = WORST | HASNL; // Tentatively.
+
+ ret = regnode(BRANCH);
+ for (;; ) {
+ latest = regconcat(&flags);
+ if (latest == NULL)
+ return NULL;
+ // If one of the branches has width, the whole thing has. If one of
+ // the branches anchors at start-of-line, the whole thing does.
+ // If one of the branches uses look-behind, the whole thing does.
+ *flagp |= flags & (HASWIDTH | SPSTART | HASLOOKBH);
+ // If one of the branches doesn't match a line-break, the whole thing
+ // doesn't.
+ *flagp &= ~HASNL | (flags & HASNL);
+ if (chain != NULL)
+ regtail(chain, latest);
+ if (peekchr() != Magic('&'))
+ break;
+ skipchr();
+ regtail(latest, regnode(END)); // operand ends
+ if (reg_toolong)
+ break;
+ reginsert(MATCH, latest);
+ chain = latest;
+ }
+
+ return ret;
+}
+
+/*
+ * Parse regular expression, i.e. main body or parenthesized thing.
+ *
+ * Caller must absorb opening parenthesis.
+ *
+ * Combining parenthesis handling with the base level of regular expression
+ * is a trifle forced, but the need to tie the tails of the branches to what
+ * follows makes it hard to avoid.
+ */
+static char_u *reg(
+ int paren, // REG_NOPAREN, REG_PAREN, REG_NPAREN or REG_ZPAREN
+ int *flagp)
+{
+ char_u *ret;
+ char_u *br;
+ char_u *ender;
+ int parno = 0;
+ int flags;
+
+ *flagp = HASWIDTH; // Tentatively.
+
+ if (paren == REG_ZPAREN) {
+ // Make a ZOPEN node.
+ if (regnzpar >= NSUBEXP)
+ EMSG_RET_NULL(_("E50: Too many \\z("));
+ parno = regnzpar;
+ regnzpar++;
+ ret = regnode(ZOPEN + parno);
+ } else if (paren == REG_PAREN) {
+ // Make a MOPEN node.
+ if (regnpar >= NSUBEXP)
+ EMSG2_RET_NULL(_("E51: Too many %s("), reg_magic == MAGIC_ALL);
+ parno = regnpar;
+ ++regnpar;
+ ret = regnode(MOPEN + parno);
+ } else if (paren == REG_NPAREN) {
+ // Make a NOPEN node.
+ ret = regnode(NOPEN);
+ } else
+ ret = NULL;
+
+ // Pick up the branches, linking them together.
+ br = regbranch(&flags);
+ if (br == NULL)
+ return NULL;
+ if (ret != NULL)
+ regtail(ret, br); // [MZ]OPEN -> first.
+ else
+ ret = br;
+ // If one of the branches can be zero-width, the whole thing can.
+ // If one of the branches has * at start or matches a line-break, the
+ // whole thing can.
+ if (!(flags & HASWIDTH))
+ *flagp &= ~HASWIDTH;
+ *flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
+ while (peekchr() == Magic('|')) {
+ skipchr();
+ br = regbranch(&flags);
+ if (br == NULL || reg_toolong)
+ return NULL;
+ regtail(ret, br); // BRANCH -> BRANCH.
+ if (!(flags & HASWIDTH))
+ *flagp &= ~HASWIDTH;
+ *flagp |= flags & (SPSTART | HASNL | HASLOOKBH);
+ }
+
+ // Make a closing node, and hook it on the end.
+ ender = regnode(
+ paren == REG_ZPAREN ? ZCLOSE + parno :
+ paren == REG_PAREN ? MCLOSE + parno :
+ paren == REG_NPAREN ? NCLOSE : END);
+ regtail(ret, ender);
+
+ // Hook the tails of the branches to the closing node.
+ for (br = ret; br != NULL; br = regnext(br))
+ regoptail(br, ender);
+
+ // Check for proper termination.
+ if (paren != REG_NOPAREN && getchr() != Magic(')')) {
+ if (paren == REG_ZPAREN)
+ EMSG_RET_NULL(_("E52: Unmatched \\z("));
+ else if (paren == REG_NPAREN)
+ EMSG2_RET_NULL(_(e_unmatchedpp), reg_magic == MAGIC_ALL);
+ else
+ EMSG2_RET_NULL(_(e_unmatchedp), reg_magic == MAGIC_ALL);
+ } else if (paren == REG_NOPAREN && peekchr() != NUL) {
+ if (curchr == Magic(')'))
+ EMSG2_RET_NULL(_(e_unmatchedpar), reg_magic == MAGIC_ALL);
+ else
+ EMSG_RET_NULL(_(e_trailing)); // "Can't happen".
+ // NOTREACHED
+ }
+ // Here we set the flag allowing back references to this set of
+ // parentheses.
+ if (paren == REG_PAREN) {
+ had_endbrace[parno] = true; // have seen the close paren
+ }
+ return ret;
+}
+
+
+/*
+ * bt_regcomp() - compile a regular expression into internal code for the
+ * traditional back track matcher.
+ * Returns the program in allocated space. Returns NULL for an error.
+ *
+ * We can't allocate space until we know how big the compiled form will be,
+ * but we can't compile it (and thus know how big it is) until we've got a
+ * place to put the code. So we cheat: we compile it twice, once with code
+ * generation turned off and size counting turned on, and once "for real".
+ * This also means that we don't allocate space until we are sure that the
+ * thing really will compile successfully, and we never have to move the
+ * code and thus invalidate pointers into it. (Note that it has to be in
+ * one piece because free() must be able to free it all.)
+ *
+ * Whether upper/lower case is to be ignored is decided when executing the
+ * program, it does not matter here.
+ *
+ * Beware that the optimization-preparation code in here knows about some
+ * of the structure of the compiled regexp.
+ * "re_flags": RE_MAGIC and/or RE_STRING.
+ */
+static regprog_T *bt_regcomp(char_u *expr, int re_flags)
+{
+ char_u *scan;
+ char_u *longest;
+ int len;
+ int flags;
+
+ if (expr == NULL) {
+ IEMSG_RET_NULL(_(e_null));
+ }
+
+ init_class_tab();
+
+ // First pass: determine size, legality.
+ regcomp_start(expr, re_flags);
+ regcode = JUST_CALC_SIZE;
+ regc(REGMAGIC);
+ if (reg(REG_NOPAREN, &flags) == NULL)
+ return NULL;
+
+ // Allocate space.
+ bt_regprog_T *r = xmalloc(sizeof(bt_regprog_T) + regsize);
+ r->re_in_use = false;
+
+ // Second pass: emit code.
+ regcomp_start(expr, re_flags);
+ regcode = r->program;
+ regc(REGMAGIC);
+ if (reg(REG_NOPAREN, &flags) == NULL || reg_toolong) {
+ xfree(r);
+ if (reg_toolong)
+ EMSG_RET_NULL(_("E339: Pattern too long"));
+ return NULL;
+ }
+
+ // Dig out information for optimizations.
+ r->regstart = NUL; // Worst-case defaults.
+ r->reganch = 0;
+ r->regmust = NULL;
+ r->regmlen = 0;
+ r->regflags = regflags;
+ if (flags & HASNL)
+ r->regflags |= RF_HASNL;
+ if (flags & HASLOOKBH)
+ r->regflags |= RF_LOOKBH;
+ // Remember whether this pattern has any \z specials in it.
+ r->reghasz = re_has_z;
+ scan = r->program + 1; // First BRANCH.
+ if (OP(regnext(scan)) == END) { // Only one top-level choice.
+ scan = OPERAND(scan);
+
+ // Starting-point info.
+ if (OP(scan) == BOL || OP(scan) == RE_BOF) {
+ r->reganch++;
+ scan = regnext(scan);
+ }
+
+ if (OP(scan) == EXACTLY) {
+ r->regstart = utf_ptr2char(OPERAND(scan));
+ } else if (OP(scan) == BOW
+ || OP(scan) == EOW
+ || OP(scan) == NOTHING
+ || OP(scan) == MOPEN + 0 || OP(scan) == NOPEN
+ || OP(scan) == MCLOSE + 0 || OP(scan) == NCLOSE) {
+ char_u *regnext_scan = regnext(scan);
+ if (OP(regnext_scan) == EXACTLY) {
+ r->regstart = utf_ptr2char(OPERAND(regnext_scan));
+ }
+ }
+
+ // If there's something expensive in the r.e., find the longest
+ // literal string that must appear and make it the regmust. Resolve
+ // ties in favor of later strings, since the regstart check works
+ // with the beginning of the r.e. and avoiding duplication
+ // strengthens checking. Not a strong reason, but sufficient in the
+ // absence of others.
+
+ // When the r.e. starts with BOW, it is faster to look for a regmust
+ // first. Used a lot for "#" and "*" commands. (Added by mool).
+ if ((flags & SPSTART || OP(scan) == BOW || OP(scan) == EOW)
+ && !(flags & HASNL)) {
+ longest = NULL;
+ len = 0;
+ for (; scan != NULL; scan = regnext(scan))
+ if (OP(scan) == EXACTLY && STRLEN(OPERAND(scan)) >= (size_t)len) {
+ longest = OPERAND(scan);
+ len = (int)STRLEN(OPERAND(scan));
+ }
+ r->regmust = longest;
+ r->regmlen = len;
+ }
+ }
+#ifdef BT_REGEXP_DUMP
+ regdump(expr, r);
+#endif
+ r->engine = &bt_regengine;
+ return (regprog_T *)r;
+}
+
+/*
+ * Check if during the previous call to vim_regcomp the EOL item "$" has been
+ * found. This is messy, but it works fine.
+ */
+int vim_regcomp_had_eol(void)
+{
+ return had_eol;
+}
+
+/*
+ * Get a number after a backslash that is inside [].
+ * When nothing is recognized return a backslash.
+ */
+static int coll_get_char(void)
+{
+ int64_t nr = -1;
+
+ switch (*regparse++) {
+ case 'd': nr = getdecchrs(); break;
+ case 'o': nr = getoctchrs(); break;
+ case 'x': nr = gethexchrs(2); break;
+ case 'u': nr = gethexchrs(4); break;
+ case 'U': nr = gethexchrs(8); break;
+ }
+ if (nr < 0 || nr > INT_MAX) {
+ // If getting the number fails be backwards compatible: the character
+ // is a backslash.
+ regparse--;
+ nr = '\\';
+ }
+ return nr;
+}
+
+/*
+ * Free a compiled regexp program, returned by bt_regcomp().
+ */
+static void bt_regfree(regprog_T *prog)
+{
+ xfree(prog);
+}
+
+#define ADVANCE_REGINPUT() MB_PTR_ADV(rex.input)
+
+/*
+ * The arguments from BRACE_LIMITS are stored here. They are actually local
+ * to regmatch(), but they are here to reduce the amount of stack space used
+ * (it can be called recursively many times).
+ */
+static long bl_minval;
+static long bl_maxval;
+
+// Save the input line and position in a regsave_T.
+static void reg_save(regsave_T *save, garray_T *gap)
+ FUNC_ATTR_NONNULL_ALL
+{
+ if (REG_MULTI) {
+ save->rs_u.pos.col = (colnr_T)(rex.input - rex.line);
+ save->rs_u.pos.lnum = rex.lnum;
+ } else {
+ save->rs_u.ptr = rex.input;
+ }
+ save->rs_len = gap->ga_len;
+}
+
+// Restore the input line and position from a regsave_T.
+static void reg_restore(regsave_T *save, garray_T *gap)
+ FUNC_ATTR_NONNULL_ALL
+{
+ if (REG_MULTI) {
+ if (rex.lnum != save->rs_u.pos.lnum) {
+ // only call reg_getline() when the line number changed to save
+ // a bit of time
+ rex.lnum = save->rs_u.pos.lnum;
+ rex.line = reg_getline(rex.lnum);
+ }
+ rex.input = rex.line + save->rs_u.pos.col;
+ } else {
+ rex.input = save->rs_u.ptr;
+ }
+ gap->ga_len = save->rs_len;
+}
+
+// Return true if current position is equal to saved position.
+static bool reg_save_equal(const regsave_T *save)
+ FUNC_ATTR_NONNULL_ALL
+{
+ if (REG_MULTI) {
+ return rex.lnum == save->rs_u.pos.lnum
+ && rex.input == rex.line + save->rs_u.pos.col;
+ }
+ return rex.input == save->rs_u.ptr;
+}
+
+// Save the sub-expressions before attempting a match.
+#define save_se(savep, posp, pp) \
+ REG_MULTI ? save_se_multi((savep), (posp)) : save_se_one((savep), (pp))
+
+// After a failed match restore the sub-expressions.
+#define restore_se(savep, posp, pp) { \
+ if (REG_MULTI) \
+ *(posp) = (savep)->se_u.pos; \
+ else \
+ *(pp) = (savep)->se_u.ptr; }
+
+/*
+ * Tentatively set the sub-expression start to the current position (after
+ * calling regmatch() they will have changed). Need to save the existing
+ * values for when there is no match.
+ * Use se_save() to use pointer (save_se_multi()) or position (save_se_one()),
+ * depending on REG_MULTI.
+ */
+static void save_se_multi(save_se_T *savep, lpos_T *posp)
+{
+ savep->se_u.pos = *posp;
+ posp->lnum = rex.lnum;
+ posp->col = (colnr_T)(rex.input - rex.line);
+}
+
+static void save_se_one(save_se_T *savep, char_u **pp)
+{
+ savep->se_u.ptr = *pp;
+ *pp = rex.input;
+}
+
+/*
+ * regrepeat - repeatedly match something simple, return how many.
+ * Advances rex.input (and rex.lnum) to just after the matched chars.
+ */
+ static int
+regrepeat(
+ char_u *p,
+ long maxcount) // maximum number of matches allowed
+{
+ long count = 0;
+ char_u *opnd;
+ int mask;
+ int testval = 0;
+
+ char_u *scan = rex.input; // Make local copy of rex.input for speed.
+ opnd = OPERAND(p);
+ switch (OP(p)) {
+ case ANY:
+ case ANY + ADD_NL:
+ while (count < maxcount) {
+ // Matching anything means we continue until end-of-line (or
+ // end-of-file for ANY + ADD_NL), only limited by maxcount.
+ while (*scan != NUL && count < maxcount) {
+ count++;
+ MB_PTR_ADV(scan);
+ }
+ if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
+ || rex.reg_line_lbr || count == maxcount) {
+ break;
+ }
+ count++; // count the line-break
+ reg_nextline();
+ scan = rex.input;
+ if (got_int) {
+ break;
+ }
+ }
+ break;
+
+ case IDENT:
+ case IDENT + ADD_NL:
+ testval = 1;
+ FALLTHROUGH;
+ case SIDENT:
+ case SIDENT + ADD_NL:
+ while (count < maxcount) {
+ if (vim_isIDc(utf_ptr2char(scan)) && (testval || !ascii_isdigit(*scan))) {
+ MB_PTR_ADV(scan);
+ } else if (*scan == NUL) {
+ if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
+ || rex.reg_line_lbr) {
+ break;
+ }
+ reg_nextline();
+ scan = rex.input;
+ if (got_int) {
+ break;
+ }
+ } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
+ scan++;
+ } else {
+ break;
+ }
+ ++count;
+ }
+ break;
+
+ case KWORD:
+ case KWORD + ADD_NL:
+ testval = 1;
+ FALLTHROUGH;
+ case SKWORD:
+ case SKWORD + ADD_NL:
+ while (count < maxcount) {
+ if (vim_iswordp_buf(scan, rex.reg_buf)
+ && (testval || !ascii_isdigit(*scan))) {
+ MB_PTR_ADV(scan);
+ } else if (*scan == NUL) {
+ if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
+ || rex.reg_line_lbr) {
+ break;
+ }
+ reg_nextline();
+ scan = rex.input;
+ if (got_int) {
+ break;
+ }
+ } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
+ scan++;
+ } else {
+ break;
+ }
+ count++;
+ }
+ break;
+
+ case FNAME:
+ case FNAME + ADD_NL:
+ testval = 1;
+ FALLTHROUGH;
+ case SFNAME:
+ case SFNAME + ADD_NL:
+ while (count < maxcount) {
+ if (vim_isfilec(utf_ptr2char(scan)) && (testval || !ascii_isdigit(*scan))) {
+ MB_PTR_ADV(scan);
+ } else if (*scan == NUL) {
+ if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
+ || rex.reg_line_lbr) {
+ break;
+ }
+ reg_nextline();
+ scan = rex.input;
+ if (got_int) {
+ break;
+ }
+ } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
+ scan++;
+ } else {
+ break;
+ }
+ count++;
+ }
+ break;
+
+ case PRINT:
+ case PRINT + ADD_NL:
+ testval = 1;
+ FALLTHROUGH;
+ case SPRINT:
+ case SPRINT + ADD_NL:
+ while (count < maxcount) {
+ if (*scan == NUL) {
+ if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
+ || rex.reg_line_lbr) {
+ break;
+ }
+ reg_nextline();
+ scan = rex.input;
+ if (got_int) {
+ break;
+ }
+ } else if (vim_isprintc(utf_ptr2char(scan)) == 1
+ && (testval || !ascii_isdigit(*scan))) {
+ MB_PTR_ADV(scan);
+ } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
+ scan++;
+ } else {
+ break;
+ }
+ count++;
+ }
+ break;
+
+ case WHITE:
+ case WHITE + ADD_NL:
+ testval = mask = RI_WHITE;
+do_class:
+ while (count < maxcount) {
+ int l;
+ if (*scan == NUL) {
+ if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
+ || rex.reg_line_lbr) {
+ break;
+ }
+ reg_nextline();
+ scan = rex.input;
+ if (got_int) {
+ break;
+ }
+ } else if ((l = utfc_ptr2len(scan)) > 1) {
+ if (testval != 0) {
+ break;
+ }
+ scan += l;
+ } else if ((class_tab[*scan] & mask) == testval) {
+ scan++;
+ } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
+ scan++;
+ } else {
+ break;
+ }
+ ++count;
+ }
+ break;
+
+ case NWHITE:
+ case NWHITE + ADD_NL:
+ mask = RI_WHITE;
+ goto do_class;
+ case DIGIT:
+ case DIGIT + ADD_NL:
+ testval = mask = RI_DIGIT;
+ goto do_class;
+ case NDIGIT:
+ case NDIGIT + ADD_NL:
+ mask = RI_DIGIT;
+ goto do_class;
+ case HEX:
+ case HEX + ADD_NL:
+ testval = mask = RI_HEX;
+ goto do_class;
+ case NHEX:
+ case NHEX + ADD_NL:
+ mask = RI_HEX;
+ goto do_class;
+ case OCTAL:
+ case OCTAL + ADD_NL:
+ testval = mask = RI_OCTAL;
+ goto do_class;
+ case NOCTAL:
+ case NOCTAL + ADD_NL:
+ mask = RI_OCTAL;
+ goto do_class;
+ case WORD:
+ case WORD + ADD_NL:
+ testval = mask = RI_WORD;
+ goto do_class;
+ case NWORD:
+ case NWORD + ADD_NL:
+ mask = RI_WORD;
+ goto do_class;
+ case HEAD:
+ case HEAD + ADD_NL:
+ testval = mask = RI_HEAD;
+ goto do_class;
+ case NHEAD:
+ case NHEAD + ADD_NL:
+ mask = RI_HEAD;
+ goto do_class;
+ case ALPHA:
+ case ALPHA + ADD_NL:
+ testval = mask = RI_ALPHA;
+ goto do_class;
+ case NALPHA:
+ case NALPHA + ADD_NL:
+ mask = RI_ALPHA;
+ goto do_class;
+ case LOWER:
+ case LOWER + ADD_NL:
+ testval = mask = RI_LOWER;
+ goto do_class;
+ case NLOWER:
+ case NLOWER + ADD_NL:
+ mask = RI_LOWER;
+ goto do_class;
+ case UPPER:
+ case UPPER + ADD_NL:
+ testval = mask = RI_UPPER;
+ goto do_class;
+ case NUPPER:
+ case NUPPER + ADD_NL:
+ mask = RI_UPPER;
+ goto do_class;
+
+ case EXACTLY:
+ {
+ int cu, cl;
+
+ // This doesn't do a multi-byte character, because a MULTIBYTECODE
+ // would have been used for it. It does handle single-byte
+ // characters, such as latin1.
+ if (rex.reg_ic) {
+ cu = mb_toupper(*opnd);
+ cl = mb_tolower(*opnd);
+ while (count < maxcount && (*scan == cu || *scan == cl)) {
+ count++;
+ scan++;
+ }
+ } else {
+ cu = *opnd;
+ while (count < maxcount && *scan == cu) {
+ count++;
+ scan++;
+ }
+ }
+ break;
+ }
+
+ case MULTIBYTECODE:
+ {
+ int i, len, cf = 0;
+
+ // Safety check (just in case 'encoding' was changed since
+ // compiling the program).
+ if ((len = utfc_ptr2len(opnd)) > 1) {
+ if (rex.reg_ic) {
+ cf = utf_fold(utf_ptr2char(opnd));
+ }
+ while (count < maxcount && utfc_ptr2len(scan) >= len) {
+ for (i = 0; i < len; i++) {
+ if (opnd[i] != scan[i]) {
+ break;
+ }
+ }
+ if (i < len && (!rex.reg_ic
+ || utf_fold(utf_ptr2char(scan)) != cf)) {
+ break;
+ }
+ scan += len;
+ ++count;
+ }
+ }
+ }
+ break;
+
+ case ANYOF:
+ case ANYOF + ADD_NL:
+ testval = 1;
+ FALLTHROUGH;
+
+ case ANYBUT:
+ case ANYBUT + ADD_NL:
+ while (count < maxcount) {
+ int len;
+ if (*scan == NUL) {
+ if (!REG_MULTI || !WITH_NL(OP(p)) || rex.lnum > rex.reg_maxline
+ || rex.reg_line_lbr) {
+ break;
+ }
+ reg_nextline();
+ scan = rex.input;
+ if (got_int) {
+ break;
+ }
+ } else if (rex.reg_line_lbr && *scan == '\n' && WITH_NL(OP(p))) {
+ scan++;
+ } else if ((len = utfc_ptr2len(scan)) > 1) {
+ if ((cstrchr(opnd, utf_ptr2char(scan)) == NULL) == testval) {
+ break;
+ }
+ scan += len;
+ } else {
+ if ((cstrchr(opnd, *scan) == NULL) == testval)
+ break;
+ ++scan;
+ }
+ ++count;
+ }
+ break;
+
+ case NEWL:
+ while (count < maxcount
+ && ((*scan == NUL && rex.lnum <= rex.reg_maxline && !rex.reg_line_lbr
+ && REG_MULTI) || (*scan == '\n' && rex.reg_line_lbr))) {
+ count++;
+ if (rex.reg_line_lbr) {
+ ADVANCE_REGINPUT();
+ } else {
+ reg_nextline();
+ }
+ scan = rex.input;
+ if (got_int) {
+ break;
+ }
+ }
+ break;
+
+ default: // Oh dear. Called inappropriately.
+ iemsg(_(e_re_corr));
+#ifdef REGEXP_DEBUG
+ printf("Called regrepeat with op code %d\n", OP(p));
+#endif
+ break;
+ }
+
+ rex.input = scan;
+
+ return (int)count;
+}
+
+/*
+ * Push an item onto the regstack.
+ * Returns pointer to new item. Returns NULL when out of memory.
+ */
+static regitem_T *regstack_push(regstate_T state, char_u *scan)
+{
+ regitem_T *rp;
+
+ if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) {
+ emsg(_(e_maxmempat));
+ return NULL;
+ }
+ ga_grow(&regstack, sizeof(regitem_T));
+
+ rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len);
+ rp->rs_state = state;
+ rp->rs_scan = scan;
+
+ regstack.ga_len += sizeof(regitem_T);
+ return rp;
+}
+
+/*
+ * Pop an item from the regstack.
+ */
+static void regstack_pop(char_u **scan)
+{
+ regitem_T *rp;
+
+ rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
+ *scan = rp->rs_scan;
+
+ regstack.ga_len -= sizeof(regitem_T);
+}
+
+// Save the current subexpr to "bp", so that they can be restored
+// later by restore_subexpr().
+static void save_subexpr(regbehind_T *bp)
+ FUNC_ATTR_NONNULL_ALL
+{
+ // When "rex.need_clear_subexpr" is set we don't need to save the values, only
+ // remember that this flag needs to be set again when restoring.
+ bp->save_need_clear_subexpr = rex.need_clear_subexpr;
+ if (!rex.need_clear_subexpr) {
+ for (int i = 0; i < NSUBEXP; i++) {
+ if (REG_MULTI) {
+ bp->save_start[i].se_u.pos = rex.reg_startpos[i];
+ bp->save_end[i].se_u.pos = rex.reg_endpos[i];
+ } else {
+ bp->save_start[i].se_u.ptr = rex.reg_startp[i];
+ bp->save_end[i].se_u.ptr = rex.reg_endp[i];
+ }
+ }
+ }
+}
+
+// Restore the subexpr from "bp".
+static void restore_subexpr(regbehind_T *bp)
+ FUNC_ATTR_NONNULL_ALL
+{
+ // Only need to restore saved values when they are not to be cleared.
+ rex.need_clear_subexpr = bp->save_need_clear_subexpr;
+ if (!rex.need_clear_subexpr) {
+ for (int i = 0; i < NSUBEXP; i++) {
+ if (REG_MULTI) {
+ rex.reg_startpos[i] = bp->save_start[i].se_u.pos;
+ rex.reg_endpos[i] = bp->save_end[i].se_u.pos;
+ } else {
+ rex.reg_startp[i] = bp->save_start[i].se_u.ptr;
+ rex.reg_endp[i] = bp->save_end[i].se_u.ptr;
+ }
+ }
+ }
+}
+/// Main matching routine
+///
+/// Conceptually the strategy is simple: Check to see whether the current node
+/// matches, push an item onto the regstack and loop to see whether the rest
+/// matches, and then act accordingly. In practice we make some effort to
+/// avoid using the regstack, in particular by going through "ordinary" nodes
+/// (that don't need to know whether the rest of the match failed) by a nested
+/// loop.
+///
+/// Returns true when there is a match. Leaves rex.input and rex.lnum
+/// just after the last matched character.
+/// Returns false when there is no match. Leaves rex.input and rex.lnum in an
+/// undefined state!
+static bool regmatch(
+ char_u *scan, // Current node.
+ proftime_T *tm, // timeout limit or NULL
+ int *timed_out) // flag set on timeout or NULL
+{
+ char_u *next; // Next node.
+ int op;
+ int c;
+ regitem_T *rp;
+ int no;
+ int status; // one of the RA_ values:
+ int tm_count = 0;
+
+ // Make "regstack" and "backpos" empty. They are allocated and freed in
+ // bt_regexec_both() to reduce malloc()/free() calls.
+ regstack.ga_len = 0;
+ backpos.ga_len = 0;
+
+ // Repeat until "regstack" is empty.
+ for (;; ) {
+ // Some patterns may take a long time to match, e.g., "\([a-z]\+\)\+Q".
+ // Allow interrupting them with CTRL-C.
+ fast_breakcheck();
+
+#ifdef REGEXP_DEBUG
+ if (scan != NULL && regnarrate) {
+ mch_errmsg((char *)regprop(scan));
+ mch_errmsg("(\n");
+ }
+#endif
+
+ // Repeat for items that can be matched sequentially, without using the
+ // regstack.
+ for (;; ) {
+ if (got_int || scan == NULL) {
+ status = RA_FAIL;
+ break;
+ }
+ // Check for timeout once in a 100 times to avoid overhead.
+ if (tm != NULL && ++tm_count == 100) {
+ tm_count = 0;
+ if (profile_passed_limit(*tm)) {
+ if (timed_out != NULL) {
+ *timed_out = true;
+ }
+ status = RA_FAIL;
+ break;
+ }
+ }
+ status = RA_CONT;
+
+#ifdef REGEXP_DEBUG
+ if (regnarrate) {
+ mch_errmsg((char *)regprop(scan));
+ mch_errmsg("...\n");
+ if (re_extmatch_in != NULL) {
+ int i;
+
+ mch_errmsg(_("External submatches:\n"));
+ for (i = 0; i < NSUBEXP; i++) {
+ mch_errmsg(" \"");
+ if (re_extmatch_in->matches[i] != NULL)
+ mch_errmsg((char *)re_extmatch_in->matches[i]);
+ mch_errmsg("\"\n");
+ }
+ }
+ }
+#endif
+ next = regnext(scan);
+
+ op = OP(scan);
+ // Check for character class with NL added.
+ if (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI
+ && *rex.input == NUL && rex.lnum <= rex.reg_maxline) {
+ reg_nextline();
+ } else if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\n') {
+ ADVANCE_REGINPUT();
+ } else {
+ if (WITH_NL(op)) {
+ op -= ADD_NL;
+ }
+ c = utf_ptr2char(rex.input);
+ switch (op) {
+ case BOL:
+ if (rex.input != rex.line) {
+ status = RA_NOMATCH;
+ }
+ break;
+
+ case EOL:
+ if (c != NUL) {
+ status = RA_NOMATCH;
+ }
+ break;
+
+ case RE_BOF:
+ // We're not at the beginning of the file when below the first
+ // line where we started, not at the start of the line or we
+ // didn't start at the first line of the buffer.
+ if (rex.lnum != 0 || rex.input != rex.line
+ || (REG_MULTI && rex.reg_firstlnum > 1)) {
+ status = RA_NOMATCH;
+ }
+ break;
+
+ case RE_EOF:
+ if (rex.lnum != rex.reg_maxline || c != NUL) {
+ status = RA_NOMATCH;
+ }
+ break;
+
+ case CURSOR:
+ // Check if the buffer is in a window and compare the
+ // rex.reg_win->w_cursor position to the match position.
+ if (rex.reg_win == NULL
+ || (rex.lnum + rex.reg_firstlnum != rex.reg_win->w_cursor.lnum)
+ || ((colnr_T)(rex.input - rex.line) !=
+ rex.reg_win->w_cursor.col)) {
+ status = RA_NOMATCH;
+ }
+ break;
+
+ case RE_MARK:
+ // Compare the mark position to the match position.
+ {
+ int mark = OPERAND(scan)[0];
+ int cmp = OPERAND(scan)[1];
+ pos_T *pos;
+
+ pos = getmark_buf(rex.reg_buf, mark, false);
+ if (pos == NULL // mark doesn't exist
+ || pos->lnum <= 0) { // mark isn't set in reg_buf
+ status = RA_NOMATCH;
+ } else {
+ const colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum
+ && pos->col == MAXCOL
+ ? (colnr_T)STRLEN(reg_getline(pos->lnum - rex.reg_firstlnum))
+ : pos->col;
+
+ if (pos->lnum == rex.lnum + rex.reg_firstlnum
+ ? (pos_col == (colnr_T)(rex.input - rex.line)
+ ? (cmp == '<' || cmp == '>')
+ : (pos_col < (colnr_T)(rex.input - rex.line)
+ ? cmp != '>'
+ : cmp != '<'))
+ : (pos->lnum < rex.lnum + rex.reg_firstlnum
+ ? cmp != '>'
+ : cmp != '<')) {
+ status = RA_NOMATCH;
+ }
+ }
+ }
+ break;
+
+ case RE_VISUAL:
+ if (!reg_match_visual())
+ status = RA_NOMATCH;
+ break;
+
+ case RE_LNUM:
+ assert(rex.lnum + rex.reg_firstlnum >= 0
+ && (uintmax_t)(rex.lnum + rex.reg_firstlnum) <= UINT32_MAX);
+ if (!REG_MULTI
+ || !re_num_cmp((uint32_t)(rex.lnum + rex.reg_firstlnum), scan)) {
+ status = RA_NOMATCH;
+ }
+ break;
+
+ case RE_COL:
+ assert(rex.input - rex.line + 1 >= 0
+ && (uintmax_t)(rex.input - rex.line + 1) <= UINT32_MAX);
+ if (!re_num_cmp((uint32_t)(rex.input - rex.line + 1), scan)) {
+ status = RA_NOMATCH;
+ }
+ break;
+
+ case RE_VCOL:
+ if (!re_num_cmp(win_linetabsize(rex.reg_win == NULL
+ ? curwin : rex.reg_win,
+ rex.line,
+ (colnr_T)(rex.input - rex.line)) + 1,
+ scan)) {
+ status = RA_NOMATCH;
+ }
+ break;
+
+ case BOW: // \<word; rex.input points to w
+ if (c == NUL) { // Can't match at end of line
+ status = RA_NOMATCH;
+ } else {
+ // Get class of current and previous char (if it exists).
+ const int this_class =
+ mb_get_class_tab(rex.input, rex.reg_buf->b_chartab);
+ if (this_class <= 1) {
+ status = RA_NOMATCH; // Not on a word at all.
+ } else if (reg_prev_class() == this_class) {
+ status = RA_NOMATCH; // Previous char is in same word.
+ }
+ }
+ break;
+
+ case EOW: // word\>; rex.input points after d
+ if (rex.input == rex.line) { // Can't match at start of line
+ status = RA_NOMATCH;
+ } else {
+ int this_class, prev_class;
+
+ // Get class of current and previous char (if it exists).
+ this_class = mb_get_class_tab(rex.input, rex.reg_buf->b_chartab);
+ prev_class = reg_prev_class();
+ if (this_class == prev_class
+ || prev_class == 0 || prev_class == 1) {
+ status = RA_NOMATCH;
+ }
+ }
+ break; // Matched with EOW
+
+ case ANY:
+ // ANY does not match new lines.
+ if (c == NUL) {
+ status = RA_NOMATCH;
+ } else {
+ ADVANCE_REGINPUT();
+ }
+ break;
+
+ case IDENT:
+ if (!vim_isIDc(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case SIDENT:
+ if (ascii_isdigit(*rex.input) || !vim_isIDc(c)) {
+ status = RA_NOMATCH;
+ } else {
+ ADVANCE_REGINPUT();
+ }
+ break;
+
+ case KWORD:
+ if (!vim_iswordp_buf(rex.input, rex.reg_buf)) {
+ status = RA_NOMATCH;
+ } else {
+ ADVANCE_REGINPUT();
+ }
+ break;
+
+ case SKWORD:
+ if (ascii_isdigit(*rex.input)
+ || !vim_iswordp_buf(rex.input, rex.reg_buf)) {
+ status = RA_NOMATCH;
+ } else {
+ ADVANCE_REGINPUT();
+ }
+ break;
+
+ case FNAME:
+ if (!vim_isfilec(c)) {
+ status = RA_NOMATCH;
+ } else {
+ ADVANCE_REGINPUT();
+ }
+ break;
+
+ case SFNAME:
+ if (ascii_isdigit(*rex.input) || !vim_isfilec(c)) {
+ status = RA_NOMATCH;
+ } else {
+ ADVANCE_REGINPUT();
+ }
+ break;
+
+ case PRINT:
+ if (!vim_isprintc(utf_ptr2char(rex.input))) {
+ status = RA_NOMATCH;
+ } else {
+ ADVANCE_REGINPUT();
+ }
+ break;
+
+ case SPRINT:
+ if (ascii_isdigit(*rex.input) || !vim_isprintc(utf_ptr2char(rex.input))) {
+ status = RA_NOMATCH;
+ } else {
+ ADVANCE_REGINPUT();
+ }
+ break;
+
+ case WHITE:
+ if (!ascii_iswhite(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case NWHITE:
+ if (c == NUL || ascii_iswhite(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case DIGIT:
+ if (!ri_digit(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case NDIGIT:
+ if (c == NUL || ri_digit(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case HEX:
+ if (!ri_hex(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case NHEX:
+ if (c == NUL || ri_hex(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case OCTAL:
+ if (!ri_octal(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case NOCTAL:
+ if (c == NUL || ri_octal(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case WORD:
+ if (!ri_word(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case NWORD:
+ if (c == NUL || ri_word(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case HEAD:
+ if (!ri_head(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case NHEAD:
+ if (c == NUL || ri_head(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case ALPHA:
+ if (!ri_alpha(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case NALPHA:
+ if (c == NUL || ri_alpha(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case LOWER:
+ if (!ri_lower(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case NLOWER:
+ if (c == NUL || ri_lower(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case UPPER:
+ if (!ri_upper(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case NUPPER:
+ if (c == NUL || ri_upper(c))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case EXACTLY:
+ {
+ int len;
+ char_u *opnd;
+
+ opnd = OPERAND(scan);
+ // Inline the first byte, for speed.
+ if (*opnd != *rex.input
+ && (!rex.reg_ic)) {
+ status = RA_NOMATCH;
+ } else if (*opnd == NUL) {
+ // match empty string always works; happens when "~" is
+ // empty.
+ } else {
+ if (opnd[1] == NUL && !rex.reg_ic) {
+ len = 1; // matched a single byte above
+ } else {
+ // Need to match first byte again for multi-byte.
+ len = (int)STRLEN(opnd);
+ if (cstrncmp(opnd, rex.input, &len) != 0) {
+ status = RA_NOMATCH;
+ }
+ }
+ // Check for following composing character, unless %C
+ // follows (skips over all composing chars).
+ if (status != RA_NOMATCH
+ && utf_composinglike(rex.input, rex.input + len)
+ && !rex.reg_icombine
+ && OP(next) != RE_COMPOSING) {
+ // raaron: This code makes a composing character get
+ // ignored, which is the correct behavior (sometimes)
+ // for voweled Hebrew texts.
+ status = RA_NOMATCH;
+ }
+ if (status != RA_NOMATCH) {
+ rex.input += len;
+ }
+ }
+ }
+ break;
+
+ case ANYOF:
+ case ANYBUT:
+ if (c == NUL)
+ status = RA_NOMATCH;
+ else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))
+ status = RA_NOMATCH;
+ else
+ ADVANCE_REGINPUT();
+ break;
+
+ case MULTIBYTECODE:
+ {
+ int i, len;
+
+ const char_u *opnd = OPERAND(scan);
+ // Safety check (just in case 'encoding' was changed since
+ // compiling the program).
+ if ((len = utfc_ptr2len(opnd)) < 2) {
+ status = RA_NOMATCH;
+ break;
+ }
+ const int opndc = utf_ptr2char(opnd);
+ if (utf_iscomposing(opndc)) {
+ // When only a composing char is given match at any
+ // position where that composing char appears.
+ status = RA_NOMATCH;
+ for (i = 0; rex.input[i] != NUL;
+ i += utf_ptr2len(rex.input + i)) {
+ const int inpc = utf_ptr2char(rex.input + i);
+ if (!utf_iscomposing(inpc)) {
+ if (i > 0) {
+ break;
+ }
+ } else if (opndc == inpc) {
+ // Include all following composing chars.
+ len = i + utfc_ptr2len(rex.input + i);
+ status = RA_MATCH;
+ break;
+ }
+ }
+ } else {
+ for (i = 0; i < len; i++) {
+ if (opnd[i] != rex.input[i]) {
+ status = RA_NOMATCH;
+ break;
+ }
+ }
+ }
+ rex.input += len;
+ }
+ break;
+
+ case RE_COMPOSING:
+ {
+ // Skip composing characters.
+ while (utf_iscomposing(utf_ptr2char(rex.input))) {
+ MB_CPTR_ADV(rex.input);
+ }
+ }
+ break;
+
+ case NOTHING:
+ break;
+
+ case BACK:
+ {
+ int i;
+
+ // When we run into BACK we need to check if we don't keep
+ // looping without matching any input. The second and later
+ // times a BACK is encountered it fails if the input is still
+ // at the same position as the previous time.
+ // The positions are stored in "backpos" and found by the
+ // current value of "scan", the position in the RE program.
+ backpos_T *bp = (backpos_T *)backpos.ga_data;
+ for (i = 0; i < backpos.ga_len; ++i)
+ if (bp[i].bp_scan == scan)
+ break;
+ if (i == backpos.ga_len) {
+ backpos_T *p = GA_APPEND_VIA_PTR(backpos_T, &backpos);
+ p->bp_scan = scan;
+ } else if (reg_save_equal(&bp[i].bp_pos))
+ // Still at same position as last time, fail.
+ status = RA_NOMATCH;
+
+ assert(status != RA_FAIL);
+ if (status != RA_NOMATCH) {
+ reg_save(&bp[i].bp_pos, &backpos);
+ }
+ }
+ break;
+
+ case MOPEN + 0: // Match start: \zs
+ case MOPEN + 1: // \(
+ case MOPEN + 2:
+ case MOPEN + 3:
+ case MOPEN + 4:
+ case MOPEN + 5:
+ case MOPEN + 6:
+ case MOPEN + 7:
+ case MOPEN + 8:
+ case MOPEN + 9:
+ {
+ no = op - MOPEN;
+ cleanup_subexpr();
+ rp = regstack_push(RS_MOPEN, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else {
+ rp->rs_no = no;
+ save_se(&rp->rs_un.sesave, &rex.reg_startpos[no],
+ &rex.reg_startp[no]);
+ // We simply continue and handle the result when done.
+ }
+ }
+ break;
+
+ case NOPEN: // \%(
+ case NCLOSE: // \) after \%(
+ if (regstack_push(RS_NOPEN, scan) == NULL)
+ status = RA_FAIL;
+ // We simply continue and handle the result when done.
+ break;
+
+ case ZOPEN + 1:
+ case ZOPEN + 2:
+ case ZOPEN + 3:
+ case ZOPEN + 4:
+ case ZOPEN + 5:
+ case ZOPEN + 6:
+ case ZOPEN + 7:
+ case ZOPEN + 8:
+ case ZOPEN + 9:
+ {
+ no = op - ZOPEN;
+ cleanup_zsubexpr();
+ rp = regstack_push(RS_ZOPEN, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else {
+ rp->rs_no = no;
+ save_se(&rp->rs_un.sesave, &reg_startzpos[no],
+ &reg_startzp[no]);
+ // We simply continue and handle the result when done.
+ }
+ }
+ break;
+
+ case MCLOSE + 0: // Match end: \ze
+ case MCLOSE + 1: // \)
+ case MCLOSE + 2:
+ case MCLOSE + 3:
+ case MCLOSE + 4:
+ case MCLOSE + 5:
+ case MCLOSE + 6:
+ case MCLOSE + 7:
+ case MCLOSE + 8:
+ case MCLOSE + 9:
+ {
+ no = op - MCLOSE;
+ cleanup_subexpr();
+ rp = regstack_push(RS_MCLOSE, scan);
+ if (rp == NULL) {
+ status = RA_FAIL;
+ } else {
+ rp->rs_no = no;
+ save_se(&rp->rs_un.sesave, &rex.reg_endpos[no], &rex.reg_endp[no]);
+ // We simply continue and handle the result when done.
+ }
+ }
+ break;
+
+ case ZCLOSE + 1: // \) after \z(
+ case ZCLOSE + 2:
+ case ZCLOSE + 3:
+ case ZCLOSE + 4:
+ case ZCLOSE + 5:
+ case ZCLOSE + 6:
+ case ZCLOSE + 7:
+ case ZCLOSE + 8:
+ case ZCLOSE + 9:
+ {
+ no = op - ZCLOSE;
+ cleanup_zsubexpr();
+ rp = regstack_push(RS_ZCLOSE, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else {
+ rp->rs_no = no;
+ save_se(&rp->rs_un.sesave, &reg_endzpos[no],
+ &reg_endzp[no]);
+ // We simply continue and handle the result when done.
+ }
+ }
+ break;
+
+ case BACKREF + 1:
+ case BACKREF + 2:
+ case BACKREF + 3:
+ case BACKREF + 4:
+ case BACKREF + 5:
+ case BACKREF + 6:
+ case BACKREF + 7:
+ case BACKREF + 8:
+ case BACKREF + 9:
+ {
+ int len;
+
+ no = op - BACKREF;
+ cleanup_subexpr();
+ if (!REG_MULTI) { // Single-line regexp
+ if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL) {
+ // Backref was not set: Match an empty string.
+ len = 0;
+ } else {
+ // Compare current input with back-ref in the same line.
+ len = (int)(rex.reg_endp[no] - rex.reg_startp[no]);
+ if (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0) {
+ status = RA_NOMATCH;
+ }
+ }
+ } else { // Multi-line regexp
+ if (rex.reg_startpos[no].lnum < 0 || rex.reg_endpos[no].lnum < 0) {
+ // Backref was not set: Match an empty string.
+ len = 0;
+ } else {
+ if (rex.reg_startpos[no].lnum == rex.lnum
+ && rex.reg_endpos[no].lnum == rex.lnum) {
+ // Compare back-ref within the current line.
+ len = rex.reg_endpos[no].col - rex.reg_startpos[no].col;
+ if (cstrncmp(rex.line + rex.reg_startpos[no].col,
+ rex.input, &len) != 0) {
+ status = RA_NOMATCH;
+ }
+ } else {
+ // Messy situation: Need to compare between two lines.
+ int r = match_with_backref(rex.reg_startpos[no].lnum,
+ rex.reg_startpos[no].col,
+ rex.reg_endpos[no].lnum,
+ rex.reg_endpos[no].col,
+ &len);
+ if (r != RA_MATCH) {
+ status = r;
+ }
+ }
+ }
+ }
+
+ // Matched the backref, skip over it.
+ rex.input += len;
+ }
+ break;
+
+ case ZREF + 1:
+ case ZREF + 2:
+ case ZREF + 3:
+ case ZREF + 4:
+ case ZREF + 5:
+ case ZREF + 6:
+ case ZREF + 7:
+ case ZREF + 8:
+ case ZREF + 9:
+ {
+ cleanup_zsubexpr();
+ no = op - ZREF;
+ if (re_extmatch_in != NULL
+ && re_extmatch_in->matches[no] != NULL) {
+ int len = (int)STRLEN(re_extmatch_in->matches[no]);
+ if (cstrncmp(re_extmatch_in->matches[no], rex.input, &len) != 0) {
+ status = RA_NOMATCH;
+ } else {
+ rex.input += len;
+ }
+ } else {
+ // Backref was not set: Match an empty string.
+ }
+ }
+ break;
+
+ case BRANCH:
+ {
+ if (OP(next) != BRANCH) // No choice.
+ next = OPERAND(scan); // Avoid recursion.
+ else {
+ rp = regstack_push(RS_BRANCH, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else
+ status = RA_BREAK; // rest is below
+ }
+ }
+ break;
+
+ case BRACE_LIMITS:
+ {
+ if (OP(next) == BRACE_SIMPLE) {
+ bl_minval = OPERAND_MIN(scan);
+ bl_maxval = OPERAND_MAX(scan);
+ } else if (OP(next) >= BRACE_COMPLEX
+ && OP(next) < BRACE_COMPLEX + 10) {
+ no = OP(next) - BRACE_COMPLEX;
+ brace_min[no] = OPERAND_MIN(scan);
+ brace_max[no] = OPERAND_MAX(scan);
+ brace_count[no] = 0;
+ } else {
+ internal_error("BRACE_LIMITS");
+ status = RA_FAIL;
+ }
+ }
+ break;
+
+ case BRACE_COMPLEX + 0:
+ case BRACE_COMPLEX + 1:
+ case BRACE_COMPLEX + 2:
+ case BRACE_COMPLEX + 3:
+ case BRACE_COMPLEX + 4:
+ case BRACE_COMPLEX + 5:
+ case BRACE_COMPLEX + 6:
+ case BRACE_COMPLEX + 7:
+ case BRACE_COMPLEX + 8:
+ case BRACE_COMPLEX + 9:
+ {
+ no = op - BRACE_COMPLEX;
+ ++brace_count[no];
+
+ // If not matched enough times yet, try one more
+ if (brace_count[no] <= (brace_min[no] <= brace_max[no]
+ ? brace_min[no] : brace_max[no])) {
+ rp = regstack_push(RS_BRCPLX_MORE, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else {
+ rp->rs_no = no;
+ reg_save(&rp->rs_un.regsave, &backpos);
+ next = OPERAND(scan);
+ // We continue and handle the result when done.
+ }
+ break;
+ }
+
+ // If matched enough times, may try matching some more
+ if (brace_min[no] <= brace_max[no]) {
+ // Range is the normal way around, use longest match
+ if (brace_count[no] <= brace_max[no]) {
+ rp = regstack_push(RS_BRCPLX_LONG, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else {
+ rp->rs_no = no;
+ reg_save(&rp->rs_un.regsave, &backpos);
+ next = OPERAND(scan);
+ // We continue and handle the result when done.
+ }
+ }
+ } else {
+ // Range is backwards, use shortest match first
+ if (brace_count[no] <= brace_min[no]) {
+ rp = regstack_push(RS_BRCPLX_SHORT, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else {
+ reg_save(&rp->rs_un.regsave, &backpos);
+ // We continue and handle the result when done.
+ }
+ }
+ }
+ }
+ break;
+
+ case BRACE_SIMPLE:
+ case STAR:
+ case PLUS:
+ {
+ regstar_T rst;
+
+ // Lookahead to avoid useless match attempts when we know
+ // what character comes next.
+ if (OP(next) == EXACTLY) {
+ rst.nextb = *OPERAND(next);
+ if (rex.reg_ic) {
+ if (mb_isupper(rst.nextb)) {
+ rst.nextb_ic = mb_tolower(rst.nextb);
+ } else {
+ rst.nextb_ic = mb_toupper(rst.nextb);
+ }
+ } else {
+ rst.nextb_ic = rst.nextb;
+ }
+ } else {
+ rst.nextb = NUL;
+ rst.nextb_ic = NUL;
+ }
+ if (op != BRACE_SIMPLE) {
+ rst.minval = (op == STAR) ? 0 : 1;
+ rst.maxval = MAX_LIMIT;
+ } else {
+ rst.minval = bl_minval;
+ rst.maxval = bl_maxval;
+ }
+
+ // When maxval > minval, try matching as much as possible, up
+ // to maxval. When maxval < minval, try matching at least the
+ // minimal number (since the range is backwards, that's also
+ // maxval!).
+ rst.count = regrepeat(OPERAND(scan), rst.maxval);
+ if (got_int) {
+ status = RA_FAIL;
+ break;
+ }
+ if (rst.minval <= rst.maxval
+ ? rst.count >= rst.minval : rst.count >= rst.maxval) {
+ // It could match. Prepare for trying to match what
+ // follows. The code is below. Parameters are stored in
+ // a regstar_T on the regstack.
+ if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) {
+ emsg(_(e_maxmempat));
+ status = RA_FAIL;
+ } else {
+ ga_grow(&regstack, sizeof(regstar_T));
+ regstack.ga_len += sizeof(regstar_T);
+ rp = regstack_push(rst.minval <= rst.maxval
+ ? RS_STAR_LONG : RS_STAR_SHORT, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else {
+ *(((regstar_T *)rp) - 1) = rst;
+ status = RA_BREAK; // skip the restore bits
+ }
+ }
+ } else
+ status = RA_NOMATCH;
+
+ }
+ break;
+
+ case NOMATCH:
+ case MATCH:
+ case SUBPAT:
+ rp = regstack_push(RS_NOMATCH, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else {
+ rp->rs_no = op;
+ reg_save(&rp->rs_un.regsave, &backpos);
+ next = OPERAND(scan);
+ // We continue and handle the result when done.
+ }
+ break;
+
+ case BEHIND:
+ case NOBEHIND:
+ // Need a bit of room to store extra positions.
+ if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp) {
+ emsg(_(e_maxmempat));
+ status = RA_FAIL;
+ } else {
+ ga_grow(&regstack, sizeof(regbehind_T));
+ regstack.ga_len += sizeof(regbehind_T);
+ rp = regstack_push(RS_BEHIND1, scan);
+ if (rp == NULL)
+ status = RA_FAIL;
+ else {
+ // Need to save the subexpr to be able to restore them
+ // when there is a match but we don't use it.
+ save_subexpr(((regbehind_T *)rp) - 1);
+
+ rp->rs_no = op;
+ reg_save(&rp->rs_un.regsave, &backpos);
+ // First try if what follows matches. If it does then we
+ // check the behind match by looping.
+ }
+ }
+ break;
+
+ case BHPOS:
+ if (REG_MULTI) {
+ if (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line)
+ || behind_pos.rs_u.pos.lnum != rex.lnum) {
+ status = RA_NOMATCH;
+ }
+ } else if (behind_pos.rs_u.ptr != rex.input) {
+ status = RA_NOMATCH;
+ }
+ break;
+
+ case NEWL:
+ if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline
+ || rex.reg_line_lbr) && (c != '\n' || !rex.reg_line_lbr)) {
+ status = RA_NOMATCH;
+ } else if (rex.reg_line_lbr) {
+ ADVANCE_REGINPUT();
+ } else {
+ reg_nextline();
+ }
+ break;
+
+ case END:
+ status = RA_MATCH; // Success!
+ break;
+
+ default:
+ iemsg(_(e_re_corr));
+#ifdef REGEXP_DEBUG
+ printf("Illegal op code %d\n", op);
+#endif
+ status = RA_FAIL;
+ break;
+ }
+ }
+
+ // If we can't continue sequentially, break the inner loop.
+ if (status != RA_CONT)
+ break;
+
+ // Continue in inner loop, advance to next item.
+ scan = next;
+
+ } // end of inner loop
+
+ // If there is something on the regstack execute the code for the state.
+ // If the state is popped then loop and use the older state.
+ while (!GA_EMPTY(&regstack) && status != RA_FAIL) {
+ rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
+ switch (rp->rs_state) {
+ case RS_NOPEN:
+ // Result is passed on as-is, simply pop the state.
+ regstack_pop(&scan);
+ break;
+
+ case RS_MOPEN:
+ // Pop the state. Restore pointers when there is no match.
+ if (status == RA_NOMATCH) {
+ restore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no],
+ &rex.reg_startp[rp->rs_no]);
+ }
+ regstack_pop(&scan);
+ break;
+
+ case RS_ZOPEN:
+ // Pop the state. Restore pointers when there is no match.
+ if (status == RA_NOMATCH)
+ restore_se(&rp->rs_un.sesave, &reg_startzpos[rp->rs_no],
+ &reg_startzp[rp->rs_no]);
+ regstack_pop(&scan);
+ break;
+
+ case RS_MCLOSE:
+ // Pop the state. Restore pointers when there is no match.
+ if (status == RA_NOMATCH) {
+ restore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no],
+ &rex.reg_endp[rp->rs_no]);
+ }
+ regstack_pop(&scan);
+ break;
+
+ case RS_ZCLOSE:
+ // Pop the state. Restore pointers when there is no match.
+ if (status == RA_NOMATCH)
+ restore_se(&rp->rs_un.sesave, &reg_endzpos[rp->rs_no],
+ &reg_endzp[rp->rs_no]);
+ regstack_pop(&scan);
+ break;
+
+ case RS_BRANCH:
+ if (status == RA_MATCH)
+ // this branch matched, use it
+ regstack_pop(&scan);
+ else {
+ if (status != RA_BREAK) {
+ // After a non-matching branch: try next one.
+ reg_restore(&rp->rs_un.regsave, &backpos);
+ scan = rp->rs_scan;
+ }
+ if (scan == NULL || OP(scan) != BRANCH) {
+ // no more branches, didn't find a match
+ status = RA_NOMATCH;
+ regstack_pop(&scan);
+ } else {
+ // Prepare to try a branch.
+ rp->rs_scan = regnext(scan);
+ reg_save(&rp->rs_un.regsave, &backpos);
+ scan = OPERAND(scan);
+ }
+ }
+ break;
+
+ case RS_BRCPLX_MORE:
+ // Pop the state. Restore pointers when there is no match.
+ if (status == RA_NOMATCH) {
+ reg_restore(&rp->rs_un.regsave, &backpos);
+ --brace_count[rp->rs_no]; // decrement match count
+ }
+ regstack_pop(&scan);
+ break;
+
+ case RS_BRCPLX_LONG:
+ // Pop the state. Restore pointers when there is no match.
+ if (status == RA_NOMATCH) {
+ // There was no match, but we did find enough matches.
+ reg_restore(&rp->rs_un.regsave, &backpos);
+ --brace_count[rp->rs_no];
+ // continue with the items after "\{}"
+ status = RA_CONT;
+ }
+ regstack_pop(&scan);
+ if (status == RA_CONT)
+ scan = regnext(scan);
+ break;
+
+ case RS_BRCPLX_SHORT:
+ // Pop the state. Restore pointers when there is no match.
+ if (status == RA_NOMATCH)
+ // There was no match, try to match one more item.
+ reg_restore(&rp->rs_un.regsave, &backpos);
+ regstack_pop(&scan);
+ if (status == RA_NOMATCH) {
+ scan = OPERAND(scan);
+ status = RA_CONT;
+ }
+ break;
+
+ case RS_NOMATCH:
+ // Pop the state. If the operand matches for NOMATCH or
+ // doesn't match for MATCH/SUBPAT, we fail. Otherwise backup,
+ // except for SUBPAT, and continue with the next item.
+ if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH))
+ status = RA_NOMATCH;
+ else {
+ status = RA_CONT;
+ if (rp->rs_no != SUBPAT) // zero-width
+ reg_restore(&rp->rs_un.regsave, &backpos);
+ }
+ regstack_pop(&scan);
+ if (status == RA_CONT)
+ scan = regnext(scan);
+ break;
+
+ case RS_BEHIND1:
+ if (status == RA_NOMATCH) {
+ regstack_pop(&scan);
+ regstack.ga_len -= sizeof(regbehind_T);
+ } else {
+ // The stuff after BEHIND/NOBEHIND matches. Now try if
+ // the behind part does (not) match before the current
+ // position in the input. This must be done at every
+ // position in the input and checking if the match ends at
+ // the current position.
+
+ // save the position after the found match for next
+ reg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos);
+
+ // Start looking for a match with operand at the current
+ // position. Go back one character until we find the
+ // result, hitting the start of the line or the previous
+ // line (for multi-line matching).
+ // Set behind_pos to where the match should end, BHPOS
+ // will match it. Save the current value.
+ (((regbehind_T *)rp) - 1)->save_behind = behind_pos;
+ behind_pos = rp->rs_un.regsave;
+
+ rp->rs_state = RS_BEHIND2;
+
+ reg_restore(&rp->rs_un.regsave, &backpos);
+ scan = OPERAND(rp->rs_scan) + 4;
+ }
+ break;
+
+ case RS_BEHIND2:
+ // Looping for BEHIND / NOBEHIND match.
+ if (status == RA_MATCH && reg_save_equal(&behind_pos)) {
+ // found a match that ends where "next" started
+ behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
+ if (rp->rs_no == BEHIND)
+ reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
+ &backpos);
+ else {
+ // But we didn't want a match. Need to restore the
+ // subexpr, because what follows matched, so they have
+ // been set.
+ status = RA_NOMATCH;
+ restore_subexpr(((regbehind_T *)rp) - 1);
+ }
+ regstack_pop(&scan);
+ regstack.ga_len -= sizeof(regbehind_T);
+ } else {
+ long limit;
+
+ // No match or a match that doesn't end where we want it: Go
+ // back one character. May go to previous line once.
+ no = OK;
+ limit = OPERAND_MIN(rp->rs_scan);
+ if (REG_MULTI) {
+ if (limit > 0
+ && ((rp->rs_un.regsave.rs_u.pos.lnum
+ < behind_pos.rs_u.pos.lnum
+ ? (colnr_T)STRLEN(rex.line)
+ : behind_pos.rs_u.pos.col)
+ - rp->rs_un.regsave.rs_u.pos.col >= limit))
+ no = FAIL;
+ else if (rp->rs_un.regsave.rs_u.pos.col == 0) {
+ if (rp->rs_un.regsave.rs_u.pos.lnum
+ < behind_pos.rs_u.pos.lnum
+ || reg_getline(
+ --rp->rs_un.regsave.rs_u.pos.lnum)
+ == NULL)
+ no = FAIL;
+ else {
+ reg_restore(&rp->rs_un.regsave, &backpos);
+ rp->rs_un.regsave.rs_u.pos.col =
+ (colnr_T)STRLEN(rex.line);
+ }
+ } else {
+ const char_u *const line =
+ reg_getline(rp->rs_un.regsave.rs_u.pos.lnum);
+
+ rp->rs_un.regsave.rs_u.pos.col -=
+ utf_head_off(line,
+ line + rp->rs_un.regsave.rs_u.pos.col - 1)
+ + 1;
+ }
+ } else {
+ if (rp->rs_un.regsave.rs_u.ptr == rex.line) {
+ no = FAIL;
+ } else {
+ MB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr);
+ if (limit > 0
+ && (behind_pos.rs_u.ptr - rp->rs_un.regsave.rs_u.ptr) > (ptrdiff_t)limit) {
+ no = FAIL;
+ }
+ }
+ }
+ if (no == OK) {
+ // Advanced, prepare for finding match again.
+ reg_restore(&rp->rs_un.regsave, &backpos);
+ scan = OPERAND(rp->rs_scan) + 4;
+ if (status == RA_MATCH) {
+ // We did match, so subexpr may have been changed,
+ // need to restore them for the next try.
+ status = RA_NOMATCH;
+ restore_subexpr(((regbehind_T *)rp) - 1);
+ }
+ } else {
+ // Can't advance. For NOBEHIND that's a match.
+ behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
+ if (rp->rs_no == NOBEHIND) {
+ reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
+ &backpos);
+ status = RA_MATCH;
+ } else {
+ // We do want a proper match. Need to restore the
+ // subexpr if we had a match, because they may have
+ // been set.
+ if (status == RA_MATCH) {
+ status = RA_NOMATCH;
+ restore_subexpr(((regbehind_T *)rp) - 1);
+ }
+ }
+ regstack_pop(&scan);
+ regstack.ga_len -= sizeof(regbehind_T);
+ }
+ }
+ break;
+
+ case RS_STAR_LONG:
+ case RS_STAR_SHORT:
+ {
+ regstar_T *rst = ((regstar_T *)rp) - 1;
+
+ if (status == RA_MATCH) {
+ regstack_pop(&scan);
+ regstack.ga_len -= sizeof(regstar_T);
+ break;
+ }
+
+ // Tried once already, restore input pointers.
+ if (status != RA_BREAK)
+ reg_restore(&rp->rs_un.regsave, &backpos);
+
+ // Repeat until we found a position where it could match.
+ for (;; ) {
+ if (status != RA_BREAK) {
+ // Tried first position already, advance.
+ if (rp->rs_state == RS_STAR_LONG) {
+ // Trying for longest match, but couldn't or
+ // didn't match -- back up one char.
+ if (--rst->count < rst->minval)
+ break;
+ if (rex.input == rex.line) {
+ // backup to last char of previous line
+ if (rex.lnum == 0) {
+ status = RA_NOMATCH;
+ break;
+ }
+ rex.lnum--;
+ rex.line = reg_getline(rex.lnum);
+ // Just in case regrepeat() didn't count right.
+ if (rex.line == NULL) {
+ break;
+ }
+ rex.input = rex.line + STRLEN(rex.line);
+ fast_breakcheck();
+ } else {
+ MB_PTR_BACK(rex.line, rex.input);
+ }
+ } else {
+ // Range is backwards, use shortest match first.
+ // Careful: maxval and minval are exchanged!
+ // Couldn't or didn't match: try advancing one
+ // char.
+ if (rst->count == rst->minval
+ || regrepeat(OPERAND(rp->rs_scan), 1L) == 0)
+ break;
+ ++rst->count;
+ }
+ if (got_int)
+ break;
+ } else
+ status = RA_NOMATCH;
+
+ // If it could match, try it.
+ if (rst->nextb == NUL || *rex.input == rst->nextb
+ || *rex.input == rst->nextb_ic) {
+ reg_save(&rp->rs_un.regsave, &backpos);
+ scan = regnext(rp->rs_scan);
+ status = RA_CONT;
+ break;
+ }
+ }
+ if (status != RA_CONT) {
+ // Failed.
+ regstack_pop(&scan);
+ regstack.ga_len -= sizeof(regstar_T);
+ status = RA_NOMATCH;
+ }
+ }
+ break;
+ }
+
+ // If we want to continue the inner loop or didn't pop a state
+ // continue matching loop
+ if (status == RA_CONT || rp == (regitem_T *)
+ ((char *)regstack.ga_data + regstack.ga_len) - 1)
+ break;
+ }
+
+ // May need to continue with the inner loop, starting at "scan".
+ if (status == RA_CONT)
+ continue;
+
+ // If the regstack is empty or something failed we are done.
+ if (GA_EMPTY(&regstack) || status == RA_FAIL) {
+ if (scan == NULL) {
+ // We get here only if there's trouble -- normally "case END" is
+ // the terminating point.
+ iemsg(_(e_re_corr));
+#ifdef REGEXP_DEBUG
+ printf("Premature EOL\n");
+#endif
+ }
+ return status == RA_MATCH;
+ }
+
+ } // End of loop until the regstack is empty.
+
+ // NOTREACHED
+}
+
+/// Try match of "prog" with at rex.line["col"].
+/// @returns 0 for failure, or number of lines contained in the match.
+static long regtry(bt_regprog_T *prog,
+ colnr_T col,
+ proftime_T *tm, // timeout limit or NULL
+ int *timed_out) // flag set on timeout or NULL
+{
+ rex.input = rex.line + col;
+ rex.need_clear_subexpr = true;
+ // Clear the external match subpointers if necessaey.
+ rex.need_clear_zsubexpr = (prog->reghasz == REX_SET);
+
+ if (regmatch(prog->program + 1, tm, timed_out) == 0) {
+ return 0;
+ }
+
+ cleanup_subexpr();
+ if (REG_MULTI) {
+ if (rex.reg_startpos[0].lnum < 0) {
+ rex.reg_startpos[0].lnum = 0;
+ rex.reg_startpos[0].col = col;
+ }
+ if (rex.reg_endpos[0].lnum < 0) {
+ rex.reg_endpos[0].lnum = rex.lnum;
+ rex.reg_endpos[0].col = (int)(rex.input - rex.line);
+ } else {
+ // Use line number of "\ze".
+ rex.lnum = rex.reg_endpos[0].lnum;
+ }
+ } else {
+ if (rex.reg_startp[0] == NULL) {
+ rex.reg_startp[0] = rex.line + col;
+ }
+ if (rex.reg_endp[0] == NULL) {
+ rex.reg_endp[0] = rex.input;
+ }
+ }
+ // Package any found \z(...\) matches for export. Default is none.
+ unref_extmatch(re_extmatch_out);
+ re_extmatch_out = NULL;
+
+ if (prog->reghasz == REX_SET) {
+ int i;
+
+ cleanup_zsubexpr();
+ re_extmatch_out = make_extmatch();
+ for (i = 0; i < NSUBEXP; i++) {
+ if (REG_MULTI) {
+ // Only accept single line matches.
+ if (reg_startzpos[i].lnum >= 0
+ && reg_endzpos[i].lnum == reg_startzpos[i].lnum
+ && reg_endzpos[i].col >= reg_startzpos[i].col) {
+ re_extmatch_out->matches[i] =
+ vim_strnsave(reg_getline(reg_startzpos[i].lnum)
+ + reg_startzpos[i].col,
+ reg_endzpos[i].col
+ - reg_startzpos[i].col);
+ }
+ } else {
+ if (reg_startzp[i] != NULL && reg_endzp[i] != NULL)
+ re_extmatch_out->matches[i] =
+ vim_strnsave(reg_startzp[i], reg_endzp[i] - reg_startzp[i]);
+ }
+ }
+ }
+ return 1 + rex.lnum;
+}
+
+/// Match a regexp against a string ("line" points to the string) or multiple
+/// lines (if "line" is NULL, use reg_getline()).
+/// @return 0 for failure, or number of lines contained in the match.
+static long bt_regexec_both(char_u *line,
+ colnr_T col, // column to start search
+ proftime_T *tm, // timeout limit or NULL
+ int *timed_out) // flag set on timeout or NULL
+{
+ bt_regprog_T *prog;
+ char_u *s;
+ long retval = 0L;
+
+ // Create "regstack" and "backpos" if they are not allocated yet.
+ // We allocate *_INITIAL amount of bytes first and then set the grow size
+ // to much bigger value to avoid many malloc calls in case of deep regular
+ // expressions.
+ if (regstack.ga_data == NULL) {
+ // Use an item size of 1 byte, since we push different things
+ // onto the regstack.
+ ga_init(&regstack, 1, REGSTACK_INITIAL);
+ ga_grow(&regstack, REGSTACK_INITIAL);
+ ga_set_growsize(&regstack, REGSTACK_INITIAL * 8);
+ }
+
+ if (backpos.ga_data == NULL) {
+ ga_init(&backpos, sizeof(backpos_T), BACKPOS_INITIAL);
+ ga_grow(&backpos, BACKPOS_INITIAL);
+ ga_set_growsize(&backpos, BACKPOS_INITIAL * 8);
+ }
+
+ if (REG_MULTI) {
+ prog = (bt_regprog_T *)rex.reg_mmatch->regprog;
+ line = reg_getline((linenr_T)0);
+ rex.reg_startpos = rex.reg_mmatch->startpos;
+ rex.reg_endpos = rex.reg_mmatch->endpos;
+ } else {
+ prog = (bt_regprog_T *)rex.reg_match->regprog;
+ rex.reg_startp = rex.reg_match->startp;
+ rex.reg_endp = rex.reg_match->endp;
+ }
+
+ // Be paranoid...
+ if (prog == NULL || line == NULL) {
+ iemsg(_(e_null));
+ goto theend;
+ }
+
+ // Check validity of program.
+ if (prog_magic_wrong())
+ goto theend;
+
+ // If the start column is past the maximum column: no need to try.
+ if (rex.reg_maxcol > 0 && col >= rex.reg_maxcol) {
+ goto theend;
+ }
+
+ // If pattern contains "\c" or "\C": overrule value of rex.reg_ic
+ if (prog->regflags & RF_ICASE) {
+ rex.reg_ic = true;
+ } else if (prog->regflags & RF_NOICASE) {
+ rex.reg_ic = false;
+ }
+
+ // If pattern contains "\Z" overrule value of rex.reg_icombine
+ if (prog->regflags & RF_ICOMBINE) {
+ rex.reg_icombine = true;
+ }
+
+ // If there is a "must appear" string, look for it.
+ if (prog->regmust != NULL) {
+ int c = utf_ptr2char(prog->regmust);
+ s = line + col;
+
+ // This is used very often, esp. for ":global". Use two versions of
+ // the loop to avoid overhead of conditions.
+ if (!rex.reg_ic) {
+ while ((s = vim_strchr(s, c)) != NULL) {
+ if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0) {
+ break; // Found it.
+ }
+ MB_PTR_ADV(s);
+ }
+ } else {
+ while ((s = cstrchr(s, c)) != NULL) {
+ if (cstrncmp(s, prog->regmust, &prog->regmlen) == 0) {
+ break; // Found it.
+ }
+ MB_PTR_ADV(s);
+ }
+ }
+ if (s == NULL) { // Not present.
+ goto theend;
+ }
+ }
+
+ rex.line = line;
+ rex.lnum = 0;
+ reg_toolong = false;
+
+ // Simplest case: Anchored match need be tried only once.
+ if (prog->reganch) {
+ int c = utf_ptr2char(rex.line + col);
+ if (prog->regstart == NUL
+ || prog->regstart == c
+ || (rex.reg_ic
+ && (utf_fold(prog->regstart) == utf_fold(c)
+ || (c < 255 && prog->regstart < 255
+ && mb_tolower(prog->regstart) == mb_tolower(c))))) {
+ retval = regtry(prog, col, tm, timed_out);
+ } else {
+ retval = 0;
+ }
+ } else {
+ int tm_count = 0;
+ // Messy cases: unanchored match.
+ while (!got_int) {
+ if (prog->regstart != NUL) {
+ // Skip until the char we know it must start with.
+ s = cstrchr(rex.line + col, prog->regstart);
+ if (s == NULL) {
+ retval = 0;
+ break;
+ }
+ col = (int)(s - rex.line);
+ }
+
+ // Check for maximum column to try.
+ if (rex.reg_maxcol > 0 && col >= rex.reg_maxcol) {
+ retval = 0;
+ break;
+ }
+
+ retval = regtry(prog, col, tm, timed_out);
+ if (retval > 0) {
+ break;
+ }
+
+ // if not currently on the first line, get it again
+ if (rex.lnum != 0) {
+ rex.lnum = 0;
+ rex.line = reg_getline((linenr_T)0);
+ }
+ if (rex.line[col] == NUL) {
+ break;
+ }
+ col += utfc_ptr2len(rex.line + col);
+ // Check for timeout once in a twenty times to avoid overhead.
+ if (tm != NULL && ++tm_count == 20) {
+ tm_count = 0;
+ if (profile_passed_limit(*tm)) {
+ if (timed_out != NULL) {
+ *timed_out = true;
+ }
+ break;
+ }
+ }
+ }
+ }
+
+theend:
+ // Free "reg_tofree" when it's a bit big.
+ // Free regstack and backpos if they are bigger than their initial size.
+ if (reg_tofreelen > 400) {
+ XFREE_CLEAR(reg_tofree);
+ }
+ if (regstack.ga_maxlen > REGSTACK_INITIAL)
+ ga_clear(&regstack);
+ if (backpos.ga_maxlen > BACKPOS_INITIAL)
+ ga_clear(&backpos);
+
+ if (retval > 0) {
+ // Make sure the end is never before the start. Can happen when \zs
+ // and \ze are used.
+ if (REG_MULTI) {
+ const lpos_T *const start = &rex.reg_mmatch->startpos[0];
+ const lpos_T *const end = &rex.reg_mmatch->endpos[0];
+
+ if (end->lnum < start->lnum
+ || (end->lnum == start->lnum && end->col < start->col)) {
+ rex.reg_mmatch->endpos[0] = rex.reg_mmatch->startpos[0];
+ }
+ } else {
+ if (rex.reg_match->endp[0] < rex.reg_match->startp[0]) {
+ rex.reg_match->endp[0] = rex.reg_match->startp[0];
+ }
+ }
+ }
+
+ return retval;
+}
+
+/*
+ * Match a regexp against a string.
+ * "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
+ * Uses curbuf for line count and 'iskeyword'.
+ * If "line_lbr" is true, consider a "\n" in "line" to be a line break.
+ *
+ * Returns 0 for failure, number of lines contained in the match otherwise.
+ */
+static int bt_regexec_nl(
+ regmatch_T *rmp,
+ char_u *line, // string to match against
+ colnr_T col, // column to start looking for match
+ bool line_lbr)
+{
+ rex.reg_match = rmp;
+ rex.reg_mmatch = NULL;
+ rex.reg_maxline = 0;
+ rex.reg_line_lbr = line_lbr;
+ rex.reg_buf = curbuf;
+ rex.reg_win = NULL;
+ rex.reg_ic = rmp->rm_ic;
+ rex.reg_icombine = false;
+ rex.reg_maxcol = 0;
+
+ long r = bt_regexec_both(line, col, NULL, NULL);
+ assert(r <= INT_MAX);
+ return (int)r;
+}
+
+
+/// Matches a regexp against multiple lines.
+/// "rmp->regprog" is a compiled regexp as returned by vim_regcomp().
+/// Uses curbuf for line count and 'iskeyword'.
+///
+/// @param win Window in which to search or NULL
+/// @param buf Buffer in which to search
+/// @param lnum Number of line to start looking for match
+/// @param col Column to start looking for match
+/// @param tm Timeout limit or NULL
+///
+/// @return zero if there is no match and number of lines contained in the match
+/// otherwise.
+static long bt_regexec_multi(regmmatch_T *rmp, win_T *win, buf_T *buf,
+ linenr_T lnum, colnr_T col,
+ proftime_T *tm, int *timed_out)
+{
+ rex.reg_match = NULL;
+ rex.reg_mmatch = rmp;
+ rex.reg_buf = buf;
+ rex.reg_win = win;
+ rex.reg_firstlnum = lnum;
+ rex.reg_maxline = rex.reg_buf->b_ml.ml_line_count - lnum;
+ rex.reg_line_lbr = false;
+ rex.reg_ic = rmp->rmm_ic;
+ rex.reg_icombine = false;
+ rex.reg_maxcol = rmp->rmm_maxcol;
+
+ return bt_regexec_both(NULL, col, tm, timed_out);
+}
+
+/*
+ * Compare a number with the operand of RE_LNUM, RE_COL or RE_VCOL.
+ */
+static int re_num_cmp(uint32_t val, char_u *scan)
+{
+ uint32_t n = (uint32_t)OPERAND_MIN(scan);
+
+ if (OPERAND_CMP(scan) == '>')
+ return val > n;
+ if (OPERAND_CMP(scan) == '<')
+ return val < n;
+ return val == n;
+}
+
+#ifdef BT_REGEXP_DUMP
+
+/*
+ * regdump - dump a regexp onto stdout in vaguely comprehensible form
+ */
+static void regdump(char_u *pattern, bt_regprog_T *r)
+{
+ char_u *s;
+ int op = EXACTLY; // Arbitrary non-END op.
+ char_u *next;
+ char_u *end = NULL;
+ FILE *f;
+
+#ifdef BT_REGEXP_LOG
+ f = fopen("bt_regexp_log.log", "a");
+#else
+ f = stdout;
+#endif
+ if (f == NULL)
+ return;
+ fprintf(f, "-------------------------------------\n\r\nregcomp(%s):\r\n",
+ pattern);
+
+ s = r->program + 1;
+ // Loop until we find the END that isn't before a referred next (an END
+ // can also appear in a NOMATCH operand).
+ while (op != END || s <= end) {
+ op = OP(s);
+ fprintf(f, "%2d%s", (int)(s - r->program), regprop(s)); // Where, what.
+ next = regnext(s);
+ if (next == NULL) // Next ptr.
+ fprintf(f, "(0)");
+ else
+ fprintf(f, "(%d)", (int)((s - r->program) + (next - s)));
+ if (end < next)
+ end = next;
+ if (op == BRACE_LIMITS) {
+ // Two ints
+ fprintf(f, " minval %" PRId64 ", maxval %" PRId64,
+ (int64_t)OPERAND_MIN(s), (int64_t)OPERAND_MAX(s));
+ s += 8;
+ } else if (op == BEHIND || op == NOBEHIND) {
+ // one int
+ fprintf(f, " count %" PRId64, (int64_t)OPERAND_MIN(s));
+ s += 4;
+ } else if (op == RE_LNUM || op == RE_COL || op == RE_VCOL) {
+ // one int plus comparator
+ fprintf(f, " count %" PRId64, (int64_t)OPERAND_MIN(s));
+ s += 5;
+ }
+ s += 3;
+ if (op == ANYOF || op == ANYOF + ADD_NL
+ || op == ANYBUT || op == ANYBUT + ADD_NL
+ || op == EXACTLY) {
+ // Literal string, where present.
+ fprintf(f, "\nxxxxxxxxx\n");
+ while (*s != NUL)
+ fprintf(f, "%c", *s++);
+ fprintf(f, "\nxxxxxxxxx\n");
+ s++;
+ }
+ fprintf(f, "\r\n");
+ }
+
+ // Header fields of interest.
+ if (r->regstart != NUL)
+ fprintf(f, "start `%s' 0x%x; ", r->regstart < 256
+ ? (char *)transchar(r->regstart)
+ : "multibyte", r->regstart);
+ if (r->reganch)
+ fprintf(f, "anchored; ");
+ if (r->regmust != NULL)
+ fprintf(f, "must have \"%s\"", r->regmust);
+ fprintf(f, "\r\n");
+
+#ifdef BT_REGEXP_LOG
+ fclose(f);
+#endif
+}
+#endif // BT_REGEXP_DUMP
+
+#ifdef REGEXP_DEBUG
+
+/*
+ * regprop - printable representation of opcode
+ */
+static char_u *regprop(char_u *op)
+{
+ char *p;
+ static char buf[50];
+
+ STRCPY(buf, ":");
+
+ switch ((int)OP(op)) {
+ case BOL:
+ p = "BOL";
+ break;
+ case EOL:
+ p = "EOL";
+ break;
+ case RE_BOF:
+ p = "BOF";
+ break;
+ case RE_EOF:
+ p = "EOF";
+ break;
+ case CURSOR:
+ p = "CURSOR";
+ break;
+ case RE_VISUAL:
+ p = "RE_VISUAL";
+ break;
+ case RE_LNUM:
+ p = "RE_LNUM";
+ break;
+ case RE_MARK:
+ p = "RE_MARK";
+ break;
+ case RE_COL:
+ p = "RE_COL";
+ break;
+ case RE_VCOL:
+ p = "RE_VCOL";
+ break;
+ case BOW:
+ p = "BOW";
+ break;
+ case EOW:
+ p = "EOW";
+ break;
+ case ANY:
+ p = "ANY";
+ break;
+ case ANY + ADD_NL:
+ p = "ANY+NL";
+ break;
+ case ANYOF:
+ p = "ANYOF";
+ break;
+ case ANYOF + ADD_NL:
+ p = "ANYOF+NL";
+ break;
+ case ANYBUT:
+ p = "ANYBUT";
+ break;
+ case ANYBUT + ADD_NL:
+ p = "ANYBUT+NL";
+ break;
+ case IDENT:
+ p = "IDENT";
+ break;
+ case IDENT + ADD_NL:
+ p = "IDENT+NL";
+ break;
+ case SIDENT:
+ p = "SIDENT";
+ break;
+ case SIDENT + ADD_NL:
+ p = "SIDENT+NL";
+ break;
+ case KWORD:
+ p = "KWORD";
+ break;
+ case KWORD + ADD_NL:
+ p = "KWORD+NL";
+ break;
+ case SKWORD:
+ p = "SKWORD";
+ break;
+ case SKWORD + ADD_NL:
+ p = "SKWORD+NL";
+ break;
+ case FNAME:
+ p = "FNAME";
+ break;
+ case FNAME + ADD_NL:
+ p = "FNAME+NL";
+ break;
+ case SFNAME:
+ p = "SFNAME";
+ break;
+ case SFNAME + ADD_NL:
+ p = "SFNAME+NL";
+ break;
+ case PRINT:
+ p = "PRINT";
+ break;
+ case PRINT + ADD_NL:
+ p = "PRINT+NL";
+ break;
+ case SPRINT:
+ p = "SPRINT";
+ break;
+ case SPRINT + ADD_NL:
+ p = "SPRINT+NL";
+ break;
+ case WHITE:
+ p = "WHITE";
+ break;
+ case WHITE + ADD_NL:
+ p = "WHITE+NL";
+ break;
+ case NWHITE:
+ p = "NWHITE";
+ break;
+ case NWHITE + ADD_NL:
+ p = "NWHITE+NL";
+ break;
+ case DIGIT:
+ p = "DIGIT";
+ break;
+ case DIGIT + ADD_NL:
+ p = "DIGIT+NL";
+ break;
+ case NDIGIT:
+ p = "NDIGIT";
+ break;
+ case NDIGIT + ADD_NL:
+ p = "NDIGIT+NL";
+ break;
+ case HEX:
+ p = "HEX";
+ break;
+ case HEX + ADD_NL:
+ p = "HEX+NL";
+ break;
+ case NHEX:
+ p = "NHEX";
+ break;
+ case NHEX + ADD_NL:
+ p = "NHEX+NL";
+ break;
+ case OCTAL:
+ p = "OCTAL";
+ break;
+ case OCTAL + ADD_NL:
+ p = "OCTAL+NL";
+ break;
+ case NOCTAL:
+ p = "NOCTAL";
+ break;
+ case NOCTAL + ADD_NL:
+ p = "NOCTAL+NL";
+ break;
+ case WORD:
+ p = "WORD";
+ break;
+ case WORD + ADD_NL:
+ p = "WORD+NL";
+ break;
+ case NWORD:
+ p = "NWORD";
+ break;
+ case NWORD + ADD_NL:
+ p = "NWORD+NL";
+ break;
+ case HEAD:
+ p = "HEAD";
+ break;
+ case HEAD + ADD_NL:
+ p = "HEAD+NL";
+ break;
+ case NHEAD:
+ p = "NHEAD";
+ break;
+ case NHEAD + ADD_NL:
+ p = "NHEAD+NL";
+ break;
+ case ALPHA:
+ p = "ALPHA";
+ break;
+ case ALPHA + ADD_NL:
+ p = "ALPHA+NL";
+ break;
+ case NALPHA:
+ p = "NALPHA";
+ break;
+ case NALPHA + ADD_NL:
+ p = "NALPHA+NL";
+ break;
+ case LOWER:
+ p = "LOWER";
+ break;
+ case LOWER + ADD_NL:
+ p = "LOWER+NL";
+ break;
+ case NLOWER:
+ p = "NLOWER";
+ break;
+ case NLOWER + ADD_NL:
+ p = "NLOWER+NL";
+ break;
+ case UPPER:
+ p = "UPPER";
+ break;
+ case UPPER + ADD_NL:
+ p = "UPPER+NL";
+ break;
+ case NUPPER:
+ p = "NUPPER";
+ break;
+ case NUPPER + ADD_NL:
+ p = "NUPPER+NL";
+ break;
+ case BRANCH:
+ p = "BRANCH";
+ break;
+ case EXACTLY:
+ p = "EXACTLY";
+ break;
+ case NOTHING:
+ p = "NOTHING";
+ break;
+ case BACK:
+ p = "BACK";
+ break;
+ case END:
+ p = "END";
+ break;
+ case MOPEN + 0:
+ p = "MATCH START";
+ break;
+ case MOPEN + 1:
+ case MOPEN + 2:
+ case MOPEN + 3:
+ case MOPEN + 4:
+ case MOPEN + 5:
+ case MOPEN + 6:
+ case MOPEN + 7:
+ case MOPEN + 8:
+ case MOPEN + 9:
+ sprintf(buf + STRLEN(buf), "MOPEN%d", OP(op) - MOPEN);
+ p = NULL;
+ break;
+ case MCLOSE + 0:
+ p = "MATCH END";
+ break;
+ case MCLOSE + 1:
+ case MCLOSE + 2:
+ case MCLOSE + 3:
+ case MCLOSE + 4:
+ case MCLOSE + 5:
+ case MCLOSE + 6:
+ case MCLOSE + 7:
+ case MCLOSE + 8:
+ case MCLOSE + 9:
+ sprintf(buf + STRLEN(buf), "MCLOSE%d", OP(op) - MCLOSE);
+ p = NULL;
+ break;
+ case BACKREF + 1:
+ case BACKREF + 2:
+ case BACKREF + 3:
+ case BACKREF + 4:
+ case BACKREF + 5:
+ case BACKREF + 6:
+ case BACKREF + 7:
+ case BACKREF + 8:
+ case BACKREF + 9:
+ sprintf(buf + STRLEN(buf), "BACKREF%d", OP(op) - BACKREF);
+ p = NULL;
+ break;
+ case NOPEN:
+ p = "NOPEN";
+ break;
+ case NCLOSE:
+ p = "NCLOSE";
+ break;
+ case ZOPEN + 1:
+ case ZOPEN + 2:
+ case ZOPEN + 3:
+ case ZOPEN + 4:
+ case ZOPEN + 5:
+ case ZOPEN + 6:
+ case ZOPEN + 7:
+ case ZOPEN + 8:
+ case ZOPEN + 9:
+ sprintf(buf + STRLEN(buf), "ZOPEN%d", OP(op) - ZOPEN);
+ p = NULL;
+ break;
+ case ZCLOSE + 1:
+ case ZCLOSE + 2:
+ case ZCLOSE + 3:
+ case ZCLOSE + 4:
+ case ZCLOSE + 5:
+ case ZCLOSE + 6:
+ case ZCLOSE + 7:
+ case ZCLOSE + 8:
+ case ZCLOSE + 9:
+ sprintf(buf + STRLEN(buf), "ZCLOSE%d", OP(op) - ZCLOSE);
+ p = NULL;
+ break;
+ case ZREF + 1:
+ case ZREF + 2:
+ case ZREF + 3:
+ case ZREF + 4:
+ case ZREF + 5:
+ case ZREF + 6:
+ case ZREF + 7:
+ case ZREF + 8:
+ case ZREF + 9:
+ sprintf(buf + STRLEN(buf), "ZREF%d", OP(op) - ZREF);
+ p = NULL;
+ break;
+ case STAR:
+ p = "STAR";
+ break;
+ case PLUS:
+ p = "PLUS";
+ break;
+ case NOMATCH:
+ p = "NOMATCH";
+ break;
+ case MATCH:
+ p = "MATCH";
+ break;
+ case BEHIND:
+ p = "BEHIND";
+ break;
+ case NOBEHIND:
+ p = "NOBEHIND";
+ break;
+ case SUBPAT:
+ p = "SUBPAT";
+ break;
+ case BRACE_LIMITS:
+ p = "BRACE_LIMITS";
+ break;
+ case BRACE_SIMPLE:
+ p = "BRACE_SIMPLE";
+ break;
+ case BRACE_COMPLEX + 0:
+ case BRACE_COMPLEX + 1:
+ case BRACE_COMPLEX + 2:
+ case BRACE_COMPLEX + 3:
+ case BRACE_COMPLEX + 4:
+ case BRACE_COMPLEX + 5:
+ case BRACE_COMPLEX + 6:
+ case BRACE_COMPLEX + 7:
+ case BRACE_COMPLEX + 8:
+ case BRACE_COMPLEX + 9:
+ sprintf(buf + STRLEN(buf), "BRACE_COMPLEX%d", OP(op) - BRACE_COMPLEX);
+ p = NULL;
+ break;
+ case MULTIBYTECODE:
+ p = "MULTIBYTECODE";
+ break;
+ case NEWL:
+ p = "NEWL";
+ break;
+ default:
+ sprintf(buf + STRLEN(buf), "corrupt %d", OP(op));
+ p = NULL;
+ break;
+ }
+ if (p != NULL)
+ STRCAT(buf, p);
+ return (char_u *)buf;
+}
+#endif // REGEXP_DEBUG
diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c
index 1c04cb16b3..1102096b32 100644
--- a/src/nvim/runtime.c
+++ b/src/nvim/runtime.c
@@ -24,6 +24,13 @@
static bool runtime_search_path_valid = false;
static int *runtime_search_path_ref = NULL;
static RuntimeSearchPath runtime_search_path;
+static RuntimeSearchPath runtime_search_path_thread;
+static uv_mutex_t runtime_search_path_mutex;
+
+void runtime_init(void)
+{
+ uv_mutex_init(&runtime_search_path_mutex);
+}
/// ":runtime [what] {name}"
void ex_runtime(exarg_T *eap)
@@ -146,7 +153,7 @@ int do_in_path(char_u *path, char *name, int flags, DoInRuntimepathCB callback,
if (flags & DIP_ERR) {
semsg(_(e_dirnotf), basepath, name);
- } else if (p_verbose > 0) {
+ } else if (p_verbose > 1) {
verbose_enter();
smsg(_("not found in '%s': \"%s\""), basepath, name);
verbose_leave();
@@ -172,6 +179,17 @@ RuntimeSearchPath runtime_search_path_get_cached(int *ref)
return runtime_search_path;
}
+RuntimeSearchPath copy_runtime_search_path(const RuntimeSearchPath src)
+{
+ RuntimeSearchPath dst = KV_INITIAL_VALUE;
+ for (size_t j = 0; j < kv_size(src); j++) {
+ SearchPathItem src_item = kv_A(src, j);
+ kv_push(dst, ((SearchPathItem){ xstrdup(src_item.path), src_item.after, src_item.has_lua }));
+ }
+
+ return dst;
+}
+
void runtime_search_path_unref(RuntimeSearchPath path, int *ref)
FUNC_ATTR_NONNULL_ALL
{
@@ -268,7 +286,7 @@ int do_in_cached_path(char_u *name, int flags, DoInRuntimepathCB callback, void
if (!did_one && name != NULL) {
if (flags & DIP_ERR) {
semsg(_(e_dirnotf), "runtime path", name);
- } else if (p_verbose > 0) {
+ } else if (p_verbose > 1) {
verbose_enter();
smsg(_("not found in runtime path: \"%s\""), name);
verbose_leave();
@@ -302,15 +320,35 @@ ArrayOf(String) runtime_get_named(bool lua, Array pat, bool all)
{
int ref;
RuntimeSearchPath path = runtime_search_path_get_cached(&ref);
- ArrayOf(String) rv = ARRAY_DICT_INIT;
static char buf[MAXPATHL];
+ ArrayOf(String) rv = runtime_get_named_common(lua, pat, all, path, buf, sizeof buf);
+
+ runtime_search_path_unref(path, &ref);
+ return rv;
+}
+
+ArrayOf(String) runtime_get_named_thread(bool lua, Array pat, bool all)
+{
+ // TODO(bfredl): avoid contention between multiple worker threads?
+ uv_mutex_lock(&runtime_search_path_mutex);
+ static char buf[MAXPATHL];
+ ArrayOf(String) rv = runtime_get_named_common(lua, pat, all, runtime_search_path_thread,
+ buf, sizeof buf);
+ uv_mutex_unlock(&runtime_search_path_mutex);
+ return rv;
+}
+
+ArrayOf(String) runtime_get_named_common(bool lua, Array pat, bool all,
+ RuntimeSearchPath path, char *buf, size_t buf_len)
+{
+ ArrayOf(String) rv = ARRAY_DICT_INIT;
for (size_t i = 0; i < kv_size(path); i++) {
SearchPathItem *item = &kv_A(path, i);
if (lua) {
if (item->has_lua == kNone) {
- size_t size = (size_t)snprintf(buf, sizeof buf, "%s/lua/", item->path);
- item->has_lua = (size < sizeof buf && os_isdir((char_u *)buf)) ? kTrue : kFalse;
+ size_t size = (size_t)snprintf(buf, buf_len, "%s/lua/", item->path);
+ item->has_lua = (size < buf_len && os_isdir((char_u *)buf));
}
if (item->has_lua == kFalse) {
continue;
@@ -320,9 +358,9 @@ ArrayOf(String) runtime_get_named(bool lua, Array pat, bool all)
for (size_t j = 0; j < pat.size; j++) {
Object pat_item = pat.items[j];
if (pat_item.type == kObjectTypeString) {
- size_t size = (size_t)snprintf(buf, sizeof buf, "%s/%s",
+ size_t size = (size_t)snprintf(buf, buf_len, "%s/%s",
item->path, pat_item.data.string.data);
- if (size < sizeof buf) {
+ if (size < buf_len) {
if (os_file_is_readable(buf)) {
ADD(rv, STRING_OBJ(cstr_to_string(buf)));
if (!all) {
@@ -333,9 +371,7 @@ ArrayOf(String) runtime_get_named(bool lua, Array pat, bool all)
}
}
}
-
done:
- runtime_search_path_unref(path, &ref);
return rv;
}
@@ -569,6 +605,10 @@ void runtime_search_path_validate(void)
runtime_search_path = runtime_search_path_build();
runtime_search_path_valid = true;
runtime_search_path_ref = NULL; // initially unowned
+ uv_mutex_lock(&runtime_search_path_mutex);
+ runtime_search_path_free(runtime_search_path_thread);
+ runtime_search_path_thread = copy_runtime_search_path(runtime_search_path);
+ uv_mutex_unlock(&runtime_search_path_mutex);
}
}
diff --git a/src/nvim/screen.c b/src/nvim/screen.c
index 15fb6901cc..3c974f62bd 100644
--- a/src/nvim/screen.c
+++ b/src/nvim/screen.c
@@ -75,6 +75,7 @@
#include "nvim/cursor.h"
#include "nvim/cursor_shape.h"
#include "nvim/decoration.h"
+#include "nvim/decoration_provider.h"
#include "nvim/diff.h"
#include "nvim/edit.h"
#include "nvim/eval.h"
@@ -126,8 +127,6 @@
#define MB_FILLER_CHAR '<' /* character used when a double-width character
* doesn't fit. */
-typedef kvec_withinit_t(DecorProvider *, 4) Providers;
-
// temporary buffer for rendering a single screenline, so it can be
// compared with previous contents to calculate smallest delta.
// Per-cell attributes
@@ -168,36 +167,6 @@ static bool resizing = false;
static char *provider_err = NULL;
-static bool provider_invoke(NS ns_id, const char *name, LuaRef ref, Array args, bool default_true)
-{
- Error err = ERROR_INIT;
-
- textlock++;
- provider_active = true;
- Object ret = nlua_call_ref(ref, name, args, true, &err);
- provider_active = false;
- textlock--;
-
- if (!ERROR_SET(&err)
- && api_object_to_bool(ret, "provider %s retval", default_true, &err)) {
- return true;
- }
-
- if (ERROR_SET(&err)) {
- const char *ns_name = describe_ns(ns_id);
- ELOG("error in provider %s:%s: %s", ns_name, name, err.msg);
- bool verbose_errs = true; // TODO(bfredl):
- if (verbose_errs && provider_err == NULL) {
- static char errbuf[IOSIZE];
- snprintf(errbuf, sizeof errbuf, "%s: %s", ns_name, err.msg);
- provider_err = xstrdup(errbuf);
- }
- }
-
- api_free_object(ret);
- return false;
-}
-
/// Redraw a window later, with update_screen(type).
///
/// Set must_redraw only if not already set to a higher value.
@@ -317,7 +286,8 @@ void update_curbuf(int type)
void redraw_buf_status_later(buf_T *buf)
{
FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
- if (wp->w_buffer == buf && wp->w_status_height) {
+ if (wp->w_buffer == buf
+ && (wp->w_status_height || (wp == curwin && global_stl_height()))) {
wp->w_redr_status = true;
if (must_redraw < VALID) {
must_redraw = VALID;
@@ -326,6 +296,18 @@ void redraw_buf_status_later(buf_T *buf)
}
}
+void redraw_win_signcol(win_T *wp)
+{
+ // If we can compute a change in the automatic sizing of the sign column
+ // under 'signcolumn=auto:X' and signs currently placed in the buffer, better
+ // figuring it out here so we can redraw the entire screen for it.
+ int scwidth = wp->w_scwidth;
+ wp->w_scwidth = win_signcol_count(wp);
+ if (wp->w_scwidth != scwidth) {
+ changed_line_abv_curs_win(wp);
+ }
+}
+
/// Redraw the parts of the screen that is marked for redraw.
///
/// Most code shouldn't call this directly, rather use redraw_later() and
@@ -335,6 +317,7 @@ void redraw_buf_status_later(buf_T *buf)
int update_screen(int type)
{
static bool did_intro = false;
+ bool is_stl_global = global_stl_height() > 0;
// Don't do anything if the screen structures are (not yet) valid.
// A VimResized autocmd can invoke redrawing in the middle of a resize,
@@ -417,10 +400,13 @@ int update_screen(int type)
if (W_ENDROW(wp) > valid) {
wp->w_redr_type = MAX(wp->w_redr_type, NOT_VALID);
}
- if (W_ENDROW(wp) + wp->w_status_height > valid) {
+ if (!is_stl_global && W_ENDROW(wp) + wp->w_status_height > valid) {
wp->w_redr_status = true;
}
}
+ if (is_stl_global && Rows - p_ch - 1 > valid) {
+ curwin->w_redr_status = true;
+ }
}
msg_grid_set_pos(Rows-p_ch, false);
msg_grid_invalid = false;
@@ -442,13 +428,15 @@ int update_screen(int type)
wp->w_redr_type = REDRAW_TOP;
} else {
wp->w_redr_type = NOT_VALID;
- if (W_ENDROW(wp) + wp->w_status_height
- <= msg_scrolled) {
- wp->w_redr_status = TRUE;
+ if (!is_stl_global && W_ENDROW(wp) + wp->w_status_height <= msg_scrolled) {
+ wp->w_redr_status = true;
}
}
}
}
+ if (is_stl_global && Rows - p_ch - 1 <= msg_scrolled) {
+ curwin->w_redr_status = true;
+ }
redraw_cmdline = true;
redraw_tabline = true;
}
@@ -489,28 +477,8 @@ int update_screen(int type)
ui_comp_set_screen_valid(true);
- Providers providers;
- kvi_init(providers);
- for (size_t i = 0; i < kv_size(decor_providers); i++) {
- DecorProvider *p = &kv_A(decor_providers, i);
- if (!p->active) {
- continue;
- }
-
- bool active;
- if (p->redraw_start != LUA_NOREF) {
- FIXED_TEMP_ARRAY(args, 2);
- args.items[0] = INTEGER_OBJ(display_tick);
- args.items[1] = INTEGER_OBJ(type);
- active = provider_invoke(p->ns_id, "start", p->redraw_start, args, true);
- } else {
- active = true;
- }
-
- if (active) {
- kvi_push(providers, p);
- }
- }
+ DecorProviders providers;
+ decor_providers_start(&providers, type, &provider_err);
// "start" callback could have changed highlights for global elements
if (win_check_ns_hl(NULL)) {
@@ -579,14 +547,7 @@ int update_screen(int type)
}
if (buf->b_mod_tick_decor < display_tick) {
- for (size_t i = 0; i < kv_size(providers); i++) {
- DecorProvider *p = kv_A(providers, i);
- if (p && p->redraw_buf != LUA_NOREF) {
- FIXED_TEMP_ARRAY(args, 1);
- args.items[0] = BUFFER_OBJ(buf->handle);
- provider_invoke(p->ns_id, "buf", p->redraw_buf, args, true);
- }
- }
+ decor_providers_invoke_buf(buf, &providers, &provider_err);
buf->b_mod_tick_decor = display_tick;
}
}
@@ -656,18 +617,7 @@ int update_screen(int type)
}
did_intro = true;
- for (size_t i = 0; i < kv_size(providers); i++) {
- DecorProvider *p = kv_A(providers, i);
- if (!p->active) {
- continue;
- }
-
- if (p->redraw_end != LUA_NOREF) {
- FIXED_TEMP_ARRAY(args, 1);
- args.items[0] = INTEGER_OBJ(display_tick);
- provider_invoke(p->ns_id, "end", p->redraw_end, args, true);
- }
- }
+ decor_providers_invoke_end(&providers, &provider_err);
kvi_destroy(providers);
@@ -754,7 +704,7 @@ bool win_cursorline_standout(const win_T *wp)
* mid: from mid_start to mid_end (update inversion or changed text)
* bot: from bot_start to last row (when scrolled up)
*/
-static void win_update(win_T *wp, Providers *providers)
+static void win_update(win_T *wp, DecorProviders *providers)
{
buf_T *buf = wp->w_buffer;
int type;
@@ -790,12 +740,6 @@ static void win_update(win_T *wp, Providers *providers)
linenr_T mod_bot = 0;
int save_got_int;
-
- // If we can compute a change in the automatic sizing of the sign column
- // under 'signcolumn=auto:X' and signs currently placed in the buffer, better
- // figuring it out here so we can redraw the entire screen for it.
- win_signcol_count(wp);
-
type = wp->w_redr_type;
if (type >= NOT_VALID) {
@@ -803,8 +747,11 @@ static void win_update(win_T *wp, Providers *providers)
wp->w_lines_valid = 0;
}
- // Window is zero-height: nothing to draw.
+ // Window is zero-height: Only need to draw the separator
if (wp->w_grid.Rows == 0) {
+ // draw the horizontal separator below this window
+ draw_hsep_win(wp);
+ draw_sep_connectors_win(wp);
wp->w_redr_type = 0;
return;
}
@@ -812,11 +759,14 @@ static void win_update(win_T *wp, Providers *providers)
// Window is zero-width: Only need to draw the separator.
if (wp->w_grid.Columns == 0) {
// draw the vertical separator right of this window
- draw_vsep_win(wp, 0);
+ draw_vsep_win(wp);
+ draw_sep_connectors_win(wp);
wp->w_redr_type = 0;
return;
}
+ redraw_win_signcol(wp);
+
init_search_hl(wp);
/* Force redraw when width of 'number' or 'relativenumber' column
@@ -1369,30 +1319,8 @@ static void win_update(win_T *wp, Providers *providers)
decor_redraw_reset(buf, &decor_state);
- Providers line_providers;
- kvi_init(line_providers);
-
- linenr_T knownmax = ((wp->w_valid & VALID_BOTLINE)
- ? wp->w_botline
- : (wp->w_topline + wp->w_height_inner));
-
- for (size_t k = 0; k < kv_size(*providers); k++) {
- DecorProvider *p = kv_A(*providers, k);
- if (p && p->redraw_win != LUA_NOREF) {
- FIXED_TEMP_ARRAY(args, 4);
- args.items[0] = WINDOW_OBJ(wp->handle);
- args.items[1] = BUFFER_OBJ(buf->handle);
- // TODO(bfredl): we are not using this, but should be first drawn line?
- args.items[2] = INTEGER_OBJ(wp->w_topline-1);
- args.items[3] = INTEGER_OBJ(knownmax);
- if (provider_invoke(p->ns_id, "win", p->redraw_win, args, true)) {
- kvi_push(line_providers, p);
- }
- }
- }
-
- win_check_ns_hl(wp);
-
+ DecorProviders line_providers;
+ decor_providers_invoke_win(wp, providers, &line_providers, &provider_err);
for (;;) {
/* stop updating when reached the end of the window (check for _past_
@@ -1747,7 +1675,9 @@ static void win_update(win_T *wp, Providers *providers)
kvi_destroy(line_providers);
if (wp->w_redr_type >= REDRAW_TOP) {
- draw_vsep_win(wp, 0);
+ draw_vsep_win(wp);
+ draw_hsep_win(wp);
+ draw_sep_connectors_win(wp);
}
syn_set_timeout(NULL);
@@ -1846,7 +1776,7 @@ static void win_draw_end(win_T *wp, int c1, int c2, bool draw_margin, int row, i
win_hl_attr(wp, HLF_FC));
}
// draw the sign column
- int count = win_signcol_count(wp);
+ int count = wp->w_scwidth;
if (count > 0) {
n = win_fill_end(wp, ' ', ' ', n, win_signcol_width(wp) * count, row,
endrow, win_hl_attr(wp, HLF_SC));
@@ -2020,6 +1950,38 @@ static size_t fill_foldcolumn(char_u *p, win_T *wp, foldinfo_T foldinfo, linenr_
return MAX(char_counter + (fdc-i), (size_t)fdc);
}
+static inline void provider_err_virt_text(linenr_T lnum, char *err)
+{
+ Decoration err_decor = DECORATION_INIT;
+ int hl_err = syn_check_group(S_LEN("ErrorMsg"));
+ kv_push(err_decor.virt_text,
+ ((VirtTextChunk){ .text = provider_err,
+ .hl_id = hl_err }));
+ err_decor.virt_text_width = mb_string2cells((char_u *)err);
+ decor_add_ephemeral(lnum-1, 0, lnum-1, 0, &err_decor);
+}
+
+static inline void get_line_number_str(win_T *wp, linenr_T lnum, char_u *buf, size_t buf_len)
+{
+ long num;
+ char *fmt = "%*ld ";
+
+ if (wp->w_p_nu && !wp->w_p_rnu) {
+ // 'number' + 'norelativenumber'
+ num = (long)lnum;
+ } else {
+ // 'relativenumber', don't use negative numbers
+ num = labs((long)get_cursor_rel_lnum(wp, lnum));
+ if (num == 0 && wp->w_p_nu && wp->w_p_rnu) {
+ // 'number' + 'relativenumber'
+ num = lnum;
+ fmt = "%-*ld ";
+ }
+ }
+
+ snprintf((char *)buf, buf_len, fmt, number_width(wp), num);
+}
+
/// Display line "lnum" of window 'wp' on the screen.
/// wp->w_virtcol needs to be valid.
///
@@ -2035,7 +1997,7 @@ static size_t fill_foldcolumn(char_u *p, win_T *wp, foldinfo_T foldinfo, linenr_
///
/// @return the number of last row the line occupies.
static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool nochange,
- bool number_only, foldinfo_T foldinfo, Providers *providers)
+ bool number_only, foldinfo_T foldinfo, DecorProviders *providers)
{
int c = 0; // init for GCC
long vcol = 0; // virtual column (for tabs)
@@ -2221,37 +2183,14 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc
}
}
- has_decor = decor_redraw_line(wp->w_buffer, lnum-1,
- &decor_state);
+ has_decor = decor_redraw_line(buf, lnum-1, &decor_state);
- for (size_t k = 0; k < kv_size(*providers); k++) {
- DecorProvider *p = kv_A(*providers, k);
- if (p && p->redraw_line != LUA_NOREF) {
- FIXED_TEMP_ARRAY(args, 3);
- args.items[0] = WINDOW_OBJ(wp->handle);
- args.items[1] = BUFFER_OBJ(buf->handle);
- args.items[2] = INTEGER_OBJ(lnum-1);
- if (provider_invoke(p->ns_id, "line", p->redraw_line, args, true)) {
- has_decor = true;
- } else {
- // return 'false' or error: skip rest of this window
- kv_A(*providers, k) = NULL;
- }
-
- win_check_ns_hl(wp);
- }
- }
+ providers_invoke_line(wp, providers, lnum-1, &has_decor, &provider_err);
if (provider_err) {
- Decoration err_decor = DECORATION_INIT;
- int hl_err = syn_check_group(S_LEN("ErrorMsg"));
- kv_push(err_decor.virt_text,
- ((VirtTextChunk){ .text = provider_err,
- .hl_id = hl_err }));
- err_decor.virt_text_width = mb_string2cells((char_u *)provider_err);
- decor_add_ephemeral(lnum-1, 0, lnum-1, 0, &err_decor);
- provider_err = NULL;
+ provider_err_virt_text(lnum, provider_err);
has_decor = true;
+ provider_err = NULL;
}
if (has_decor) {
@@ -2452,6 +2391,7 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc
memset(sattrs, 0, sizeof(sattrs));
num_signs = buf_get_signattrs(wp->w_buffer, lnum, sattrs);
+ decor_redraw_signs(buf, lnum-1, &num_signs, sattrs);
// If this line has a sign with line highlighting set line_attr.
// TODO(bfredl, vigoux): this should not take priority over decoration!
@@ -2792,13 +2732,17 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc
draw_state = WL_SIGN;
/* Show the sign column when there are any signs in this
* buffer or when using Netbeans. */
- int count = win_signcol_count(wp);
- if (count > 0) {
+ if (wp->w_scwidth > 0) {
get_sign_display_info(false, wp, lnum, sattrs, row,
- startrow, filler_lines, filler_todo, count,
+ startrow, filler_lines, filler_todo,
&c_extra, &c_final, extra, sizeof(extra),
- &p_extra, &n_extra,
- &char_attr, &draw_state, &sign_idx);
+ &p_extra, &n_extra, &char_attr, sign_idx);
+ sign_idx++;
+ if (sign_idx < wp->w_scwidth) {
+ draw_state = WL_SIGN - 1;
+ } else {
+ sign_idx = 0;
+ }
}
}
@@ -2814,33 +2758,14 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc
// number.
if (*wp->w_p_scl == 'n' && *(wp->w_p_scl + 1) == 'u'
&& num_signs > 0 && sign_get_attr(SIGN_TEXT, sattrs, 0, 1)) {
- int count = win_signcol_count(wp);
get_sign_display_info(true, wp, lnum, sattrs, row,
- startrow, filler_lines, filler_todo, count,
+ startrow, filler_lines, filler_todo,
&c_extra, &c_final, extra, sizeof(extra),
- &p_extra, &n_extra,
- &char_attr, &draw_state, &sign_idx);
+ &p_extra, &n_extra, &char_attr, sign_idx);
} else {
+ // Draw the line number (empty space after wrapping).
if (row == startrow + filler_lines) {
- // Draw the line number (empty space after wrapping). */
- long num;
- char *fmt = "%*ld ";
-
- if (wp->w_p_nu && !wp->w_p_rnu) {
- // 'number' + 'norelativenumber'
- num = (long)lnum;
- } else {
- // 'relativenumber', don't use negative numbers
- num = labs((long)get_cursor_rel_lnum(wp, lnum));
- if (num == 0 && wp->w_p_nu && wp->w_p_rnu) {
- // 'number' + 'relativenumber'
- num = lnum;
- fmt = "%-*ld ";
- }
- }
-
- snprintf((char *)extra, sizeof(extra),
- fmt, number_width(wp), num);
+ get_line_number_str(wp, lnum, (char_u *)extra, sizeof(extra));
if (wp->w_skipcol > 0) {
for (p_extra = extra; *p_extra == ' '; p_extra++) {
*p_extra = '-';
@@ -2858,41 +2783,12 @@ static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, bool noc
}
p_extra = extra;
c_extra = NUL;
- c_final = NUL;
} else {
c_extra = ' ';
- c_final = NUL;
}
+ c_final = NUL;
n_extra = number_width(wp) + 1;
- char_attr = win_hl_attr(wp, HLF_N);
-
- if (wp->w_p_rnu && lnum < wp->w_cursor.lnum) {
- // Use LineNrAbove
- char_attr = win_hl_attr(wp, HLF_LNA);
- }
- if (wp->w_p_rnu && lnum > wp->w_cursor.lnum) {
- // Use LineNrBelow
- char_attr = win_hl_attr(wp, HLF_LNB);
- }
-
- sign_attrs_T *num_sattr = sign_get_attr(SIGN_NUMHL, sattrs, 0, 1);
- if (num_sattr != NULL) {
- // :sign defined with "numhl" highlight.
- char_attr = num_sattr->sat_numhl;
- } else if (wp->w_p_cul
- && lnum == wp->w_cursor.lnum
- && (wp->w_p_culopt_flags & CULOPT_NBR)
- && (row == startrow
- || wp->w_p_culopt_flags & CULOPT_LINE)
- && filler_todo == 0) {
- // When 'cursorline' is set highlight the line number of
- // the current line differently.
- // When 'cursorlineopt' has "screenline" only highlight
- // the line number itself.
- // TODO(vim): Can we use CursorLine instead of CursorLineNr
- // when CursorLineNr isn't set?
- char_attr = win_hl_attr(wp, HLF_CLN);
- }
+ char_attr = get_line_number_attr(wp, lnum, row, startrow, filler_lines, sattrs);
}
}
}
@@ -4665,18 +4561,65 @@ static bool use_cursor_line_sign(win_T *wp, linenr_T lnum)
&& (wp->w_p_culopt_flags & CULOPT_NBR);
}
+/// Return true if CursorLineNr highlight is to be used for the number column.
+///
+/// - 'cursorline' must be set
+/// - lnum must be the cursor line
+/// - 'cursorlineopt' has "number"
+/// - don't highlight filler lines (when in diff mode)
+/// - When line is wrapped and 'cursorlineopt' does not have "line", only highlight the line number
+/// itself on the first screenline of the wrapped line, otherwise highlight the number column of
+/// all screenlines of the wrapped line.
+static bool use_cursor_line_nr(win_T *wp, linenr_T lnum, int row, int startrow, int filler_lines)
+{
+ return wp->w_p_cul
+ && lnum == wp->w_cursor.lnum
+ && (wp->w_p_culopt_flags & CULOPT_NBR)
+ && (row == startrow + filler_lines
+ || (row > startrow + filler_lines
+ && (wp->w_p_culopt_flags & CULOPT_LINE)));
+}
+
+static int get_line_number_attr(win_T *wp, linenr_T lnum, int row, int startrow, int filler_lines,
+ sign_attrs_T *sattrs)
+{
+ sign_attrs_T *num_sattr = sign_get_attr(SIGN_NUMHL, sattrs, 0, 1);
+ if (num_sattr != NULL) {
+ // :sign defined with "numhl" highlight.
+ return num_sattr->sat_numhl;
+ }
+
+ if (wp->w_p_rnu) {
+ if (lnum < wp->w_cursor.lnum) {
+ // Use LineNrAbove
+ return win_hl_attr(wp, HLF_LNA);
+ }
+ if (lnum > wp->w_cursor.lnum) {
+ // Use LineNrBelow
+ return win_hl_attr(wp, HLF_LNB);
+ }
+ }
+
+ if (use_cursor_line_nr(wp, lnum, row, startrow, filler_lines)) {
+ // TODO(vim): Can we use CursorLine instead of CursorLineNr
+ // when CursorLineNr isn't set?
+ return win_hl_attr(wp, HLF_CLN);
+ }
+
+ return win_hl_attr(wp, HLF_N);
+}
+
// Get information needed to display the sign in line 'lnum' in window 'wp'.
// If 'nrcol' is TRUE, the sign is going to be displayed in the number column.
// Otherwise the sign is going to be displayed in the sign column.
//
// @param count max number of signs
// @param[out] n_extrap number of characters from pp_extra to display
-// @param[in, out] sign_idxp Index of the displayed sign
+// @param sign_idxp Index of the displayed sign
static void get_sign_display_info(bool nrcol, win_T *wp, linenr_T lnum, sign_attrs_T sattrs[],
int row, int startrow, int filler_lines, int filler_todo,
- int count, int *c_extrap, int *c_finalp, char_u *extra,
- size_t extra_size, char_u **pp_extra, int *n_extrap,
- int *char_attrp, int *draw_statep, int *sign_idxp)
+ int *c_extrap, int *c_finalp, char_u *extra, size_t extra_size,
+ char_u **pp_extra, int *n_extrap, int *char_attrp, int sign_idx)
{
// Draw cells with the sign value or blank.
*c_extrap = ' ';
@@ -4693,7 +4636,7 @@ static void get_sign_display_info(bool nrcol, win_T *wp, linenr_T lnum, sign_att
}
if (row == startrow + filler_lines && filler_todo <= 0) {
- sign_attrs_T *sattr = sign_get_attr(SIGN_TEXT, sattrs, *sign_idxp, count);
+ sign_attrs_T *sattr = sign_get_attr(SIGN_TEXT, sattrs, sign_idx, wp->w_scwidth);
if (sattr != NULL) {
*pp_extra = sattr->sat_text;
if (*pp_extra != NULL) {
@@ -4736,13 +4679,6 @@ static void get_sign_display_info(bool nrcol, win_T *wp, linenr_T lnum, sign_att
}
}
}
-
- (*sign_idxp)++;
- if (*sign_idxp < count) {
- *draw_statep = WL_SIGN - 1;
- } else {
- *sign_idxp = 0;
- }
}
@@ -4958,10 +4894,15 @@ void rl_mirror(char_u *str)
*/
void status_redraw_all(void)
{
- FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
- if (wp->w_status_height) {
- wp->w_redr_status = true;
- redraw_later(wp, VALID);
+ if (global_stl_height()) {
+ curwin->w_redr_status = true;
+ redraw_later(curwin, VALID);
+ } else {
+ FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
+ if (wp->w_status_height) {
+ wp->w_redr_status = true;
+ redraw_later(wp, VALID);
+ }
}
}
}
@@ -4975,10 +4916,15 @@ void status_redraw_curbuf(void)
/// Marks all status lines of the specified buffer for redraw.
void status_redraw_buf(buf_T *buf)
{
- FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
- if (wp->w_status_height != 0 && wp->w_buffer == buf) {
- wp->w_redr_status = true;
- redraw_later(wp, VALID);
+ if (global_stl_height() != 0 && curwin->w_buffer == buf) {
+ curwin->w_redr_status = true;
+ redraw_later(curwin, VALID);
+ } else {
+ FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
+ if (wp->w_status_height != 0 && wp->w_buffer == buf) {
+ wp->w_redr_status = true;
+ redraw_later(wp, VALID);
+ }
}
}
}
@@ -5020,10 +4966,8 @@ void win_redraw_last_status(const frame_T *frp)
}
}
-/*
- * Draw the verticap separator right of window "wp" starting with line "row".
- */
-static void draw_vsep_win(win_T *wp, int row)
+/// Draw the vertical separator right of window "wp"
+static void draw_vsep_win(win_T *wp)
{
int hl;
int c;
@@ -5031,15 +4975,97 @@ static void draw_vsep_win(win_T *wp, int row)
if (wp->w_vsep_width) {
// draw the vertical separator right of this window
c = fillchar_vsep(wp, &hl);
- grid_fill(&default_grid, wp->w_winrow + row, W_ENDROW(wp),
+ grid_fill(&default_grid, wp->w_winrow, W_ENDROW(wp),
W_ENDCOL(wp), W_ENDCOL(wp) + 1, c, ' ', hl);
}
}
+/// Draw the horizontal separator below window "wp"
+static void draw_hsep_win(win_T *wp)
+{
+ int hl;
+ int c;
-/*
- * Get the length of an item as it will be shown in the status line.
- */
+ if (wp->w_hsep_height) {
+ // draw the horizontal separator below this window
+ c = fillchar_hsep(wp, &hl);
+ grid_fill(&default_grid, W_ENDROW(wp), W_ENDROW(wp) + 1,
+ wp->w_wincol, W_ENDCOL(wp), c, c, hl);
+ }
+}
+
+/// Get the separator connector for specified window corner of window "wp"
+static int get_corner_sep_connector(win_T *wp, WindowCorner corner)
+{
+ // It's impossible for windows to be connected neither vertically nor horizontally
+ // So if they're not vertically connected, assume they're horizontally connected
+ if (vsep_connected(wp, corner)) {
+ if (hsep_connected(wp, corner)) {
+ return wp->w_p_fcs_chars.verthoriz;
+ } else if (corner == WC_TOP_LEFT || corner == WC_BOTTOM_LEFT) {
+ return wp->w_p_fcs_chars.vertright;
+ } else {
+ return wp->w_p_fcs_chars.vertleft;
+ }
+ } else if (corner == WC_TOP_LEFT || corner == WC_TOP_RIGHT) {
+ return wp->w_p_fcs_chars.horizdown;
+ } else {
+ return wp->w_p_fcs_chars.horizup;
+ }
+}
+
+/// Draw seperator connecting characters on the corners of window "wp"
+static void draw_sep_connectors_win(win_T *wp)
+{
+ // Don't draw separator connectors unless global statusline is enabled and the window has
+ // either a horizontal or vertical separator
+ if (global_stl_height() == 0 || !(wp->w_hsep_height == 1 || wp->w_vsep_width == 1)) {
+ return;
+ }
+
+ int hl = win_hl_attr(wp, HLF_C);
+
+ // Determine which edges of the screen the window is located on so we can avoid drawing separators
+ // on corners contained in those edges
+ bool win_at_top;
+ bool win_at_bottom = wp->w_hsep_height == 0;
+ bool win_at_left;
+ bool win_at_right = wp->w_vsep_width == 0;
+ frame_T *frp;
+
+ for (frp = wp->w_frame; frp->fr_parent != NULL; frp = frp->fr_parent) {
+ if (frp->fr_parent->fr_layout == FR_COL && frp->fr_prev != NULL) {
+ break;
+ }
+ }
+ win_at_top = frp->fr_parent == NULL;
+ for (frp = wp->w_frame; frp->fr_parent != NULL; frp = frp->fr_parent) {
+ if (frp->fr_parent->fr_layout == FR_ROW && frp->fr_prev != NULL) {
+ break;
+ }
+ }
+ win_at_left = frp->fr_parent == NULL;
+
+ // Draw the appropriate separator connector in every corner where drawing them is necessary
+ if (!(win_at_top || win_at_left)) {
+ grid_putchar(&default_grid, get_corner_sep_connector(wp, WC_TOP_LEFT),
+ wp->w_winrow - 1, wp->w_wincol - 1, hl);
+ }
+ if (!(win_at_top || win_at_right)) {
+ grid_putchar(&default_grid, get_corner_sep_connector(wp, WC_TOP_RIGHT),
+ wp->w_winrow - 1, W_ENDCOL(wp), hl);
+ }
+ if (!(win_at_bottom || win_at_left)) {
+ grid_putchar(&default_grid, get_corner_sep_connector(wp, WC_BOTTOM_LEFT),
+ W_ENDROW(wp), wp->w_wincol - 1, hl);
+ }
+ if (!(win_at_bottom || win_at_right)) {
+ grid_putchar(&default_grid, get_corner_sep_connector(wp, WC_BOTTOM_RIGHT),
+ W_ENDROW(wp), W_ENDCOL(wp), hl);
+ }
+}
+
+/// Get the length of an item as it will be shown in the status line.
static int status_match_len(expand_T *xp, char_u *s)
{
int len = 0;
@@ -5240,7 +5266,7 @@ void win_redr_status_matches(expand_T *xp, int num_matches, char_u **matches, in
// Create status line if needed by setting 'laststatus' to 2.
// Set 'winminheight' to zero to avoid that the window is
// resized.
- if (lastwin->w_status_height == 0) {
+ if (lastwin->w_status_height == 0 && global_stl_height() == 0) {
save_p_ls = p_ls;
save_p_wmh = p_wmh;
p_ls = 2;
@@ -5276,12 +5302,15 @@ void win_redr_status_matches(expand_T *xp, int num_matches, char_u **matches, in
static void win_redr_status(win_T *wp)
{
int row;
+ int col;
char_u *p;
int len;
int fillchar;
int attr;
+ int width;
int this_ru_col;
- static int busy = FALSE;
+ bool is_stl_global = global_stl_height() > 0;
+ static int busy = false;
// May get here recursively when 'statusline' (indirectly)
// invokes ":redrawstatus". Simply ignore the call then.
@@ -5292,9 +5321,9 @@ static void win_redr_status(win_T *wp)
}
busy = true;
- wp->w_redr_status = FALSE;
- if (wp->w_status_height == 0) {
- // no status line, can only be last window
+ wp->w_redr_status = false;
+ if (wp->w_status_height == 0 && !(is_stl_global && wp == curwin)) {
+ // no status line, either global statusline is enabled or the window is a last window
redraw_cmdline = true;
} else if (!redrawing()) {
// Don't redraw right now, do it later. Don't update status line when
@@ -5305,6 +5334,7 @@ static void win_redr_status(win_T *wp)
redraw_custom_statusline(wp);
} else {
fillchar = fillchar_status(&attr, wp);
+ width = is_stl_global ? Columns : wp->w_width;
get_trans_bufname(wp->w_buffer);
p = NameBuff;
@@ -5333,9 +5363,9 @@ static void win_redr_status(win_T *wp)
// len += (int)STRLEN(p + len); // dead assignment
}
- this_ru_col = ru_col - (Columns - wp->w_width);
- if (this_ru_col < (wp->w_width + 1) / 2) {
- this_ru_col = (wp->w_width + 1) / 2;
+ this_ru_col = ru_col - (Columns - width);
+ if (this_ru_col < (width + 1) / 2) {
+ this_ru_col = (width + 1) / 2;
}
if (this_ru_col <= 1) {
p = (char_u *)"<"; // No room for file name!
@@ -5360,10 +5390,11 @@ static void win_redr_status(win_T *wp)
}
}
- row = W_ENDROW(wp);
- grid_puts(&default_grid, p, row, wp->w_wincol, attr);
- grid_fill(&default_grid, row, row + 1, len + wp->w_wincol,
- this_ru_col + wp->w_wincol, fillchar, fillchar, attr);
+ row = is_stl_global ? (Rows - p_ch - 1) : W_ENDROW(wp);
+ col = is_stl_global ? 0 : wp->w_wincol;
+ grid_puts(&default_grid, p, row, col, attr);
+ grid_fill(&default_grid, row, row + 1, len + col,
+ this_ru_col + col, fillchar, fillchar, attr);
if (get_keymap_str(wp, (char_u *)"<%s>", NameBuff, MAXPATHL)
&& this_ru_col - len > (int)(STRLEN(NameBuff) + 1)) {
@@ -5442,6 +5473,76 @@ bool stl_connected(win_T *wp)
return false;
}
+/// Check if horizontal separator of window "wp" at specified window corner is connected to the
+/// horizontal separator of another window
+/// Assumes global statusline is enabled
+static bool hsep_connected(win_T *wp, WindowCorner corner)
+{
+ bool before = (corner == WC_TOP_LEFT || corner == WC_BOTTOM_LEFT);
+ int sep_row = (corner == WC_TOP_LEFT || corner == WC_TOP_RIGHT)
+ ? wp->w_winrow - 1 : W_ENDROW(wp);
+ frame_T *fr = wp->w_frame;
+
+ while (fr->fr_parent != NULL) {
+ if (fr->fr_parent->fr_layout == FR_ROW && (before ? fr->fr_prev : fr->fr_next) != NULL) {
+ fr = before ? fr->fr_prev : fr->fr_next;
+ break;
+ }
+ fr = fr->fr_parent;
+ }
+ if (fr->fr_parent == NULL) {
+ return false;
+ }
+ while (fr->fr_layout != FR_LEAF) {
+ fr = fr->fr_child;
+ if (fr->fr_parent->fr_layout == FR_ROW && before) {
+ while (fr->fr_next != NULL) {
+ fr = fr->fr_next;
+ }
+ } else {
+ while (fr->fr_next != NULL && frame2win(fr)->w_winrow + fr->fr_height < sep_row) {
+ fr = fr->fr_next;
+ }
+ }
+ }
+
+ return (sep_row == fr->fr_win->w_winrow - 1 || sep_row == W_ENDROW(fr->fr_win));
+}
+
+/// Check if vertical separator of window "wp" at specified window corner is connected to the
+/// vertical separator of another window
+static bool vsep_connected(win_T *wp, WindowCorner corner)
+{
+ bool before = (corner == WC_TOP_LEFT || corner == WC_TOP_RIGHT);
+ int sep_col = (corner == WC_TOP_LEFT || corner == WC_BOTTOM_LEFT)
+ ? wp->w_wincol - 1 : W_ENDCOL(wp);
+ frame_T *fr = wp->w_frame;
+
+ while (fr->fr_parent != NULL) {
+ if (fr->fr_parent->fr_layout == FR_COL && (before ? fr->fr_prev : fr->fr_next) != NULL) {
+ fr = before ? fr->fr_prev : fr->fr_next;
+ break;
+ }
+ fr = fr->fr_parent;
+ }
+ if (fr->fr_parent == NULL) {
+ return false;
+ }
+ while (fr->fr_layout != FR_LEAF) {
+ fr = fr->fr_child;
+ if (fr->fr_parent->fr_layout == FR_COL && before) {
+ while (fr->fr_next != NULL) {
+ fr = fr->fr_next;
+ }
+ } else {
+ while (fr->fr_next != NULL && frame2win(fr)->w_wincol + fr->fr_width < sep_col) {
+ fr = fr->fr_next;
+ }
+ }
+ }
+
+ return (sep_col == fr->fr_win->w_wincol - 1 || sep_col == W_ENDCOL(fr->fr_win));
+}
/// Get the value to show for the language mappings, active 'keymap'.
///
@@ -5508,6 +5609,7 @@ static void win_redr_custom(win_T *wp, bool draw_ruler)
int use_sandbox = false;
win_T *ewp;
int p_crb_save;
+ bool is_stl_global = global_stl_height() > 0;
ScreenGrid *grid = &default_grid;
@@ -5529,9 +5631,9 @@ static void win_redr_custom(win_T *wp, bool draw_ruler)
maxwidth = Columns;
use_sandbox = was_set_insecurely(wp, "tabline", 0);
} else {
- row = W_ENDROW(wp);
+ row = is_stl_global ? (Rows - p_ch - 1) : W_ENDROW(wp);
fillchar = fillchar_status(&attr, wp);
- maxwidth = wp->w_width;
+ maxwidth = is_stl_global ? Columns : wp->w_width;
if (draw_ruler) {
stl = p_ruf;
@@ -5549,12 +5651,12 @@ static void win_redr_custom(win_T *wp, bool draw_ruler)
stl = p_ruf;
}
}
- col = ru_col - (Columns - wp->w_width);
- if (col < (wp->w_width + 1) / 2) {
- col = (wp->w_width + 1) / 2;
+ col = ru_col - (Columns - maxwidth);
+ if (col < (maxwidth + 1) / 2) {
+ col = (maxwidth + 1) / 2;
}
- maxwidth = wp->w_width - col;
- if (!wp->w_status_height) {
+ maxwidth = maxwidth - col;
+ if (!wp->w_status_height && !is_stl_global) {
grid = &msg_grid_adj;
row = Rows - 1;
maxwidth--; // writing in last column may cause scrolling
@@ -5572,7 +5674,7 @@ static void win_redr_custom(win_T *wp, bool draw_ruler)
use_sandbox = was_set_insecurely(wp, "statusline", *wp->w_p_stl == NUL ? 0 : OPT_LOCAL);
}
- col += wp->w_wincol;
+ col += is_stl_global ? 0 : wp->w_wincol;
}
if (maxwidth <= 0) {
@@ -7154,10 +7256,10 @@ int showmode(void)
clear_showcmd();
}
- // If the last window has no status line, the ruler is after the mode
- // message and must be redrawn
+ // If the last window has no status line and global statusline is disabled,
+ // the ruler is after the mode message and must be redrawn
win_T *last = lastwin_nofloating();
- if (redrawing() && last->w_status_height == 0) {
+ if (redrawing() && last->w_status_height == 0 && global_stl_height() == 0) {
win_redr_ruler(last, true);
}
redraw_cmdline = false;
@@ -7472,16 +7574,22 @@ int fillchar_status(int *attr, win_T *wp)
return '=';
}
-/*
- * Get the character to use in a separator between vertically split windows.
- * Get its attributes in "*attr".
- */
+/// Get the character to use in a separator between vertically split windows.
+/// Get its attributes in "*attr".
static int fillchar_vsep(win_T *wp, int *attr)
{
*attr = win_hl_attr(wp, HLF_C);
return wp->w_p_fcs_chars.vert;
}
+/// Get the character to use in a separator between horizontally split windows.
+/// Get its attributes in "*attr".
+static int fillchar_hsep(win_T *wp, int *attr)
+{
+ *attr = win_hl_attr(wp, HLF_C);
+ return wp->w_p_fcs_chars.horiz;
+}
+
/*
* Return TRUE if redrawing should currently be done.
*/
@@ -7507,7 +7615,8 @@ void showruler(bool always)
if (!always && !redrawing()) {
return;
}
- if ((*p_stl != NUL || *curwin->w_p_stl != NUL) && curwin->w_status_height) {
+ if ((*p_stl != NUL || *curwin->w_p_stl != NUL)
+ && (curwin->w_status_height || global_stl_height())) {
redraw_custom_statusline(curwin);
} else {
win_redr_ruler(curwin, always);
@@ -7526,6 +7635,7 @@ void showruler(bool always)
static void win_redr_ruler(win_T *wp, bool always)
{
+ bool is_stl_global = global_stl_height() > 0;
static bool did_show_ext_ruler = false;
// If 'ruler' off or redrawing disabled, don't do anything
@@ -7543,7 +7653,7 @@ static void win_redr_ruler(win_T *wp, bool always)
// Don't draw the ruler while doing insert-completion, it might overwrite
// the (long) mode message.
- if (wp == lastwin && lastwin->w_status_height == 0) {
+ if (wp == lastwin && lastwin->w_status_height == 0 && !is_stl_global) {
if (edit_submode != NULL) {
return;
}
@@ -7598,6 +7708,12 @@ static void win_redr_ruler(win_T *wp, bool always)
off = wp->w_wincol;
width = wp->w_width;
part_of_status = true;
+ } else if (is_stl_global) {
+ row = Rows - p_ch - 1;
+ fillchar = fillchar_status(&attr, wp);
+ off = 0;
+ width = Columns;
+ part_of_status = true;
} else {
row = Rows - 1;
fillchar = ' ';
@@ -7637,7 +7753,7 @@ static void win_redr_ruler(win_T *wp, bool always)
int i = (int)STRLEN(buffer);
get_rel_pos(wp, buffer + i + 1, RULER_BUF_LEN - i - 1);
int o = i + vim_strsize(buffer + i + 1);
- if (wp->w_status_height == 0) { // can't use last char of screen
+ if (wp->w_status_height == 0 && !is_stl_global) { // can't use last char of screen
o++;
}
int this_ru_col = ru_col - (Columns - width);
diff --git a/src/nvim/screen.h b/src/nvim/screen.h
index d704a6eb8a..d15e4b7e45 100644
--- a/src/nvim/screen.h
+++ b/src/nvim/screen.h
@@ -8,12 +8,10 @@
#include "nvim/pos.h"
#include "nvim/types.h"
-/*
- * flags for update_screen()
- * The higher the value, the higher the priority
- */
-#define VALID 10 /* buffer not changed, or changes marked
- with b_mod_* */
+// flags for update_screen()
+// The higher the value, the higher the priority
+#define VALID 10 // buffer not changed, or changes marked
+ // with b_mod_*
#define INVERTED 20 // redisplay inverted part that changed
#define INVERTED_ALL 25 // redisplay whole inverted part
#define REDRAW_TOP 30 // display first w_upd_rows screen lines
@@ -21,6 +19,14 @@
#define NOT_VALID 40 // buffer needs complete redraw
#define CLEAR 50 // screen messed up, clear it
+/// corner value flags for hsep_connected and vsep_connected
+typedef enum {
+ WC_TOP_LEFT = 0,
+ WC_TOP_RIGHT,
+ WC_BOTTOM_LEFT,
+ WC_BOTTOM_RIGHT
+} WindowCorner;
+
/// By default, all widows are draw on a single rectangular grid, represented by
/// this ScreenGrid instance. In multigrid mode each window will have its own
/// grid, then this is only used for global screen elements that hasn't been
diff --git a/src/nvim/search.c b/src/nvim/search.c
index 682fa417a9..a69bd641f8 100644
--- a/src/nvim/search.c
+++ b/src/nvim/search.c
@@ -13,8 +13,8 @@
#include "nvim/ascii.h"
#include "nvim/buffer.h"
-#include "nvim/charset.h"
#include "nvim/change.h"
+#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/edit.h"
#include "nvim/eval.h"
@@ -1071,7 +1071,7 @@ int do_search(oparg_T *oap, int dirc, int search_delim, char_u *pat, long count,
* Find out the direction of the search.
*/
if (dirc == 0) {
- dirc = spats[0].off.dir;
+ dirc = (char_u)spats[0].off.dir;
} else {
spats[0].off.dir = dirc;
set_vv_searchforward();
@@ -5048,8 +5048,8 @@ bool fuzzy_match(char_u *const str, const char_u *const pat_arg, const bool matc
int score = 0;
int recursionCount = 0;
const int matchCount
- = fuzzy_match_recursive(pat, str, 0, &score, str, len, NULL, matches + numMatches,
- maxMatches - numMatches, 0, &recursionCount);
+ = fuzzy_match_recursive(pat, str, 0, &score, str, len, NULL, matches + numMatches,
+ maxMatches - numMatches, 0, &recursionCount);
if (matchCount == 0) {
numMatches = 0;
break;
@@ -5689,7 +5689,7 @@ search_line:
// we read a line, set "already" to check this "line" later
// if depth >= 0 we'll increase files[depth].lnum far
- // bellow -- Acevedo
+ // below -- Acevedo
already = aux = p = skipwhite(line);
p = find_word_start(p);
p = find_word_end(p);
diff --git a/src/nvim/shada.c b/src/nvim/shada.c
index e75a244031..b909888783 100644
--- a/src/nvim/shada.c
+++ b/src/nvim/shada.c
@@ -831,7 +831,7 @@ static int shada_read_file(const char *const file, const int flags)
ShaDaReadDef sd_reader;
const int of_ret = open_shada_file_for_reading(fname, &sd_reader);
- if (p_verbose > 0) {
+ if (p_verbose > 1) {
verbose_enter();
smsg(_("Reading ShaDa file \"%s\"%s%s%s%s"),
fname,
@@ -3036,7 +3036,7 @@ shada_write_file_nomerge: {}
return FAIL;
}
- if (p_verbose > 0) {
+ if (p_verbose > 1) {
verbose_enter();
smsg(_("Writing ShaDa file \"%s\""), fname);
verbose_leave();
diff --git a/src/nvim/sign.c b/src/nvim/sign.c
index 8b41781c98..6d0ac30003 100644
--- a/src/nvim/sign.c
+++ b/src/nvim/sign.c
@@ -196,7 +196,8 @@ static void insert_sign(buf_T *buf, sign_entry_T *prev, sign_entry_T *next, int
if (next != NULL) {
next->se_prev = newsign;
}
- buf->b_signcols_valid = false;
+
+ buf_signcols_add_check(buf, newsign);
if (prev == NULL) {
// When adding first sign need to redraw the windows to create the
@@ -506,6 +507,8 @@ int buf_get_signattrs(buf_T *buf, linenr_T lnum, sign_attrs_T sattrs[])
if (sp->sn_num_hl != 0) {
sattr.sat_numhl = syn_id2attr(sp->sn_num_hl);
}
+ // Store the priority so we can mesh in extmark signs later
+ sattr.sat_prio = sign->se_priority;
}
sattrs[nr_matches] = sattr;
@@ -539,7 +542,6 @@ linenr_T buf_delsign(buf_T *buf, linenr_T atlnum, int id, char_u *group)
sign_entry_T *next; // the next sign in a b_signlist
linenr_T lnum; // line number whose sign was deleted
- buf->b_signcols_valid = false;
lastp = &buf->b_signlist;
lnum = 0;
for (sign = buf->b_signlist; sign != NULL; sign = next) {
@@ -552,6 +554,7 @@ linenr_T buf_delsign(buf_T *buf, linenr_T atlnum, int id, char_u *group)
next->se_prev = sign->se_prev;
}
lnum = sign->se_lnum;
+ buf_signcols_del_check(buf, lnum, lnum);
if (sign->se_group != NULL) {
sign_group_unref(sign->se_group->sg_name);
}
@@ -673,7 +676,7 @@ void buf_delete_signs(buf_T *buf, char_u *group)
lastp = &sign->se_next;
}
}
- buf->b_signcols_valid = false;
+ buf_signcols_del_check(buf, 1, MAXLNUM);
}
/// List placed signs for "rbuf". If "rbuf" is NULL do it for all buffers.
@@ -735,14 +738,19 @@ void sign_mark_adjust(linenr_T line1, linenr_T line2, long amount, long amount_a
int is_fixed = 0;
int signcol = win_signcol_configured(curwin, &is_fixed);
- curbuf->b_signcols_valid = false;
+ bool delete = amount == MAXLNUM;
+
+ if (delete) {
+ buf_signcols_del_check(curbuf, line1, line2);
+ }
+
lastp = &curbuf->b_signlist;
for (sign = curbuf->b_signlist; sign != NULL; sign = next) {
next = sign->se_next;
new_lnum = sign->se_lnum;
if (sign->se_lnum >= line1 && sign->se_lnum <= line2) {
- if (amount != MAXLNUM) {
+ if (!delete) {
new_lnum += amount;
} else if (!is_fixed || signcol >= 2) {
*lastp = next;
diff --git a/src/nvim/sign_defs.h b/src/nvim/sign_defs.h
index c734502878..6d28c1849a 100644
--- a/src/nvim/sign_defs.h
+++ b/src/nvim/sign_defs.h
@@ -40,6 +40,7 @@ typedef struct sign_attrs_S {
int sat_linehl;
int sat_culhl;
int sat_numhl;
+ int sat_prio; // Used for inserting extmark signs
} sign_attrs_T;
#define SIGN_SHOW_MAX 9
diff --git a/src/nvim/spell.c b/src/nvim/spell.c
index 1296d410f6..fb644daa39 100644
--- a/src/nvim/spell.c
+++ b/src/nvim/spell.c
@@ -3824,7 +3824,7 @@ static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, bool so
// At end of a prefix or at start of prefixtree: check for
// following word.
- if (byts[arridx] == 0 || n == (int)STATE_NOPREFIX) {
+ if (byts[arridx] == 0 || n == STATE_NOPREFIX) {
// Set su->su_badflags to the caps type at this position.
// Use the caps type until here for the prefix itself.
n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
diff --git a/src/nvim/strings.c b/src/nvim/strings.c
index 291138ef23..9d4c64e4b1 100644
--- a/src/nvim/strings.c
+++ b/src/nvim/strings.c
@@ -354,7 +354,7 @@ char *strcase_save(const char *const orig, bool upper)
int l = utf_ptr2len((const char_u *)p);
if (c == 0) {
// overlong sequence, use only the first byte
- c = *p;
+ c = (char_u)(*p);
l = 1;
}
int uc = upper ? mb_toupper(c) : mb_tolower(c);
diff --git a/src/nvim/syntax.c b/src/nvim/syntax.c
index 2b74c45478..068c007d93 100644
--- a/src/nvim/syntax.c
+++ b/src/nvim/syntax.c
@@ -27,6 +27,7 @@
#include "nvim/highlight.h"
#include "nvim/indent_c.h"
#include "nvim/keymap.h"
+#include "nvim/lua/executor.h"
#include "nvim/macros.h"
#include "nvim/mbyte.h"
#include "nvim/memline.h"
@@ -120,11 +121,11 @@ static int include_link = 0; // when 2 include "nvim/link" and "clear"
/// The "term", "cterm" and "gui" arguments can be any combination of the
/// following names, separated by commas (but no spaces!).
static char *(hl_name_table[]) =
-{ "bold", "standout", "underline", "undercurl",
- "italic", "reverse", "inverse", "strikethrough", "nocombine", "NONE" };
+{ "bold", "standout", "underline", "underlineline", "undercurl", "underdot",
+ "underdash", "italic", "reverse", "inverse", "strikethrough", "nocombine", "NONE" };
static int hl_attr_table[] =
-{ HL_BOLD, HL_STANDOUT, HL_UNDERLINE, HL_UNDERCURL, HL_ITALIC, HL_INVERSE,
- HL_INVERSE, HL_STRIKETHROUGH, HL_NOCOMBINE, 0 };
+{ HL_BOLD, HL_STANDOUT, HL_UNDERLINE, HL_UNDERLINELINE, HL_UNDERCURL, HL_UNDERDOT, HL_UNDERDASH,
+ HL_ITALIC, HL_INVERSE, HL_INVERSE, HL_STRIKETHROUGH, HL_NOCOMBINE, 0 };
static char e_illegal_arg[] = N_("E390: Illegal argument: %s");
@@ -4207,7 +4208,7 @@ static char_u *get_syn_options(char_u *arg, syn_opt_arg_T *opt, int *conceal_cha
p = flagtab[fidx].name;
int i;
for (i = 0, len = 0; p[i] != NUL; i += 2, ++len) {
- if (arg[len] != p[i] && arg[len] != p[i + 1]) {
+ if (arg[len] != (char_u)p[i] && arg[len] != (char_u)p[i + 1]) {
break;
}
}
@@ -6173,6 +6174,7 @@ static const char *highlight_init_both[] = {
"TermCursor cterm=reverse gui=reverse",
"VertSplit cterm=reverse gui=reverse",
"WildMenu ctermbg=Yellow ctermfg=Black guibg=Yellow guifg=Black",
+ "default link WinSeparator VertSplit",
"default link EndOfBuffer NonText",
"default link LineNrAbove LineNr",
"default link LineNrBelow LineNr",
@@ -6183,7 +6185,7 @@ static const char *highlight_init_both[] = {
"default link Whitespace NonText",
"default link MsgSeparator StatusLine",
"default link NormalFloat Pmenu",
- "default link FloatBorder VertSplit",
+ "default link FloatBorder WinSeparator",
"default FloatShadow blend=80 guibg=Black",
"default FloatShadowThrough blend=100 guibg=Black",
"RedrawDebugNormal cterm=reverse gui=reverse",
@@ -6919,6 +6921,7 @@ void do_highlight(const char *line, const bool forceit, const bool init)
hlgroup->sg_deflink = to_id;
hlgroup->sg_deflink_sctx = current_sctx;
hlgroup->sg_deflink_sctx.sc_lnum += sourcing_lnum;
+ nlua_set_sctx(&hlgroup->sg_deflink_sctx);
}
}
@@ -6939,6 +6942,7 @@ void do_highlight(const char *line, const bool forceit, const bool init)
hlgroup->sg_link = to_id;
hlgroup->sg_script_ctx = current_sctx;
hlgroup->sg_script_ctx.sc_lnum += sourcing_lnum;
+ nlua_set_sctx(&hlgroup->sg_script_ctx);
hlgroup->sg_cleared = false;
redraw_all_later(SOME_VALID);
@@ -7319,6 +7323,7 @@ void do_highlight(const char *line, const bool forceit, const bool init)
}
HL_TABLE()[idx].sg_script_ctx = current_sctx;
HL_TABLE()[idx].sg_script_ctx.sc_lnum += sourcing_lnum;
+ nlua_set_sctx(&HL_TABLE()[idx].sg_script_ctx);
}
xfree(key);
xfree(arg);
diff --git a/src/nvim/syntax_defs.h b/src/nvim/syntax_defs.h
index 526be905e9..a005f67209 100644
--- a/src/nvim/syntax_defs.h
+++ b/src/nvim/syntax_defs.h
@@ -21,9 +21,7 @@ struct sp_syn {
int16_t *cont_in_list; // cont.in group IDs, if non-zero
};
-/*
- * Each keyword has one keyentry, which is linked in a hash list.
- */
+// Each keyword has one keyentry, which is linked in a hash list.
typedef struct keyentry keyentry_T;
struct keyentry {
@@ -35,9 +33,7 @@ struct keyentry {
char_u keyword[1]; // actually longer
};
-/*
- * Struct used to store one state of the state stack.
- */
+// Struct used to store one state of the state stack.
typedef struct buf_state {
int bs_idx; // index of pattern
int bs_flags; // flags for pattern
@@ -46,10 +42,8 @@ typedef struct buf_state {
reg_extmatch_T *bs_extmatch; // external matches from start pattern
} bufstate_T;
-/*
- * syn_state contains the syntax state stack for the start of one line.
- * Used by b_sst_array[].
- */
+// syn_state contains the syntax state stack for the start of one line.
+// Used by b_sst_array[].
struct syn_state {
synstate_T *sst_next; // next entry in used or free list
linenr_T sst_lnum; // line number for this state
@@ -66,4 +60,4 @@ struct syn_state {
// may have made the state invalid
};
-#endif // NVIM_SYNTAX_DEFS_H
+#endif // NVIM_SYNTAX_DEFS_H
diff --git a/src/nvim/tag.h b/src/nvim/tag.h
index 64bacceb1b..902fe0c7ba 100644
--- a/src/nvim/tag.h
+++ b/src/nvim/tag.h
@@ -4,9 +4,7 @@
#include "nvim/ex_cmds_defs.h"
#include "nvim/types.h"
-/*
- * Values for do_tag().
- */
+// Values for do_tag().
#define DT_TAG 1 // jump to newer position or same tag again
#define DT_POP 2 // jump to older position
#define DT_NEXT 3 // jump to next match of same tag
@@ -20,9 +18,7 @@
#define DT_LTAG 11 // tag using location list
#define DT_FREE 99 // free cached matches
-//
// flags for find_tags().
-//
#define TAG_HELP 1 // only search for help tags
#define TAG_NAMES 2 // only return name of tag
#define TAG_REGEXP 4 // use tag pattern as regexp
@@ -36,9 +32,7 @@
#define TAG_MANY 300 // When finding many tags (for completion),
// find up to this many tags
-/*
- * Structure used for get_tagfname().
- */
+// Structure used for get_tagfname().
typedef struct {
char_u *tn_tags; // value of 'tags' when starting
char_u *tn_np; // current position in tn_tags
diff --git a/src/nvim/terminal.c b/src/nvim/terminal.c
index 1c26e46a21..5189705a36 100644
--- a/src/nvim/terminal.c
+++ b/src/nvim/terminal.c
@@ -317,10 +317,14 @@ void terminal_close(Terminal *term, int status)
term->opts.close_cb(term->opts.data);
}
} else if (!only_destroy) {
- // This was called by channel_process_exit_cb() not in process_teardown().
+ // Associated channel has been closed and the editor is not exiting.
// Do not call the close callback now. Wait for the user to press a key.
char msg[sizeof("\r\n[Process exited ]") + NUMBUFLEN];
- snprintf(msg, sizeof msg, "\r\n[Process exited %d]", status);
+ if (((Channel *)term->opts.data)->streamtype == kChannelStreamInternal) {
+ snprintf(msg, sizeof msg, "\r\n[Terminal closed]");
+ } else {
+ snprintf(msg, sizeof msg, "\r\n[Process exited %d]", status);
+ }
terminal_receive(term, msg, strlen(msg));
}
@@ -1284,7 +1288,7 @@ static bool send_mouse_event(Terminal *term, int c)
return mouse_win == curwin;
}
- // ignore left release action if it was not proccessed above
+ // ignore left release action if it was not processed 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;
diff --git a/src/nvim/testdir/check.vim b/src/nvim/testdir/check.vim
index 883f036fe1..8f97d959ce 100644
--- a/src/nvim/testdir/check.vim
+++ b/src/nvim/testdir/check.vim
@@ -137,6 +137,14 @@ func CheckNotMSWindows()
endif
endfunc
+" Command to check for not running under ASAN
+command CheckNotAsan call CheckNotAsan()
+func CheckNotAsan()
+ if execute('version') =~# '-fsanitize=[a-z,]*\<address\>'
+ throw 'Skipped: does not work with ASAN'
+ endif
+endfunc
+
" Command to check for satisfying any of the conditions.
" e.g. CheckAnyOf Feature:bsd Feature:sun Linux
command -nargs=+ CheckAnyOf call CheckAnyOf(<f-args>)
diff --git a/src/nvim/testdir/runnvim.sh b/src/nvim/testdir/runnvim.sh
index fdd3f3144b..322265737a 100755
--- a/src/nvim/testdir/runnvim.sh
+++ b/src/nvim/testdir/runnvim.sh
@@ -38,7 +38,7 @@ main() {(
-S runnvim.vim \
"$tlog" > "out-$tlog" 2> "err-$tlog"
then
- fail "$test_name" F "Nvim exited with non-zero code"
+ fail "$test_name" "Nvim exited with non-zero code"
fi
{
echo "Stdout of :terminal runner"
@@ -53,7 +53,7 @@ main() {(
if test "$oldesttest" = 1 ; then
if ! diff -q test.out "$test_name.ok" > /dev/null 2>&1 ; then
if test -f test.out ; then
- fail "$test_name" F "Oldest test .out file differs from .ok file"
+ fail "$test_name" "Oldest test .out file differs from .ok file"
{
echo "Diff between test.out and $test_name.ok"
echo "$separator"
@@ -65,9 +65,6 @@ main() {(
fi
fi
fi
- if test "$FAILED" = 1 ; then
- ci_fold start "$test_name"
- fi
valgrind_check .
if test -n "$LOG_DIR" ; then
check_sanitizer "$LOG_DIR"
@@ -78,9 +75,6 @@ main() {(
fi
rm -f "$tlog"
if test "$FAILED" = 1 ; then
- ci_fold end ""
- fi
- if test "$FAILED" = 1 ; then
echo "Test $test_name failed, see output above and summary for more details" >> test.log
# When Neovim crashed/aborted it might not have created messages.
# test.log itself is used as an indicator to exit non-zero in the Makefile.
diff --git a/src/nvim/testdir/test_alot.vim b/src/nvim/testdir/test_alot.vim
index c0ac4393c4..bb744f7b41 100644
--- a/src/nvim/testdir/test_alot.vim
+++ b/src/nvim/testdir/test_alot.vim
@@ -3,55 +3,33 @@
source test_backup.vim
source test_behave.vim
-source test_cd.vim
-source test_changedtick.vim
source test_compiler.vim
-source test_cursor_func.vim
-source test_cursorline.vim
source test_ex_equal.vim
source test_ex_undo.vim
source test_ex_z.vim
source test_ex_mode.vim
-source test_execute_func.vim
+source test_expand.vim
source test_expand_func.vim
source test_feedkeys.vim
-source test_filter_cmd.vim
-source test_filter_map.vim
-source test_findfile.vim
-source test_float_func.vim
-source test_functions.vim
+source test_file_perm.vim
+source test_fnamemodify.vim
source test_ga.vim
+source test_glob2regpat.vim
source test_global.vim
-source test_goto.vim
-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_lispwords.vim
source test_menu.vim
-source test_messages.vim
-source test_modeline.vim
source test_move.vim
-source test_partial.vim
-source test_popup.vim
source test_put.vim
-source test_rename.vim
+source test_reltime.vim
source test_scroll_opt.vim
+source test_searchpos.vim
+source test_set.vim
source test_shift.vim
-source test_sort.vim
source test_sha256.vim
-source test_suspend.vim
-source test_syn_attr.vim
source test_tabline.vim
-source test_tabpage.vim
source test_tagcase.vim
source test_tagfunc.vim
-source test_tagjump.vim
-source test_taglist.vim
-source test_true_false.vim
source test_unlet.vim
source test_version.vim
-source test_virtualedit.vim
-source test_window_cmd.vim
source test_wnext.vim
diff --git a/src/nvim/testdir/test_autochdir.vim b/src/nvim/testdir/test_autochdir.vim
index 9ad727241e..4229095f9f 100644
--- a/src/nvim/testdir/test_autochdir.vim
+++ b/src/nvim/testdir/test_autochdir.vim
@@ -26,6 +26,54 @@ func Test_set_filename()
call delete('samples/Xtest')
endfunc
+func Test_set_filename_other_window()
+ CheckFunction test_autochdir
+ let cwd = getcwd()
+ call test_autochdir()
+ call mkdir('Xa')
+ call mkdir('Xb')
+ call mkdir('Xc')
+ try
+ args Xa/aaa.txt Xb/bbb.txt
+ set acd
+ let winid = win_getid()
+ snext
+ call assert_equal('Xb', substitute(getcwd(), '.*/\([^/]*\)$', '\1', ''))
+ call win_execute(winid, 'file ' .. cwd .. '/Xc/ccc.txt')
+ call assert_equal('Xb', substitute(getcwd(), '.*/\([^/]*\)$', '\1', ''))
+ finally
+ set noacd
+ call chdir(cwd)
+ call delete('Xa', 'rf')
+ call delete('Xb', 'rf')
+ call delete('Xc', 'rf')
+ bwipe! aaa.txt
+ bwipe! bbb.txt
+ bwipe! ccc.txt
+ endtry
+endfunc
+
+func Test_acd_win_execute()
+ CheckFunction test_autochdir
+ let cwd = getcwd()
+ set acd
+ call test_autochdir()
+
+ call mkdir('Xfile')
+ let winid = win_getid()
+ new Xfile/file
+ call assert_match('testdir.Xfile$', getcwd())
+ cd ..
+ call assert_match('testdir$', getcwd())
+ call win_execute(winid, 'echo')
+ call assert_match('testdir$', getcwd())
+
+ bwipe!
+ set noacd
+ call chdir(cwd)
+ call delete('Xfile', 'rf')
+endfunc
+
func Test_verbose_pwd()
CheckFunction test_autochdir
let cwd = getcwd()
@@ -42,20 +90,27 @@ func Test_verbose_pwd()
set acd
wincmd w
call assert_match('\[autochdir\].*testdir$', execute('verbose pwd'))
- execute 'lcd' cwd
- call assert_match('\[window\].*testdir$', execute('verbose pwd'))
execute 'tcd' cwd
call assert_match('\[tabpage\].*testdir$', execute('verbose pwd'))
execute 'cd' cwd
call assert_match('\[global\].*testdir$', execute('verbose pwd'))
+ execute 'lcd' cwd
+ call assert_match('\[window\].*testdir$', execute('verbose pwd'))
edit
call assert_match('\[autochdir\].*testdir$', execute('verbose pwd'))
+ enew
+ wincmd w
+ call assert_match('\[autochdir\].*testdir[/\\]Xautodir', execute('verbose pwd'))
+ wincmd w
+ call assert_match('\[window\].*testdir$', execute('verbose pwd'))
wincmd w
call assert_match('\[autochdir\].*testdir[/\\]Xautodir', execute('verbose pwd'))
set noacd
call assert_match('\[autochdir\].*testdir[/\\]Xautodir', execute('verbose pwd'))
wincmd w
- call assert_match('\[global\].*testdir', execute('verbose pwd'))
+ call assert_match('\[window\].*testdir$', execute('verbose pwd'))
+ execute 'cd' cwd
+ call assert_match('\[global\].*testdir$', execute('verbose pwd'))
wincmd w
call assert_match('\[window\].*testdir[/\\]Xautodir', execute('verbose pwd'))
@@ -64,4 +119,14 @@ func Test_verbose_pwd()
call delete('Xautodir', 'rf')
endfunc
+func Test_multibyte()
+ " using an invalid character should not cause a crash
+ set wic
+ " Except on Windows, E472 is also thrown last, but v8.1.1183 isn't ported yet
+ " call assert_fails('tc *', has('win32') ? 'E480:' : 'E344:')
+ call assert_fails('tc *', has('win32') ? 'E480:' : 'E472:')
+ set nowic
+endfunc
+
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_autocmd.vim b/src/nvim/testdir/test_autocmd.vim
index 0146c06109..c39546b9ea 100644
--- a/src/nvim/testdir/test_autocmd.vim
+++ b/src/nvim/testdir/test_autocmd.vim
@@ -502,7 +502,7 @@ func Test_autocmd_bufwipe_in_SessLoadPost()
[CODE]
call writefile(content, 'Xvimrc')
- call system(v:progpath. ' --headless -i NONE -u Xvimrc --noplugins -S Session.vim -c cq')
+ call system(GetVimCommand('Xvimrc') .. ' --headless --noplugins -S Session.vim -c cq')
let errors = join(readfile('Xerrors'))
call assert_match('E814', errors)
@@ -562,7 +562,7 @@ func Test_autocmd_bufwipe_in_SessLoadPost2()
[CODE]
call writefile(content, 'Xvimrc')
- call system(v:progpath. ' --headless -i NONE -u Xvimrc --noplugins -S Session.vim -c cq')
+ call system(GetVimCommand('Xvimrc') .. ' --headless --noplugins -S Session.vim -c cq')
let errors = join(readfile('Xerrors'))
" This probably only ever matches on unix.
call assert_notmatch('Caught deadly signal SEGV', errors)
@@ -1506,7 +1506,7 @@ func Test_bufunload_all()
call writefile(content, 'Xtest')
call delete('Xout')
- call system(v:progpath. ' -u NORC -i NONE -N -S Xtest')
+ call system(GetVimCommandClean() .. ' -N --headless -S Xtest')
call assert_true(filereadable('Xout'))
call delete('Xxx1')
diff --git a/src/nvim/testdir/test_breakindent.vim b/src/nvim/testdir/test_breakindent.vim
index b619f2adb6..438edb0257 100644
--- a/src/nvim/testdir/test_breakindent.vim
+++ b/src/nvim/testdir/test_breakindent.vim
@@ -1,7 +1,7 @@
" Test for breakindent
"
" Note: if you get strange failures when adding new tests, it might be that
-" while the test is run, the breakindent cacheing gets in its way.
+" while the test is run, the breakindent caching gets in its way.
" It helps to change the tabstop setting and force a redraw (e.g. see
" Test_breakindent08())
if !exists('+breakindent')
diff --git a/src/nvim/testdir/test_cindent.vim b/src/nvim/testdir/test_cindent.vim
index 5dc54111e7..4b702bf2b8 100644
--- a/src/nvim/testdir/test_cindent.vim
+++ b/src/nvim/testdir/test_cindent.vim
@@ -815,7 +815,7 @@ func Test_cindent_1()
}
}
- public: // <-- this was incoreectly indented before!!
+ public: // <-- this was incorrectly indented before!!
void testfall();
protected:
void testfall();
@@ -1792,7 +1792,7 @@ func Test_cindent_1()
}
}
- public: // <-- this was incoreectly indented before!!
+ public: // <-- this was incorrectly indented before!!
void testfall();
protected:
void testfall();
@@ -5302,9 +5302,12 @@ endfunc
" this was going beyond the end of the line.
func Test_cindent_case()
new
- call setline(1, "case x: // x")
+ call setline(1, 'case x: // x')
set cindent
norm! f:a:
+ call assert_equal('case x:: // x', getline(1))
+
+ set cindent&
bwipe!
endfunc
diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim
index ff4cbe544c..c589d941da 100644
--- a/src/nvim/testdir/test_cmdline.vim
+++ b/src/nvim/testdir/test_cmdline.vim
@@ -1123,6 +1123,18 @@ func Test_cmdlineclear_tabenter()
call delete('XtestCmdlineClearTabenter')
endfunc
+func Test_cmdwin_tabpage()
+ tabedit
+ " v8.2.1919 isn't ported yet, so E492 is thrown after E11 here.
+ " v8.2.1183 also isn't ported yet, so we also can't assert E11 directly.
+ " For now, assert E11 and E492 seperately. When v8.2.1183 is ported, the
+ " assert for E492 will fail and this workaround should be removed.
+ " call assert_fails("silent norm q/g :I\<Esc>", 'E11:')
+ call assert_fails("silent norm q/g ", 'E11:')
+ call assert_fails("silent norm q/g :I\<Esc>", 'E492:')
+ tabclose!
+endfunc
+
" test that ";" works to find a match at the start of the first line
func Test_zero_line_search()
new
diff --git a/src/nvim/testdir/test_delete.vim b/src/nvim/testdir/test_delete.vim
new file mode 100644
index 0000000000..b23a3bd025
--- /dev/null
+++ b/src/nvim/testdir/test_delete.vim
@@ -0,0 +1,114 @@
+" Test for delete().
+
+func Test_file_delete()
+ split Xfile
+ call setline(1, ['a', 'b'])
+ wq
+ call assert_equal(['a', 'b'], readfile('Xfile'))
+ call assert_equal(0, delete('Xfile'))
+ call assert_fails('call readfile("Xfile")', 'E484:')
+ call assert_equal(-1, delete('Xfile'))
+ bwipe Xfile
+endfunc
+
+func Test_dir_delete()
+ call mkdir('Xdir1')
+ call assert_true(isdirectory('Xdir1'))
+ call assert_equal(0, delete('Xdir1', 'd'))
+ call assert_false(isdirectory('Xdir1'))
+ call assert_equal(-1, delete('Xdir1', 'd'))
+endfunc
+
+func Test_recursive_delete()
+ call mkdir('Xdir1')
+ call mkdir('Xdir1/subdir')
+ call mkdir('Xdir1/empty')
+ split Xdir1/Xfile
+ call setline(1, ['a', 'b'])
+ w
+ w Xdir1/subdir/Xfile
+ close
+ call assert_true(isdirectory('Xdir1'))
+ call assert_equal(['a', 'b'], readfile('Xdir1/Xfile'))
+ call assert_true(isdirectory('Xdir1/subdir'))
+ call assert_equal(['a', 'b'], readfile('Xdir1/subdir/Xfile'))
+ call assert_true('Xdir1/empty'->isdirectory())
+ call assert_equal(0, delete('Xdir1', 'rf'))
+ call assert_false(isdirectory('Xdir1'))
+ call assert_equal(-1, delete('Xdir1', 'd'))
+ bwipe Xdir1/Xfile
+ bwipe Xdir1/subdir/Xfile
+endfunc
+
+func Test_symlink_delete()
+ if !has('unix')
+ return
+ endif
+ split Xfile
+ call setline(1, ['a', 'b'])
+ wq
+ silent !ln -s Xfile Xlink
+ " Delete the link, not the file
+ call assert_equal(0, delete('Xlink'))
+ call assert_equal(-1, delete('Xlink'))
+ call assert_equal(0, delete('Xfile'))
+ bwipe Xfile
+endfunc
+
+func Test_symlink_dir_delete()
+ if !has('unix')
+ return
+ endif
+ call mkdir('Xdir1')
+ silent !ln -s Xdir1 Xlink
+ call assert_true(isdirectory('Xdir1'))
+ call assert_true(isdirectory('Xlink'))
+ " Delete the link, not the directory
+ call assert_equal(0, delete('Xlink'))
+ call assert_equal(-1, delete('Xlink'))
+ call assert_equal(0, delete('Xdir1', 'd'))
+endfunc
+
+func Test_symlink_recursive_delete()
+ if !has('unix')
+ return
+ endif
+ call mkdir('Xdir3')
+ call mkdir('Xdir3/subdir')
+ call mkdir('Xdir4')
+ split Xdir3/Xfile
+ call setline(1, ['a', 'b'])
+ w
+ w Xdir3/subdir/Xfile
+ w Xdir4/Xfile
+ close
+ silent !ln -s ../Xdir4 Xdir3/Xlink
+
+ call assert_true(isdirectory('Xdir3'))
+ call assert_equal(['a', 'b'], readfile('Xdir3/Xfile'))
+ call assert_true(isdirectory('Xdir3/subdir'))
+ call assert_equal(['a', 'b'], readfile('Xdir3/subdir/Xfile'))
+ call assert_true(isdirectory('Xdir4'))
+ call assert_true(isdirectory('Xdir3/Xlink'))
+ call assert_equal(['a', 'b'], readfile('Xdir4/Xfile'))
+
+ call assert_equal(0, delete('Xdir3', 'rf'))
+ call assert_false(isdirectory('Xdir3'))
+ call assert_equal(-1, delete('Xdir3', 'd'))
+ " symlink is deleted, not the directory it points to
+ call assert_true(isdirectory('Xdir4'))
+ call assert_equal(['a', 'b'], readfile('Xdir4/Xfile'))
+ call assert_equal(0, delete('Xdir4/Xfile'))
+ call assert_equal(0, delete('Xdir4', 'd'))
+
+ bwipe Xdir3/Xfile
+ bwipe Xdir3/subdir/Xfile
+ bwipe Xdir4/Xfile
+endfunc
+
+func Test_delete_errors()
+ call assert_fails('call delete('''')', 'E474:')
+ call assert_fails('call delete(''foo'', 0)', 'E15:')
+endfunc
+
+" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_diffmode.vim b/src/nvim/testdir/test_diffmode.vim
index 482d39056f..10eb979b45 100644
--- a/src/nvim/testdir/test_diffmode.vim
+++ b/src/nvim/testdir/test_diffmode.vim
@@ -1017,6 +1017,32 @@ func Test_diff_with_cursorline()
call delete('Xtest_diff_cursorline')
endfunc
+func Test_diff_with_cursorline_number()
+ CheckScreendump
+
+ let lines =<< trim END
+ hi CursorLine ctermbg=red ctermfg=white
+ hi CursorLineNr ctermbg=white ctermfg=black cterm=underline
+ set cursorline number
+ call setline(1, ["baz", "foo", "foo", "bar"])
+ 2
+ vnew
+ call setline(1, ["foo", "foo", "bar"])
+ windo diffthis
+ 1wincmd w
+ END
+ call writefile(lines, 'Xtest_diff_cursorline_number')
+ let buf = RunVimInTerminal('-S Xtest_diff_cursorline_number', {})
+
+ call VerifyScreenDump(buf, 'Test_diff_with_cursorline_number_01', {})
+ call term_sendkeys(buf, ":set cursorlineopt=number\r")
+ call VerifyScreenDump(buf, 'Test_diff_with_cursorline_number_02', {})
+
+ " clean up
+ call StopVimInTerminal(buf)
+ call delete('Xtest_diff_cursorline_number')
+endfunc
+
func Test_diff_with_cursorline_breakindent()
CheckScreendump
diff --git a/src/nvim/testdir/test_digraph.vim b/src/nvim/testdir/test_digraph.vim
index d23748a3e3..5965ee48ef 100644
--- a/src/nvim/testdir/test_digraph.vim
+++ b/src/nvim/testdir/test_digraph.vim
@@ -81,7 +81,7 @@ func Test_digraphs()
call Put_Dig(".e")
call Put_Dig("a.") " not defined
call assert_equal(['ḃ', 'ė', '.'], getline(line('.')-2,line('.')))
- " Diaresis
+ " Diaeresis
call Put_Dig("a:")
call Put_Dig(":u")
call Put_Dig("b:") " not defined
@@ -288,7 +288,7 @@ func Test_digraphs_option()
call Put_Dig_BS(".","e")
call Put_Dig_BS("a",".") " not defined
call assert_equal(['ḃ', 'ė', '.'], getline(line('.')-2,line('.')))
- " Diaresis
+ " Diaeresis
call Put_Dig_BS("a",":")
call Put_Dig_BS(":","u")
call Put_Dig_BS("b",":") " not defined
diff --git a/src/nvim/testdir/test_edit.vim b/src/nvim/testdir/test_edit.vim
index a1f6a84a99..360b3aaaa0 100644
--- a/src/nvim/testdir/test_edit.vim
+++ b/src/nvim/testdir/test_edit.vim
@@ -590,7 +590,7 @@ func Test_edit_CTRL_K()
call feedkeys("A\<c-x>\<c-k>\<down>\<down>\<down>\<down>\<cr>\<esc>", 'tnix')
call assert_equal(['AA'], getline(1, '$'))
- " press an unexecpted key after dictionary completion
+ " press an unexpected key after dictionary completion
%d
call setline(1, 'A')
call cursor(1, 1)
diff --git a/src/nvim/testdir/test_exit.vim b/src/nvim/testdir/test_exit.vim
index bd3e9eb4d4..befcaec2b2 100644
--- a/src/nvim/testdir/test_exit.vim
+++ b/src/nvim/testdir/test_exit.vim
@@ -1,6 +1,7 @@
" Tests for exiting Vim.
source shared.vim
+source check.vim
func Test_exiting()
let after =<< trim [CODE]
@@ -109,4 +110,25 @@ func Test_exit_code()
call delete('Xtestout')
endfunc
+func Test_exit_error_reading_input()
+ throw 'Skipped: Nvim does not exit after stdin is read'
+
+ CheckNotGui
+ CheckNotMSWindows
+ " The early exit causes memory not to be freed somehow
+ CheckNotAsan
+
+ call writefile([":au VimLeave * call writefile(['l = ' .. v:exiting], 'Xtestout')", ":tabnew", "q:"], 'Xscript', 'b')
+
+ " Nvim requires "-s -" to read stdin as Normal mode input
+ " if RunVim([], [], '<Xscript')
+ if RunVim([], [], '-s - <Xscript')
+ call assert_equal(1, v:shell_error)
+ call assert_equal(['l = 1'], readfile('Xtestout'))
+ endif
+ call delete('Xscript')
+ call delete('Xtestout')
+endfun
+
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_file_perm.vim b/src/nvim/testdir/test_file_perm.vim
new file mode 100644
index 0000000000..1cb09e8647
--- /dev/null
+++ b/src/nvim/testdir/test_file_perm.vim
@@ -0,0 +1,30 @@
+" Test getting and setting file permissions.
+
+func Test_file_perm()
+ call assert_equal('', getfperm('Xtest'))
+ call assert_equal(0, 'Xtest'->setfperm('r--------'))
+
+ call writefile(['one'], 'Xtest')
+ call assert_true(len('Xtest'->getfperm()) == 9)
+
+ call assert_equal(1, setfperm('Xtest', 'rwx------'))
+ if has('win32')
+ call assert_equal('rw-rw-rw-', getfperm('Xtest'))
+ else
+ call assert_equal('rwx------', getfperm('Xtest'))
+ endif
+
+ call assert_equal(1, setfperm('Xtest', 'r--r--r--'))
+ call assert_equal('r--r--r--', getfperm('Xtest'))
+
+ call assert_fails("setfperm('Xtest', '---')")
+
+ call assert_equal(1, setfperm('Xtest', 'rwx------'))
+ call delete('Xtest')
+
+ call assert_fails("call setfperm(['Xfile'], 'rw-rw-rw-')", 'E730:')
+ call assert_fails("call setfperm('Xfile', [])", 'E730:')
+ call assert_fails("call setfperm('Xfile', 'rwxrwxrwxrw')", 'E475:')
+endfunc
+
+" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_filetype.vim b/src/nvim/testdir/test_filetype.vim
index 46d35a102a..839d160e39 100644
--- a/src/nvim/testdir/test_filetype.vim
+++ b/src/nvim/testdir/test_filetype.vim
@@ -132,6 +132,7 @@ let s:filename_checks = {
\ 'cvs': ['cvs123'],
\ 'cvsrc': ['.cvsrc'],
\ 'cynpp': ['file.cyn'],
+ \ 'd': ['file.d'],
\ 'dart': ['file.dart', 'file.drt'],
\ 'datascript': ['file.ds'],
\ 'dcd': ['file.dcd'],
@@ -154,6 +155,7 @@ let s:filename_checks = {
\ 'dot': ['file.dot', 'file.gv'],
\ 'dracula': ['file.drac', 'file.drc', 'filelvs', 'filelpe', 'drac.file', 'lpe', 'lvs', 'some-lpe', 'some-lvs'],
\ 'dtd': ['file.dtd'],
+ \ 'dtrace': ['/usr/lib/dtrace/io.d'],
\ 'dts': ['file.dts', 'file.dtsi'],
\ 'dune': ['jbuild', 'dune', 'dune-project', 'dune-workspace'],
\ 'dylan': ['file.dylan'],
@@ -194,7 +196,7 @@ let s:filename_checks = {
\ 'fstab': ['fstab', 'mtab'],
\ 'fusion': ['file.fusion'],
\ 'fvwm': ['/.fvwm/file', 'any/.fvwm/file'],
- \ 'gdb': ['.gdbinit', 'gdbinit'],
+ \ 'gdb': ['.gdbinit', 'gdbinit', 'file.gdb', '.config/gdbearlyinit', '.gdbearlyinit'],
\ 'gdresource': ['file.tscn', 'file.tres'],
\ 'gdscript': ['file.gd'],
\ 'gdmo': ['file.mo', 'file.gdmo'],
@@ -272,6 +274,7 @@ let s:filename_checks = {
\ 'java': ['file.java', 'file.jav'],
\ 'javacc': ['file.jj', 'file.jjt'],
\ 'javascript': ['file.js', 'file.javascript', 'file.es', 'file.mjs', 'file.cjs'],
+ \ 'javascript.glimmer': ['file.gjs'],
\ 'javascriptreact': ['file.jsx'],
\ 'jess': ['file.clp'],
\ 'jgraph': ['file.jgr'],
@@ -546,6 +549,7 @@ let s:filename_checks = {
\ 'tssgm': ['file.tssgm'],
\ 'tssop': ['file.tssop'],
\ 'twig': ['file.twig'],
+ \ 'typescript.glimmer': ['file.gts'],
\ 'typescriptreact': ['file.tsx'],
\ 'uc': ['file.uc'],
\ 'udevconf': ['/etc/udev/udev.conf', 'any/etc/udev/udev.conf'],
@@ -800,6 +804,42 @@ func Test_bas_file()
filetype off
endfunc
+func Test_d_file()
+ filetype on
+
+ call writefile(['looks like D'], 'Xfile.d')
+ split Xfile.d
+ call assert_equal('d', &filetype)
+ bwipe!
+
+ call writefile(['#!/some/bin/dtrace'], 'Xfile.d')
+ split Xfile.d
+ call assert_equal('dtrace', &filetype)
+ bwipe!
+
+ call writefile(['#pragma D option'], 'Xfile.d')
+ split Xfile.d
+ call assert_equal('dtrace', &filetype)
+ bwipe!
+
+ call writefile([':some:thing:'], 'Xfile.d')
+ split Xfile.d
+ call assert_equal('dtrace', &filetype)
+ bwipe!
+
+ call writefile(['module this', '#pragma D option'], 'Xfile.d')
+ split Xfile.d
+ call assert_equal('d', &filetype)
+ bwipe!
+
+ call writefile(['import that', '#pragma D option'], 'Xfile.d')
+ split Xfile.d
+ call assert_equal('d', &filetype)
+ bwipe!
+
+ filetype off
+endfunc
+
func Test_dep3patch_file()
filetype on
diff --git a/src/nvim/testdir/test_functions.vim b/src/nvim/testdir/test_functions.vim
index 6e36f4e3d2..c2b5653a29 100644
--- a/src/nvim/testdir/test_functions.vim
+++ b/src/nvim/testdir/test_functions.vim
@@ -1451,6 +1451,10 @@ func Test_getchar()
call assert_equal('', getcharstr(0))
call assert_equal('', getcharstr(1))
+ call feedkeys("\<M-F2>", '')
+ call assert_equal("\<M-F2>", getchar(0))
+ call assert_equal(0, getchar(0))
+
call setline(1, 'xxxx')
" call test_setmouse(1, 3)
" let v:mouse_win = 9
@@ -1758,6 +1762,75 @@ func Test_getcurpos_setpos()
call assert_equal([0, 0, 0, 0, 0], getcurpos(1999))
endfunc
+func Test_getmousepos()
+ enew!
+ call setline(1, "\t\t\t1234")
+ " call test_setmouse(1, 1)
+ call nvim_input_mouse('left', 'press', '', 0, 0, 0)
+ call getchar() " wait for and consume the mouse press
+ call assert_equal(#{
+ \ screenrow: 1,
+ \ screencol: 1,
+ \ winid: win_getid(),
+ \ winrow: 1,
+ \ wincol: 1,
+ \ line: 1,
+ \ column: 1,
+ \ }, getmousepos())
+ " call test_setmouse(1, 25)
+ call nvim_input_mouse('left', 'press', '', 0, 0, 24)
+ call getchar() " wait for and consume the mouse press
+ call assert_equal(#{
+ \ screenrow: 1,
+ \ screencol: 25,
+ \ winid: win_getid(),
+ \ winrow: 1,
+ \ wincol: 25,
+ \ line: 1,
+ \ column: 4,
+ \ }, getmousepos())
+ " call test_setmouse(1, 50)
+ call nvim_input_mouse('left', 'press', '', 0, 0, 49)
+ call getchar() " wait for and consume the mouse press
+ call assert_equal(#{
+ \ screenrow: 1,
+ \ screencol: 50,
+ \ winid: win_getid(),
+ \ winrow: 1,
+ \ wincol: 50,
+ \ line: 1,
+ \ column: 8,
+ \ }, getmousepos())
+
+ " If the mouse is positioned past the last buffer line, "line" and "column"
+ " should act like it's positioned on the last buffer line.
+ " call test_setmouse(2, 25)
+ call nvim_input_mouse('left', 'press', '', 0, 1, 24)
+ call getchar() " wait for and consume the mouse press
+ call assert_equal(#{
+ \ screenrow: 2,
+ \ screencol: 25,
+ \ winid: win_getid(),
+ \ winrow: 2,
+ \ wincol: 25,
+ \ line: 1,
+ \ column: 4,
+ \ }, getmousepos())
+ " call test_setmouse(2, 50)
+ call nvim_input_mouse('left', 'press', '', 0, 1, 49)
+ call getchar() " wait for and consume the mouse press
+ call assert_equal(#{
+ \ screenrow: 2,
+ \ screencol: 50,
+ \ winid: win_getid(),
+ \ winrow: 2,
+ \ wincol: 50,
+ \ line: 1,
+ \ column: 8,
+ \ }, getmousepos())
+ bwipe!
+endfunc
+
func HasDefault(msg = 'msg')
return a:msg
endfunc
diff --git a/src/nvim/testdir/test_highlight.vim b/src/nvim/testdir/test_highlight.vim
index 6971ecd357..aa7b3a225b 100644
--- a/src/nvim/testdir/test_highlight.vim
+++ b/src/nvim/testdir/test_highlight.vim
@@ -146,7 +146,7 @@ func Test_highlight_eol_with_cursorline_vertsplit()
" 'abcd |abcd '
" ^^^^ ^^^^^^^^^ no highlight
" ^ 'Search' highlight
- " ^ 'VertSplit' highlight
+ " ^ 'WinSeparator' highlight
let attrs0 = ScreenAttrs(1, 15)[0]
call assert_equal(repeat([attrs0[0]], 4), attrs0[0:3])
call assert_equal(repeat([attrs0[0]], 9), attrs0[6:14])
@@ -160,7 +160,7 @@ func Test_highlight_eol_with_cursorline_vertsplit()
" 'abcd |abcd '
" ^^^^ underline
" ^ 'Search' highlight with underline
- " ^ 'VertSplit' highlight
+ " ^ 'WinSeparator' highlight
" ^^^^^^^^^ no highlight
" underline
diff --git a/src/nvim/testdir/test_mapping.vim b/src/nvim/testdir/test_mapping.vim
index f88e8cf843..98440ccdd7 100644
--- a/src/nvim/testdir/test_mapping.vim
+++ b/src/nvim/testdir/test_mapping.vim
@@ -1,6 +1,8 @@
" Tests for mappings and abbreviations
source shared.vim
+source check.vim
+source screendump.vim
func Test_abbreviation()
" abbreviation with 0x80 should work
@@ -451,6 +453,82 @@ func Test_expr_map_gets_cursor()
nunmap !
endfunc
+func Test_expr_map_restore_cursor()
+ CheckScreendump
+
+ let lines =<< trim END
+ call setline(1, ['one', 'two', 'three'])
+ 2
+ set ls=2
+ hi! link StatusLine ErrorMsg
+ noremap <expr> <C-B> Func()
+ func Func()
+ let g:on = !get(g:, 'on', 0)
+ redraws
+ return ''
+ endfunc
+ func Status()
+ return get(g:, 'on', 0) ? '[on]' : ''
+ endfunc
+ set stl=%{Status()}
+ END
+ call writefile(lines, 'XtestExprMap')
+ let buf = RunVimInTerminal('-S XtestExprMap', #{rows: 10})
+ call term_sendkeys(buf, "\<C-B>")
+ call VerifyScreenDump(buf, 'Test_map_expr_1', {})
+
+ " clean up
+ call StopVimInTerminal(buf)
+ call delete('XtestExprMap')
+endfunc
+
+func Test_map_listing()
+ CheckScreendump
+
+ let lines =<< trim END
+ nmap a b
+ END
+ call writefile(lines, 'XtestMapList')
+ let buf = RunVimInTerminal('-S XtestMapList', #{rows: 6})
+ call term_sendkeys(buf, ": nmap a\<CR>")
+ call VerifyScreenDump(buf, 'Test_map_list_1', {})
+
+ " clean up
+ call StopVimInTerminal(buf)
+ call delete('XtestMapList')
+endfunc
+
+func Test_expr_map_error()
+ CheckScreendump
+
+ let lines =<< trim END
+ func Func()
+ throw 'test'
+ return ''
+ endfunc
+
+ nnoremap <expr> <F2> Func()
+ cnoremap <expr> <F2> Func()
+
+ call test_override('ui_delay', 10)
+ END
+ call writefile(lines, 'XtestExprMap')
+ let buf = RunVimInTerminal('-S XtestExprMap', #{rows: 10})
+ call term_sendkeys(buf, "\<F2>")
+ call TermWait(buf)
+ call term_sendkeys(buf, "\<CR>")
+ call VerifyScreenDump(buf, 'Test_map_expr_2', {})
+
+ call term_sendkeys(buf, ":abc\<F2>")
+ call VerifyScreenDump(buf, 'Test_map_expr_3', {})
+ call term_sendkeys(buf, "\<Esc>0")
+ call VerifyScreenDump(buf, 'Test_map_expr_4', {})
+
+ " clean up
+ call StopVimInTerminal(buf)
+ call delete('XtestExprMap')
+endfunc
+
" Test for mapping errors
func Test_map_error()
call assert_fails('unmap', 'E474:')
@@ -568,4 +646,34 @@ func Test_abbreviate_multi_byte()
bwipe!
endfunc
+" Test for <Plug> always being mapped, even when used with "noremap".
+func Test_plug_remap()
+ let g:foo = 0
+ nnoremap <Plug>(Increase_x) <Cmd>let g:foo += 1<CR>
+ nmap <F2> <Plug>(Increase_x)
+ nnoremap <F3> <Plug>(Increase_x)
+ call feedkeys("\<F2>", 'xt')
+ call assert_equal(1, g:foo)
+ call feedkeys("\<F3>", 'xt')
+ call assert_equal(2, g:foo)
+ nnoremap x <Nop>
+ nmap <F4> x<Plug>(Increase_x)x
+ nnoremap <F5> x<Plug>(Increase_x)x
+ call setline(1, 'Some text')
+ normal! gg$
+ call feedkeys("\<F4>", 'xt')
+ call assert_equal(3, g:foo)
+ call assert_equal('Some text', getline(1))
+ call feedkeys("\<F5>", 'xt')
+ call assert_equal(4, g:foo)
+ call assert_equal('Some te', getline(1))
+ nunmap <Plug>(Increase_x)
+ nunmap <F2>
+ nunmap <F3>
+ nunmap <F4>
+ nunmap <F5>
+ unlet g:foo
+ %bw!
+endfunc
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_mksession.vim b/src/nvim/testdir/test_mksession.vim
index a8e50af510..798cb9e54f 100644
--- a/src/nvim/testdir/test_mksession.vim
+++ b/src/nvim/testdir/test_mksession.vim
@@ -219,6 +219,7 @@ func Test_mksession_one_buffer_two_windows()
let count1 = 0
let count2 = 0
let count2buf = 0
+ let bufexists = 0
for line in lines
if line =~ 'edit \f*Xtest1$'
let count1 += 1
@@ -229,10 +230,14 @@ func Test_mksession_one_buffer_two_windows()
if line =~ 'buffer \f\{-}Xtest2'
let count2buf += 1
endif
+ if line =~ 'bufexists(fnamemodify(.*, ":p")'
+ let bufexists += 1
+ endif
endfor
call assert_equal(1, count1, 'Xtest1 count')
call assert_equal(2, count2, 'Xtest2 count')
call assert_equal(2, count2buf, 'Xtest2 buffer count')
+ call assert_equal(2, bufexists)
close
bwipe!
diff --git a/src/nvim/testdir/test_normal.vim b/src/nvim/testdir/test_normal.vim
index e8eebb3fdd..f45cd96733 100644
--- a/src/nvim/testdir/test_normal.vim
+++ b/src/nvim/testdir/test_normal.vim
@@ -1118,7 +1118,7 @@ func Test_normal20_exmode()
endif
call writefile(['1a', 'foo', 'bar', '.', 'w! Xfile2', 'q!'], 'Xscript')
call writefile(['1', '2'], 'Xfile')
- call system(v:progpath .' -e -s < Xscript Xfile')
+ call system(GetVimCommand() .. ' -e -s < Xscript Xfile')
let a=readfile('Xfile2')
call assert_equal(['1', 'foo', 'bar', '2'], a)
@@ -1171,13 +1171,13 @@ func Test_normal22_zet()
endfor
call writefile(['1', '2'], 'Xfile_Test_normal22_zet')
- let args = ' --headless -u NONE -N -U NONE -i NONE --noplugins'
- call system(v:progpath . args . ' -c "%d" -c ":norm! ZZ" Xfile_Test_normal22_zet')
+ let args = ' -N -i NONE --noplugins -X --headless'
+ call system(GetVimCommand() .. args .. ' -c "%d" -c ":norm! ZZ" Xfile_Test_normal22_zet')
let a = readfile('Xfile_Test_normal22_zet')
call assert_equal([], a)
" Test for ZQ
call writefile(['1', '2'], 'Xfile_Test_normal22_zet')
- call system(v:progpath . args . ' -c "%d" -c ":norm! ZQ" Xfile_Test_normal22_zet')
+ call system(GetVimCommand() . args . ' -c "%d" -c ":norm! ZQ" Xfile_Test_normal22_zet')
let a = readfile('Xfile_Test_normal22_zet')
call assert_equal(['1', '2'], a)
diff --git a/src/nvim/testdir/test_profile.vim b/src/nvim/testdir/test_profile.vim
index 4b0097617e..fdb6f13e2b 100644
--- a/src/nvim/testdir/test_profile.vim
+++ b/src/nvim/testdir/test_profile.vim
@@ -1,8 +1,9 @@
" Test Vim profiler
-if !has('profile')
- finish
-endif
+source check.vim
+CheckFeature profile
+
+source shared.vim
source screendump.vim
func Test_profile_func()
@@ -37,7 +38,7 @@ func Test_profile_func()
[CODE]
call writefile(lines, 'Xprofile_func.vim')
- call system(v:progpath
+ call system(GetVimCommand()
\ . ' -es --clean'
\ . ' -c "so Xprofile_func.vim"'
\ . ' -c "qall!"')
@@ -124,8 +125,8 @@ func Test_profile_func_with_ifelse()
[CODE]
call writefile(lines, 'Xprofile_func.vim')
- call system(v:progpath
- \ . ' -es -u NONE -U NONE -i NONE --noplugin'
+ call system(GetVimCommand()
+ \ . ' -es -i NONE --noplugin'
\ . ' -c "profile start Xprofile_func.log"'
\ . ' -c "profile func Foo*"'
\ . ' -c "so Xprofile_func.vim"'
@@ -237,8 +238,8 @@ func Test_profile_func_with_trycatch()
[CODE]
call writefile(lines, 'Xprofile_func.vim')
- call system(v:progpath
- \ . ' -es -u NONE -U NONE -i NONE --noplugin'
+ call system(GetVimCommand()
+ \ . ' -es -i NONE --noplugin'
\ . ' -c "profile start Xprofile_func.log"'
\ . ' -c "profile func Foo*"'
\ . ' -c "so Xprofile_func.vim"'
@@ -324,8 +325,8 @@ func Test_profile_file()
[CODE]
call writefile(lines, 'Xprofile_file.vim')
- call system(v:progpath
- \ . ' -es --clean'
+ call system(GetVimCommandClean()
+ \ . ' -es'
\ . ' -c "profile start Xprofile_file.log"'
\ . ' -c "profile file Xprofile_file.vim"'
\ . ' -c "so Xprofile_file.vim"'
@@ -369,8 +370,8 @@ func Test_profile_file_with_cont()
\ ]
call writefile(lines, 'Xprofile_file.vim')
- call system(v:progpath
- \ . ' -es -u NONE -U NONE -i NONE --noplugin'
+ call system(GetVimCommandClean()
+ \ . ' -es'
\ . ' -c "profile start Xprofile_file.log"'
\ . ' -c "profile file Xprofile_file.vim"'
\ . ' -c "so Xprofile_file.vim"'
@@ -427,7 +428,7 @@ func Test_profile_truncate_mbyte()
\ ]
call writefile(lines, 'Xprofile_file.vim')
- call system(v:progpath
+ call system(GetVimCommandClean()
\ . ' -es --cmd "set enc=utf-8"'
\ . ' -c "profile start Xprofile_file.log"'
\ . ' -c "profile file Xprofile_file.vim"'
@@ -474,7 +475,7 @@ func Test_profdel_func()
call Foo3()
[CODE]
call writefile(lines, 'Xprofile_file.vim')
- call system(v:progpath . ' -es --clean -c "so Xprofile_file.vim" -c q')
+ call system(GetVimCommandClean() . ' -es -c "so Xprofile_file.vim" -c q')
call assert_equal(0, v:shell_error)
let lines = readfile('Xprofile_file.log')
@@ -509,7 +510,7 @@ func Test_profdel_star()
call Foo()
[CODE]
call writefile(lines, 'Xprofile_file.vim')
- call system(v:progpath . ' -es --clean -c "so Xprofile_file.vim" -c q')
+ call system(GetVimCommandClean() . ' -es -c "so Xprofile_file.vim" -c q')
call assert_equal(0, v:shell_error)
let lines = readfile('Xprofile_file.log')
diff --git a/src/nvim/testdir/test_quickfix.vim b/src/nvim/testdir/test_quickfix.vim
index c4d70fb1de..14d13049d9 100644
--- a/src/nvim/testdir/test_quickfix.vim
+++ b/src/nvim/testdir/test_quickfix.vim
@@ -1,4 +1,4 @@
-" Test for the quickfix commands.
+" Test for the quickfix feature.
source check.vim
CheckFeature quickfix
@@ -169,8 +169,8 @@ func XlistTests(cchar)
\ {'lnum':30,'col':15,'type':'W','filename':'Data/Text.hs','text':'FileWarning','nr':33,'valid':v:true}])
let l = split(execute('Xlist', ""), "\n")
call assert_equal([' 1 Data.Text:10 col 5 warning 11: ModuleWarning',
- \ ' 2 Data.Text:20 col 10 warning 22: ModuleWarning',
- \ ' 3 Data/Text.hs:30 col 15 warning 33: FileWarning'], l)
+ \ ' 2 Data.Text:20 col 10 warning 22: ModuleWarning',
+ \ ' 3 Data/Text.hs:30 col 15 warning 33: FileWarning'], l)
" For help entries in the quickfix list, only the filename without directory
" should be displayed
@@ -1655,7 +1655,7 @@ func XquickfixSetListWithAct(cchar)
\ {'filename': 'fnameD', 'text': 'D'},
\ {'filename': 'fnameE', 'text': 'E'}]
- " {action} is unspecified. Same as specifing ' '.
+ " {action} is unspecified. Same as specifying ' '.
new | only
silent! Xnewer 99
call g:Xsetlist(list1)
@@ -2020,6 +2020,7 @@ func s:test_xgrep(cchar)
enew
set makeef=Temp_File_##
silent Xgrepadd GrepAdd_Test_Text: test_quickfix.vim
+ call assert_true(len(g:Xgetlist()) == 9)
" Try with 'grepprg' set to 'internal'
set grepprg=internal
@@ -2028,12 +2029,12 @@ func s:test_xgrep(cchar)
call assert_true(len(g:Xgetlist()) == 9)
set grepprg&vim
- call writefile(['Vim'], 'XtestTempFile')
- set makeef=XtestTempFile
- silent Xgrep Grep_Test_Text: test_quickfix.vim
- call assert_equal(5, len(g:Xgetlist()))
- call assert_false(filereadable('XtestTempFile'))
- set makeef&vim
+ call writefile(['Vim'], 'XtestTempFile')
+ set makeef=XtestTempFile
+ silent Xgrep Grep_Test_Text: test_quickfix.vim
+ call assert_equal(5, len(g:Xgetlist()))
+ call assert_false(filereadable('XtestTempFile'))
+ set makeef&vim
endfunc
func Test_grep()
@@ -2706,7 +2707,7 @@ func Test_cwindow_jump()
" Open a new window and create a location list
" Open the location list window and close the other window
" Jump to an entry.
- " Should create a new window and jump to the entry. The scrtach buffer
+ " Should create a new window and jump to the entry. The scratch buffer
" should not be used.
enew | only
set buftype=nofile
@@ -2739,7 +2740,26 @@ func Test_cwindow_jump()
call assert_true(winnr('$') == 2)
call assert_true(winnr() == 1)
- " Jumping to a file from the location list window should find a usuable
+ " open the quickfix buffer in two windows and jump to an entry. Should open
+ " the file in the first quickfix window.
+ enew | only
+ copen
+ let bnum = bufnr('')
+ exe 'sbuffer ' . bnum
+ wincmd b
+ cfirst
+ call assert_equal(2, winnr())
+ call assert_equal('F1', bufname(''))
+ enew | only
+ exe 'sb' bnum
+ exe 'botright sb' bnum
+ wincmd t
+ clast
+ call assert_equal(2, winnr())
+ call assert_equal('quickfix', getwinvar(1, '&buftype'))
+ call assert_equal('quickfix', getwinvar(3, '&buftype'))
+
+ " Jumping to a file from the location list window should find a usable
" window by wrapping around the window list.
enew | only
call setloclist(0, [], 'f')
@@ -3548,20 +3568,21 @@ func Xgetlist_empty_tests(cchar)
call assert_equal(0, g:Xgetlist({'changedtick' : 0}).changedtick)
if a:cchar == 'c'
call assert_equal({'context' : '', 'id' : 0, 'idx' : 0,
- \ 'items' : [], 'nr' : 0, 'size' : 0,
+ \ 'items' : [], 'nr' : 0, 'size' : 0, 'qfbufnr' : 0,
\ 'title' : '', 'winid' : 0, 'changedtick': 0,
\ 'quickfixtextfunc' : ''}, g:Xgetlist({'all' : 0}))
else
call assert_equal({'context' : '', 'id' : 0, 'idx' : 0,
\ 'items' : [], 'nr' : 0, 'size' : 0, 'title' : '',
\ 'winid' : 0, 'changedtick': 0, 'filewinid' : 0,
- \ 'quickfixtextfunc' : ''},
+ \ 'qfbufnr' : 0, 'quickfixtextfunc' : ''},
\ g:Xgetlist({'all' : 0}))
endif
" Quickfix window with empty stack
silent! Xopen
let qfwinid = (a:cchar == 'c') ? win_getid() : 0
+ let qfbufnr = (a:cchar == 'c') ? bufnr('') : 0
call assert_equal(qfwinid, g:Xgetlist({'winid' : 0}).winid)
Xclose
@@ -3593,12 +3614,12 @@ func Xgetlist_empty_tests(cchar)
if a:cchar == 'c'
call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [],
\ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0,
- \ 'quickfixtextfunc' : '',
+ \ 'qfbufnr' : qfbufnr, 'quickfixtextfunc' : '',
\ 'changedtick' : 0}, g:Xgetlist({'id' : qfid, 'all' : 0}))
else
call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [],
\ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0,
- \ 'changedtick' : 0, 'filewinid' : 0,
+ \ 'changedtick' : 0, 'filewinid' : 0, 'qfbufnr' : 0,
\ 'quickfixtextfunc' : ''},
\ g:Xgetlist({'id' : qfid, 'all' : 0}))
endif
@@ -3616,12 +3637,12 @@ func Xgetlist_empty_tests(cchar)
if a:cchar == 'c'
call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [],
\ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0,
- \ 'changedtick' : 0,
+ \ 'changedtick' : 0, 'qfbufnr' : qfbufnr,
\ 'quickfixtextfunc' : ''}, g:Xgetlist({'nr' : 5, 'all' : 0}))
else
call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [],
\ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0,
- \ 'changedtick' : 0, 'filewinid' : 0,
+ \ 'changedtick' : 0, 'filewinid' : 0, 'qfbufnr' : 0,
\ 'quickfixtextfunc' : ''}, g:Xgetlist({'nr' : 5, 'all' : 0}))
endif
endfunc
@@ -4360,7 +4381,7 @@ func Test_splitview()
new | only
" When split opening files from a helpgrep location list window, a new help
- " window should be opend with a copy of the location list.
+ " window should be opened with a copy of the location list.
lhelpgrep window
let locid = getloclist(0, {'id' : 0}).id
lwindow
@@ -4456,11 +4477,19 @@ func Xqfbuf_test(cchar)
Xclose
" Even after the quickfix window is closed, the buffer should be loaded
call assert_true(bufloaded(qfbnum))
+ call assert_true(qfbnum, g:Xgetlist({'qfbufnr' : 0}).qfbufnr)
Xopen
" Buffer should be reused when opening the window again
call assert_equal(qfbnum, bufnr(''))
Xclose
+ " When quickfix buffer is wiped out, getqflist() should return 0
+ %bw!
+ Xexpr ""
+ Xopen
+ bw!
+ call assert_equal(0, g:Xgetlist({'qfbufnr': 0}).qfbufnr)
+
if a:cchar == 'l'
%bwipe
" For a location list, when both the file window and the location list
@@ -4474,7 +4503,7 @@ func Xqfbuf_test(cchar)
close
" When the location list window is closed, the buffer name should not
" change to 'Quickfix List'
- call assert_match(qfbnum . ' h- "\[Location List]"', execute('ls'))
+ call assert_match(qfbnum . 'u h- "\[Location List]"', execute('ls!'))
call assert_true(bufloaded(qfbnum))
" After deleting a location list buffer using ":bdelete", opening the
@@ -4491,6 +4520,7 @@ func Xqfbuf_test(cchar)
" removed
call setloclist(0, [], 'f')
call assert_false(bufexists(qfbnum))
+ call assert_equal(0, getloclist(0, {'qfbufnr' : 0}).qfbufnr)
" When the location list is freed with the location list window open, the
" location list buffer should not be lost. It should be reused when the
@@ -4515,11 +4545,36 @@ func Xqfbuf_test(cchar)
endfunc
func Test_qfbuf()
- throw 'skipped: enable after porting patch 8.1.0877'
call Xqfbuf_test('c')
call Xqfbuf_test('l')
endfunc
+" If there is an autocmd to use only one window, then opening the location
+" list window used to crash Vim.
+func Test_winonly_autocmd()
+ call s:create_test_file('Xtest1')
+ " Autocmd to show only one Vim window at a time
+ autocmd WinEnter * only
+ new
+ " Load the location list
+ lexpr "Xtest1:5:Line5\nXtest1:10:Line10\nXtest1:15:Line15"
+ let loclistid = getloclist(0, {'id' : 0}).id
+ " Open the location list window. Only this window will be shown and the file
+ " window is closed.
+ lopen
+ call assert_equal(loclistid, getloclist(0, {'id' : 0}).id)
+ " Jump to an entry in the location list and make sure that the cursor is
+ " positioned correctly.
+ ll 3
+ call assert_equal(loclistid, getloclist(0, {'id' : 0}).id)
+ call assert_equal('Xtest1', bufname(''))
+ call assert_equal(15, line('.'))
+ " Cleanup
+ autocmd! WinEnter
+ new | only
+ call delete('Xtest1')
+endfunc
+
" Test to make sure that an empty quickfix buffer is not reused for loading
" a normal buffer.
func Test_empty_qfbuf()
@@ -5207,16 +5262,14 @@ func Xtest_qftextfunc(cchar)
" Non-existing function
set quickfixtextfunc=Tabc
- " call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E117:')
- Xexpr ['F1:10:2:green', 'F1:20:4:blue']"
+ call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E117:')
call assert_fails("Xwindow", 'E117:')
Xclose
set quickfixtextfunc&
" set option to a non-function
set quickfixtextfunc=[10,\ 20]
- " call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E117:')
- Xexpr ['F1:10:2:green', 'F1:20:4:blue']"
+ call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E117:')
call assert_fails("Xwindow", 'E117:')
Xclose
set quickfixtextfunc&
@@ -5226,8 +5279,7 @@ func Xtest_qftextfunc(cchar)
return a:a .. a:b .. a:c
endfunc
set quickfixtextfunc=Xqftext
- " call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E119:')
- Xexpr ['F1:10:2:green', 'F1:20:4:blue']"
+ call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue']", 'E119:')
call assert_fails("Xwindow", 'E119:')
Xclose
@@ -5236,9 +5288,8 @@ func Xtest_qftextfunc(cchar)
return ['one', [], 'two']
endfunc
set quickfixtextfunc=Xqftext2
- " call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue', 'F1:30:6:red']",
- " \ 'E730:')
- Xexpr ['F1:10:2:green', 'F1:20:4:blue', 'F1:30:6:red']
+ call assert_fails("Xexpr ['F1:10:2:green', 'F1:20:4:blue', 'F1:30:6:red']",
+ \ 'E730:')
call assert_fails('Xwindow', 'E730:')
call assert_equal(['one', 'F1|20 col 4| blue', 'F1|30 col 6| red'],
\ getline(1, '$'))
@@ -5402,4 +5453,40 @@ func Test_win_gettype()
lclose
endfunc
+" Test for opening the quickfix window in two tab pages and then closing one
+" of the quickfix windows. This should not make the quickfix buffer unlisted.
+" (github issue #9300).
+func Test_two_qf_windows()
+ cexpr "F1:1:line1"
+ copen
+ tabnew
+ copen
+ call assert_true(&buflisted)
+ cclose
+ tabfirst
+ call assert_true(&buflisted)
+ let bnum = bufnr()
+ cclose
+ " if all the quickfix windows are closed, then buffer should be unlisted.
+ call assert_false(buflisted(bnum))
+ %bw!
+
+ " Repeat the test for a location list
+ lexpr "F2:2:line2"
+ lopen
+ let bnum = bufnr()
+ tabnew
+ exe "buffer" bnum
+ tabfirst
+ lclose
+ tablast
+ call assert_true(buflisted(bnum))
+ tabclose
+ lopen
+ call assert_true(buflisted(bnum))
+ lclose
+ call assert_false(buflisted(bnum))
+ %bw!
+endfunc
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_regexp_latin.vim b/src/nvim/testdir/test_regexp_latin.vim
index a92f7e1192..a0f5ebfb9f 100644
--- a/src/nvim/testdir/test_regexp_latin.vim
+++ b/src/nvim/testdir/test_regexp_latin.vim
@@ -795,4 +795,20 @@ func Test_using_mark_position()
bwipe!
endfunc
+func Test_using_visual_position()
+ " this was using freed memory
+ new
+ exe "norm 0o\<Esc>\<C-V>k\<C-X>o0"
+ /\%V
+ bwipe!
+endfunc
+
+func Test_using_invalid_visual_position()
+ " this was going beyond the end of the line
+ new
+ exe "norm 0o000\<Esc>0\<C-V>$s0"
+ /\%V
+ bwipe!
+endfunc
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_regexp_utf8.vim b/src/nvim/testdir/test_regexp_utf8.vim
index b640a6d043..eab47dbccc 100644
--- a/src/nvim/testdir/test_regexp_utf8.vim
+++ b/src/nvim/testdir/test_regexp_utf8.vim
@@ -540,7 +540,6 @@ endfunc
" Check that [[:upper:]] matches for automatic engine
func Test_match_char_class_upper()
new
- let _engine=&regexpengine
" Test 1: [[:upper:]]\{2,\}
set regexpengine=0
@@ -581,7 +580,7 @@ func Test_match_char_class_upper()
call assert_equal(4, searchcount().total, 'TEST 3 lower')
" clean up
- let &regexpengine=_engine
+ set regexpengine=0
bwipe!
endfunc
@@ -593,4 +592,13 @@ func Test_match_invalid_byte()
call delete('Xinvalid')
endfunc
+func Test_match_too_complicated()
+ set regexpengine=1
+ exe "noswapfile vsplit \xeb\xdb\x99"
+ silent! buf \&\zs*\zs*0
+ bwipe!
+ set regexpengine=0
+endfunc
+
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_registers.vim b/src/nvim/testdir/test_registers.vim
index 2e92d9aa2f..f78b748d71 100644
--- a/src/nvim/testdir/test_registers.vim
+++ b/src/nvim/testdir/test_registers.vim
@@ -62,7 +62,6 @@ func Test_display_registers()
call assert_match('^\nType Name Content\n'
\ . ' c "" a\n'
\ . ' c "0 ba\n'
- \ . ' c "1 b\n'
\ . ' c "a b\n'
\ . '.*'
\ . ' c "- a\n'
@@ -85,6 +84,90 @@ func Test_display_registers()
let g:clipboard = save_clipboard
endfunc
+func Test_register_one()
+ " delete a line goes into register one
+ new
+ call setline(1, "one")
+ normal dd
+ call assert_equal("one\n", @1)
+
+ " delete a word does not change register one, does change "-
+ call setline(1, "two")
+ normal de
+ call assert_equal("one\n", @1)
+ call assert_equal("two", @-)
+
+ " delete a word with a register does not change register one
+ call setline(1, "three")
+ normal "ade
+ call assert_equal("three", @a)
+ call assert_equal("one\n", @1)
+
+ " delete a word with register DOES change register one with one of a list of
+ " operators
+ " %
+ call setline(1, ["(12)3"])
+ normal "ad%
+ call assert_equal("(12)", @a)
+ call assert_equal("(12)", @1)
+
+ " (
+ call setline(1, ["first second"])
+ normal $"ad(
+ call assert_equal("first secon", @a)
+ call assert_equal("first secon", @1)
+
+ " )
+ call setline(1, ["First Second."])
+ normal gg0"ad)
+ call assert_equal("First Second.", @a)
+ call assert_equal("First Second.", @1)
+
+ " `
+ call setline(1, ["start here."])
+ normal gg0fhmx0"ad`x
+ call assert_equal("start ", @a)
+ call assert_equal("start ", @1)
+
+ " /
+ call setline(1, ["searchX"])
+ exe "normal gg0\"ad/X\<CR>"
+ call assert_equal("search", @a)
+ call assert_equal("search", @1)
+
+ " ?
+ call setline(1, ["Ysearch"])
+ exe "normal gg$\"ad?Y\<CR>"
+ call assert_equal("Ysearc", @a)
+ call assert_equal("Ysearc", @1)
+
+ " n
+ call setline(1, ["Ynext"])
+ normal gg$"adn
+ call assert_equal("Ynex", @a)
+ call assert_equal("Ynex", @1)
+
+ " N
+ call setline(1, ["prevY"])
+ normal gg0"adN
+ call assert_equal("prev", @a)
+ call assert_equal("prev", @1)
+
+ " }
+ call setline(1, ["one", ""])
+ normal gg0"ad}
+ call assert_equal("one\n", @a)
+ call assert_equal("one\n", @1)
+
+ " {
+ call setline(1, ["", "two"])
+ normal 2G$"ad{
+ call assert_equal("\ntw", @a)
+ call assert_equal("\ntw", @1)
+
+ bwipe!
+endfunc
+
func Test_recording_status_in_ex_line()
norm qx
redraw!
@@ -219,7 +302,7 @@ func Test_set_register()
call setreg('=', 'b', 'a')
call assert_equal('regwrite', getreg('='))
- " Test for settting a list of lines to special registers
+ " Test for setting a list of lines to special registers
call setreg('/', [])
call assert_equal('', @/)
call setreg('=', [])
@@ -482,6 +565,82 @@ func Test_v_register()
bwipe!
endfunc
+" Test for executing the contents of a register as an Ex command with line
+" continuation.
+func Test_execute_reg_as_ex_cmd()
+ " Line continuation with just two lines
+ let code =<< trim END
+ let l = [
+ \ 1]
+ END
+ let @r = code->join("\n")
+ let l = []
+ @r
+ call assert_equal([1], l)
+
+ " Line continuation with more than two lines
+ let code =<< trim END
+ let l = [
+ \ 1,
+ \ 2,
+ \ 3]
+ END
+ let @r = code->join("\n")
+ let l = []
+ @r
+ call assert_equal([1, 2, 3], l)
+
+ " use comments interspersed with code
+ let code =<< trim END
+ let l = [
+ "\ one
+ \ 1,
+ "\ two
+ \ 2,
+ "\ three
+ \ 3]
+ END
+ let @r = code->join("\n")
+ let l = []
+ @r
+ call assert_equal([1, 2, 3], l)
+
+ " use line continuation in the middle
+ let code =<< trim END
+ let a = "one"
+ let l = [
+ \ 1,
+ \ 2]
+ let b = "two"
+ END
+ let @r = code->join("\n")
+ let l = []
+ @r
+ call assert_equal([1, 2], l)
+ call assert_equal("one", a)
+ call assert_equal("two", b)
+
+ " only one line with a \
+ let @r = "\\let l = 1"
+ call assert_fails('@r', 'E10:')
+
+ " only one line with a "\
+ let @r = ' "\ let i = 1'
+ @r
+ call assert_false(exists('i'))
+
+ " first line also begins with a \
+ let @r = "\\let l = [\n\\ 1]"
+ call assert_fails('@r', 'E10:')
+
+ " Test with a large number of lines
+ let @r = "let str = \n"
+ let @r ..= repeat(" \\ 'abcdefghijklmnopqrstuvwxyz' ..\n", 312)
+ let @r ..= ' \ ""'
+ @r
+ call assert_equal(repeat('abcdefghijklmnopqrstuvwxyz', 312), str)
+endfunc
+
func Test_ve_blockpaste()
new
set ve=all
diff --git a/src/nvim/testdir/test_searchpos.vim b/src/nvim/testdir/test_searchpos.vim
new file mode 100644
index 0000000000..dd13c305c5
--- /dev/null
+++ b/src/nvim/testdir/test_searchpos.vim
@@ -0,0 +1,30 @@
+" Tests for searchpos()
+
+func Test_searchpos()
+ new one
+ 0put ='1a3'
+ 1put ='123xyz'
+ call cursor(1, 1)
+ call assert_equal([1, 1, 2], searchpos('\%(\([a-z]\)\|\_.\)\{-}xyz', 'pcW'))
+ call cursor(1, 2)
+ call assert_equal([2, 1, 1], '\%(\([a-z]\)\|\_.\)\{-}xyz'->searchpos('pcW'))
+ set cpo-=c
+ call cursor(1, 2)
+ call assert_equal([1, 2, 2], searchpos('\%(\([a-z]\)\|\_.\)\{-}xyz', 'pcW'))
+ call cursor(1, 3)
+ call assert_equal([1, 3, 1], searchpos('\%(\([a-z]\)\|\_.\)\{-}xyz', 'pcW'))
+
+ " Now with \zs, first match is in column 0, "a" is matched.
+ call cursor(1, 3)
+ call assert_equal([2, 4, 2], searchpos('\%(\([a-z]\)\|\_.\)\{-}\zsxyz', 'pcW'))
+ " With z flag start at cursor column, don't see the "a".
+ call cursor(1, 3)
+ call assert_equal([2, 4, 1], searchpos('\%(\([a-z]\)\|\_.\)\{-}\zsxyz', 'pcWz'))
+
+ set cpo+=c
+ " close the window
+ q!
+
+endfunc
+
+" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_set.vim b/src/nvim/testdir/test_set.vim
new file mode 100644
index 0000000000..2b1e9eeee0
--- /dev/null
+++ b/src/nvim/testdir/test_set.vim
@@ -0,0 +1,29 @@
+" Tests for the :set command
+
+function Test_set_backslash()
+ let isk_save = &isk
+
+ set isk=a,b,c
+ set isk+=d
+ call assert_equal('a,b,c,d', &isk)
+ set isk+=\\,e
+ call assert_equal('a,b,c,d,\,e', &isk)
+ set isk-=e
+ call assert_equal('a,b,c,d,\', &isk)
+ set isk-=\\
+ call assert_equal('a,b,c,d', &isk)
+
+ let &isk = isk_save
+endfunction
+
+function Test_set_add()
+ let wig_save = &wig
+
+ set wildignore=*.png,
+ set wildignore+=*.jpg
+ call assert_equal('*.png,*.jpg', &wig)
+
+ let &wig = wig_save
+endfunction
+
+" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_sort.vim b/src/nvim/testdir/test_sort.vim
index 570c4415c6..f72368fc59 100644
--- a/src/nvim/testdir/test_sort.vim
+++ b/src/nvim/testdir/test_sort.vim
@@ -12,6 +12,7 @@ func Compare2(a, b) abort
endfunc
func Test_sort_strings()
+ CheckNotMSWindows " FIXME: Why does this fail with MSVC?
" numbers compared as strings
call assert_equal([1, 2, 3], sort([3, 2, 1]))
call assert_equal([13, 28, 3], sort([3, 28, 13]))
diff --git a/src/nvim/testdir/test_stat.vim b/src/nvim/testdir/test_stat.vim
index b44f3e9b94..d3059664e9 100644
--- a/src/nvim/testdir/test_stat.vim
+++ b/src/nvim/testdir/test_stat.vim
@@ -7,7 +7,7 @@ func CheckFileTime(doSleep)
let times = []
let result = 0
- " Use three files istead of localtim(), with a network filesystem the file
+ " Use three files instead of localtim(), with a network filesystem the file
" times may differ at bit
let fl = ['Hello World!']
for fname in fnames
diff --git a/src/nvim/testdir/test_suspend.vim b/src/nvim/testdir/test_suspend.vim
index 4b3bd5eadf..bf88bd4453 100644
--- a/src/nvim/testdir/test_suspend.vim
+++ b/src/nvim/testdir/test_suspend.vim
@@ -26,8 +26,8 @@ func Test_suspend()
" Wait for shell prompt.
call WaitForAssert({-> assert_match('[$#] $', term_getline(buf, '.'))})
- call term_sendkeys(buf, v:progpath
- \ . " --clean -X"
+ call term_sendkeys(buf, GetVimCommandClean()
+ \ . " -X"
\ . " -c 'set nu'"
\ . " -c 'call setline(1, \"foo\")'"
\ . " Xfoo\<CR>")
diff --git a/src/nvim/testdir/test_system.vim b/src/nvim/testdir/test_system.vim
index 5b8079d7b6..18692f42c9 100644
--- a/src/nvim/testdir/test_system.vim
+++ b/src/nvim/testdir/test_system.vim
@@ -50,11 +50,11 @@ endfunc
func Test_system_exmode()
if has('unix') " echo $? only works on Unix
- let cmd = ' -es --headless -u NONE -c "source Xscript" +q; echo "result=$?"'
+ let cmd = ' -es -c "source Xscript" +q; echo "result=$?"'
" Need to put this in a script, "catch" isn't found after an unknown
" function.
call writefile(['try', 'call doesnotexist()', 'catch', 'endtry'], 'Xscript')
- let a = system(v:progpath . cmd)
+ let a = system(GetVimCommand() . cmd)
call assert_match('result=0', a)
call assert_equal(0, v:shell_error)
endif
@@ -62,33 +62,33 @@ func Test_system_exmode()
" Error before try does set error flag.
call writefile(['call nosuchfunction()', 'try', 'call doesnotexist()', 'catch', 'endtry'], 'Xscript')
if has('unix') " echo $? only works on Unix
- let a = system(v:progpath . cmd)
+ let a = system(GetVimCommand() . cmd)
call assert_notequal('0', a[0])
endif
- let cmd = ' -es --headless -u NONE -c "source Xscript" +q'
- let a = system(v:progpath . cmd)
+ let cmd = ' -es -c "source Xscript" +q'
+ let a = system(GetVimCommand() . cmd)
call assert_notequal(0, v:shell_error)
call delete('Xscript')
if has('unix') " echo $? only works on Unix
- let cmd = ' -es --headless -u NONE -c "call doesnotexist()" +q; echo $?'
- let a = system(v:progpath. cmd)
+ let cmd = ' -es -c "call doesnotexist()" +q; echo $?'
+ let a = system(GetVimCommand() . cmd)
call assert_notequal(0, a[0])
endif
- let cmd = ' -es --headless -u NONE -c "call doesnotexist()" +q'
- let a = system(v:progpath. cmd)
+ let cmd = ' -es -c "call doesnotexist()" +q'
+ let a = system(GetVimCommand(). cmd)
call assert_notequal(0, v:shell_error)
if has('unix') " echo $? only works on Unix
- let cmd = ' -es --headless -u NONE -c "call doesnotexist()|let a=1" +q; echo $?'
- let a = system(v:progpath. cmd)
+ let cmd = ' -es -c "call doesnotexist()|let a=1" +q; echo $?'
+ let a = system(GetVimCommand() . cmd)
call assert_notequal(0, a[0])
endif
- let cmd = ' -es --headless -u NONE -c "call doesnotexist()|let a=1" +q'
- let a = system(v:progpath. cmd)
+ let cmd = ' -es -c "call doesnotexist()|let a=1" +q'
+ let a = system(GetVimCommand() . cmd)
call assert_notequal(0, v:shell_error)
endfunc
diff --git a/src/nvim/testdir/test_tabline.vim b/src/nvim/testdir/test_tabline.vim
index 117d962d08..3a18206078 100644
--- a/src/nvim/testdir/test_tabline.vim
+++ b/src/nvim/testdir/test_tabline.vim
@@ -86,6 +86,17 @@ func Test_tabline_empty_group()
set tabline=
endfunc
+" When there are exactly 20 tabline format items (the exact size of the
+" initial tabline items array), test that we don't write beyond the size
+" of the array.
+func Test_tabline_20_format_items_no_overrun()
+ set showtabline=2
+
+ let tabline = repeat('%#StatColorHi2#', 20)
+ let &tabline = tabline
+ redrawtabline
+ set showtabline& tabline&
+endfunc
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_tabpage.vim b/src/nvim/testdir/test_tabpage.vim
index 9869dc7590..51ab5c1022 100644
--- a/src/nvim/testdir/test_tabpage.vim
+++ b/src/nvim/testdir/test_tabpage.vim
@@ -128,6 +128,8 @@ function Test_tabpage()
1tabmove
call assert_equal(2, tabpagenr())
+ call assert_fails('let t = tabpagenr("@")', 'E15:')
+ call assert_equal(0, tabpagewinnr(-1))
call assert_fails("99tabmove", 'E16:')
call assert_fails("+99tabmove", 'E16:')
call assert_fails("-99tabmove", 'E16:')
@@ -683,4 +685,73 @@ func Test_tabline_tabmenu()
%bw!
endfunc
+" Test for jumping to last accessed tabpage
+func Test_lastused_tabpage()
+ tabonly!
+ call assert_equal(0, tabpagenr('#'))
+ call assert_beeps('call feedkeys("g\<Tab>", "xt")')
+ call assert_beeps('call feedkeys("\<C-Tab>", "xt")')
+ call assert_beeps('call feedkeys("\<C-W>g\<Tab>", "xt")')
+ call assert_fails('tabnext #', 'E475:')
+
+ " open four tab pages
+ tabnew
+ tabnew
+ tabnew
+
+ 2tabnext
+
+ " Test for g<Tab>
+ call assert_equal(4, tabpagenr('#'))
+ call feedkeys("g\<Tab>", "xt")
+ call assert_equal(4, tabpagenr())
+ call assert_equal(2, tabpagenr('#'))
+
+ " Test for <C-Tab>
+ call feedkeys("\<C-Tab>", "xt")
+ call assert_equal(2, tabpagenr())
+ call assert_equal(4, tabpagenr('#'))
+
+ " Test for <C-W>g<Tab>
+ call feedkeys("\<C-W>g\<Tab>", "xt")
+ call assert_equal(4, tabpagenr())
+ call assert_equal(2, tabpagenr('#'))
+
+ " Test for :tabnext #
+ tabnext #
+ call assert_equal(2, tabpagenr())
+ call assert_equal(4, tabpagenr('#'))
+
+ " Try to jump to a closed tab page
+ tabclose #
+ call assert_equal(0, tabpagenr('#'))
+ call feedkeys("g\<Tab>", "xt")
+ call assert_equal(2, tabpagenr())
+ call feedkeys("\<C-Tab>", "xt")
+ call assert_equal(2, tabpagenr())
+ call feedkeys("\<C-W>g\<Tab>", "xt")
+ call assert_equal(2, tabpagenr())
+ call assert_fails('tabnext #', 'E475:')
+ call assert_equal(2, tabpagenr())
+
+ " Test for :tabonly #
+ let wnum = win_getid()
+ $tabnew
+ tabonly #
+ call assert_equal(wnum, win_getid())
+ call assert_equal(1, tabpagenr('$'))
+
+ " Test for :tabmove #
+ tabnew
+ let wnum = win_getid()
+ tabnew
+ tabnew
+ tabnext 2
+ tabmove #
+ call assert_equal(4, tabpagenr())
+ call assert_equal(wnum, win_getid())
+
+ tabonly!
+endfunc
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_usercommands.vim b/src/nvim/testdir/test_usercommands.vim
index 967ad85a64..e96e3d94e5 100644
--- a/src/nvim/testdir/test_usercommands.vim
+++ b/src/nvim/testdir/test_usercommands.vim
@@ -572,4 +572,24 @@ func Test_delcommand_buffer()
call assert_equal(0, exists(':Global'))
endfunc
+func DefCmd(name)
+ if len(a:name) > 30
+ return
+ endif
+ exe 'command ' .. a:name .. ' call DefCmd("' .. a:name .. 'x")'
+ echo a:name
+ exe a:name
+endfunc
+
+func Test_recursive_define()
+ call DefCmd('Command')
+
+ let name = 'Command'
+ while len(name) < 30
+ exe 'delcommand ' .. name
+ let name ..= 'x'
+ endwhile
+endfunc
+
+
" vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/nvim/testdir/test_vimscript.vim b/src/nvim/testdir/test_vimscript.vim
index 75a965f16d..f93eb6e274 100644
--- a/src/nvim/testdir/test_vimscript.vim
+++ b/src/nvim/testdir/test_vimscript.vim
@@ -1,6 +1,9 @@
" Test various aspects of the Vim script language.
" Most of this was formerly in test49.
+source check.vim
+source shared.vim
+
"-------------------------------------------------------------------------------
" Test environment {{{1
"-------------------------------------------------------------------------------
@@ -1744,7 +1747,7 @@ func Test_function_defined_line()
[CODE]
call writefile(lines, 'Xtest.vim')
- let res = system(v:progpath .. ' --clean -es -X -S Xtest.vim')
+ let res = system(GetVimCommandClean() .. ' -es -X -S Xtest.vim')
call assert_equal(0, v:shell_error)
let m = matchstr(res, 'function F1()[^[:print:]]*[[:print:]]*')
diff --git a/src/nvim/tui/input.c b/src/nvim/tui/input.c
index 6b889cf97c..917847608a 100644
--- a/src/nvim/tui/input.c
+++ b/src/nvim/tui/input.c
@@ -5,7 +5,7 @@
#include "nvim/api/private/helpers.h"
#include "nvim/api/vim.h"
#include "nvim/ascii.h"
-#include "nvim/aucmd.h"
+#include "nvim/autocmd.h"
#include "nvim/charset.h"
#include "nvim/ex_docmd.h"
#include "nvim/macros.h"
@@ -19,6 +19,7 @@
# include "nvim/os/os_win_console.h"
#endif
#include "nvim/event/rstream.h"
+#include "nvim/msgpack_rpc/channel.h"
#define KEY_BUFFER_SIZE 0xfff
@@ -115,6 +116,7 @@ static void tinput_wait_enqueue(void **argv)
{
TermInput *input = argv[0];
if (rbuffer_size(input->key_buffer) == 0 && input->paste == 3) {
+ // End streamed paste with an empty string.
const String keys = { .data = "", .size = 0 };
String copy = copy_string(keys);
multiqueue_put(main_loop.events, tinput_paste_event, 3,
@@ -124,8 +126,16 @@ static void tinput_wait_enqueue(void **argv)
const String keys = { .data = buf, .size = len };
if (input->paste) {
String copy = copy_string(keys);
- multiqueue_put(main_loop.events, tinput_paste_event, 3,
- copy.data, copy.size, (intptr_t)input->paste);
+ if (ui_client_channel_id) {
+ Array args = ARRAY_DICT_INIT;
+ ADD(args, STRING_OBJ(copy_string(keys))); // 'data'
+ ADD(args, BOOLEAN_OBJ(true)); // 'crlf'
+ ADD(args, INTEGER_OBJ(input->paste)); // 'phase'
+ rpc_send_event(ui_client_channel_id, "nvim_paste", args);
+ } else {
+ multiqueue_put(main_loop.events, tinput_paste_event, 3,
+ copy.data, copy.size, (intptr_t)input->paste);
+ }
if (input->paste == 1) {
// Paste phase: "continue"
input->paste = 2;
@@ -133,7 +143,17 @@ static void tinput_wait_enqueue(void **argv)
rbuffer_consumed(input->key_buffer, len);
rbuffer_reset(input->key_buffer);
} else {
- const size_t consumed = input_enqueue(keys);
+ size_t consumed;
+ if (ui_client_channel_id) {
+ Array args = ARRAY_DICT_INIT;
+ Error err = ERROR_INIT;
+ ADD(args, STRING_OBJ(copy_string(keys)));
+ // TODO(bfredl): could be non-blocking now with paste?
+ Object result = rpc_send_call(ui_client_channel_id, "nvim_input", args, &err);
+ consumed = result.type == kObjectTypeInteger ? (size_t)result.data.integer : 0;
+ } else {
+ consumed = input_enqueue(keys);
+ }
if (consumed) {
rbuffer_consumed(input->key_buffer, consumed);
}
@@ -378,7 +398,7 @@ static bool handle_focus_event(TermInput *input)
bool focus_gained = *rbuffer_get(input->read_stream.buffer, 2) == 'I';
// Advance past the sequence
rbuffer_consumed(input->read_stream.buffer, 3);
- aucmd_schedule_focusgained(focus_gained);
+ autocmd_schedule_focusgained(focus_gained);
return true;
}
return false;
diff --git a/src/nvim/tui/tui.c b/src/nvim/tui/tui.c
index 58061f020d..79a6b9ed0e 100644
--- a/src/nvim/tui/tui.c
+++ b/src/nvim/tui/tui.c
@@ -528,7 +528,7 @@ static bool attrs_differ(UI *ui, int id1, int id2, bool rgb)
return a1.cterm_fg_color != a2.cterm_fg_color
|| a1.cterm_bg_color != a2.cterm_bg_color
|| a1.cterm_ae_attr != a2.cterm_ae_attr
- || (a1.cterm_ae_attr & (HL_UNDERLINE|HL_UNDERCURL)
+ || (a1.cterm_ae_attr & HL_ANY_UNDERLINE
&& a1.rgb_sp_color != a2.rgb_sp_color);
}
}
@@ -552,15 +552,27 @@ static void update_attrs(UI *ui, int attr_id)
bool strikethrough = attr & HL_STRIKETHROUGH;
bool underline;
+ bool underlineline;
bool undercurl;
+ bool underdot;
+ bool underdash;
if (data->unibi_ext.set_underline_style != -1) {
underline = attr & HL_UNDERLINE;
+ underlineline = attr & HL_UNDERLINELINE;
undercurl = attr & HL_UNDERCURL;
+ underdash = attr & HL_UNDERDASH;
+ underdot = attr & HL_UNDERDOT;
} else {
- underline = (attr & HL_UNDERLINE) || (attr & HL_UNDERCURL);
+ underline = attr & HL_ANY_UNDERLINE;
+ underlineline = false;
undercurl = false;
+ underdot = false;
+ underdash = false;
}
+ bool has_any_underline = undercurl || underline
+ || underdot || underdash || underlineline;
+
if (unibi_get_str(data->ut, unibi_set_attributes)) {
if (bold || reverse || underline || standout) {
UNIBI_SET_NUM_VAR(data->params[0], standout);
@@ -599,11 +611,24 @@ static void update_attrs(UI *ui, int attr_id)
if (strikethrough && data->unibi_ext.enter_strikethrough_mode != -1) {
unibi_out_ext(ui, data->unibi_ext.enter_strikethrough_mode);
}
+ if (underlineline && data->unibi_ext.set_underline_style != -1) {
+ UNIBI_SET_NUM_VAR(data->params[0], 2);
+ unibi_out_ext(ui, data->unibi_ext.set_underline_style);
+ }
if (undercurl && data->unibi_ext.set_underline_style != -1) {
UNIBI_SET_NUM_VAR(data->params[0], 3);
unibi_out_ext(ui, data->unibi_ext.set_underline_style);
}
- if ((undercurl || underline) && data->unibi_ext.set_underline_color != -1) {
+ if (underdot && data->unibi_ext.set_underline_style != -1) {
+ UNIBI_SET_NUM_VAR(data->params[0], 4);
+ unibi_out_ext(ui, data->unibi_ext.set_underline_style);
+ }
+ if (underdash && data->unibi_ext.set_underline_style != -1) {
+ UNIBI_SET_NUM_VAR(data->params[0], 5);
+ unibi_out_ext(ui, data->unibi_ext.set_underline_style);
+ }
+
+ if (has_any_underline && data->unibi_ext.set_underline_color != -1) {
int color = attrs.rgb_sp_color;
if (color != -1) {
UNIBI_SET_NUM_VAR(data->params[0], (color >> 16) & 0xff); // red
@@ -652,13 +677,13 @@ static void update_attrs(UI *ui, int attr_id)
data->default_attr = fg == -1 && bg == -1
- && !bold && !italic && !underline && !undercurl && !reverse && !standout
+ && !bold && !italic && !has_any_underline && !reverse && !standout
&& !strikethrough;
// Non-BCE terminals can't clear with non-default background color. Some BCE
// terminals don't support attributes either, so don't rely on it. But assume
// italic and bold has no effect if there is no text.
- data->can_clear_attr = !reverse && !standout && !underline && !undercurl
+ data->can_clear_attr = !reverse && !standout && !has_any_underline
&& !strikethrough && (data->bce || bg == -1);
}
@@ -1450,8 +1475,8 @@ static void tui_guess_size(UI *ui)
// 1 - look for non-default 'columns' and 'lines' options during startup
if (data->is_starting && (Columns != DFLT_COLS || Rows != DFLT_ROWS)) {
did_user_set_dimensions = true;
- assert(Columns >= INT_MIN && Columns <= INT_MAX);
- assert(Rows >= INT_MIN && Rows <= INT_MAX);
+ assert(Columns >= 0);
+ assert(Rows >= 0);
width = Columns;
height = Rows;
goto end;
diff --git a/src/nvim/ui.c b/src/nvim/ui.c
index 1aadaf5c9d..da50f068b7 100644
--- a/src/nvim/ui.c
+++ b/src/nvim/ui.c
@@ -8,10 +8,11 @@
#include <string.h>
#include "nvim/ascii.h"
-#include "nvim/aucmd.h"
+#include "nvim/autocmd.h"
#include "nvim/charset.h"
#include "nvim/cursor.h"
#include "nvim/cursor_shape.h"
+#include "nvim/msgpack_rpc/channel.h"
#include "nvim/diff.h"
#include "nvim/event/loop.h"
#include "nvim/ex_cmds2.h"
@@ -224,7 +225,21 @@ void ui_refresh(void)
int save_p_lz = p_lz;
p_lz = false; // convince redrawing() to return true ...
- screen_resize(width, height);
+ if (!ui_client_channel_id) {
+ screen_resize(width, height);
+ } else {
+ Array args = ARRAY_DICT_INIT;
+ Error err = ERROR_INIT;
+ ADD(args, INTEGER_OBJ((int)width));
+ ADD(args, INTEGER_OBJ((int)height));
+ rpc_send_call(ui_client_channel_id, "nvim_ui_try_resize", args, &err);
+
+ if (ERROR_SET(&err)) {
+ ELOG("ui_client resize: %s", err.msg);
+ }
+ api_clear_error(&err);
+ }
+
p_lz = save_p_lz;
if (ext_widgets[kUIMessages]) {
@@ -639,8 +654,8 @@ void ui_grid_resize(handle_T grid_handle, int width, int height, Error *error)
}
} else {
// non-positive indicates no request
- wp->w_height_request = (int)MAX(height, 0);
- wp->w_width_request = (int)MAX(width, 0);
+ wp->w_height_request = MAX(height, 0);
+ wp->w_width_request = MAX(width, 0);
win_set_inner_size(wp);
}
}
diff --git a/src/nvim/ui_client.c b/src/nvim/ui_client.c
new file mode 100644
index 0000000000..6e45a28e89
--- /dev/null
+++ b/src/nvim/ui_client.c
@@ -0,0 +1,215 @@
+// 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 <stdbool.h>
+#include <stdint.h>
+#include <assert.h>
+
+#include "nvim/vim.h"
+#include "nvim/log.h"
+#include "nvim/map.h"
+#include "nvim/ui_client.h"
+#include "nvim/api/private/helpers.h"
+#include "nvim/msgpack_rpc/channel.h"
+#include "nvim/api/private/dispatch.h"
+#include "nvim/ui.h"
+#include "nvim/highlight.h"
+#include "nvim/screen.h"
+
+static Map(String, UIClientHandler) ui_client_handlers = MAP_INIT;
+
+// Temporary buffer for converting a single grid_line event
+static size_t buf_size = 0;
+static schar_T *buf_char = NULL;
+static sattr_T *buf_attr = NULL;
+
+static void add_ui_client_event_handler(String method, UIClientHandler handler)
+{
+ map_put(String, UIClientHandler)(&ui_client_handlers, method, handler);
+}
+
+void ui_client_init(uint64_t chan)
+{
+ Array args = ARRAY_DICT_INIT;
+ int width = Columns;
+ int height = Rows;
+ Dictionary opts = ARRAY_DICT_INIT;
+
+ PUT(opts, "rgb", BOOLEAN_OBJ(true));
+ PUT(opts, "ext_linegrid", BOOLEAN_OBJ(true));
+ PUT(opts, "ext_termcolors", BOOLEAN_OBJ(true));
+
+ ADD(args, INTEGER_OBJ((int)width));
+ ADD(args, INTEGER_OBJ((int)height));
+ ADD(args, DICTIONARY_OBJ(opts));
+
+ rpc_send_event(chan, "nvim_ui_attach", args);
+ msgpack_rpc_add_redraw(); // GAME!
+ // TODO(bfredl): use a keyset instead
+ ui_client_methods_table_init();
+ ui_client_channel_id = chan;
+}
+
+/// Handler for "redraw" events sent by the NVIM server
+///
+/// This function will be called by handle_request (in msgpack_rpc/channel.c)
+/// The individual ui_events sent by the server are individually handled
+/// by their respective handlers defined in ui_events_client.generated.h
+///
+/// @note The "flush" event is called only once and only after handling all
+/// the other events
+/// @param channel_id: The id of the rpc channel
+/// @param uidata: The dense array containing the ui_events sent by the server
+/// @param[out] err Error details, if any
+Object ui_client_handle_redraw(uint64_t channel_id, Array args, Error *error)
+{
+ for (size_t i = 0; i < args.size; i++) {
+ Array call = args.items[i].data.array;
+ String name = call.items[0].data.string;
+
+ UIClientHandler handler = map_get(String, UIClientHandler)(&ui_client_handlers, name);
+ if (!handler) {
+ ELOG("No ui client handler for %s", name.size ? name.data : "<empty>");
+ continue;
+ }
+
+ // fprintf(stderr, "%s: %zu\n", name.data, call.size-1);
+ DLOG("Invoke ui client handler for %s", name.data);
+ for (size_t j = 1; j < call.size; j++) {
+ handler(call.items[j].data.array);
+ }
+ }
+
+ return NIL;
+}
+
+/// run the main thread in ui client mode
+///
+/// This is just a stub. the full version will handle input, resizing, etc
+void ui_client_execute(uint64_t chan)
+{
+ while (true) {
+ loop_poll_events(&main_loop, -1);
+ multiqueue_process_events(resize_events);
+ }
+
+ getout(0);
+}
+
+static HlAttrs ui_client_dict2hlattrs(Dictionary d, bool rgb)
+{
+ Error err = ERROR_INIT;
+ Dict(highlight) dict = { 0 };
+ if (!api_dict_to_keydict(&dict, KeyDict_highlight_get_field, d, &err)) {
+ // TODO(bfredl): log "err"
+ return HLATTRS_INIT;
+ }
+ return dict2hlattrs(&dict, true, NULL, &err);
+}
+
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+#include "ui_events_client.generated.h"
+#endif
+
+void ui_client_event_grid_resize(Array args)
+{
+ if (args.size < 3
+ || args.items[0].type != kObjectTypeInteger
+ || args.items[1].type != kObjectTypeInteger
+ || args.items[2].type != kObjectTypeInteger) {
+ ELOG("Error handling ui event 'grid_resize'");
+ return;
+ }
+
+ Integer grid = args.items[0].data.integer;
+ Integer width = args.items[1].data.integer;
+ Integer height = args.items[2].data.integer;
+ ui_call_grid_resize(grid, width, height);
+
+ if (buf_size < (size_t)width) {
+ xfree(buf_char);
+ xfree(buf_attr);
+ buf_size = (size_t)width;
+ buf_char = xmalloc(buf_size * sizeof(schar_T));
+ buf_attr = xmalloc(buf_size * sizeof(sattr_T));
+ }
+}
+
+void ui_client_event_grid_line(Array args)
+{
+ if (args.size < 4
+ || args.items[0].type != kObjectTypeInteger
+ || args.items[1].type != kObjectTypeInteger
+ || args.items[2].type != kObjectTypeInteger
+ || args.items[3].type != kObjectTypeArray) {
+ goto error;
+ }
+
+ Integer grid = args.items[0].data.integer;
+ Integer row = args.items[1].data.integer;
+ Integer startcol = args.items[2].data.integer;
+ Array cells = args.items[3].data.array;
+
+ Integer endcol, clearcol;
+ // TODO(hlpr98): Accomodate other LineFlags when included in grid_line
+ LineFlags lineflags = 0;
+ endcol = startcol;
+
+ size_t j = 0;
+ int cur_attr = 0;
+ int clear_attr = 0;
+ int clear_width = 0;
+ for (size_t i = 0; i < cells.size; i++) {
+ if (cells.items[i].type != kObjectTypeArray) {
+ goto error;
+ }
+ Array cell = cells.items[i].data.array;
+
+ if (cell.size < 1 || cell.items[0].type != kObjectTypeString) {
+ goto error;
+ }
+ String sstring = cell.items[0].data.string;
+
+ char *schar = sstring.data;
+ int repeat = 1;
+ if (cell.size >= 2) {
+ if (cell.items[1].type != kObjectTypeInteger
+ || cell.items[1].data.integer < 0) {
+ goto error;
+ }
+ cur_attr = (int)cell.items[1].data.integer;
+ }
+
+ if (cell.size >= 3) {
+ if (cell.items[2].type != kObjectTypeInteger
+ || cell.items[2].data.integer < 0) {
+ goto error;
+ }
+ repeat = (int)cell.items[2].data.integer;
+ }
+
+ if (i == cells.size - 1 && sstring.size == 1 && sstring.data[0] == ' ' && repeat > 1) {
+ clear_width = repeat;
+ break;
+ }
+
+ for (int r = 0; r < repeat; r++) {
+ if (j >= buf_size) {
+ goto error; // _YIKES_
+ }
+ STRLCPY(buf_char[j], schar, sizeof(schar_T));
+ buf_attr[j++] = cur_attr;
+ }
+ }
+
+ endcol = startcol + (int)j;
+ clearcol = endcol + clear_width;
+ clear_attr = cur_attr;
+
+ ui_call_raw_line(grid, row, startcol, endcol, clearcol, clear_attr, lineflags,
+ (const schar_T *)buf_char, (const sattr_T *)buf_attr);
+ return;
+
+error:
+ ELOG("Error handling ui event 'grid_line'");
+}
diff --git a/src/nvim/ui_client.h b/src/nvim/ui_client.h
new file mode 100644
index 0000000000..253deecc52
--- /dev/null
+++ b/src/nvim/ui_client.h
@@ -0,0 +1,13 @@
+#ifndef NVIM_UI_CLIENT_H
+#define NVIM_UI_CLIENT_H
+
+#include "nvim/api/private/defs.h"
+
+typedef void (*UIClientHandler)(Array args);
+
+#ifdef INCLUDE_GENERATED_DECLARATIONS
+#include "ui_client.h.generated.h"
+#include "ui_events_client.h.generated.h"
+#endif
+
+#endif // NVIM_UI_CLIENT_H
diff --git a/src/nvim/undo_defs.h b/src/nvim/undo_defs.h
index 3267b2f71e..d8470b07b1 100644
--- a/src/nvim/undo_defs.h
+++ b/src/nvim/undo_defs.h
@@ -33,8 +33,8 @@ struct u_entry {
};
struct u_header {
- /* The following have a pointer and a number. The number is used when
- * reading the undo file in u_read_undo() */
+ // The following have a pointer and a number. The number is used when reading
+ // the undo file in u_read_undo()
union {
u_header_T *ptr; // pointer to next undo header in list
long seq;
@@ -80,4 +80,4 @@ typedef struct {
FILE *bi_fp;
} bufinfo_T;
-#endif // NVIM_UNDO_DEFS_H
+#endif // NVIM_UNDO_DEFS_H
diff --git a/src/nvim/vim.h b/src/nvim/vim.h
index 6e0e9922a6..5d632b1b25 100644
--- a/src/nvim/vim.h
+++ b/src/nvim/vim.h
@@ -217,9 +217,9 @@ enum { FOLD_TEXT_LEN = 51, }; //!< buffer size for get_foldtext()
#define STRLEN(s) strlen((char *)(s))
#ifdef HAVE_STRNLEN
-# define STRNLEN(s, n) strnlen((char *)(s), (size_t)(n))
+# define STRNLEN(s, n) strnlen((char *)(s), (size_t)(n))
#else
-# define STRNLEN(s, n) xstrnlen((char *)(s), (size_t)(n))
+# define STRNLEN(s, n) xstrnlen((char *)(s), (size_t)(n))
#endif
#define STRCPY(d, s) strcpy((char *)(d), (char *)(s))
#define STRNCPY(d, s, n) strncpy((char *)(d), (char *)(s), (size_t)(n))
diff --git a/src/nvim/viml/parser/expressions.c b/src/nvim/viml/parser/expressions.c
index 8a14710351..9d1318724e 100644
--- a/src/nvim/viml/parser/expressions.c
+++ b/src/nvim/viml/parser/expressions.c
@@ -1592,7 +1592,7 @@ typedef struct {
/// string is a regex.
/// @param[in] is_invalid Whether currently processed token is not valid.
static void parse_quoted_string(ParserState *const pstate, ExprASTNode *const node,
- const LexExprToken token, const ExprASTStack ast_stack,
+ const LexExprToken token, const ExprASTStack *ast_stack,
const bool is_invalid)
FUNC_ATTR_NONNULL_ALL
{
@@ -2907,7 +2907,7 @@ viml_pexpr_parse_no_paren_closing_error: {}
? kExprNodeDoubleQuotedString
: kExprNodeSingleQuotedString));
*top_node_p = cur_node;
- parse_quoted_string(pstate, cur_node, cur_token, ast_stack, is_invalid);
+ parse_quoted_string(pstate, cur_node, cur_token, &ast_stack, is_invalid);
want_node = kENodeOperator;
break;
}
diff --git a/src/nvim/viml/parser/parser.h b/src/nvim/viml/parser/parser.h
index b2933c3781..b8835127e7 100644
--- a/src/nvim/viml/parser/parser.h
+++ b/src/nvim/viml/parser/parser.h
@@ -81,10 +81,8 @@ typedef struct {
bool can_continuate;
} ParserState;
-static inline void viml_parser_init(
- ParserState *const ret_pstate,
- const ParserLineGetter get_line, void *const cookie,
- ParserHighlight *const colors)
+static inline void viml_parser_init(ParserState *const ret_pstate, const ParserLineGetter get_line,
+ void *const cookie, ParserHighlight *const colors)
REAL_FATTR_ALWAYS_INLINE REAL_FATTR_NONNULL_ARG(1, 2);
/// Initialize a new parser state instance
diff --git a/src/nvim/window.c b/src/nvim/window.c
index 43667377c5..e9c7d0d8e2 100644
--- a/src/nvim/window.c
+++ b/src/nvim/window.c
@@ -60,7 +60,7 @@
#define NOWIN (win_T *)-1 // non-existing window
-#define ROWS_AVAIL (Rows - p_ch - tabline_height())
+#define ROWS_AVAIL (Rows - p_ch - tabline_height() - global_stl_height())
/// flags for win_enter_ext()
typedef enum {
@@ -73,6 +73,15 @@ typedef enum {
static char *m_onlyone = N_("Already only one window");
+/// @return the current window, unless in the cmdline window and "prevwin" is
+/// set, then return "prevwin".
+win_T *prevwin_curwin(void)
+ FUNC_ATTR_WARN_UNUSED_RESULT
+{
+ // In cmdwin, the alternative buffer should be used.
+ return is_in_cmdwin() && prevwin != NULL ? prevwin : curwin;
+}
+
/// all CTRL-W window commands are handled here, called from normal_cmd().
///
/// @param xchar extra char from ":wincmd gx" or NUL
@@ -521,10 +530,6 @@ wingotofile:
do_nv_ident('g', xchar);
break;
- case TAB:
- goto_tabpage_lastused();
- break;
-
case 'f': // CTRL-W gf: "gf" in a new tab page
case 'F': // CTRL-W gF: "gF" in a new tab page
cmdmod.tab = tabpage_index(curtab) + 1;
@@ -538,6 +543,12 @@ wingotofile:
goto_tabpage(-(int)Prenum1);
break;
+ case TAB: // CTRL-W g<Tab>: go to last used tab page
+ if (!goto_tabpage_lastused()) {
+ beep_flush();
+ }
+ break;
+
case 'e':
if (curwin->w_floating || !ui_has(kUIMultigrid)) {
beep_flush();
@@ -647,6 +658,7 @@ win_T *win_new_float(win_T *wp, FloatConfig fconfig, Error *err)
}
wp->w_floating = 1;
wp->w_status_height = 0;
+ wp->w_hsep_height = 0;
wp->w_vsep_width = 0;
win_config_float(wp, fconfig);
@@ -956,8 +968,14 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
int before;
int minheight;
int wmh1;
+ int hsep_height;
bool did_set_fraction = false;
+ // aucmd_win should always remain floating
+ if (new_wp != NULL && new_wp == aucmd_win) {
+ return FAIL;
+ }
+
if (flags & WSP_TOP) {
oldwin = firstwin;
} else if (flags & WSP_BOT || curwin->w_floating) {
@@ -1063,6 +1081,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
}
}
} else {
+ hsep_height = global_stl_height() > 0 ? 1 : STATUS_HEIGHT;
layout = FR_COL;
/*
@@ -1071,7 +1090,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
*/
// Current window requires at least 1 space.
wmh1 = p_wmh == 0 ? 1 : p_wmh;
- needed = wmh1 + STATUS_HEIGHT;
+ needed = wmh1 + hsep_height;
if (flags & WSP_ROOM) {
needed += p_wh - wmh1;
}
@@ -1113,15 +1132,15 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
new_size = oldwin_height / 2;
}
- if (new_size > available - minheight - STATUS_HEIGHT) {
- new_size = available - minheight - STATUS_HEIGHT;
+ if (new_size > available - minheight - hsep_height) {
+ new_size = available - minheight - hsep_height;
}
if (new_size < wmh1) {
new_size = wmh1;
}
// if it doesn't fit in the current window, need win_equal()
- if (oldwin_height - new_size - STATUS_HEIGHT < p_wmh) {
+ if (oldwin_height - new_size - hsep_height < p_wmh) {
do_equal = true;
}
@@ -1134,7 +1153,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
set_fraction(oldwin);
did_set_fraction = true;
- win_setheight_win(oldwin->w_height + new_size + STATUS_HEIGHT,
+ win_setheight_win(oldwin->w_height + new_size + hsep_height,
oldwin);
oldwin_height = oldwin->w_height;
if (need_status) {
@@ -1151,8 +1170,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
while (frp != NULL) {
if (frp->fr_win != oldwin && frp->fr_win != NULL
&& (frp->fr_win->w_height > new_size
- || frp->fr_win->w_height > oldwin_height - new_size
- - STATUS_HEIGHT)) {
+ || frp->fr_win->w_height > oldwin_height - new_size - hsep_height)) {
do_equal = true;
break;
}
@@ -1278,13 +1296,15 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
if (flags & (WSP_TOP | WSP_BOT)) {
// set height and row of new window to full height
wp->w_winrow = tabline_height();
- win_new_height(wp, curfrp->fr_height - (p_ls > 0));
- wp->w_status_height = (p_ls > 0);
+ win_new_height(wp, curfrp->fr_height - (p_ls == 1 || p_ls == 2));
+ wp->w_status_height = (p_ls == 1 || p_ls == 2);
+ wp->w_hsep_height = 0;
} else {
// height and row of new window is same as current window
wp->w_winrow = oldwin->w_winrow;
win_new_height(wp, oldwin->w_height);
wp->w_status_height = oldwin->w_status_height;
+ wp->w_hsep_height = oldwin->w_hsep_height;
}
frp->fr_height = curfrp->fr_height;
@@ -1317,6 +1337,7 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
frame_fix_width(oldwin);
frame_fix_width(wp);
} else {
+ bool is_stl_global = global_stl_height() > 0;
// width and column of new window is same as current window
if (flags & (WSP_TOP | WSP_BOT)) {
wp->w_wincol = 0;
@@ -1332,28 +1353,53 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
// "new_size" of the current window goes to the new window, use
// one row for the status line
win_new_height(wp, new_size);
+ if (before) {
+ wp->w_hsep_height = is_stl_global ? 1 : 0;
+ } else {
+ wp->w_hsep_height = oldwin->w_hsep_height;
+ oldwin->w_hsep_height = is_stl_global ? 1 : 0;
+ }
if (flags & (WSP_TOP | WSP_BOT)) {
int new_fr_height = curfrp->fr_height - new_size;
- if (!((flags & WSP_BOT) && p_ls == 0)) {
+ if (!((flags & WSP_BOT) && p_ls == 0) && global_stl_height() == 0) {
new_fr_height -= STATUS_HEIGHT;
+ } else if (global_stl_height() > 0) {
+ if (flags & WSP_BOT) {
+ frame_add_hsep(curfrp);
+ } else {
+ new_fr_height -= 1;
+ }
}
frame_new_height(curfrp, new_fr_height, flags & WSP_TOP, false);
} else {
- win_new_height(oldwin, oldwin_height - (new_size + STATUS_HEIGHT));
+ win_new_height(oldwin, oldwin_height - (new_size
+ + (global_stl_height() > 0 ? 1 : STATUS_HEIGHT)));
}
+
if (before) { // new window above current one
wp->w_winrow = oldwin->w_winrow;
- wp->w_status_height = STATUS_HEIGHT;
- oldwin->w_winrow += wp->w_height + STATUS_HEIGHT;
+
+ if (is_stl_global) {
+ wp->w_status_height = 0;
+ oldwin->w_winrow += wp->w_height + 1;
+ } else {
+ wp->w_status_height = STATUS_HEIGHT;
+ oldwin->w_winrow += wp->w_height + STATUS_HEIGHT;
+ }
} else { // new window below current one
- wp->w_winrow = oldwin->w_winrow + oldwin->w_height + STATUS_HEIGHT;
- wp->w_status_height = oldwin->w_status_height;
- if (!(flags & WSP_BOT)) {
- oldwin->w_status_height = STATUS_HEIGHT;
+ if (is_stl_global) {
+ wp->w_winrow = oldwin->w_winrow + oldwin->w_height + 1;
+ wp->w_status_height = 0;
+ } else {
+ wp->w_winrow = oldwin->w_winrow + oldwin->w_height + STATUS_HEIGHT;
+ wp->w_status_height = oldwin->w_status_height;
+ if (!(flags & WSP_BOT)) {
+ oldwin->w_status_height = STATUS_HEIGHT;
+ }
}
}
- if (flags & WSP_BOT) {
+ if ((flags & WSP_BOT) && global_stl_height() == 0) {
frame_add_statusline(curfrp);
}
frame_fix_height(wp);
@@ -1415,13 +1461,11 @@ int win_split_ins(int size, int flags, win_T *new_wp, int dir)
p_wh = i;
}
- if (!win_valid(oldwin)) {
- return FAIL;
+ if (win_valid(oldwin)) {
+ // Send the window positions to the UI
+ oldwin->w_pos_changed = true;
}
- // Send the window positions to the UI
- oldwin->w_pos_changed = true;
-
return OK;
}
@@ -1595,10 +1639,10 @@ int make_windows(int count, bool vertical)
maxcount = (curwin->w_width + curwin->w_vsep_width
- (p_wiw - p_wmw)) / (p_wmw + 1);
} else {
- // Each window needs at least 'winminheight' lines and a status line.
- maxcount = (curwin->w_height
- + curwin->w_status_height
- - (p_wh - p_wmh)) / (p_wmh + STATUS_HEIGHT);
+ // Each window needs at least 'winminheight' lines
+ // If statusline isn't global, each window also needs a statusline
+ maxcount = (curwin->w_height + curwin->w_hsep_height + curwin->w_status_height
+ - (p_wh - p_wmh)) / (p_wmh + (global_stl_height() > 0 ? 1 : STATUS_HEIGHT));
}
if (maxcount < 2) {
@@ -1693,7 +1737,7 @@ static void win_exchange(long Prenum)
* if wp != wp2
* 3. remove wp from the list
* 4. insert wp after wp2
- * 5. exchange the status line height and vsep width.
+ * 5. exchange the status line height, hsep height and vsep width.
*/
wp2 = curwin->w_prev;
frp2 = curwin->w_frame->fr_prev;
@@ -1719,6 +1763,9 @@ static void win_exchange(long Prenum)
temp = curwin->w_vsep_width;
curwin->w_vsep_width = wp->w_vsep_width;
wp->w_vsep_width = temp;
+ temp = curwin->w_hsep_height;
+ curwin->w_hsep_height = wp->w_hsep_height;
+ wp->w_hsep_height = temp;
frame_fix_height(curwin);
frame_fix_height(wp);
@@ -1799,10 +1846,13 @@ static void win_rotate(bool upwards, int count)
frame_insert(frp->fr_parent->fr_child, frp);
}
- // exchange status height and vsep width of old and new last window
+ // exchange status height, hsep height and vsep width of old and new last window
n = wp2->w_status_height;
wp2->w_status_height = wp1->w_status_height;
wp1->w_status_height = n;
+ n = wp2->w_hsep_height;
+ wp2->w_hsep_height = wp1->w_hsep_height;
+ wp1->w_hsep_height = n;
frame_fix_height(wp1);
frame_fix_height(wp2);
n = wp2->w_vsep_width;
@@ -1833,6 +1883,9 @@ static void win_totop(int size, int flags)
beep_flush();
return;
}
+ if (curwin == aucmd_win) {
+ return;
+ }
if (curwin->w_floating) {
ui_comp_remove_grid(&curwin->w_grid_alloc);
@@ -1876,11 +1929,16 @@ void win_move_after(win_T *win1, win_T *win2)
// check if there is something to do
if (win2->w_next != win1) {
- // may need move the status line/vertical separator of the last window
+ // may need move the status line, horizontal or vertical separator of the last window
if (win1 == lastwin) {
height = win1->w_prev->w_status_height;
win1->w_prev->w_status_height = win1->w_status_height;
win1->w_status_height = height;
+
+ height = win1->w_prev->w_hsep_height;
+ win1->w_prev->w_hsep_height = win1->w_hsep_height;
+ win1->w_hsep_height = height;
+
if (win1->w_prev->w_vsep_width == 1) {
// Remove the vertical separator from the last-but-one window,
// add it to the last window. Adjust the frame widths.
@@ -1893,6 +1951,11 @@ void win_move_after(win_T *win1, win_T *win2)
height = win1->w_status_height;
win1->w_status_height = win2->w_status_height;
win2->w_status_height = height;
+
+ height = win1->w_hsep_height;
+ win1->w_hsep_height = win2->w_hsep_height;
+ win2->w_hsep_height = height;
+
if (win1->w_vsep_width == 1) {
// Remove the vertical separator from win1, add it to the last
// window, win2. Adjust the frame widths.
@@ -1956,6 +2019,7 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int
int room = 0;
int new_size;
int has_next_curwin = 0;
+ int hsep_height;
bool hnc;
if (topfr->fr_layout == FR_LEAF) {
@@ -2101,19 +2165,22 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int
totwincount -= wincount;
}
} else { // topfr->fr_layout == FR_COL
+ hsep_height = global_stl_height() > 0 ? 1 : STATUS_HEIGHT;
topfr->fr_width = width;
topfr->fr_height = height;
if (dir != 'h') { // equalize frame heights
// Compute maximum number of windows vertically in this frame.
n = frame_minheight(topfr, NOWIN);
- // add one for the bottom window if it doesn't have a statusline
+ // add one for the bottom window if it doesn't have a statusline or separator
if (row + height == cmdline_row && p_ls == 0) {
+ extra_sep = STATUS_HEIGHT;
+ } else if (global_stl_height() > 0) {
extra_sep = 1;
} else {
extra_sep = 0;
}
- totwincount = (n + extra_sep) / (p_wmh + 1);
+ totwincount = (n + extra_sep) / (p_wmh + hsep_height);
has_next_curwin = frame_has_win(topfr, next_curwin);
/*
@@ -2148,7 +2215,7 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int
} else {
// These windows don't use up room.
totwincount -= (n + (fr->fr_next == NULL
- ? extra_sep : 0)) / (p_wmh + 1);
+ ? extra_sep : 0)) / (p_wmh + hsep_height);
}
room -= new_size - n;
if (room < 0) {
@@ -2194,7 +2261,7 @@ static void win_equal_rec(win_T *next_curwin, bool current, frame_T *topfr, int
// Compute the maximum number of windows vert. in "fr".
n = frame_minheight(fr, NOWIN);
wincount = (n + (fr->fr_next == NULL ? extra_sep : 0))
- / (p_wmh + 1);
+ / (p_wmh + hsep_height);
m = frame_minheight(fr, next_curwin);
if (has_next_curwin) {
hnc = frame_has_win(fr, next_curwin);
@@ -2590,6 +2657,13 @@ int win_close(win_T *win, bool free_buf, bool force)
reset_synblock(win);
}
+ // When a quickfix/location list window is closed and the buffer is
+ // displayed in only one window, then unlist the buffer.
+ if (win->w_buffer != NULL && bt_quickfix(win->w_buffer)
+ && win->w_buffer->b_nwindows == 1) {
+ win->w_buffer->b_p_bl = false;
+ }
+
/*
* Close the link to the buffer.
*/
@@ -2882,6 +2956,9 @@ void win_free_all(void)
{
int dummy;
+ // avoid an error for switching tabpage with the cmdline window open
+ cmdwin_type = 0;
+
while (first_tabpage->tp_next != NULL) {
tabpage_close(TRUE);
}
@@ -3140,7 +3217,7 @@ static tabpage_T *alt_tabpage(void)
/*
* Find the left-upper window in frame "frp".
*/
-static win_T *frame2win(frame_T *frp)
+win_T *frame2win(frame_T *frp)
{
while (frp->fr_win == NULL) {
frp = frp->fr_child;
@@ -3167,23 +3244,40 @@ static bool frame_has_win(const frame_T *frp, const win_T *wp)
return false;
}
+/// Check if current window is at the bottom
+/// Returns true if there are no windows below current window
+static bool is_bottom_win(win_T *wp)
+ FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
+{
+ frame_T *frp;
+ for (frp = wp->w_frame; frp->fr_parent != NULL; frp = frp->fr_parent) {
+ if (frp->fr_parent->fr_layout == FR_COL && frp->fr_next != NULL) {
+ return false;
+ }
+ }
+ return true;
+}
/// Set a new height for a frame. Recursively sets the height for contained
/// frames and windows. Caller must take care of positions.
///
/// @param topfirst resize topmost contained frame first.
/// @param wfh obey 'winfixheight' when there is a choice;
/// may cause the height not to be set.
-static void frame_new_height(frame_T *topfrp, int height, bool topfirst, bool wfh)
+void frame_new_height(frame_T *topfrp, int height, bool topfirst, bool wfh)
FUNC_ATTR_NONNULL_ALL
{
frame_T *frp;
int extra_lines;
int h;
+ win_T *wp;
if (topfrp->fr_win != NULL) {
// Simple case: just one window.
- win_new_height(topfrp->fr_win,
- height - topfrp->fr_win->w_status_height);
+ wp = topfrp->fr_win;
+ if (is_bottom_win(wp)) {
+ wp->w_hsep_height = 0;
+ }
+ win_new_height(wp, height - wp->w_hsep_height - wp->w_status_height);
} else if (topfrp->fr_layout == FR_ROW) {
do {
// All frames in this row get the same new height.
@@ -3339,8 +3433,8 @@ static void frame_add_statusline(frame_T *frp)
if (frp->fr_layout == FR_LEAF) {
wp = frp->fr_win;
if (wp->w_status_height == 0) {
- if (wp->w_height > 0) { // don't make it negative
- --wp->w_height;
+ if (wp->w_height - STATUS_HEIGHT >= 0) { // don't make it negative
+ wp->w_height -= STATUS_HEIGHT;
}
wp->w_status_height = STATUS_HEIGHT;
}
@@ -3460,10 +3554,8 @@ static void frame_new_width(frame_T *topfrp, int width, bool leftfirst, bool wfw
topfrp->fr_width = width;
}
-/*
- * Add the vertical separator to windows at the right side of "frp".
- * Note: Does not check if there is room!
- */
+/// Add the vertical separator to windows at the right side of "frp".
+/// Note: Does not check if there is room!
static void frame_add_vsep(const frame_T *frp)
FUNC_ATTR_NONNULL_ARG(1)
{
@@ -3493,6 +3585,37 @@ static void frame_add_vsep(const frame_T *frp)
}
}
+/// Add the horizontal separator to windows at the bottom of "frp".
+/// Note: Does not check if there is room or whether the windows have a statusline!
+static void frame_add_hsep(const frame_T *frp)
+ FUNC_ATTR_NONNULL_ARG(1)
+{
+ win_T *wp;
+
+ if (frp->fr_layout == FR_LEAF) {
+ wp = frp->fr_win;
+ if (wp->w_hsep_height == 0) {
+ if (wp->w_height > 0) { // don't make it negative
+ wp->w_height++;
+ }
+ wp->w_hsep_height = 1;
+ }
+ } else if (frp->fr_layout == FR_ROW) {
+ // Handle all the frames in the row.
+ FOR_ALL_FRAMES(frp, frp->fr_child) {
+ frame_add_hsep(frp);
+ }
+ } else {
+ assert(frp->fr_layout == FR_COL);
+ // Only need to handle the last frame in the column.
+ frp = frp->fr_child;
+ while (frp->fr_next != NULL) {
+ frp = frp->fr_next;
+ }
+ frame_add_hsep(frp);
+ }
+}
+
/*
* Set frame width from the window it contains.
*/
@@ -3507,7 +3630,7 @@ static void frame_fix_width(win_T *wp)
static void frame_fix_height(win_T *wp)
FUNC_ATTR_NONNULL_ALL
{
- wp->w_frame->fr_height = wp->w_height + wp->w_status_height;
+ wp->w_frame->fr_height = wp->w_height + wp->w_hsep_height + wp->w_status_height;
}
/*
@@ -3525,10 +3648,11 @@ static int frame_minheight(frame_T *topfrp, win_T *next_curwin)
if (topfrp->fr_win != NULL) {
if (topfrp->fr_win == next_curwin) {
- m = p_wh + topfrp->fr_win->w_status_height;
+ m = p_wh + topfrp->fr_win->w_hsep_height + topfrp->fr_win->w_status_height;
} else {
- // window: minimal height of the window plus status line
- m = p_wmh + topfrp->fr_win->w_status_height;
+ // window: minimal height of the window plus separator column or status line
+ // depending on whether global statusline is enabled
+ m = p_wmh + topfrp->fr_win->w_hsep_height + topfrp->fr_win->w_status_height;
if (topfrp->fr_win == curwin && next_curwin == NULL) {
// Current window is minimal one line high.
if (p_wmh == 0) {
@@ -3757,7 +3881,7 @@ static int win_alloc_firstwin(win_T *oldwin)
new_frame(curwin);
topframe = curwin->w_frame;
topframe->fr_width = Columns;
- topframe->fr_height = Rows - p_ch;
+ topframe->fr_height = Rows - p_ch - global_stl_height();
return OK;
}
@@ -3844,6 +3968,11 @@ int win_new_tabpage(int after, char_u *filename)
tabpage_T *newtp;
int n;
+ if (cmdwin_type != 0) {
+ emsg(_(e_cmdwin));
+ return FAIL;
+ }
+
newtp = alloc_tabpage();
// Remember the current windows in this Tab page.
@@ -4089,8 +4218,8 @@ static void enter_tabpage(tabpage_T *tp, buf_T *old_curbuf, bool trigger_enter_a
{
int old_off = tp->tp_firstwin->w_winrow;
win_T *next_prevwin = tp->tp_prevwin;
-
tabpage_T *old_curtab = curtab;
+
curtab = tp;
firstwin = tp->tp_firstwin;
lastwin = tp->tp_lastwin;
@@ -4242,6 +4371,10 @@ void goto_tabpage(int n)
/// @param trigger_leave_autocmds when true trigger *Leave autocommands.
void goto_tabpage_tp(tabpage_T *tp, bool trigger_enter_autocmds, bool trigger_leave_autocmds)
{
+ if (trigger_enter_autocmds || trigger_leave_autocmds) {
+ CHECK_CMDWIN;
+ }
+
// Don't repeat a message in another tab page.
set_keep_msg(NULL, 0);
@@ -4257,13 +4390,15 @@ void goto_tabpage_tp(tabpage_T *tp, bool trigger_enter_autocmds, bool trigger_le
}
}
-// Go to the last accessed tab page, if there is one.
-void goto_tabpage_lastused(void)
+/// Go to the last accessed tab page, if there is one.
+/// @return true if the tab page is valid, false otherwise.
+bool goto_tabpage_lastused(void)
{
- int index = tabpage_index(lastused_tabpage);
- if (index < tabpage_index(NULL)) {
- goto_tabpage(index);
+ if (valid_tabpage(lastused_tabpage)) {
+ goto_tabpage_tp(lastused_tabpage, true, true);
+ return true;
}
+ return false;
}
/*
@@ -5162,11 +5297,8 @@ void win_size_restore(garray_T *gap)
}
}
-/*
- * Update the position for all windows, using the width and height of the
- * frames.
- * Returns the row just after the last window.
- */
+// Update the position for all windows, using the width and height of the frames.
+// Returns the row just after the last window and global statusline (if there is one).
int win_comp_pos(void)
{
int row = tabline_height();
@@ -5181,7 +5313,7 @@ int win_comp_pos(void)
}
}
- return row;
+ return row + global_stl_height();
}
void win_reconfig_floats(void)
@@ -5215,7 +5347,7 @@ static void frame_comp_pos(frame_T *topfrp, int *row, int *col)
wp->w_redr_status = true;
wp->w_pos_changed = true;
}
- const int h = wp->w_height + wp->w_status_height;
+ const int h = wp->w_height + wp->w_hsep_height + wp->w_status_height;
*row += h > topfrp->fr_height ? topfrp->fr_height : h;
*col += wp->w_width + wp->w_vsep_width;
} else {
@@ -5264,7 +5396,7 @@ void win_setheight_win(int height, win_T *win)
win_config_float(win, win->w_float_config);
redraw_later(win, NOT_VALID);
} else {
- frame_setheight(win->w_frame, height + win->w_status_height);
+ frame_setheight(win->w_frame, height + win->w_hsep_height + win->w_status_height);
// recompute the window positions
int row = win_comp_pos();
@@ -5355,8 +5487,8 @@ static void frame_setheight(frame_T *curfrp, int height)
room_cmdline = 0;
} else {
win_T *wp = lastwin_nofloating();
- room_cmdline = Rows - p_ch
- - (wp->w_winrow + wp->w_height + wp->w_status_height);
+ room_cmdline = Rows - p_ch - global_stl_height()
+ - (wp->w_winrow + wp->w_height + wp->w_hsep_height + wp->w_status_height);
if (room_cmdline < 0) {
room_cmdline = 0;
}
@@ -5718,7 +5850,7 @@ void win_drag_status_line(win_T *dragwin, int offset)
} else { // drag down
up = false;
// Only dragging the last status line can reduce p_ch.
- room = Rows - cmdline_row;
+ room = Rows - cmdline_row - global_stl_height();
if (curfr->fr_next == NULL) {
room -= 1;
} else {
@@ -6359,72 +6491,104 @@ char_u *file_name_in_line(char_u *line, int col, int options, long count, char_u
return find_file_name_in_path(ptr, len, options, count, rel_fname);
}
-/// Add or remove a status line for the bottom window(s), according to the
+/// Add or remove a status line from window(s), according to the
/// value of 'laststatus'.
///
/// @param morewin pretend there are two or more windows if true.
void last_status(bool morewin)
{
// Don't make a difference between horizontal or vertical split.
- last_status_rec(topframe, (p_ls == 2
- || (p_ls == 1 && (morewin || !one_window()))));
+ last_status_rec(topframe, (p_ls == 2 || (p_ls == 1 && (morewin || !one_window()))),
+ global_stl_height() > 0);
}
-static void last_status_rec(frame_T *fr, bool statusline)
+// Look for resizable frames and take lines from them to make room for the statusline
+static void resize_frame_for_status(frame_T *fr, int resize_amount)
+{
+ // Find a frame to take a line from.
+ frame_T *fp = fr;
+ win_T *wp = fr->fr_win;
+ int n;
+
+ while (resize_amount > 0) {
+ while (fp->fr_height <= frame_minheight(fp, NULL)) {
+ if (fp == topframe) {
+ emsg(_(e_noroom));
+ return;
+ }
+ // In a column of frames: go to frame above. If already at
+ // the top or in a row of frames: go to parent.
+ if (fp->fr_parent->fr_layout == FR_COL && fp->fr_prev != NULL) {
+ fp = fp->fr_prev;
+ } else {
+ fp = fp->fr_parent;
+ }
+ }
+ n = MIN(fp->fr_height - frame_minheight(fp, NULL), resize_amount);
+ resize_amount -= n;
+
+ if (fp != fr) {
+ frame_new_height(fp, fp->fr_height - n, false, false);
+ frame_fix_height(wp);
+ (void)win_comp_pos();
+ } else {
+ win_new_height(wp, wp->w_height - n);
+ }
+ }
+}
+
+static void last_status_rec(frame_T *fr, bool statusline, bool is_stl_global)
{
frame_T *fp;
win_T *wp;
if (fr->fr_layout == FR_LEAF) {
wp = fr->fr_win;
- if (wp->w_status_height != 0 && !statusline) {
- // remove status line
- win_new_height(wp, wp->w_height + 1);
+ bool is_last = is_bottom_win(wp);
+
+ if (is_last) {
+ if (wp->w_status_height != 0 && (!statusline || is_stl_global)) {
+ // Remove status line
+ wp->w_status_height = 0;
+ win_new_height(wp, wp->w_height + STATUS_HEIGHT);
+ comp_col();
+ } else if (wp->w_status_height == 0 && !is_stl_global && statusline) {
+ // Add statusline to window if needed
+ wp->w_status_height = STATUS_HEIGHT;
+ resize_frame_for_status(fr, STATUS_HEIGHT);
+ comp_col();
+ }
+ } else if (wp->w_status_height != 0 && is_stl_global) {
+ // If statusline is global and the window has a statusline, replace it with a horizontal
+ // separator
+ if (STATUS_HEIGHT - 1 != 0) {
+ win_new_height(wp, wp->w_height + STATUS_HEIGHT - 1);
+ }
wp->w_status_height = 0;
+ wp->w_hsep_height = 1;
comp_col();
- } else if (wp->w_status_height == 0 && statusline) {
- // Find a frame to take a line from.
- fp = fr;
- while (fp->fr_height <= frame_minheight(fp, NULL)) {
- if (fp == topframe) {
- emsg(_(e_noroom));
- return;
- }
- // In a column of frames: go to frame above. If already at
- // the top or in a row of frames: go to parent.
- if (fp->fr_parent->fr_layout == FR_COL && fp->fr_prev != NULL) {
- fp = fp->fr_prev;
- } else {
- fp = fp->fr_parent;
- }
- }
- wp->w_status_height = 1;
- if (fp != fr) {
- frame_new_height(fp, fp->fr_height - 1, false, false);
- frame_fix_height(wp);
- (void)win_comp_pos();
- } else {
- win_new_height(wp, wp->w_height - 1);
- }
+ } else if (wp->w_status_height == 0 && !is_stl_global) {
+ // If statusline isn't global and the window doesn't have a statusline, re-add it
+ wp->w_status_height = STATUS_HEIGHT;
+ wp->w_hsep_height = 0;
+ resize_frame_for_status(fr, STATUS_HEIGHT - 1);
comp_col();
- redraw_all_later(SOME_VALID);
}
- } else if (fr->fr_layout == FR_ROW) {
- // vertically split windows, set status line for each one
+ redraw_all_later(SOME_VALID);
+ } else if (fr->fr_layout == FR_COL) {
+ // For a column frame, recursively call this function for all child frames
FOR_ALL_FRAMES(fp, fr->fr_child) {
- last_status_rec(fp, statusline);
+ last_status_rec(fp, statusline, is_stl_global);
}
} else {
- // horizontally split window, set status line for last one
- for (fp = fr->fr_child; fp->fr_next != NULL; fp = fp->fr_next) {
+ // For a row frame, recursively call this function for all child frames
+ FOR_ALL_FRAMES(fp, fr->fr_child) {
+ last_status_rec(fp, statusline, is_stl_global);
}
- last_status_rec(fp, statusline);
}
}
-/*
- * Return the number of lines used by the tab page line.
- */
+/// Return the number of lines used by the tab page line.
int tabline_height(void)
{
if (ui_has(kUITabline)) {
@@ -6440,10 +6604,14 @@ int tabline_height(void)
return 1;
}
-/*
- * Return the minimal number of rows that is needed on the screen to display
- * the current number of windows.
- */
+/// Return the number of lines used by the global statusline
+int global_stl_height(void)
+{
+ return (p_ls == 3) ? STATUS_HEIGHT : 0;
+}
+
+/// Return the minimal number of rows that is needed on the screen to display
+/// the current number of windows.
int min_rows(void)
{
if (firstwin == NULL) { // not initialized yet
@@ -6457,7 +6625,7 @@ int min_rows(void)
total = n;
}
}
- total += tabline_height();
+ total += tabline_height() + global_stl_height();
total += 1; // count the room for the command line
return total;
}
@@ -6755,9 +6923,6 @@ void restore_win_noblock(switchwin_T *switchwin, bool no_display)
curwin = switchwin->sw_curwin;
curbuf = curwin->w_buffer;
}
- // If called by win_execute() and executing the command changed the
- // directory, it now has to be restored.
- fix_current_dir();
}
/// Make "buf" the current buffer.
@@ -7192,16 +7357,14 @@ void win_id2tabwin(typval_T *const argvars, typval_T *const rettv)
tv_list_append_number(list, winnr);
}
-win_T *win_id2wp(typval_T *argvars)
+win_T *win_id2wp(int id)
{
- return win_id2wp_tp(argvars, NULL);
+ return win_id2wp_tp(id, NULL);
}
// Return the window and tab pointer of window "id".
-win_T *win_id2wp_tp(typval_T *argvars, tabpage_T **tpp)
+win_T *win_id2wp_tp(int id, tabpage_T **tpp)
{
- int id = tv_get_number(&argvars[0]);
-
FOR_ALL_TAB_WINDOWS(tp, wp) {
if (wp->handle == id) {
if (tpp != NULL) {
diff --git a/src/nvim/window.h b/src/nvim/window.h
index e2fd2c515d..b75b8abd9b 100644
--- a/src/nvim/window.h
+++ b/src/nvim/window.h
@@ -5,19 +5,18 @@
#include "nvim/buffer_defs.h"
#include "nvim/mark.h"
+#include "nvim/os/os.h"
// Values for file_name_in_line()
#define FNAME_MESS 1 // give error message
#define FNAME_EXP 2 // expand to path
#define FNAME_HYP 4 // check for hypertext link
#define FNAME_INCL 8 // apply 'includeexpr'
-#define FNAME_REL 16 /* ".." and "./" are relative to the (current)
- file instead of the current directory */
+#define FNAME_REL 16 // ".." and "./" are relative to the (current)
+ // file instead of the current directory
#define FNAME_UNESC 32 // remove backslashes used for escaping
-/*
- * arguments for win_split()
- */
+// arguments for win_split()
#define WSP_ROOM 1 // require enough room
#define WSP_VERT 2 // split vertically
#define WSP_TOP 4 // window at top-left of shell
@@ -27,9 +26,7 @@
#define WSP_ABOVE 64 // put new window above/left
#define WSP_NEWLOC 128 // don't copy location list
-/*
- * Minimum screen size
- */
+// Minimum screen size
#define MIN_COLUMNS 12 // minimal columns for screen
#define MIN_LINES 2 // minimal lines for screen
@@ -47,12 +44,36 @@ typedef struct {
do { \
win_T *const wp_ = (wp); \
const pos_T curpos_ = wp_->w_cursor; \
+ char_u cwd_[MAXPATHL]; \
+ char_u autocwd_[MAXPATHL]; \
+ bool apply_acd_ = false; \
+ int cwd_status_ = FAIL; \
+ /* Getting and setting directory can be slow on some systems, only do */ \
+ /* this when the current or target window/tab have a local directory or */ \
+ /* 'acd' is set. */ \
+ if (curwin != wp \
+ && (curwin->w_localdir != NULL || wp->w_localdir != NULL \
+ || (curtab != tp && (curtab->tp_localdir != NULL || tp->tp_localdir != NULL)) \
+ || p_acd)) { \
+ cwd_status_ = os_dirname(cwd_, MAXPATHL); \
+ } \
+ /* If 'acd' is set, check we are using that directory. If yes, then */ \
+ /* apply 'acd' afterwards, otherwise restore the current directory. */ \
+ if (cwd_status_ == OK && p_acd) { \
+ do_autochdir(); \
+ apply_acd_ = os_dirname(autocwd_, MAXPATHL) == OK && STRCMP(cwd_, autocwd_) == 0; \
+ } \
switchwin_T switchwin_; \
if (switch_win_noblock(&switchwin_, wp_, (tp), true) == OK) { \
check_cursor(); \
block; \
} \
restore_win_noblock(&switchwin_, true); \
+ if (apply_acd_) { \
+ do_autochdir(); \
+ } else if (cwd_status_ == OK) { \
+ os_chdir((char *)cwd_); \
+ } \
/* Update the status line if the cursor moved. */ \
if (win_valid(wp_) && !equalpos(curpos_, wp_->w_cursor)) { \
wp_->w_redr_status = true; \
diff --git a/test/functional/api/autocmd_spec.lua b/test/functional/api/autocmd_spec.lua
new file mode 100644
index 0000000000..372cbf2c30
--- /dev/null
+++ b/test/functional/api/autocmd_spec.lua
@@ -0,0 +1,920 @@
+local helpers = require('test.functional.helpers')(after_each)
+
+local clear = helpers.clear
+local command = helpers.command
+local eq = helpers.eq
+local neq = helpers.neq
+local exec_lua = helpers.exec_lua
+local matches = helpers.matches
+local meths = helpers.meths
+local source = helpers.source
+local pcall_err = helpers.pcall_err
+
+before_each(clear)
+
+describe('autocmd api', function()
+ describe('nvim_create_autocmd', function()
+ it('does not allow "command" and "callback" in the same autocmd', function()
+ local ok, _ = pcall(meths.create_autocmd, "BufReadPost", {
+ pattern = "*.py,*.pyi",
+ command = "echo 'Should Have Errored",
+ callback = "not allowed",
+ })
+
+ eq(false, ok)
+ end)
+
+ it('doesnt leak when you use ++once', function()
+ eq(1, exec_lua([[
+ local count = 0
+
+ vim.api.nvim_create_autocmd("FileType", {
+ pattern = "*",
+ callback = function() count = count + 1 end,
+ once = true
+ })
+
+ vim.cmd "set filetype=txt"
+ vim.cmd "set filetype=python"
+
+ return count
+ ]], {}))
+ end)
+
+ it('allows passing buffer by key', function()
+ meths.set_var('called', 0)
+
+ meths.create_autocmd("FileType", {
+ command = "let g:called = g:called + 1",
+ buffer = 0,
+ })
+
+ meths.command "set filetype=txt"
+ eq(1, meths.get_var('called'))
+
+ -- switch to a new buffer
+ meths.command "new"
+ meths.command "set filetype=python"
+
+ eq(1, meths.get_var('called'))
+ end)
+
+ it('does not allow passing buffer and patterns', function()
+ local ok = pcall(meths.create_autocmd, "Filetype", {
+ command = "let g:called = g:called + 1",
+ buffer = 0,
+ pattern = "*.py",
+ })
+
+ eq(false, ok)
+ end)
+
+ it('does not allow passing invalid buffers', function()
+ local ok, msg = pcall(meths.create_autocmd, "Filetype", {
+ command = "let g:called = g:called + 1",
+ buffer = -1,
+ })
+
+ eq(false, ok)
+ matches('Invalid buffer id', msg)
+ end)
+
+ it('errors on non-functions for cb', function()
+ eq(false, pcall(exec_lua, [[
+ vim.api.nvim_create_autocmd("BufReadPost", {
+ pattern = "*.py,*.pyi",
+ callback = 5,
+ })
+ ]]))
+ end)
+
+ it('allow passing pattern and <buffer> in same pattern', function()
+ local ok = pcall(meths.create_autocmd, "BufReadPost", {
+ pattern = "*.py,<buffer>",
+ command = "echo 'Should Not Error'"
+ })
+
+ eq(true, ok)
+ end)
+
+ it('should handle multiple values as comma separated list', function()
+ meths.create_autocmd("BufReadPost", {
+ pattern = "*.py,*.pyi",
+ command = "echo 'Should Not Have Errored'"
+ })
+
+ -- We should have one autocmd for *.py and one for *.pyi
+ eq(2, #meths.get_autocmds { event = "BufReadPost" })
+ end)
+
+ it('should handle multiple values as array', function()
+ meths.create_autocmd("BufReadPost", {
+ pattern = { "*.py", "*.pyi", },
+ command = "echo 'Should Not Have Errored'"
+ })
+
+ -- We should have one autocmd for *.py and one for *.pyi
+ eq(2, #meths.get_autocmds { event = "BufReadPost" })
+ end)
+
+ describe('desc', function()
+ it('can add description to one autocmd', function()
+ meths.create_autocmd("BufReadPost", {
+ pattern = "*.py",
+ command = "echo 'Should Not Have Errored'",
+ desc = "Can show description",
+ })
+
+ eq("Can show description", meths.get_autocmds { event = "BufReadPost" }[1].desc)
+ end)
+
+ it('can add description to multiple autocmd', function()
+ meths.create_autocmd("BufReadPost", {
+ pattern = {"*.py", "*.pyi"},
+ command = "echo 'Should Not Have Errored'",
+ desc = "Can show description",
+ })
+
+ local aus = meths.get_autocmds { event = "BufReadPost" }
+ eq(2, #aus)
+ eq("Can show description", aus[1].desc)
+ eq("Can show description", aus[2].desc)
+ end)
+ end)
+
+ pending('script and verbose settings', function()
+ it('marks API client', function()
+ meths.create_autocmd("BufReadPost", {
+ pattern = "*.py",
+ command = "echo 'Should Not Have Errored'",
+ desc = "Can show description",
+ })
+
+ local aus = meths.get_autocmds { event = "BufReadPost" }
+ eq(1, #aus, aus)
+ end)
+ end)
+ end)
+
+ describe('nvim_get_autocmds', function()
+ describe('events', function()
+ it('should return one autocmd when there is only one for an event', function()
+ command [[au! InsertEnter]]
+ command [[au InsertEnter * :echo "1"]]
+
+ local aus = meths.get_autocmds { event = "InsertEnter" }
+ eq(1, #aus)
+ end)
+
+ it('should return two autocmds when there are two for an event', function()
+ command [[au! InsertEnter]]
+ command [[au InsertEnter * :echo "1"]]
+ command [[au InsertEnter * :echo "2"]]
+
+ local aus = meths.get_autocmds { event = "InsertEnter" }
+ eq(2, #aus)
+ end)
+
+ it('should return the same thing if you use string or list', function()
+ command [[au! InsertEnter]]
+ command [[au InsertEnter * :echo "1"]]
+ command [[au InsertEnter * :echo "2"]]
+
+ local string_aus = meths.get_autocmds { event = "InsertEnter" }
+ local array_aus = meths.get_autocmds { event = { "InsertEnter" } }
+ eq(string_aus, array_aus)
+ end)
+
+ it('should return two autocmds when there are two for an event', function()
+ command [[au! InsertEnter]]
+ command [[au! InsertLeave]]
+ command [[au InsertEnter * :echo "1"]]
+ command [[au InsertEnter * :echo "2"]]
+
+ local aus = meths.get_autocmds { event = { "InsertEnter", "InsertLeave" } }
+ eq(2, #aus)
+ end)
+
+ it('should return different IDs for different autocmds', function()
+ command [[au! InsertEnter]]
+ command [[au! InsertLeave]]
+ command [[au InsertEnter * :echo "1"]]
+ source [[
+ call nvim_create_autocmd("InsertLeave", #{
+ \ command: ":echo 2",
+ \ })
+ ]]
+
+ local aus = meths.get_autocmds { event = { "InsertEnter", "InsertLeave" } }
+ local first = aus[1]
+ eq(first.id, nil)
+
+ -- TODO: Maybe don't have this number, just assert it's not nil
+ local second = aus[2]
+ neq(second.id, nil)
+
+ meths.del_autocmd(second.id)
+ local new_aus = meths.get_autocmds { event = { "InsertEnter", "InsertLeave" } }
+ eq(1, #new_aus)
+ eq(first, new_aus[1])
+ end)
+
+ it('should return event name', function()
+ command [[au! InsertEnter]]
+ command [[au InsertEnter * :echo "1"]]
+
+ local aus = meths.get_autocmds { event = "InsertEnter" }
+ eq({ { buflocal = false, command = ':echo "1"', event = "InsertEnter", once = false, pattern = "*" } }, aus)
+ end)
+
+ it('should work with buffer numbers', function()
+ command [[new]]
+ command [[au! InsertEnter]]
+ command [[au InsertEnter <buffer=1> :echo "1"]]
+ command [[au InsertEnter <buffer=2> :echo "2"]]
+
+ local aus = meths.get_autocmds { event = "InsertEnter", buffer = 0 }
+ eq({{
+ buffer = 2,
+ buflocal = true,
+ command = ':echo "2"',
+ event = 'InsertEnter',
+ once = false,
+ pattern = '<buffer=2>',
+ }}, aus)
+
+ aus = meths.get_autocmds { event = "InsertEnter", buffer = 1 }
+ eq({{
+ buffer = 1,
+ buflocal = true,
+ command = ':echo "1"',
+ event = "InsertEnter",
+ once = false,
+ pattern = "<buffer=1>",
+ }}, aus)
+
+ aus = meths.get_autocmds { event = "InsertEnter", buffer = { 1, 2 } }
+ eq({{
+ buffer = 1,
+ buflocal = true,
+ command = ':echo "1"',
+ event = "InsertEnter",
+ once = false,
+ pattern = "<buffer=1>",
+ }, {
+ buffer = 2,
+ buflocal = true,
+ command = ':echo "2"',
+ event = "InsertEnter",
+ once = false,
+ pattern = "<buffer=2>",
+ }}, aus)
+
+ eq("Invalid value for 'buffer': must be an integer or array of integers", pcall_err(meths.get_autocmds, { event = "InsertEnter", buffer = "foo" }))
+ eq("Invalid value for 'buffer': must be an integer", pcall_err(meths.get_autocmds, { event = "InsertEnter", buffer = { "foo", 42 } }))
+ eq("Invalid buffer id: 42", pcall_err(meths.get_autocmds, { event = "InsertEnter", buffer = { 42 } }))
+
+ local bufs = {}
+ for _ = 1, 257 do
+ table.insert(bufs, meths.create_buf(true, false))
+ end
+
+ eq("Too many buffers. Please limit yourself to 256 or fewer", pcall_err(meths.get_autocmds, { event = "InsertEnter", buffer = bufs }))
+ end)
+
+ it('should return autocmds when group is specified by id', function()
+ local auid = meths.create_augroup("nvim_test_augroup", { clear = true })
+ meths.create_autocmd("FileType", { group = auid, command = 'echo "1"' })
+ meths.create_autocmd("FileType", { group = auid, command = 'echo "2"' })
+
+ local aus = meths.get_autocmds { group = auid }
+ eq(2, #aus)
+
+ local aus2 = meths.get_autocmds { group = auid, event = "InsertEnter" }
+ eq(0, #aus2)
+ end)
+
+ it('should return autocmds when group is specified by name', function()
+ local auname = "nvim_test_augroup"
+ meths.create_augroup(auname, { clear = true })
+ meths.create_autocmd("FileType", { group = auname, command = 'echo "1"' })
+ meths.create_autocmd("FileType", { group = auname, command = 'echo "2"' })
+
+ local aus = meths.get_autocmds { group = auname }
+ eq(2, #aus)
+
+ local aus2 = meths.get_autocmds { group = auname, event = "InsertEnter" }
+ eq(0, #aus2)
+ end)
+ end)
+
+ describe('groups', function()
+ before_each(function()
+ command [[au! InsertEnter]]
+
+ command [[au InsertEnter * :echo "No Group"]]
+
+ command [[augroup GroupOne]]
+ command [[ au InsertEnter * :echo "GroupOne:1"]]
+ command [[augroup END]]
+
+ command [[augroup GroupTwo]]
+ command [[ au InsertEnter * :echo "GroupTwo:2"]]
+ command [[ au InsertEnter * :echo "GroupTwo:3"]]
+ command [[augroup END]]
+ end)
+
+ it('should return all groups if no group is specified', function()
+ local aus = meths.get_autocmds { event = "InsertEnter" }
+ if #aus ~= 4 then
+ eq({}, aus)
+ end
+
+ eq(4, #aus)
+ end)
+
+ it('should return only the group specified', function()
+ local aus = meths.get_autocmds {
+ event = "InsertEnter",
+ group = "GroupOne",
+ }
+
+ eq(1, #aus)
+ eq([[:echo "GroupOne:1"]], aus[1].command)
+ end)
+
+ it('should return only the group specified, multiple values', function()
+ local aus = meths.get_autocmds {
+ event = "InsertEnter",
+ group = "GroupTwo",
+ }
+
+ eq(2, #aus)
+ eq([[:echo "GroupTwo:2"]], aus[1].command)
+ eq([[:echo "GroupTwo:3"]], aus[2].command)
+ end)
+ end)
+
+ describe('groups: 2', function()
+ it('raises error for undefined augroup name', function()
+ local success, code = unpack(meths.exec_lua([[
+ return {pcall(function()
+ vim.api.nvim_create_autocmd("FileType", {
+ pattern = "*",
+ group = "NotDefined",
+ command = "echo 'hello'",
+ })
+ end)}
+ ]], {}))
+
+ eq(false, success)
+ matches('invalid augroup: NotDefined', code)
+ end)
+
+ it('raises error for undefined augroup id', function()
+ local success, code = unpack(meths.exec_lua([[
+ return {pcall(function()
+ -- Make sure the augroup is deleted
+ vim.api.nvim_del_augroup_by_id(1)
+
+ vim.api.nvim_create_autocmd("FileType", {
+ pattern = "*",
+ group = 1,
+ command = "echo 'hello'",
+ })
+ end)}
+ ]], {}))
+
+ eq(false, success)
+ matches('invalid augroup: 1', code)
+ end)
+
+ it('raises error for invalid group type', function()
+ local success, code = unpack(meths.exec_lua([[
+ return {pcall(function()
+ vim.api.nvim_create_autocmd("FileType", {
+ pattern = "*",
+ group = true,
+ command = "echo 'hello'",
+ })
+ end)}
+ ]], {}))
+
+ eq(false, success)
+ matches("'group' must be a string or an integer", code)
+ end)
+ end)
+
+ describe('patterns', function()
+ before_each(function()
+ command [[au! InsertEnter]]
+
+ command [[au InsertEnter * :echo "No Group"]]
+ command [[au InsertEnter *.one :echo "GroupOne:1"]]
+ command [[au InsertEnter *.two :echo "GroupTwo:2"]]
+ command [[au InsertEnter *.two :echo "GroupTwo:3"]]
+ command [[au InsertEnter <buffer> :echo "Buffer"]]
+ end)
+
+ it('should should return for literal match', function()
+ local aus = meths.get_autocmds {
+ event = "InsertEnter",
+ pattern = "*"
+ }
+
+ eq(1, #aus)
+ eq([[:echo "No Group"]], aus[1].command)
+ end)
+
+ it('should return for multiple matches', function()
+ -- vim.api.nvim_get_autocmds
+ local aus = meths.get_autocmds {
+ event = "InsertEnter",
+ pattern = { "*.one", "*.two" },
+ }
+
+ eq(3, #aus)
+ eq([[:echo "GroupOne:1"]], aus[1].command)
+ eq([[:echo "GroupTwo:2"]], aus[2].command)
+ eq([[:echo "GroupTwo:3"]], aus[3].command)
+ end)
+
+ it('should work for buffer autocmds', function()
+ local normalized_aus = meths.get_autocmds {
+ event = "InsertEnter",
+ pattern = "<buffer=1>",
+ }
+
+ local raw_aus = meths.get_autocmds {
+ event = "InsertEnter",
+ pattern = "<buffer>",
+ }
+
+ local zero_aus = meths.get_autocmds {
+ event = "InsertEnter",
+ pattern = "<buffer=0>",
+ }
+
+ eq(normalized_aus, raw_aus)
+ eq(normalized_aus, zero_aus)
+ eq([[:echo "Buffer"]], normalized_aus[1].command)
+ end)
+ end)
+ end)
+
+ describe('nvim_do_autocmd', function()
+ it("can trigger builtin autocmds", function()
+ meths.set_var("autocmd_executed", false)
+
+ meths.create_autocmd("BufReadPost", {
+ pattern = "*",
+ command = "let g:autocmd_executed = v:true",
+ })
+
+ eq(false, meths.get_var("autocmd_executed"))
+ meths.do_autocmd("BufReadPost", {})
+ eq(true, meths.get_var("autocmd_executed"))
+ end)
+
+ it("can pass the buffer", function()
+ meths.set_var("buffer_executed", -1)
+ eq(-1, meths.get_var("buffer_executed"))
+
+ meths.create_autocmd("BufLeave", {
+ pattern = "*",
+ command = 'let g:buffer_executed = +expand("<abuf>")',
+ })
+
+ -- Doesn't execute for other non-matching events
+ meths.do_autocmd("CursorHold", { buffer = 1 })
+ eq(-1, meths.get_var("buffer_executed"))
+
+ meths.do_autocmd("BufLeave", { buffer = 1 })
+ eq(1, meths.get_var("buffer_executed"))
+ end)
+
+ it("can pass the filename, pattern match", function()
+ meths.set_var("filename_executed", 'none')
+ eq('none', meths.get_var("filename_executed"))
+
+ meths.create_autocmd("BufEnter", {
+ pattern = "*.py",
+ command = 'let g:filename_executed = expand("<afile>")',
+ })
+
+ -- Doesn't execute for other non-matching events
+ meths.do_autocmd("CursorHold", { buffer = 1 })
+ eq('none', meths.get_var("filename_executed"))
+
+ meths.command('edit __init__.py')
+ eq('__init__.py', meths.get_var("filename_executed"))
+ end)
+
+ it('cannot pass buf and fname', function()
+ local ok = pcall(meths.do_autocmd, "BufReadPre", { pattern = "literally_cannot_error.rs", buffer = 1 })
+ eq(false, ok)
+ end)
+
+ it("can pass the filename, exact match", function()
+ meths.set_var("filename_executed", 'none')
+ eq('none', meths.get_var("filename_executed"))
+
+ meths.command('edit other_file.txt')
+ meths.command('edit __init__.py')
+ eq('none', meths.get_var("filename_executed"))
+
+ meths.create_autocmd("CursorHoldI", {
+ pattern = "__init__.py",
+ command = 'let g:filename_executed = expand("<afile>")',
+ })
+
+ -- Doesn't execute for other non-matching events
+ meths.do_autocmd("CursorHoldI", { buffer = 1 })
+ eq('none', meths.get_var("filename_executed"))
+
+ meths.do_autocmd("CursorHoldI", { buffer = tonumber(meths.get_current_buf()) })
+ eq('__init__.py', meths.get_var("filename_executed"))
+
+ -- Reset filename
+ meths.set_var("filename_executed", 'none')
+
+ meths.do_autocmd("CursorHoldI", { pattern = '__init__.py' })
+ eq('__init__.py', meths.get_var("filename_executed"))
+ end)
+
+ it("works with user autocmds", function()
+ meths.set_var("matched", 'none')
+
+ meths.create_autocmd("User", {
+ pattern = "TestCommand",
+ command = 'let g:matched = "matched"'
+ })
+
+ meths.do_autocmd("User", { pattern = "OtherCommand" })
+ eq('none', meths.get_var('matched'))
+ meths.do_autocmd("User", { pattern = "TestCommand" })
+ eq('matched', meths.get_var('matched'))
+ end)
+
+ it('can pass group by id', function()
+ meths.set_var("group_executed", false)
+
+ local auid = meths.create_augroup("nvim_test_augroup", { clear = true })
+ meths.create_autocmd("FileType", {
+ group = auid,
+ command = 'let g:group_executed = v:true',
+ })
+
+ eq(false, meths.get_var("group_executed"))
+ meths.do_autocmd("FileType", { group = auid })
+ eq(true, meths.get_var("group_executed"))
+ end)
+
+ it('can pass group by name', function()
+ meths.set_var("group_executed", false)
+
+ local auname = "nvim_test_augroup"
+ meths.create_augroup(auname, { clear = true })
+ meths.create_autocmd("FileType", {
+ group = auname,
+ command = 'let g:group_executed = v:true',
+ })
+
+ eq(false, meths.get_var("group_executed"))
+ meths.do_autocmd("FileType", { group = auname })
+ eq(true, meths.get_var("group_executed"))
+ end)
+ end)
+
+ describe('nvim_create_augroup', function()
+ before_each(function()
+ clear()
+
+ meths.set_var('executed', 0)
+ end)
+
+ local make_counting_autocmd = function(opts)
+ opts = opts or {}
+
+ local resulting = {
+ pattern = "*",
+ command = "let g:executed = g:executed + 1",
+ }
+
+ resulting.group = opts.group
+ resulting.once = opts.once
+
+ meths.create_autocmd("FileType", resulting)
+ end
+
+ local set_ft = function(ft)
+ ft = ft or "txt"
+ source(string.format("set filetype=%s", ft))
+ end
+
+ local get_executed_count = function()
+ return meths.get_var('executed')
+ end
+
+ it('can be added in a group', function()
+ local augroup = "TestGroup"
+ meths.create_augroup(augroup, { clear = true })
+ make_counting_autocmd { group = augroup }
+
+ set_ft("txt")
+ set_ft("python")
+
+ eq(get_executed_count(), 2)
+ end)
+
+ it('works getting called multiple times', function()
+ make_counting_autocmd()
+ set_ft()
+ set_ft()
+ set_ft()
+
+ eq(get_executed_count(), 3)
+ end)
+
+ it('handles ++once', function()
+ make_counting_autocmd {once = true}
+ set_ft('txt')
+ set_ft('help')
+ set_ft('txt')
+ set_ft('help')
+
+ eq(get_executed_count(), 1)
+ end)
+
+ it('errors on unexpected keys', function()
+ local success, code = pcall(meths.create_autocmd, "FileType", {
+ pattern = "*",
+ not_a_valid_key = "NotDefined",
+ })
+
+ eq(false, success)
+ matches('not_a_valid_key', code)
+ end)
+
+ it('can execute simple callback', function()
+ exec_lua([[
+ vim.g.executed = false
+
+ vim.api.nvim_create_autocmd("FileType", {
+ pattern = "*",
+ callback = function() vim.g.executed = true end,
+ })
+ ]], {})
+
+
+ eq(true, exec_lua([[
+ vim.cmd "set filetype=txt"
+ return vim.g.executed
+ ]], {}))
+ end)
+
+ it('calls multiple lua callbacks for the same autocmd execution', function()
+ eq(4, exec_lua([[
+ local count = 0
+ local counter = function()
+ count = count + 1
+ end
+
+ vim.api.nvim_create_autocmd("FileType", {
+ pattern = "*",
+ callback = counter,
+ })
+
+ vim.api.nvim_create_autocmd("FileType", {
+ pattern = "*",
+ callback = counter,
+ })
+
+ vim.cmd "set filetype=txt"
+ vim.cmd "set filetype=txt"
+
+ return count
+ ]], {}))
+ end)
+
+ it('properly releases functions with ++once', function()
+ exec_lua([[
+ WeakTable = setmetatable({}, { __mode = "k" })
+
+ OnceCount = 0
+
+ MyVal = {}
+ WeakTable[MyVal] = true
+
+ vim.api.nvim_create_autocmd("FileType", {
+ pattern = "*",
+ callback = function()
+ OnceCount = OnceCount + 1
+ MyVal = {}
+ end,
+ once = true
+ })
+ ]])
+
+ command [[set filetype=txt]]
+ eq(1, exec_lua([[return OnceCount]], {}))
+
+ exec_lua([[collectgarbage()]], {})
+
+ command [[set filetype=txt]]
+ eq(1, exec_lua([[return OnceCount]], {}))
+
+ eq(0, exec_lua([[
+ local count = 0
+ for _ in pairs(WeakTable) do
+ count = count + 1
+ end
+
+ return count
+ ]]), "Should have no keys remaining")
+ end)
+
+ it('groups can be cleared', function()
+ local augroup = "TestGroup"
+ meths.create_augroup(augroup, { clear = true })
+ meths.create_autocmd("FileType", {
+ group = augroup,
+ command = "let g:executed = g:executed + 1"
+ })
+
+ set_ft("txt")
+ set_ft("txt")
+ eq(2, get_executed_count(), "should only count twice")
+
+ meths.create_augroup(augroup, { clear = true })
+ eq({}, meths.get_autocmds { group = augroup })
+
+ set_ft("txt")
+ set_ft("txt")
+ eq(2, get_executed_count(), "No additional counts")
+ end)
+
+ it('groups work with once', function()
+ local augroup = "TestGroup"
+
+ meths.create_augroup(augroup, { clear = true })
+ make_counting_autocmd { group = augroup, once = true }
+
+ set_ft("txt")
+ set_ft("python")
+
+ eq(get_executed_count(), 1)
+ end)
+
+ it('autocmds can be registered multiple times.', function()
+ local augroup = "TestGroup"
+
+ meths.create_augroup(augroup, { clear = true })
+ make_counting_autocmd { group = augroup, once = false }
+ make_counting_autocmd { group = augroup, once = false }
+ make_counting_autocmd { group = augroup, once = false }
+
+ set_ft("txt")
+ set_ft("python")
+
+ eq(get_executed_count(), 3 * 2)
+ end)
+
+ it('can be deleted', function()
+ local augroup = "WillBeDeleted"
+
+ meths.create_augroup(augroup, { clear = true })
+ meths.create_autocmd({"Filetype"}, {
+ pattern = "*",
+ command = "echo 'does not matter'",
+ })
+
+ -- Clears the augroup from before, which erases the autocmd
+ meths.create_augroup(augroup, { clear = true })
+
+ local result = #meths.get_autocmds { group = augroup }
+
+ eq(0, result)
+ end)
+
+ it('can be used for buffer local autocmds', function()
+ local augroup = "WillBeDeleted"
+
+ meths.set_var("value_set", false)
+
+ meths.create_augroup(augroup, { clear = true })
+ meths.create_autocmd("Filetype", {
+ pattern = "<buffer>",
+ command = "let g:value_set = v:true",
+ })
+
+ command "new"
+ command "set filetype=python"
+
+ eq(false, meths.get_var("value_set"))
+ end)
+
+ it('can accept vimscript functions', function()
+ source [[
+ let g:vimscript_executed = 0
+
+ function! MyVimscriptFunction() abort
+ let g:vimscript_executed = g:vimscript_executed + 1
+ endfunction
+
+ call nvim_create_autocmd("FileType", #{
+ \ pattern: ["python", "javascript"],
+ \ callback: "MyVimscriptFunction",
+ \ })
+
+ set filetype=txt
+ set filetype=python
+ set filetype=txt
+ set filetype=javascript
+ set filetype=txt
+ ]]
+
+ eq(2, meths.get_var("vimscript_executed"))
+ end)
+ end)
+
+ describe('augroup!', function()
+ it('legacy: should clear and not return any autocmds for delete groups', function()
+ command('augroup TEMP_A')
+ command(' autocmd! BufReadPost *.py :echo "Hello"')
+ command('augroup END')
+
+ command('augroup! TEMP_A')
+
+ eq(false, pcall(meths.get_autocmds, { group = 'TEMP_A' }))
+
+ -- For some reason, augroup! doesn't clear the autocmds themselves, which is just wild
+ -- but we managed to keep this behavior.
+ eq(1, #meths.get_autocmds { event = 'BufReadPost' })
+ end)
+
+ it('legacy: remove augroups that have no autocmds', function()
+ command('augroup TEMP_AB')
+ command('augroup END')
+
+ command('augroup! TEMP_AB')
+
+ eq(false, pcall(meths.get_autocmds, { group = 'TEMP_AB' }))
+ eq(0, #meths.get_autocmds { event = 'BufReadPost' })
+ end)
+
+ it('legacy: multiple remove and add augroup', function()
+ command('augroup TEMP_ABC')
+ command(' au!')
+ command(' autocmd BufReadPost *.py echo "Hello"')
+ command('augroup END')
+
+ command('augroup! TEMP_ABC')
+
+ -- Should still have one autocmd :'(
+ local aus = meths.get_autocmds { event = 'BufReadPost' }
+ eq(1, #aus, aus)
+
+ command('augroup TEMP_ABC')
+ command(' au!')
+ command(' autocmd BufReadPost *.py echo "Hello"')
+ command('augroup END')
+
+ -- Should now have two autocmds :'(
+ aus = meths.get_autocmds { event = 'BufReadPost' }
+ eq(2, #aus, aus)
+
+ command('augroup! TEMP_ABC')
+
+ eq(false, pcall(meths.get_autocmds, { group = 'TEMP_ABC' }))
+ eq(2, #meths.get_autocmds { event = 'BufReadPost' })
+ end)
+
+ it('api: should clear and not return any autocmds for delete groups by id', function()
+ command('augroup TEMP_ABCD')
+ command('autocmd! BufReadPost *.py :echo "Hello"')
+ command('augroup END')
+
+ local augroup_id = meths.create_augroup("TEMP_ABCD", { clear = false })
+ meths.del_augroup_by_id(augroup_id)
+
+ -- For good reason, we kill all the autocmds from del_augroup,
+ -- so now this works as expected
+ eq(false, pcall(meths.get_autocmds, { group = 'TEMP_ABCD' }))
+ eq(0, #meths.get_autocmds { event = 'BufReadPost' })
+ end)
+
+ it('api: should clear and not return any autocmds for delete groups by name', function()
+ command('augroup TEMP_ABCDE')
+ command('autocmd! BufReadPost *.py :echo "Hello"')
+ command('augroup END')
+
+ meths.del_augroup_by_name("TEMP_ABCDE")
+
+ -- For good reason, we kill all the autocmds from del_augroup,
+ -- so now this works as expected
+ eq(false, pcall(meths.get_autocmds, { group = 'TEMP_ABCDE' }))
+ eq(0, #meths.get_autocmds { event = 'BufReadPost' })
+ end)
+ end)
+end)
diff --git a/test/functional/api/buffer_spec.lua b/test/functional/api/buffer_spec.lua
index 688f3abba5..dd3af8c28f 100644
--- a/test/functional/api/buffer_spec.lua
+++ b/test/functional/api/buffer_spec.lua
@@ -423,6 +423,13 @@ describe('api/buf', function()
-- will join multiple lines if needed
set_text(0, 6, 3, 4, {'bar'})
eq({'hello bar'}, get_lines(0, 1, true))
+
+ -- can use negative line numbers
+ set_text(-2, 0, -2, 5, {'goodbye'})
+ eq({'goodbye bar', ''}, get_lines(0, -1, true))
+
+ set_text(-1, 0, -1, 0, {'text'})
+ eq({'goodbye bar', 'text'}, get_lines(0, 2, true))
end)
it('works with undo', function()
@@ -537,6 +544,34 @@ describe('api/buf', function()
end)
end)
+ describe('nvim_buf_get_text', function()
+ local get_text = curbufmeths.get_text
+
+ it('works', function()
+ insert([[
+ hello foo!
+ text]])
+
+ eq({'hello'}, get_text(0, 0, 0, 5, {}))
+ eq({'hello foo!'}, get_text(0, 0, 0, 42, {}))
+ eq({'foo!'}, get_text(0, 6, 0, 10, {}))
+ eq({'foo!', 'tex'}, get_text(0, 6, 1, 3, {}))
+ eq({'foo!', 'tex'}, get_text(-2, 6, -1, 3, {}))
+ eq({''}, get_text(0, 18, 0, 20, {}))
+ eq({'ext'}, get_text(-1, 1, -1, 4, {}))
+ end)
+
+ it('errors on out-of-range', function()
+ eq(false, pcall(get_text, 2, 0, 3, 0, {}))
+ eq(false, pcall(get_text, 0, 0, 4, 0, {}))
+ end)
+
+ it('errors when start is greater than end', function()
+ eq(false, pcall(get_text, 1, 0, 0, 0, {}))
+ eq(false, pcall(get_text, 0, 1, 0, 0, {}))
+ end)
+ end)
+
describe('nvim_buf_get_offset', function()
local get_offset = curbufmeths.get_offset
it('works', function()
diff --git a/test/functional/api/buffer_updates_spec.lua b/test/functional/api/buffer_updates_spec.lua
index c9c9be5406..fc09e4cde0 100644
--- a/test/functional/api/buffer_updates_spec.lua
+++ b/test/functional/api/buffer_updates_spec.lua
@@ -827,6 +827,7 @@ describe('API: buffer events:', function()
end
it('when :terminal lines change', function()
+ if helpers.pending_win32(pending) then return end
local buffer_lines = {}
local expected_lines = {}
command('terminal "'..nvim_prog..'" -u NONE -i NONE -n -c "set shortmess+=A"')
diff --git a/test/functional/api/command_spec.lua b/test/functional/api/command_spec.lua
index de22c9078c..b80004f67c 100644
--- a/test/functional/api/command_spec.lua
+++ b/test/functional/api/command_spec.lua
@@ -107,7 +107,8 @@ describe('nvim_add_user_command', function()
]]
eq({
- args = "hello",
+ args = [[hello my\ friend how\ are\ you?]],
+ fargs = {[[hello]], [[my\ friend]], [[how\ are\ you?]]},
bang = false,
line1 = 1,
line2 = 1,
@@ -115,13 +116,14 @@ describe('nvim_add_user_command', function()
range = 0,
count = 2,
reg = "",
- }, exec_lua [[
- vim.api.nvim_command('CommandWithLuaCallback hello')
+ }, exec_lua [=[
+ vim.api.nvim_command([[CommandWithLuaCallback hello my\ friend how\ are\ you?]])
return result
- ]])
+ ]=])
eq({
- args = "",
+ args = 'h\tey',
+ fargs = {[[h]], [[ey]]},
bang = true,
line1 = 10,
line2 = 10,
@@ -129,13 +131,14 @@ describe('nvim_add_user_command', function()
range = 1,
count = 10,
reg = "",
- }, exec_lua [[
- vim.api.nvim_command('botright 10CommandWithLuaCallback!')
+ }, exec_lua [=[
+ vim.api.nvim_command('botright 10CommandWithLuaCallback! h\tey')
return result
- ]])
+ ]=])
eq({
- args = "",
+ args = "h",
+ fargs = {"h"},
bang = false,
line1 = 1,
line2 = 42,
@@ -144,9 +147,52 @@ describe('nvim_add_user_command', function()
count = 42,
reg = "",
}, exec_lua [[
- vim.api.nvim_command('CommandWithLuaCallback 42')
+ vim.api.nvim_command('CommandWithLuaCallback 42 h')
return result
]])
+
+ eq({
+ args = "",
+ fargs = {""}, -- fargs works without args
+ bang = false,
+ line1 = 1,
+ line2 = 1,
+ mods = "",
+ range = 0,
+ count = 2,
+ reg = "",
+ }, exec_lua [[
+ vim.api.nvim_command('CommandWithLuaCallback')
+ return result
+ ]])
+
+ -- f-args doesn't split when command nargs is 1 or "?"
+ exec_lua [[
+ result = {}
+ vim.api.nvim_add_user_command('CommandWithOneArg', function(opts)
+ result = opts
+ end, {
+ nargs = "?",
+ bang = true,
+ count = 2,
+ })
+ ]]
+
+ eq({
+ args = "hello I'm one argmuent",
+ fargs = {"hello I'm one argmuent"}, -- Doesn't split args
+ bang = false,
+ line1 = 1,
+ line2 = 1,
+ mods = "",
+ range = 0,
+ count = 2,
+ reg = "",
+ }, exec_lua [[
+ vim.api.nvim_command('CommandWithOneArg hello I\'m one argmuent')
+ return result
+ ]])
+
end)
it('can define buffer-local commands', function()
diff --git a/test/functional/api/highlight_spec.lua b/test/functional/api/highlight_spec.lua
index 03b407f4e0..06cdb0bc19 100644
--- a/test/functional/api/highlight_spec.lua
+++ b/test/functional/api/highlight_spec.lua
@@ -28,8 +28,11 @@ describe('API: highlight',function()
bold = true,
italic = true,
reverse = true,
- undercurl = true,
underline = true,
+ underlineline = true,
+ undercurl = true,
+ underdot = true,
+ underdash = true,
strikethrough = true,
}
@@ -52,7 +55,7 @@ describe('API: highlight',function()
eq('Invalid highlight id: 30000', string.match(emsg, 'Invalid.*'))
-- Test all highlight properties.
- command('hi NewHighlight gui=underline,bold,undercurl,italic,reverse,strikethrough')
+ command('hi NewHighlight gui=underline,bold,underlineline,undercurl,underdot,underdash,italic,reverse,strikethrough')
eq(expected_rgb2, nvim("get_hl_by_id", hl_id, true))
-- Test nil argument.
@@ -195,6 +198,9 @@ describe("API: set highlight", function()
reverse = true,
undercurl = true,
underline = true,
+ underdash = true,
+ underdot = true,
+ underlineline = true,
strikethrough = true,
cterm = {
italic = true,
@@ -211,6 +217,9 @@ describe("API: set highlight", function()
reverse = true,
undercurl = true,
underline = true,
+ underdash = true,
+ underdot = true,
+ underlineline = true,
strikethrough = true,
}
local highlight3_result_cterm = {
@@ -274,7 +283,7 @@ describe("API: set highlight", function()
exec_capture('highlight Test_hl'))
meths.set_hl(0, 'Test_hl2', highlight3_config)
- eq('Test_hl2 xxx cterm=undercurl,italic,reverse,strikethrough ctermfg=8 ctermbg=15 gui=bold,underline,undercurl,italic,reverse,strikethrough guifg=#ff0000 guibg=#0032aa',
+ eq('Test_hl2 xxx cterm=undercurl,italic,reverse,strikethrough ctermfg=8 ctermbg=15 gui=bold,underline,underlineline,undercurl,underdot,underdash,italic,reverse,strikethrough guifg=#ff0000 guibg=#0032aa',
exec_capture('highlight Test_hl2'))
-- Colors are stored exactly as they are defined.
@@ -304,10 +313,6 @@ describe("API: set highlight", function()
eq('Test_hl3 xxx ctermbg=9',
exec_capture('highlight Test_hl3'))
- meths.set_hl(0, 'Test_hl3', {})
- eq('Test_hl3 xxx cleared',
- exec_capture('highlight Test_hl3'))
-
eq("'redd' is not a valid color",
pcall_err(meths.set_hl, 0, 'Test_hl3', {fg='redd'}))
@@ -320,5 +325,16 @@ describe("API: set highlight", function()
eq("'#FF00FF' is not a valid color",
pcall_err(meths.set_hl, 0, 'Test_hl3', {ctermfg='#FF00FF'}))
+
+ for _, fg_val in ipairs{ nil, 'NONE', 'nOnE', '', -1 } do
+ meths.set_hl(0, 'Test_hl3', {fg = fg_val})
+ eq('Test_hl3 xxx cleared',
+ exec_capture('highlight Test_hl3'))
+ end
+
+ meths.set_hl(0, 'Test_hl3', {fg='#FF00FF', blend=50})
+ eq('Test_hl3 xxx guifg=#FF00FF blend=50',
+ exec_capture('highlight Test_hl3'))
+
end)
end)
diff --git a/test/functional/api/keymap_spec.lua b/test/functional/api/keymap_spec.lua
index e49e0b8cc4..c0edcde476 100644
--- a/test/functional/api/keymap_spec.lua
+++ b/test/functional/api/keymap_spec.lua
@@ -15,6 +15,9 @@ local pcall_err = helpers.pcall_err
local shallowcopy = helpers.shallowcopy
local sleep = helpers.sleep
+local sid_api_client = -9
+local sid_lua = -8
+
describe('nvim_get_keymap', function()
before_each(clear)
@@ -340,7 +343,7 @@ describe('nvim_get_keymap', function()
script=0,
silent=0,
expr=0,
- sid=0,
+ sid=sid_lua,
buffer=0,
nowait=0,
mode='n',
@@ -357,7 +360,7 @@ describe('nvim_get_keymap', function()
script=0,
silent=0,
expr=0,
- sid=0,
+ sid=sid_api_client,
buffer=0,
nowait=0,
mode='n',
@@ -400,7 +403,7 @@ describe('nvim_set_keymap, nvim_del_keymap', function()
to_return.silent = not opts.silent and 0 or 1
to_return.nowait = not opts.nowait and 0 or 1
to_return.expr = not opts.expr and 0 or 1
- to_return.sid = not opts.sid and 0 or opts.sid
+ to_return.sid = not opts.sid and sid_api_client 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
@@ -625,7 +628,7 @@ describe('nvim_set_keymap, nvim_del_keymap', function()
it('interprets control sequences in expr-quotes correctly when called '
..'inside vim', function()
command([[call nvim_set_keymap('i', "\<space>", "\<tab>", {})]])
- eq(generate_mapargs('i', '<Space>', '\t', {}),
+ eq(generate_mapargs('i', '<Space>', '\t', {sid=0}),
get_mapargs('i', '<Space>'))
feed('i ')
eq({'\t'}, curbufmeths.get_lines(0, -1, 0))
@@ -807,7 +810,7 @@ describe('nvim_set_keymap, nvim_del_keymap', function()
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)
+ eq(generate_mapargs('n', 'asdf', nil, {sid=sid_lua}), mapargs)
end)
it('can make lua expr mappings', function()
@@ -877,24 +880,6 @@ describe('nvim_set_keymap, nvim_del_keymap', function()
eq("\nn lhs rhs\n map description",
helpers.exec_capture("nmap lhs"))
end)
-
- it ('can :filter maps based on description', function()
- meths.set_keymap('n', 'asdf1', 'qwert', {desc='do the one thing'})
- meths.set_keymap('n', 'asdf2', 'qwert', {desc='doesnot really do anything'})
- meths.set_keymap('n', 'asdf3', 'qwert', {desc='do the other thing'})
- eq([[
-
-n asdf3 qwert
- do the other thing
-n asdf1 qwert
- do the one thing]],
- helpers.exec_capture('filter the nmap'))
- end)
-
- it ('shows <nop> as map rhs', function()
- meths.set_keymap('n', 'asdf', '<nop>', {})
- eq('\nn asdf <Nop>', helpers.exec_capture('nmap asdf'))
- end)
end)
describe('nvim_buf_set_keymap, nvim_buf_del_keymap', function()
diff --git a/test/functional/api/vim_spec.lua b/test/functional/api/vim_spec.lua
index 71cd055e08..af6872760a 100644
--- a/test/functional/api/vim_spec.lua
+++ b/test/functional/api/vim_spec.lua
@@ -636,34 +636,374 @@ describe('API', function()
eq('Invalid phase: 4',
pcall_err(request, 'nvim_paste', 'foo', true, 4))
end)
- it('stream: multiple chunks form one undo-block', function()
- nvim('paste', '1/chunk 1 (start)\n', true, 1)
- nvim('paste', '1/chunk 2 (end)\n', true, 3)
- local expected1 = [[
- 1/chunk 1 (start)
- 1/chunk 2 (end)
- ]]
- expect(expected1)
- nvim('paste', '2/chunk 1 (start)\n', true, 1)
- nvim('paste', '2/chunk 2\n', true, 2)
- expect([[
- 1/chunk 1 (start)
- 1/chunk 2 (end)
- 2/chunk 1 (start)
- 2/chunk 2
- ]])
- nvim('paste', '2/chunk 3\n', true, 2)
- nvim('paste', '2/chunk 4 (end)\n', true, 3)
- expect([[
- 1/chunk 1 (start)
- 1/chunk 2 (end)
- 2/chunk 1 (start)
- 2/chunk 2
- 2/chunk 3
- 2/chunk 4 (end)
- ]])
- feed('u') -- Undo.
- expect(expected1)
+ local function run_streamed_paste_tests()
+ it('stream: multiple chunks form one undo-block', function()
+ nvim('paste', '1/chunk 1 (start)\n', true, 1)
+ nvim('paste', '1/chunk 2 (end)\n', true, 3)
+ local expected1 = [[
+ 1/chunk 1 (start)
+ 1/chunk 2 (end)
+ ]]
+ expect(expected1)
+ nvim('paste', '2/chunk 1 (start)\n', true, 1)
+ nvim('paste', '2/chunk 2\n', true, 2)
+ expect([[
+ 1/chunk 1 (start)
+ 1/chunk 2 (end)
+ 2/chunk 1 (start)
+ 2/chunk 2
+ ]])
+ nvim('paste', '2/chunk 3\n', true, 2)
+ nvim('paste', '2/chunk 4 (end)\n', true, 3)
+ expect([[
+ 1/chunk 1 (start)
+ 1/chunk 2 (end)
+ 2/chunk 1 (start)
+ 2/chunk 2
+ 2/chunk 3
+ 2/chunk 4 (end)
+ ]])
+ feed('u') -- Undo.
+ expect(expected1)
+ end)
+ it('stream: Insert mode', function()
+ -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
+ feed('afoo<Esc>u')
+ feed('i')
+ nvim('paste', 'aaaaaa', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('aaaaaabbbbbbccccccdddddd')
+ feed('<Esc>u')
+ expect('')
+ end)
+ describe('stream: Normal mode', function()
+ describe('on empty line', function()
+ before_each(function()
+ -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
+ feed('afoo<Esc>u')
+ end)
+ after_each(function()
+ feed('u')
+ expect('')
+ end)
+ it('pasting one line', function()
+ nvim('paste', 'aaaaaa', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('aaaaaabbbbbbccccccdddddd')
+ end)
+ it('pasting multiple lines', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect([[
+ aaaaaa
+ bbbbbb
+ cccccc
+ dddddd]])
+ end)
+ end)
+ describe('not at the end of a line', function()
+ before_each(function()
+ feed('i||<Esc>')
+ -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
+ feed('afoo<Esc>u')
+ feed('0')
+ end)
+ after_each(function()
+ feed('u')
+ expect('||')
+ end)
+ it('pasting one line', function()
+ nvim('paste', 'aaaaaa', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('|aaaaaabbbbbbccccccdddddd|')
+ end)
+ it('pasting multiple lines', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect([[
+ |aaaaaa
+ bbbbbb
+ cccccc
+ dddddd|]])
+ end)
+ end)
+ describe('at the end of a line', function()
+ before_each(function()
+ feed('i||<Esc>')
+ -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
+ feed('afoo<Esc>u')
+ feed('2|')
+ end)
+ after_each(function()
+ feed('u')
+ expect('||')
+ end)
+ it('pasting one line', function()
+ nvim('paste', 'aaaaaa', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('||aaaaaabbbbbbccccccdddddd')
+ end)
+ it('pasting multiple lines', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect([[
+ ||aaaaaa
+ bbbbbb
+ cccccc
+ dddddd]])
+ end)
+ end)
+ end)
+ describe('stream: Visual mode', function()
+ describe('neither end at the end of a line', function()
+ before_each(function()
+ feed('i|xxx<CR>xxx|<Esc>')
+ -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
+ feed('afoo<Esc>u')
+ feed('3|vhk')
+ end)
+ after_each(function()
+ feed('u')
+ expect([[
+ |xxx
+ xxx|]])
+ end)
+ it('with non-empty chunks', function()
+ nvim('paste', 'aaaaaa', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('|aaaaaabbbbbbccccccdddddd|')
+ end)
+ it('with empty first chunk', function()
+ nvim('paste', '', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('|bbbbbbccccccdddddd|')
+ end)
+ it('with all chunks empty', function()
+ nvim('paste', '', false, 1)
+ nvim('paste', '', false, 2)
+ nvim('paste', '', false, 2)
+ nvim('paste', '', false, 3)
+ expect('||')
+ end)
+ end)
+ describe('cursor at the end of a line', function()
+ before_each(function()
+ feed('i||xxx<CR>xxx<Esc>')
+ -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
+ feed('afoo<Esc>u')
+ feed('3|vko')
+ end)
+ after_each(function()
+ feed('u')
+ expect([[
+ ||xxx
+ xxx]])
+ end)
+ it('with non-empty chunks', function()
+ nvim('paste', 'aaaaaa', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('||aaaaaabbbbbbccccccdddddd')
+ end)
+ it('with empty first chunk', function()
+ nvim('paste', '', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('||bbbbbbccccccdddddd')
+ end)
+ end)
+ describe('other end at the end of a line', function()
+ before_each(function()
+ feed('i||xxx<CR>xxx<Esc>')
+ -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
+ feed('afoo<Esc>u')
+ feed('3|vk')
+ end)
+ after_each(function()
+ feed('u')
+ expect([[
+ ||xxx
+ xxx]])
+ end)
+ it('with non-empty chunks', function()
+ nvim('paste', 'aaaaaa', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('||aaaaaabbbbbbccccccdddddd')
+ end)
+ it('with empty first chunk', function()
+ nvim('paste', '', false, 1)
+ nvim('paste', 'bbbbbb', false, 2)
+ nvim('paste', 'cccccc', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect('||bbbbbbccccccdddddd')
+ end)
+ end)
+ end)
+ describe('stream: linewise Visual mode', function()
+ before_each(function()
+ feed('i123456789<CR>987654321<CR>123456789<Esc>')
+ -- If nvim_paste() calls :undojoin without making any changes, this makes it an error.
+ feed('afoo<Esc>u')
+ end)
+ after_each(function()
+ feed('u')
+ expect([[
+ 123456789
+ 987654321
+ 123456789]])
+ end)
+ describe('selecting the start of a file', function()
+ before_each(function()
+ feed('ggV')
+ end)
+ it('pasting text without final new line', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect([[
+ aaaaaa
+ bbbbbb
+ cccccc
+ dddddd987654321
+ 123456789]])
+ end)
+ it('pasting text with final new line', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd\n', false, 3)
+ expect([[
+ aaaaaa
+ bbbbbb
+ cccccc
+ dddddd
+ 987654321
+ 123456789]])
+ end)
+ end)
+ describe('selecting the middle of a file', function()
+ before_each(function()
+ feed('2ggV')
+ end)
+ it('pasting text without final new line', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect([[
+ 123456789
+ aaaaaa
+ bbbbbb
+ cccccc
+ dddddd123456789]])
+ end)
+ it('pasting text with final new line', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd\n', false, 3)
+ expect([[
+ 123456789
+ aaaaaa
+ bbbbbb
+ cccccc
+ dddddd
+ 123456789]])
+ end)
+ end)
+ describe('selecting the end of a file', function()
+ before_each(function()
+ feed('3ggV')
+ end)
+ it('pasting text without final new line', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect([[
+ 123456789
+ 987654321
+ aaaaaa
+ bbbbbb
+ cccccc
+ dddddd]])
+ end)
+ it('pasting text with final new line', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd\n', false, 3)
+ expect([[
+ 123456789
+ 987654321
+ aaaaaa
+ bbbbbb
+ cccccc
+ dddddd
+ ]])
+ end)
+ end)
+ describe('selecting the whole file', function()
+ before_each(function()
+ feed('ggVG')
+ end)
+ it('pasting text without final new line', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd', false, 3)
+ expect([[
+ aaaaaa
+ bbbbbb
+ cccccc
+ dddddd]])
+ end)
+ it('pasting text with final new line', function()
+ nvim('paste', 'aaaaaa\n', false, 1)
+ nvim('paste', 'bbbbbb\n', false, 2)
+ nvim('paste', 'cccccc\n', false, 2)
+ nvim('paste', 'dddddd\n', false, 3)
+ expect([[
+ aaaaaa
+ bbbbbb
+ cccccc
+ dddddd
+ ]])
+ end)
+ end)
+ end)
+ end
+ describe('without virtualedit,', function()
+ run_streamed_paste_tests()
+ end)
+ describe('with virtualedit=onemore,', function()
+ before_each(function()
+ command('set virtualedit=onemore')
+ end)
+ run_streamed_paste_tests()
end)
it('non-streaming', function()
-- With final "\n".
@@ -738,6 +1078,37 @@ describe('API', function()
eeffgghh
iijjkkll]])
end)
+ it('when searching in Visual mode', function()
+ feed('v/')
+ nvim('paste', 'aabbccdd', true, -1)
+ eq('aabbccdd', funcs.getcmdline())
+ expect('')
+ end)
+ it('pasting with empty last chunk in Cmdline mode', function()
+ local screen = Screen.new(20, 4)
+ screen:attach()
+ feed(':')
+ nvim('paste', 'Foo', true, 1)
+ nvim('paste', '', true, 3)
+ screen:expect([[
+ |
+ ~ |
+ ~ |
+ :Foo^ |
+ ]])
+ end)
+ it('pasting text with control characters in Cmdline mode', function()
+ local screen = Screen.new(20, 4)
+ screen:attach()
+ feed(':')
+ nvim('paste', 'normal! \023\022\006\027', true, -1)
+ screen:expect([[
+ |
+ ~ |
+ ~ |
+ :normal! ^W^V^F^[^ |
+ ]])
+ end)
it('crlf=false does not break lines at CR, CRLF', function()
nvim('paste', 'line 1\r\n\r\rline 2\nline 3\rline 4\r', false, -1)
expect('line 1\r\n\r\rline 2\nline 3\rline 4\r')
@@ -2621,24 +2992,24 @@ describe('API', function()
eq({ str = 'a━━━b', width = 5 },
meths.eval_statusline('a%=b', { fillchar = '━', maxwidth = 5 }))
end)
- it('rejects double-width fillchar', function()
- eq('fillchar must be a single-width character',
- pcall_err(meths.eval_statusline, '', { fillchar = '哦' }))
+ it('treats double-width fillchar as single-width', function()
+ eq({ str = 'a哦哦哦b', width = 5 },
+ meths.eval_statusline('a%=b', { fillchar = '哦', maxwidth = 5 }))
end)
- it('rejects control character fillchar', function()
- eq('fillchar must be a single-width character',
- pcall_err(meths.eval_statusline, '', { fillchar = '\a' }))
+ it('treats control character fillchar as single-width', function()
+ eq({ str = 'a\031\031\031b', width = 5 },
+ meths.eval_statusline('a%=b', { fillchar = '\031', maxwidth = 5 }))
end)
it('rejects multiple-character fillchar', function()
- eq('fillchar must be a single-width character',
+ eq('fillchar must be a single character',
pcall_err(meths.eval_statusline, '', { fillchar = 'aa' }))
end)
it('rejects empty string fillchar', function()
- eq('fillchar must be a single-width character',
+ eq('fillchar must be a single character',
pcall_err(meths.eval_statusline, '', { fillchar = '' }))
end)
it('rejects non-string fillchar', function()
- eq('fillchar must be a single-width character',
+ eq('fillchar must be a single character',
pcall_err(meths.eval_statusline, '', { fillchar = 1 }))
end)
describe('highlight parsing', function()
diff --git a/test/functional/api/window_spec.lua b/test/functional/api/window_spec.lua
index 4d2ffa316a..c31ab2060a 100644
--- a/test/functional/api/window_spec.lua
+++ b/test/functional/api/window_spec.lua
@@ -1,4 +1,5 @@
local helpers = require('test.functional.helpers')(after_each)
+local Screen = require('test.functional.ui.screen')
local clear, nvim, curbuf, curbuf_contents, window, curwin, eq, neq,
ok, feed, insert, eval, tabpage = helpers.clear, helpers.nvim, helpers.curbuf,
helpers.curbuf_contents, helpers.window, helpers.curwin, helpers.eq,
@@ -73,8 +74,7 @@ describe('API/win', function()
eq('typing\n some dumb text', curbuf_contents())
end)
- it('does not leak memory when using invalid window ID with invalid pos',
- function()
+ it('does not leak memory when using invalid window ID with invalid pos', function()
eq('Invalid window id: 1', pcall_err(meths.win_set_cursor, 1, {"b\na"}))
end)
@@ -147,6 +147,46 @@ describe('API/win', function()
eq({2, 5}, window('get_cursor', win))
end)
+ it('updates cursorline and statusline ruler in non-current window', function()
+ local screen = Screen.new(60, 8)
+ screen:set_default_attr_ids({
+ [1] = {bold = true, foreground = Screen.colors.Blue}, -- NonText
+ [2] = {background = Screen.colors.Grey90}, -- CursorLine
+ [3] = {bold = true, reverse = true}, -- StatusLine
+ [4] = {reverse = true}, -- VertSplit, StatusLineNC
+ })
+ screen:attach()
+ command('set ruler')
+ command('set cursorline')
+ insert([[
+ aaa
+ bbb
+ ccc
+ ddd]])
+ local oldwin = curwin()
+ command('vsplit')
+ screen:expect([[
+ aaa {4:│}aaa |
+ bbb {4:│}bbb |
+ ccc {4:│}ccc |
+ {2:dd^d }{4:│}{2:ddd }|
+ {1:~ }{4:│}{1:~ }|
+ {1:~ }{4:│}{1:~ }|
+ {3:[No Name] [+] 4,3 All }{4:[No Name] [+] 4,3 All}|
+ |
+ ]])
+ window('set_cursor', oldwin, {1, 0})
+ screen:expect([[
+ aaa {4:│}{2:aaa }|
+ bbb {4:│}bbb |
+ ccc {4:│}ccc |
+ {2:dd^d }{4:│}ddd |
+ {1:~ }{4:│}{1:~ }|
+ {1:~ }{4:│}{1:~ }|
+ {3:[No Name] [+] 4,3 All }{4:[No Name] [+] 1,1 All}|
+ |
+ ]])
+ end)
end)
describe('{get,set}_height', function()
diff --git a/test/functional/autocmd/autocmd_oldtest_spec.lua b/test/functional/autocmd/autocmd_oldtest_spec.lua
new file mode 100644
index 0000000000..ad3687d7b0
--- /dev/null
+++ b/test/functional/autocmd/autocmd_oldtest_spec.lua
@@ -0,0 +1,86 @@
+local helpers = require('test.functional.helpers')(after_each)
+
+local clear = helpers.clear
+local eq = helpers.eq
+local meths = helpers.meths
+local funcs = helpers.funcs
+
+local exec = function(str)
+ meths.exec(str, false)
+end
+
+describe('oldtests', function()
+ before_each(clear)
+
+ local exec_lines = function(str)
+ return funcs.split(funcs.execute(str), "\n")
+ end
+
+ local add_an_autocmd = function()
+ exec [[
+ augroup vimBarTest
+ au BufReadCmd * echo 'hello'
+ augroup END
+ ]]
+
+ eq(3, #exec_lines('au vimBarTest'))
+ eq(1, #meths.get_autocmds({ group = 'vimBarTest' }))
+ end
+
+ it('should recognize a bar before the {event}', function()
+ -- Good spacing
+ add_an_autocmd()
+ exec [[ augroup vimBarTest | au! | augroup END ]]
+ eq(1, #exec_lines('au vimBarTest'))
+ eq({}, meths.get_autocmds({ group = 'vimBarTest' }))
+
+ -- Sad spacing
+ add_an_autocmd()
+ exec [[ augroup vimBarTest| au!| augroup END ]]
+ eq(1, #exec_lines('au vimBarTest'))
+
+
+ -- test that a bar is recognized after the {event}
+ add_an_autocmd()
+ exec [[ augroup vimBarTest| au!BufReadCmd| augroup END ]]
+ eq(1, #exec_lines('au vimBarTest'))
+
+ add_an_autocmd()
+ exec [[ au! vimBarTest|echo 'hello' ]]
+ eq(1, #exec_lines('au vimBarTest'))
+ end)
+
+ it('should fire on unload buf', function()
+ funcs.writefile({'Test file Xxx1'}, 'Xxx1')
+ funcs.writefile({'Test file Xxx2'}, 'Xxx2')
+
+ local content = [[
+ func UnloadAllBufs()
+ let i = 1
+ while i <= bufnr('$')
+ if i != bufnr('%') && bufloaded(i)
+ exe i . 'bunload'
+ endif
+ let i += 1
+ endwhile
+ endfunc
+ au BufUnload * call UnloadAllBufs()
+ au VimLeave * call writefile(['Test Finished'], 'Xout')
+ set nohidden
+ edit Xxx1
+ split Xxx2
+ q
+ ]]
+
+ funcs.writefile(funcs.split(content, "\n"), 'Xtest')
+
+ funcs.delete('Xout')
+ funcs.system(meths.get_vvar('progpath') .. ' -u NORC -i NONE -N -S Xtest')
+ eq(1, funcs.filereadable('Xout'))
+
+ funcs.delete('Xxx1')
+ funcs.delete('Xxx2')
+ funcs.delete('Xtest')
+ funcs.delete('Xout')
+ end)
+end)
diff --git a/test/functional/autocmd/autocmd_spec.lua b/test/functional/autocmd/autocmd_spec.lua
index 93d71a9e45..f37f04b32f 100644
--- a/test/functional/autocmd/autocmd_spec.lua
+++ b/test/functional/autocmd/autocmd_spec.lua
@@ -2,8 +2,10 @@ local helpers = require('test.functional.helpers')(after_each)
local Screen = require('test.functional.ui.screen')
local assert_visible = helpers.assert_visible
+local assert_alive = helpers.assert_alive
local dedent = helpers.dedent
local eq = helpers.eq
+local neq = helpers.neq
local eval = helpers.eval
local feed = helpers.feed
local clear = helpers.clear
@@ -13,6 +15,7 @@ local funcs = helpers.funcs
local expect = helpers.expect
local command = helpers.command
local exc_exec = helpers.exc_exec
+local exec_lua = helpers.exec_lua
local curbufmeths = helpers.curbufmeths
local source = helpers.source
@@ -333,6 +336,68 @@ describe('autocmd', function()
pcall_err(command, "call nvim_set_current_win(g:winid)"))
end)
+ it("`aucmd_win` cannot be changed into a normal window #13699", function()
+ local screen = Screen.new(50, 10)
+ screen:attach()
+ screen:set_default_attr_ids {
+ [1] = {bold = true, foreground = Screen.colors.Blue1},
+ [2] = {reverse = true},
+ [3] = {bold = true, reverse = true},
+ }
+
+ -- Create specific layout and ensure it's left unchanged.
+ -- Use nvim_buf_call on a hidden buffer so aucmd_win is used.
+ exec_lua [[
+ vim.cmd "wincmd s | wincmd _"
+ _G.buf = vim.api.nvim_create_buf(true, true)
+ vim.api.nvim_buf_call(_G.buf, function() vim.cmd "wincmd J" end)
+ ]]
+ screen:expect [[
+ ^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {3:[No Name] }|
+ |
+ {2:[No Name] }|
+ |
+ ]]
+ -- This used to crash after making aucmd_win a normal window via the above.
+ exec_lua [[
+ vim.cmd "tabnew | tabclose # | wincmd s | wincmd _"
+ vim.api.nvim_buf_call(_G.buf, function() vim.cmd "wincmd K" end)
+ ]]
+ assert_alive()
+ screen:expect_unchanged()
+
+ -- Ensure splitting still works from inside the aucmd_win.
+ exec_lua [[vim.api.nvim_buf_call(_G.buf, function() vim.cmd "split" end)]]
+ screen:expect [[
+ ^ |
+ {1:~ }|
+ {3:[No Name] }|
+ |
+ {1:~ }|
+ {2:[Scratch] }|
+ |
+ {1:~ }|
+ {2:[No Name] }|
+ |
+ ]]
+
+ -- After all of our messing around, aucmd_win should still be floating.
+ -- Use :only to ensure _G.buf is hidden again (so the aucmd_win is used).
+ eq("editor", exec_lua [[
+ vim.cmd "only"
+ vim.api.nvim_buf_call(_G.buf, function()
+ _G.config = vim.api.nvim_win_get_config(0)
+ end)
+ return _G.config.relative
+ ]])
+ end)
+
it(':doautocmd does not warn "No matching autocommands" #10689', function()
local screen = Screen.new(32, 3)
screen:attach()
@@ -354,4 +419,106 @@ describe('autocmd', function()
:doautocmd SessionLoadPost |
]]}
end)
+
+ describe('old_tests', function()
+ it('vimscript: WinNew ++once', function()
+ source [[
+ " Without ++once WinNew triggers twice
+ let g:did_split = 0
+ augroup Testing
+ au!
+ au WinNew * let g:did_split += 1
+ augroup END
+ split
+ split
+ call assert_equal(2, g:did_split)
+ call assert_true(exists('#WinNew'))
+ close
+ close
+
+ " With ++once WinNew triggers once
+ let g:did_split = 0
+ augroup Testing
+ au!
+ au WinNew * ++once let g:did_split += 1
+ augroup END
+ split
+ split
+ call assert_equal(1, g:did_split)
+ call assert_false(exists('#WinNew'))
+ close
+ close
+
+ call assert_fails('au WinNew * ++once ++once echo bad', 'E983:')
+ ]]
+
+ meths.set_var('did_split', 0)
+
+ source [[
+ augroup Testing
+ au!
+ au WinNew * let g:did_split += 1
+ augroup END
+
+ split
+ split
+ ]]
+
+ eq(2, meths.get_var('did_split'))
+ eq(1, funcs.exists('#WinNew'))
+
+ -- Now with once
+ meths.set_var('did_split', 0)
+
+ source [[
+ augroup Testing
+ au!
+ au WinNew * ++once let g:did_split += 1
+ augroup END
+
+ split
+ split
+ ]]
+
+ eq(1, meths.get_var('did_split'))
+ eq(0, funcs.exists('#WinNew'))
+
+ -- call assert_fails('au WinNew * ++once ++once echo bad', 'E983:')
+ local ok, msg = pcall(source, [[
+ au WinNew * ++once ++once echo bad
+ ]])
+
+ eq(false, ok)
+ eq(true, not not string.find(msg, 'E983:'))
+ end)
+
+ it('should have autocmds in filetypedetect group', function()
+ source [[filetype on]]
+ neq({}, meths.get_autocmds { group = "filetypedetect" })
+ end)
+
+ it('should not access freed mem', function()
+ source [[
+ au BufEnter,BufLeave,WinEnter,WinLeave 0 vs xxx
+ arg 0
+ argadd
+ all
+ all
+ au!
+ bwipe xxx
+ ]]
+ end)
+
+ it('should allow comma-separated patterns', function()
+ source [[
+ augroup TestingPatterns
+ au!
+ autocmd BufReadCmd *.shada,*.shada.tmp.[a-z] echo 'hello'
+ autocmd BufReadCmd *.shada,*.shada.tmp.[a-z] echo 'hello'
+ augroup END
+ ]]
+
+ eq(4, #meths.get_autocmds { event = "BufReadCmd", group = "TestingPatterns" })
+ end)
+ end)
end)
diff --git a/test/functional/autocmd/cursormoved_spec.lua b/test/functional/autocmd/cursormoved_spec.lua
index 9641d4b096..85d8628d7e 100644
--- a/test/functional/autocmd/cursormoved_spec.lua
+++ b/test/functional/autocmd/cursormoved_spec.lua
@@ -35,6 +35,7 @@ describe('CursorMoved', function()
it("is not triggered by cursor movement prior to first CursorMoved instantiation", function()
source([[
let g:cursormoved = 0
+ autocmd! CursorMoved
autocmd CursorMoved * let g:cursormoved += 1
]])
eq(0, eval('g:cursormoved'))
diff --git a/test/functional/autocmd/show_spec.lua b/test/functional/autocmd/show_spec.lua
new file mode 100644
index 0000000000..59757a7d61
--- /dev/null
+++ b/test/functional/autocmd/show_spec.lua
@@ -0,0 +1,35 @@
+local helpers = require('test.functional.helpers')(after_each)
+
+local clear = helpers.clear
+local command = helpers.command
+local dedent = helpers.dedent
+local eq = helpers.eq
+local funcs = helpers.funcs
+
+describe(":autocmd", function()
+ before_each(clear)
+
+ it("should not segfault when you just do autocmd", function()
+ command ":autocmd"
+ end)
+
+ it("should filter based on ++once", function()
+ command "autocmd! BufEnter"
+ command "autocmd BufEnter * :echo 'Hello'"
+ command [[augroup TestingOne]]
+ command [[ autocmd BufEnter * :echo "Line 1"]]
+ command [[ autocmd BufEnter * :echo "Line 2"]]
+ command [[augroup END]]
+
+ eq(dedent([[
+
+ --- Autocommands ---
+ BufEnter
+ * :echo 'Hello'
+ TestingOne BufEnter
+ * :echo "Line 1"
+ :echo "Line 2"]]),
+ funcs.execute('autocmd BufEnter'))
+
+ end)
+end)
diff --git a/test/functional/autocmd/termxx_spec.lua b/test/functional/autocmd/termxx_spec.lua
index 1e8f981437..bc7a6d6c36 100644
--- a/test/functional/autocmd/termxx_spec.lua
+++ b/test/functional/autocmd/termxx_spec.lua
@@ -32,7 +32,7 @@ describe('autocmd TermClose', function()
retry(nil, nil, function() eq(23, eval('g:test_termclose')) end)
end)
- it('kills job trapping SIGTERM', function()
+ pending('kills job trapping SIGTERM', function()
if iswin() then return end
nvim('set_option', 'shell', 'sh')
nvim('set_option', 'shellcmdflag', '-c')
@@ -52,7 +52,7 @@ describe('autocmd TermClose', function()
ok(duration <= 4000) -- Epsilon for slow CI
end)
- it('kills PTY job trapping SIGHUP and SIGTERM', function()
+ pending('kills PTY job trapping SIGHUP and SIGTERM', function()
if iswin() then return end
nvim('set_option', 'shell', 'sh')
nvim('set_option', 'shellcmdflag', '-c')
diff --git a/test/functional/core/channels_spec.lua b/test/functional/core/channels_spec.lua
index c28300f0f4..ca52404d3b 100644
--- a/test/functional/core/channels_spec.lua
+++ b/test/functional/core/channels_spec.lua
@@ -10,6 +10,8 @@ local nvim_prog = helpers.nvim_prog
local is_os = helpers.is_os
local retry = helpers.retry
local expect_twostreams = helpers.expect_twostreams
+local assert_alive = helpers.assert_alive
+local pcall_err = helpers.pcall_err
describe('channels', function()
local init = [[
@@ -314,3 +316,22 @@ describe('channels', function()
eq({"notification", "exit", {id, 1, {''}}}, next_msg())
end)
end)
+
+describe('loopback', function()
+ before_each(function()
+ clear()
+ command("let chan = sockconnect('pipe', v:servername, {'rpc': v:true})")
+ end)
+
+ it('does not crash when sending raw data', function()
+ eq("Vim(call):Can't send raw data to rpc channel",
+ pcall_err(command, "call chansend(chan, 'test')"))
+ assert_alive()
+ end)
+
+ it('are released when closed', function()
+ local chans = eval('len(nvim_list_chans())')
+ command('call chanclose(chan)')
+ eq(chans - 1, eval('len(nvim_list_chans())'))
+ end)
+end)
diff --git a/test/functional/core/job_spec.lua b/test/functional/core/job_spec.lua
index 0a69660871..a0df3b7767 100644
--- a/test/functional/core/job_spec.lua
+++ b/test/functional/core/job_spec.lua
@@ -78,6 +78,7 @@ describe('jobs', function()
end)
it('append environment with pty #env', function()
+ if helpers.pending_win32(pending) then return end
nvim('command', "let $VAR = 'abc'")
nvim('command', "let $TOTO = 'goodbye world'")
nvim('command', "let g:job_opts.pty = v:true")
diff --git a/test/functional/core/remote_spec.lua b/test/functional/core/remote_spec.lua
new file mode 100644
index 0000000000..602a5a71eb
--- /dev/null
+++ b/test/functional/core/remote_spec.lua
@@ -0,0 +1,142 @@
+local helpers = require('test.functional.helpers')(after_each)
+
+local clear = helpers.clear
+local command = helpers.command
+local eq = helpers.eq
+local expect = helpers.expect
+local funcs = helpers.funcs
+local insert = helpers.insert
+local meths = helpers.meths
+local new_argv = helpers.new_argv
+local neq = helpers.neq
+local set_session = helpers.set_session
+local spawn = helpers.spawn
+local tmpname = helpers.tmpname
+local write_file = helpers.write_file
+
+describe('Remote', function()
+ local fname, other_fname
+ local contents = 'The call is coming from outside the process'
+ local other_contents = "A second file's contents"
+
+ before_each(function()
+ fname = tmpname() .. ' with spaces in the filename'
+ other_fname = tmpname()
+ write_file(fname, contents)
+ write_file(other_fname, other_contents)
+ end)
+
+ describe('connect to server and', function()
+ local server
+ before_each(function()
+ server = spawn(new_argv(), true)
+ set_session(server)
+ end)
+
+ after_each(function()
+ server:close()
+ end)
+
+ local function run_remote(...)
+ set_session(server)
+ local addr = funcs.serverlist()[1]
+ local client_argv = new_argv({args={'--server', addr, ...}})
+
+ -- Create an nvim instance just to run the remote-invoking nvim. We want
+ -- to wait for the remote instance to exit and calling jobwait blocks
+ -- the event loop. If the server event loop is blocked, it can't process
+ -- our incoming --remote calls.
+ local client_starter = spawn(new_argv(), false, nil, true)
+ set_session(client_starter)
+ local client_job_id = funcs.jobstart(client_argv)
+ eq({ 0 }, funcs.jobwait({client_job_id}))
+ client_starter:close()
+ set_session(server)
+ end
+
+ it('edit a single file', function()
+ run_remote('--remote', fname)
+ expect(contents)
+ eq(2, #funcs.getbufinfo())
+ end)
+
+ it('tab edit a single file with a non-changed buffer', function()
+ run_remote('--remote-tab', fname)
+ expect(contents)
+ eq(1, #funcs.gettabinfo())
+ end)
+
+ it('tab edit a single file with a changed buffer', function()
+ insert('hello')
+ run_remote('--remote-tab', fname)
+ expect(contents)
+ eq(2, #funcs.gettabinfo())
+ end)
+
+ it('edit multiple files', function()
+ run_remote('--remote', fname, other_fname)
+ expect(contents)
+ command('next')
+ expect(other_contents)
+ eq(3, #funcs.getbufinfo())
+ end)
+
+ it('send keys', function()
+ run_remote('--remote-send', ':edit '..fname..'<CR><C-W>v')
+ expect(contents)
+ eq(2, #funcs.getwininfo())
+ -- Only a single buffer as we're using edit and not drop like --remote does
+ eq(1, #funcs.getbufinfo())
+ end)
+
+ it('evaluate expressions', function()
+ run_remote('--remote-expr', 'setline(1, "Yo")')
+ expect('Yo')
+ end)
+ end)
+
+ it('creates server if not found', function()
+ clear('--remote', fname)
+ expect(contents)
+ eq(1, #funcs.getbufinfo())
+ -- Since we didn't pass silent, we should get a complaint
+ neq(nil, string.find(meths.exec('messages', true), 'E247'))
+ end)
+
+ it('creates server if not found with tabs', function()
+ clear('--remote-tab-silent', fname, other_fname)
+ expect(contents)
+ eq(2, #funcs.gettabinfo())
+ eq(2, #funcs.getbufinfo())
+ -- We passed silent, so no message should be issued about the server not being found
+ eq(nil, string.find(meths.exec('messages', true), 'E247'))
+ end)
+
+ describe('exits with error on', function()
+ local function run_and_check_exit_code(...)
+ local bogus_argv = new_argv(...)
+
+ -- Create an nvim instance just to run the remote-invoking nvim. We want
+ -- to wait for the remote instance to exit and calling jobwait blocks
+ -- the event loop. If the server event loop is blocked, it can't process
+ -- our incoming --remote calls.
+ clear()
+ local bogus_job_id = funcs.jobstart(bogus_argv)
+ eq({2}, funcs.jobwait({bogus_job_id}))
+ end
+ it('bogus subcommand', function()
+ run_and_check_exit_code('--remote-bogus')
+ end)
+
+ it('send without server', function()
+ run_and_check_exit_code('--remote-send', 'i')
+ end)
+
+ it('expr without server', function()
+ run_and_check_exit_code('--remote-expr', 'setline(1, "Yo")')
+ end)
+ it('wait subcommand', function()
+ run_and_check_exit_code('--remote-wait', fname)
+ end)
+ end)
+end)
diff --git a/test/functional/core/startup_spec.lua b/test/functional/core/startup_spec.lua
index 2fa84e8313..3da7f6ffde 100644
--- a/test/functional/core/startup_spec.lua
+++ b/test/functional/core/startup_spec.lua
@@ -53,6 +53,7 @@ describe('startup', function()
]])
end)
it('in a TTY: has("ttyin")==1 has("ttyout")==1', function()
+ if helpers.pending_win32(pending) then return end
local screen = Screen.new(25, 4)
screen:attach()
if iswin() then
@@ -104,6 +105,7 @@ describe('startup', function()
end)
end)
it('input from pipe (implicit) #7679', function()
+ if helpers.pending_win32(pending) then return end
local screen = Screen.new(25, 4)
screen:attach()
if iswin() then
@@ -259,6 +261,7 @@ describe('startup', function()
end)
it('ENTER dismisses early message #7967', function()
+ if helpers.pending_win32(pending) then return end
local screen
screen = Screen.new(60, 6)
screen:attach()
@@ -491,6 +494,7 @@ describe('sysinit', function()
end)
it('fixed hang issue with -D (#12647)', function()
+ if helpers.pending_win32(pending) then return end
local screen
screen = Screen.new(60, 6)
screen:attach()
diff --git a/test/functional/editor/completion_spec.lua b/test/functional/editor/completion_spec.lua
index befad29922..1a0ee54505 100644
--- a/test/functional/editor/completion_spec.lua
+++ b/test/functional/editor/completion_spec.lua
@@ -1193,4 +1193,23 @@ describe('completion', function()
eq('foobar', eval('g:word'))
feed('<esc>')
end)
+
+ it('does not crash if text is changed by first call to complete function #17489', function()
+ source([[
+ func Complete(findstart, base) abort
+ if a:findstart
+ let col = col('.')
+ call complete_add('#')
+ return col - 1
+ else
+ return []
+ endif
+ endfunc
+
+ set completeopt=longest
+ set completefunc=Complete
+ ]])
+ feed('ifoo#<C-X><C-U>')
+ assert_alive()
+ end)
end)
diff --git a/test/functional/editor/put_spec.lua b/test/functional/editor/put_spec.lua
index c367f8fdd0..cc9fce8f67 100644
--- a/test/functional/editor/put_spec.lua
+++ b/test/functional/editor/put_spec.lua
@@ -138,9 +138,9 @@ describe('put command', function()
end -- create_test_defs() }}}
local function find_cursor_position(expect_string) -- {{{
- -- There must only be one occurance of the character 'x' in
+ -- There must only be one occurrence of the character 'x' in
-- expect_string.
- -- This function removes that occurance, and returns the position that
+ -- This function removes that occurrence, and returns the position that
-- it was in.
-- This returns the cursor position that would leave the 'x' in that
-- place if we feed 'ix<esc>' and the string existed before it.
diff --git a/test/functional/ex_cmds/map_spec.lua b/test/functional/ex_cmds/map_spec.lua
index 84d5bc2335..eae36b9ae9 100644
--- a/test/functional/ex_cmds/map_spec.lua
+++ b/test/functional/ex_cmds/map_spec.lua
@@ -1,11 +1,15 @@
local helpers = require("test.functional.helpers")(after_each)
+local Screen = require('test.functional.ui.screen')
local eq = helpers.eq
+local exec = helpers.exec
local feed = helpers.feed
local meths = helpers.meths
local clear = helpers.clear
local command = helpers.command
local expect = helpers.expect
+local insert = helpers.insert
+local eval = helpers.eval
describe(':*map', function()
before_each(clear)
@@ -25,4 +29,221 @@ describe(':*map', function()
feed('i-<M-">-')
expect('-foo-')
end)
+
+ it('shows <nop> as mapping rhs', function()
+ command('nmap asdf <Nop>')
+ eq([[
+
+n asdf <Nop>]],
+ helpers.exec_capture('nmap asdf'))
+ end)
+
+ it('mappings with description can be filtered', function()
+ meths.set_keymap('n', 'asdf1', 'qwert', {desc='do the one thing'})
+ meths.set_keymap('n', 'asdf2', 'qwert', {desc='doesnot really do anything'})
+ meths.set_keymap('n', 'asdf3', 'qwert', {desc='do the other thing'})
+ eq([[
+
+n asdf3 qwert
+ do the other thing
+n asdf1 qwert
+ do the one thing]],
+ helpers.exec_capture('filter the nmap'))
+ end)
+
+ it('<Plug> mappings ignore nore', function()
+ command('let x = 0')
+ eq(0, meths.eval('x'))
+ command [[
+ nnoremap <Plug>(Increase_x) <cmd>let x+=1<cr>
+ nmap increase_x_remap <Plug>(Increase_x)
+ nnoremap increase_x_noremap <Plug>(Increase_x)
+ ]]
+ feed('increase_x_remap')
+ eq(1, meths.eval('x'))
+ feed('increase_x_noremap')
+ eq(2, meths.eval('x'))
+ end)
+
+ it("Doesn't auto ignore nore for keys before or after <Plug> mapping", function()
+ command('let x = 0')
+ eq(0, meths.eval('x'))
+ command [[
+ nnoremap x <nop>
+ nnoremap <Plug>(Increase_x) <cmd>let x+=1<cr>
+ nmap increase_x_remap x<Plug>(Increase_x)x
+ nnoremap increase_x_noremap x<Plug>(Increase_x)x
+ ]]
+ insert("Some text")
+ eq('Some text', eval("getline('.')"))
+
+ feed('increase_x_remap')
+ eq(1, meths.eval('x'))
+ eq('Some text', eval("getline('.')"))
+ feed('increase_x_noremap')
+ eq(2, meths.eval('x'))
+ eq('Some te', eval("getline('.')"))
+ end)
+end)
+
+describe(':*map cursor and redrawing', function()
+ local screen
+ before_each(function()
+ clear()
+ screen = Screen.new(20, 5)
+ screen:attach()
+ end)
+
+ it('cursor is restored after :map <expr> which calls input()', function()
+ command('map <expr> x input("> ")')
+ screen:expect([[
+ ^ |
+ ~ |
+ ~ |
+ ~ |
+ |
+ ]])
+ feed('x')
+ screen:expect([[
+ |
+ ~ |
+ ~ |
+ ~ |
+ > ^ |
+ ]])
+ feed('\n')
+ screen:expect([[
+ ^ |
+ ~ |
+ ~ |
+ ~ |
+ > |
+ ]])
+ end)
+
+ it('cursor is restored after :imap <expr> which calls input()', function()
+ command('imap <expr> x input("> ")')
+ feed('i')
+ screen:expect([[
+ ^ |
+ ~ |
+ ~ |
+ ~ |
+ -- INSERT -- |
+ ]])
+ feed('x')
+ screen:expect([[
+ |
+ ~ |
+ ~ |
+ ~ |
+ > ^ |
+ ]])
+ feed('\n')
+ screen:expect([[
+ ^ |
+ ~ |
+ ~ |
+ ~ |
+ > |
+ ]])
+ end)
+
+ it('cursor is restored after :map <expr> which redraws statusline vim-patch:8.1.2336', function()
+ exec([[
+ call setline(1, ['one', 'two', 'three'])
+ 2
+ set ls=2
+ hi! link StatusLine ErrorMsg
+ noremap <expr> <C-B> Func()
+ func Func()
+ let g:on = !get(g:, 'on', 0)
+ redraws
+ return ''
+ endfunc
+ func Status()
+ return get(g:, 'on', 0) ? '[on]' : ''
+ endfunc
+ set stl=%{Status()}
+ ]])
+ feed('<C-B>')
+ screen:expect([[
+ one |
+ ^two |
+ three |
+ [on] |
+ |
+ ]])
+ end)
+
+ it('error in :nmap <expr> does not mess up display vim-patch:4.2.4338', function()
+ screen:try_resize(40, 5)
+ command('nmap <expr> <F2> execute("throw 42")')
+ feed('<F2>')
+ screen:expect([[
+ |
+ |
+ Error detected while processing : |
+ E605: Exception not caught: 42 |
+ Press ENTER or type command to continue^ |
+ ]])
+ feed('<CR>')
+ screen:expect([[
+ ^ |
+ ~ |
+ ~ |
+ ~ |
+ |
+ ]])
+ end)
+
+ it('error in :cmap <expr> handled correctly vim-patch:4.2.4338', function()
+ screen:try_resize(40, 5)
+ command('cmap <expr> <F2> execute("throw 42")')
+ feed(':echo "foo')
+ screen:expect([[
+ |
+ ~ |
+ ~ |
+ ~ |
+ :echo "foo^ |
+ ]])
+ feed('<F2>')
+ screen:expect([[
+ |
+ :echo "foo |
+ Error detected while processing : |
+ E605: Exception not caught: 42 |
+ :echo "foo^ |
+ ]])
+ feed('"')
+ screen:expect([[
+ |
+ :echo "foo |
+ Error detected while processing : |
+ E605: Exception not caught: 42 |
+ :echo "foo"^ |
+ ]])
+ feed('\n')
+ screen:expect([[
+ :echo "foo |
+ Error detected while processing : |
+ E605: Exception not caught: 42 |
+ foo |
+ Press ENTER or type command to continue^ |
+ ]])
+ end)
+
+ it('listing mappings clears command line vim-patch:8.2.4401', function()
+ screen:try_resize(40, 5)
+ command('nmap a b')
+ feed(': nmap a<CR>')
+ screen:expect([[
+ ^ |
+ ~ |
+ ~ |
+ ~ |
+ n a b |
+ ]])
+ end)
end)
diff --git a/test/functional/ex_cmds/mksession_spec.lua b/test/functional/ex_cmds/mksession_spec.lua
index aefcc53cab..2702fb196f 100644
--- a/test/functional/ex_cmds/mksession_spec.lua
+++ b/test/functional/ex_cmds/mksession_spec.lua
@@ -14,6 +14,7 @@ local rmdir = helpers.rmdir
local file_prefix = 'Xtest-functional-ex_cmds-mksession_spec'
describe(':mksession', function()
+ if helpers.pending_win32(pending) then return end
local session_file = file_prefix .. '.vim'
local tab_dir = file_prefix .. '.d'
diff --git a/test/functional/ex_cmds/verbose_spec.lua b/test/functional/ex_cmds/verbose_spec.lua
new file mode 100644
index 0000000000..326104dc3c
--- /dev/null
+++ b/test/functional/ex_cmds/verbose_spec.lua
@@ -0,0 +1,168 @@
+local helpers = require('test.functional.helpers')(after_each)
+
+local clear = helpers.clear
+local eq = helpers.eq
+local exec = helpers.exec
+local exec_capture = helpers.exec_capture
+local write_file = helpers.write_file
+local call_viml_function = helpers.meths.call_function
+
+describe('lua :verbose', function()
+ local script_location, script_file
+ -- All test cases below use the same nvim instance.
+ setup(function()
+ clear{args={'-V1'}}
+ script_file = 'test_verbose.lua'
+ local current_dir = call_viml_function('getcwd', {})
+ current_dir = call_viml_function('fnamemodify', {current_dir, ':~'})
+ script_location = table.concat{current_dir, helpers.get_pathsep(), script_file}
+
+ write_file(script_file, [[
+vim.api.nvim_set_option('hlsearch', false)
+vim.bo.expandtab = true
+vim.opt.number = true
+vim.api.nvim_set_keymap('n', '<leader>key1', ':echo "test"<cr>', {noremap = true})
+vim.keymap.set('n', '<leader>key2', ':echo "test"<cr>')
+
+vim.api.nvim_exec("augroup test_group\
+ autocmd!\
+ autocmd FileType c setl cindent\
+ augroup END\
+ ", false)
+
+vim.api.nvim_command("command Bdelete :bd")
+vim.api.nvim_add_user_command("TestCommand", ":echo 'Hello'", {})
+
+vim.api.nvim_exec ("\
+function Close_Window() abort\
+ wincmd -\
+endfunction\
+", false)
+
+local ret = vim.api.nvim_exec ("\
+function! s:return80()\
+ return 80\
+endfunction\
+let &tw = s:return80()\
+", true)
+]])
+ exec(':source '..script_file)
+ end)
+
+ teardown(function()
+ os.remove(script_file)
+ end)
+
+ it('"Last set" for option set by Lua', function()
+ local result = exec_capture(':verbose set hlsearch?')
+ eq(string.format([[
+nohlsearch
+ Last set from %s line 1]],
+ script_location), result)
+ end)
+
+ it('"Last set" for option set by vim.o', function()
+ local result = exec_capture(':verbose set expandtab?')
+ eq(string.format([[
+ expandtab
+ Last set from %s line 2]],
+ script_location), result)
+ end)
+
+ it('"Last set" for option set by vim.opt', function()
+ local result = exec_capture(':verbose set number?')
+ eq(string.format([[
+ number
+ Last set from %s line 3]],
+ script_location), result)
+ end)
+
+ it('"Last set" for keymap set by Lua', function()
+ local result = exec_capture(':verbose map <leader>key1')
+ eq(string.format([[
+
+n \key1 * :echo "test"<CR>
+ Last set from %s line 4]],
+ script_location), result)
+ end)
+
+ it('"Last set" for keymap set by vim.keymap', function()
+ local result = exec_capture(':verbose map <leader>key2')
+ eq(string.format([[
+
+n \key2 * :echo "test"<CR>
+ Last set from %s line 5]],
+ script_location), result)
+ end)
+
+ it('"Last set" for autocmd by vim.api.nvim_exec', function()
+ local result = exec_capture(':verbose autocmd test_group Filetype c')
+ eq(string.format([[
+--- Autocommands ---
+test_group FileType
+ c setl cindent
+ Last set from %s line 7]],
+ script_location), result)
+ end)
+
+ it('"Last set" for command defined by nvim_command', function()
+ local result = exec_capture(':verbose command Bdelete')
+ eq(string.format([[
+ Name Args Address Complete Definition
+ Bdelete 0 :bd
+ Last set from %s line 13]],
+ script_location), result)
+ end)
+
+ it('"Last set" for command defined by nvim_add_user_command', function()
+ local result = exec_capture(':verbose command TestCommand')
+ eq(string.format([[
+ Name Args Address Complete Definition
+ TestCommand 0 :echo 'Hello'
+ Last set from %s line 14]],
+ script_location), result)
+ end)
+
+ it('"Last set for function', function()
+ local result = exec_capture(':verbose function Close_Window')
+ eq(string.format([[
+ function Close_Window() abort
+ Last set from %s line 16
+1 wincmd -
+ endfunction]],
+ script_location), result)
+ end)
+
+ it('"Last set" works with anonymous sid', function()
+ local result = exec_capture(':verbose set tw?')
+ eq(string.format([[
+ textwidth=80
+ Last set from %s line 22]],
+ script_location), result)
+ end)
+end)
+
+describe('lua verbose:', function()
+ local script_file
+
+ setup(function()
+ clear()
+ script_file = 'test_luafile.lua'
+ write_file(script_file, [[
+ vim.api.nvim_set_option('hlsearch', false)
+ ]])
+ exec(':source '..script_file)
+ end)
+
+ teardown(function()
+ os.remove(script_file)
+ end)
+
+ it('is disabled when verbose = 0', function()
+ local result = exec_capture(':verbose set hlsearch?')
+ eq([[
+nohlsearch
+ Last set from Lua]], result)
+ end)
+end)
+
diff --git a/test/functional/legacy/autochdir_spec.lua b/test/functional/legacy/autochdir_spec.lua
index 37a94476a0..13cb6cd287 100644
--- a/test/functional/legacy/autochdir_spec.lua
+++ b/test/functional/legacy/autochdir_spec.lua
@@ -1,8 +1,12 @@
local lfs = require('lfs')
local helpers = require('test.functional.helpers')(after_each)
local clear, eq, matches = helpers.clear, helpers.eq, helpers.matches
-local eval, command, call = helpers.eval, helpers.command, helpers.call
-local exec_capture = helpers.exec_capture
+local eval, command, call, meths = helpers.eval, helpers.command, helpers.call, helpers.meths
+local source, exec_capture = helpers.source, helpers.exec_capture
+
+local function expected_empty()
+ eq({}, meths.get_vvar('errors'))
+end
describe('autochdir behavior', function()
local dir = 'Xtest_functional_legacy_autochdir'
@@ -10,19 +14,66 @@ describe('autochdir behavior', function()
before_each(function()
lfs.mkdir(dir)
clear()
+ command('set shellslash')
end)
after_each(function()
helpers.rmdir(dir)
end)
- -- Tests vim/vim/777 without test_autochdir().
+ -- Tests vim/vim#777 without test_autochdir().
it('sets filename', function()
command('set acd')
command('new')
command('w '..dir..'/Xtest')
eq('Xtest', eval("expand('%')"))
- eq(dir, eval([[substitute(getcwd(), '.*[/\\]\(\k*\)', '\1', '')]]))
+ eq(dir, eval([[substitute(getcwd(), '.*/\(\k*\)', '\1', '')]]))
+ end)
+
+ it(':file in win_execute() does not cause wrong directory', function()
+ command('cd '..dir)
+ source([[
+ func Test_set_filename_other_window()
+ let cwd = getcwd()
+ call mkdir('Xa')
+ call mkdir('Xb')
+ call mkdir('Xc')
+ try
+ args Xa/aaa.txt Xb/bbb.txt
+ set acd
+ let winid = win_getid()
+ snext
+ call assert_equal('Xb', substitute(getcwd(), '.*/\([^/]*\)$', '\1', ''))
+ call win_execute(winid, 'file ' .. cwd .. '/Xc/ccc.txt')
+ call assert_equal('Xb', substitute(getcwd(), '.*/\([^/]*\)$', '\1', ''))
+ finally
+ set noacd
+ call chdir(cwd)
+ call delete('Xa', 'rf')
+ call delete('Xb', 'rf')
+ call delete('Xc', 'rf')
+ bwipe! aaa.txt
+ bwipe! bbb.txt
+ bwipe! ccc.txt
+ endtry
+ endfunc
+ ]])
+ call('Test_set_filename_other_window')
+ expected_empty()
+ end)
+
+ it('win_execute() does not change directory', function()
+ local subdir = 'Xfile'
+ command('cd '..dir)
+ command('set acd')
+ call('mkdir', subdir)
+ local winid = eval('win_getid()')
+ command('new '..subdir..'/file')
+ matches(dir..'/'..subdir..'$', eval('getcwd()'))
+ command('cd ..')
+ matches(dir..'$', eval('getcwd()'))
+ call('win_execute', winid, 'echo')
+ matches(dir..'$', eval('getcwd()'))
end)
it(':verbose pwd shows whether autochdir is used', function()
@@ -30,29 +81,36 @@ describe('autochdir behavior', function()
command('cd '..dir)
local cwd = eval('getcwd()')
command('edit global.txt')
- matches('%[global%].*'..dir, exec_capture('verbose pwd'))
+ matches('%[global%].*'..dir..'$', exec_capture('verbose pwd'))
call('mkdir', subdir)
command('split '..subdir..'/local.txt')
command('lcd '..subdir)
- matches('%[window%].*'..dir..'[/\\]'..subdir, exec_capture('verbose pwd'))
- command('set autochdir')
+ matches('%[window%].*'..dir..'/'..subdir..'$', exec_capture('verbose pwd'))
+ command('set acd')
command('wincmd w')
- matches('%[autochdir%].*'..dir, exec_capture('verbose pwd'))
- command('lcd '..cwd)
- matches('%[window%].*'..dir, exec_capture('verbose pwd'))
+ matches('%[autochdir%].*'..dir..'$', exec_capture('verbose pwd'))
command('tcd '..cwd)
- matches('%[tabpage%].*'..dir, exec_capture('verbose pwd'))
+ matches('%[tabpage%].*'..dir..'$', exec_capture('verbose pwd'))
command('cd '..cwd)
- matches('%[global%].*'..dir, exec_capture('verbose pwd'))
+ matches('%[global%].*'..dir..'$', exec_capture('verbose pwd'))
+ command('lcd '..cwd)
+ matches('%[window%].*'..dir..'$', exec_capture('verbose pwd'))
command('edit')
- matches('%[autochdir%].*'..dir, exec_capture('verbose pwd'))
+ matches('%[autochdir%].*'..dir..'$', exec_capture('verbose pwd'))
+ command('enew')
command('wincmd w')
- matches('%[autochdir%].*'..dir..'[/\\]'..subdir, exec_capture('verbose pwd'))
- command('set noautochdir')
- matches('%[autochdir%].*'..dir..'[/\\]'..subdir, exec_capture('verbose pwd'))
+ matches('%[autochdir%].*'..dir..'/'..subdir..'$', exec_capture('verbose pwd'))
command('wincmd w')
- matches('%[global%].*'..dir, exec_capture('verbose pwd'))
+ matches('%[window%].*'..dir..'$', exec_capture('verbose pwd'))
+ command('wincmd w')
+ matches('%[autochdir%].*'..dir..'/'..subdir..'$', exec_capture('verbose pwd'))
+ command('set noacd')
+ matches('%[autochdir%].*'..dir..'/'..subdir..'$', exec_capture('verbose pwd'))
+ command('wincmd w')
+ matches('%[window%].*'..dir..'$', exec_capture('verbose pwd'))
+ command('cd '..cwd)
+ matches('%[global%].*'..dir..'$', exec_capture('verbose pwd'))
command('wincmd w')
- matches('%[window%].*'..dir..'[/\\]'..subdir, exec_capture('verbose pwd'))
+ matches('%[window%].*'..dir..'/'..subdir..'$', exec_capture('verbose pwd'))
end)
end)
diff --git a/test/functional/legacy/delete_spec.lua b/test/functional/legacy/delete_spec.lua
index 141d9583e6..623b6b14a5 100644
--- a/test/functional/legacy/delete_spec.lua
+++ b/test/functional/legacy/delete_spec.lua
@@ -1,7 +1,6 @@
local helpers = require('test.functional.helpers')(after_each)
local clear, source = helpers.clear, helpers.source
local eq, eval, command = helpers.eq, helpers.eval, helpers.command
-local exc_exec = helpers.exc_exec
describe('Test for delete()', function()
before_each(clear)
@@ -9,42 +8,6 @@ describe('Test for delete()', function()
os.remove('Xfile')
end)
- it('file delete', function()
- command('split Xfile')
- command("call setline(1, ['a', 'b'])")
- command('wq')
- eq(eval("['a', 'b']"), eval("readfile('Xfile')"))
- eq(0, eval("delete('Xfile')"))
- eq(-1, eval("delete('Xfile')"))
- end)
-
- it('directory delete', function()
- command("call mkdir('Xdir1')")
- eq(1, eval("isdirectory('Xdir1')"))
- eq(0, eval("delete('Xdir1', 'd')"))
- eq(0, eval("isdirectory('Xdir1')"))
- eq(-1, eval("delete('Xdir1', 'd')"))
- end)
- it('recursive delete', function()
- command("call mkdir('Xdir1')")
- command("call mkdir('Xdir1/subdir')")
- command("call mkdir('Xdir1/empty')")
- command('split Xdir1/Xfile')
- command("call setline(1, ['a', 'b'])")
- command('w')
- command('w Xdir1/subdir/Xfile')
- command('close')
-
- eq(1, eval("isdirectory('Xdir1')"))
- eq(eval("['a', 'b']"), eval("readfile('Xdir1/Xfile')"))
- eq(1, eval("isdirectory('Xdir1/subdir')"))
- eq(eval("['a', 'b']"), eval("readfile('Xdir1/subdir/Xfile')"))
- eq(1, eval("'Xdir1/empty'->isdirectory()"))
- eq(0, eval("delete('Xdir1', 'rf')"))
- eq(0, eval("isdirectory('Xdir1')"))
- eq(-1, eval("delete('Xdir1', 'd')"))
- end)
-
it('symlink delete', function()
source([[
split Xfile
@@ -115,10 +78,4 @@ describe('Test for delete()', function()
eq(0, eval("delete('Xdir4/Xfile')"))
eq(0, eval("delete('Xdir4', 'd')"))
end)
-
- it('gives correct emsgs', function()
- eq('Vim(call):E474: Invalid argument', exc_exec("call delete('')"))
- eq('Vim(call):E15: Invalid expression: 0',
- exc_exec("call delete('foo', 0)"))
- end)
end)
diff --git a/test/functional/legacy/file_perm_spec.lua b/test/functional/legacy/file_perm_spec.lua
deleted file mode 100644
index ccdbfe0534..0000000000
--- a/test/functional/legacy/file_perm_spec.lua
+++ /dev/null
@@ -1,43 +0,0 @@
--- Test getting and setting file permissions.
-require('os')
-
-local helpers = require('test.functional.helpers')(after_each)
-local clear, call, eq = helpers.clear, helpers.call, helpers.eq
-local neq, exc_exec, eval = helpers.neq, helpers.exc_exec, helpers.eval
-
-describe('Test getting and setting file permissions', function()
- local tempfile = helpers.tmpname()
-
- before_each(function()
- os.remove(tempfile)
- clear()
- end)
-
- it('file permissions', function()
- -- eval() is used to test VimL method syntax for setfperm() and getfperm()
- eq('', call('getfperm', tempfile))
- eq(0, eval("'" .. tempfile .. "'->setfperm('r--------')"))
-
- call('writefile', {'one'}, tempfile)
- eq(9, eval("len('" .. tempfile .. "'->getfperm())"))
-
- eq(1, call('setfperm', tempfile, 'rwx------'))
- if helpers.is_os('win') then
- eq('rw-rw-rw-', call('getfperm', tempfile))
- else
- eq('rwx------', call('getfperm', tempfile))
- end
-
- eq(1, call('setfperm', tempfile, 'r--r--r--'))
- eq('r--r--r--', call('getfperm', tempfile))
-
- local err = exc_exec(('call setfperm("%s", "---")'):format(tempfile))
- neq(err:find('E475:'), nil)
-
- eq(1, call('setfperm', tempfile, 'rwx------'))
- end)
-
- after_each(function()
- os.remove(tempfile)
- end)
-end)
diff --git a/test/functional/legacy/searchpos_spec.lua b/test/functional/legacy/searchpos_spec.lua
deleted file mode 100644
index fc18341c38..0000000000
--- a/test/functional/legacy/searchpos_spec.lua
+++ /dev/null
@@ -1,35 +0,0 @@
-local helpers = require('test.functional.helpers')(after_each)
-local call = helpers.call
-local clear = helpers.clear
-local command = helpers.command
-local eq = helpers.eq
-local eval = helpers.eval
-local insert = helpers.insert
-
-describe('searchpos', function()
- before_each(clear)
-
- it('is working', function()
- insert([[
- 1a3
- 123xyz]])
-
- call('cursor', 1, 1)
- eq({1, 1, 2}, eval([[searchpos('\%(\([a-z]\)\|\_.\)\{-}xyz', 'pcW')]]))
- call('cursor', 1, 2)
- eq({2, 1, 1}, eval([['\%(\([a-z]\)\|\_.\)\{-}xyz'->searchpos('pcW')]]))
-
- command('set cpo-=c')
- call('cursor', 1, 2)
- eq({1, 2, 2}, eval([[searchpos('\%(\([a-z]\)\|\_.\)\{-}xyz', 'pcW')]]))
- call('cursor', 1, 3)
- eq({1, 3, 1}, eval([[searchpos('\%(\([a-z]\)\|\_.\)\{-}xyz', 'pcW')]]))
-
- -- Now with \zs, first match is in column 0, "a" is matched.
- call('cursor', 1, 3)
- eq({2, 4, 2}, eval([[searchpos('\%(\([a-z]\)\|\_.\)\{-}\zsxyz', 'pcW')]]))
- -- With z flag start at cursor column, don't see the "a".
- call('cursor', 1, 3)
- eq({2, 4, 1}, eval([[searchpos('\%(\([a-z]\)\|\_.\)\{-}\zsxyz', 'pcWz')]]))
- end)
-end)
diff --git a/test/functional/legacy/set_spec.lua b/test/functional/legacy/set_spec.lua
deleted file mode 100644
index deb268b1e8..0000000000
--- a/test/functional/legacy/set_spec.lua
+++ /dev/null
@@ -1,30 +0,0 @@
--- Tests for :set
-
-local helpers = require('test.functional.helpers')(after_each)
-local clear, command, eval, eq =
- helpers.clear, helpers.command, helpers.eval, helpers.eq
-
-describe(':set', function()
- before_each(clear)
-
- it('handles backslash properly', function()
- command('set iskeyword=a,b,c')
- command('set iskeyword+=d')
- eq('a,b,c,d', eval('&iskeyword'))
-
- command([[set iskeyword+=\\,e]])
- eq([[a,b,c,d,\,e]], eval('&iskeyword'))
-
- command('set iskeyword-=e')
- eq([[a,b,c,d,\]], eval('&iskeyword'))
-
- command([[set iskeyword-=\]])
- eq('a,b,c,d', eval('&iskeyword'))
- end)
-
- it('recognizes a trailing comma with +=', function()
- command('set wildignore=*.png,')
- command('set wildignore+=*.jpg')
- eq('*.png,*.jpg', eval('&wildignore'))
- end)
-end)
diff --git a/test/functional/lua/api_spec.lua b/test/functional/lua/api_spec.lua
index cb37fb9a1c..f173a15d32 100644
--- a/test/functional/lua/api_spec.lua
+++ b/test/functional/lua/api_spec.lua
@@ -102,6 +102,13 @@ describe('luaeval(vim.api.…)', function()
eq(false, funcs.luaeval('vim.api.nvim__id(false)'))
eq(NIL, funcs.luaeval('vim.api.nvim__id(nil)'))
+ -- API strings from Blobs can work as NUL-terminated C strings
+ eq('Vim(call):E5555: API call: Vim:E15: Invalid expression: ',
+ exc_exec('call nvim_eval(v:_null_blob)'))
+ eq('Vim(call):E5555: API call: Vim:E15: Invalid expression: ',
+ exc_exec('call nvim_eval(0z)'))
+ eq(1, eval('nvim_eval(0z31)'))
+
eq(0, eval([[type(luaeval('vim.api.nvim__id(1)'))]]))
eq(1, eval([[type(luaeval('vim.api.nvim__id("1")'))]]))
eq(3, eval([[type(luaeval('vim.api.nvim__id({1})'))]]))
diff --git a/test/functional/lua/command_line_completion_spec.lua b/test/functional/lua/command_line_completion_spec.lua
index 3ba7e1589f..3a5966755e 100644
--- a/test/functional/lua/command_line_completion_spec.lua
+++ b/test/functional/lua/command_line_completion_spec.lua
@@ -106,6 +106,14 @@ describe('nlua_expand_pat', function()
)
end)
+ it('should work with lazy submodules of "vim" global', function()
+ eq({{ 'inspect' }, 4 },
+ get_completions('vim.inspec'))
+
+ eq({{ 'set' }, 11 },
+ get_completions('vim.keymap.se'))
+ end)
+
it('should be able to interpolate globals', function()
eq(
{{
diff --git a/test/functional/lua/thread_spec.lua b/test/functional/lua/thread_spec.lua
new file mode 100644
index 0000000000..e183ce3a57
--- /dev/null
+++ b/test/functional/lua/thread_spec.lua
@@ -0,0 +1,408 @@
+local helpers = require('test.functional.helpers')(after_each)
+local Screen = require('test.functional.ui.screen')
+local assert_alive = helpers.assert_alive
+local clear = helpers.clear
+local feed = helpers.feed
+local eq = helpers.eq
+local exec_lua = helpers.exec_lua
+local next_msg = helpers.next_msg
+local NIL = helpers.NIL
+local pcall_err = helpers.pcall_err
+
+describe('thread', function()
+ local screen
+
+ before_each(function()
+ clear()
+ screen = Screen.new(50, 10)
+ screen:attach()
+ screen:set_default_attr_ids({
+ [1] = {bold = true, foreground = Screen.colors.Blue1},
+ [2] = {bold = true, reverse = true},
+ [3] = {foreground = Screen.colors.Grey100, background = Screen.colors.Red},
+ [4] = {bold = true, foreground = Screen.colors.SeaGreen4},
+ [5] = {bold = true},
+ })
+ end)
+
+ it('entry func is executed in protected mode', function()
+ exec_lua [[
+ local thread = vim.loop.new_thread(function()
+ error('Error in thread entry func')
+ end)
+ vim.loop.thread_join(thread)
+ ]]
+
+ screen:expect([[
+ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {2: }|
+ {3:Error in luv thread:} |
+ {3:[string "<nvim>"]:2: Error in thread entry func} |
+ {4:Press ENTER or type command to continue}^ |
+ ]])
+ feed('<cr>')
+ assert_alive()
+ end)
+
+ it('callback is executed in protected mode', function()
+ exec_lua [[
+ local thread = vim.loop.new_thread(function()
+ local timer = vim.loop.new_timer()
+ local function ontimeout()
+ timer:stop()
+ timer:close()
+ error('Error in thread callback')
+ end
+ timer:start(10, 0, ontimeout)
+ vim.loop.run()
+ end)
+ vim.loop.thread_join(thread)
+ ]]
+
+ screen:expect([[
+ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {2: }|
+ {3:Error in luv callback, thread:} |
+ {3:[string "<nvim>"]:6: Error in thread callback} |
+ {4:Press ENTER or type command to continue}^ |
+ ]])
+ feed('<cr>')
+ assert_alive()
+ end)
+
+ describe('print', function()
+ it('works', function()
+ exec_lua [[
+ local thread = vim.loop.new_thread(function()
+ print('print in thread')
+ end)
+ vim.loop.thread_join(thread)
+ ]]
+
+ screen:expect([[
+ ^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ print in thread |
+ ]])
+ end)
+
+ it('vim.inspect', function()
+ exec_lua [[
+ local thread = vim.loop.new_thread(function()
+ print(vim.inspect({1,2}))
+ end)
+ vim.loop.thread_join(thread)
+ ]]
+
+ screen:expect([[
+ ^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ { 1, 2 } |
+ ]])
+ end)
+ end)
+
+ describe('vim.*', function()
+ before_each(function()
+ clear()
+ exec_lua [[
+ Thread_Test = {}
+
+ Thread_Test.entry_func = function(async, entry_str, args)
+ local decoded_args = vim.mpack.decode(args)
+ assert(loadstring(entry_str))(async, decoded_args)
+ end
+
+ function Thread_Test:do_test()
+ local async
+ local on_async = self.on_async
+ async = vim.loop.new_async(function(ret)
+ on_async(ret)
+ async:close()
+ end)
+ local thread =
+ vim.loop.new_thread(self.entry_func, async, self.entry_str, self.args)
+ vim.loop.thread_join(thread)
+ end
+
+ Thread_Test.new = function(entry, on_async, ...)
+ self = {}
+ setmetatable(self, {__index = Thread_Test})
+ self.args = vim.mpack.encode({...})
+ self.entry_str = string.dump(entry)
+ self.on_async = on_async
+ return self
+ end
+ ]]
+ end)
+
+ it('is_thread', function()
+ exec_lua [[
+ local entry = function(async)
+ async:send(vim.is_thread())
+ end
+ local on_async = function(ret)
+ vim.rpcnotify(1, 'result', ret)
+ end
+ local thread_test = Thread_Test.new(entry, on_async)
+ thread_test:do_test()
+ ]]
+
+ eq({'notification', 'result', {true}}, next_msg())
+ end)
+
+ it('loop', function()
+ exec_lua [[
+ local entry = function(async)
+ async:send(vim.loop.version())
+ end
+ local on_async = function(ret)
+ vim.rpcnotify(1, ret)
+ end
+ local thread_test = Thread_Test.new(entry, on_async)
+ thread_test:do_test()
+ ]]
+
+ local msg = next_msg()
+ eq(msg[1], 'notification')
+ assert(tonumber(msg[2]) >= 72961)
+ end)
+
+ it('mpack', function()
+ exec_lua [[
+ local entry = function(async)
+ async:send(vim.mpack.encode({33, vim.NIL, 'text'}))
+ end
+ local on_async = function(ret)
+ vim.rpcnotify(1, 'result', vim.mpack.decode(ret))
+ end
+ local thread_test = Thread_Test.new(entry, on_async)
+ thread_test:do_test()
+ ]]
+
+ eq({'notification', 'result', {{33, NIL, 'text'}}}, next_msg())
+ end)
+
+ it('json', function()
+ exec_lua [[
+ local entry = function(async)
+ async:send(vim.json.encode({33, vim.NIL, 'text'}))
+ end
+ local on_async = function(ret)
+ vim.rpcnotify(1, 'result', vim.json.decode(ret))
+ end
+ local thread_test = Thread_Test.new(entry, on_async)
+ thread_test:do_test()
+ ]]
+
+ eq({'notification', 'result', {{33, NIL, 'text'}}}, next_msg())
+ end)
+
+ it('diff', function()
+ exec_lua [[
+ local entry = function(async)
+ async:send(vim.diff('Hello\n', 'Helli\n'))
+ end
+ local on_async = function(ret)
+ vim.rpcnotify(1, 'result', ret)
+ end
+ local thread_test = Thread_Test.new(entry, on_async)
+ thread_test:do_test()
+ ]]
+
+ eq({'notification', 'result',
+ {table.concat({
+ '@@ -1 +1 @@',
+ '-Hello',
+ '+Helli',
+ ''
+ }, '\n')}},
+ next_msg())
+ end)
+ end)
+end)
+
+describe('threadpool', function()
+ before_each(clear)
+
+ it('is_thread', function()
+ eq(false, exec_lua [[return vim.is_thread()]])
+
+ exec_lua [[
+ local work_fn = function()
+ return vim.is_thread()
+ end
+ local after_work_fn = function(ret)
+ vim.rpcnotify(1, 'result', ret)
+ end
+ local work = vim.loop.new_work(work_fn, after_work_fn)
+ work:queue()
+ ]]
+
+ eq({'notification', 'result', {true}}, next_msg())
+ end)
+
+ it('with invalid argument', function()
+ local status = pcall_err(exec_lua, [[
+ local work = vim.loop.new_thread(function() end, function() end)
+ work:queue({})
+ ]])
+
+ eq([[Error executing lua: [string "<nvim>"]:0: Error: thread arg not support type 'function' at 1]],
+ status)
+ end)
+
+ it('with invalid return value', function()
+ local screen = Screen.new(50, 10)
+ screen:attach()
+ screen:set_default_attr_ids({
+ [1] = {bold = true, foreground = Screen.colors.Blue1},
+ [2] = {bold = true, reverse = true},
+ [3] = {foreground = Screen.colors.Grey100, background = Screen.colors.Red},
+ [4] = {bold = true, foreground = Screen.colors.SeaGreen4},
+ [5] = {bold = true},
+ })
+
+ exec_lua [[
+ local work = vim.loop.new_work(function() return {} end, function() end)
+ work:queue()
+ ]]
+
+ screen:expect([[
+ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {2: }|
+ {3:Error in luv thread:} |
+ {3:Error: thread arg not support type 'table' at 1} |
+ {4:Press ENTER or type command to continue}^ |
+ ]])
+ end)
+
+ describe('vim.*', function()
+ before_each(function()
+ clear()
+ exec_lua [[
+ Threadpool_Test = {}
+
+ Threadpool_Test.work_fn = function(work_fn_str, args)
+ local decoded_args = vim.mpack.decode(args)
+ return assert(loadstring(work_fn_str))(decoded_args)
+ end
+
+ function Threadpool_Test:do_test()
+ local work =
+ vim.loop.new_work(self.work_fn, self.after_work)
+ work:queue(self.work_fn_str, self.args)
+ end
+
+ Threadpool_Test.new = function(work_fn, after_work, ...)
+ self = {}
+ setmetatable(self, {__index = Threadpool_Test})
+ self.args = vim.mpack.encode({...})
+ self.work_fn_str = string.dump(work_fn)
+ self.after_work = after_work
+ return self
+ end
+ ]]
+ end)
+
+ it('loop', function()
+ exec_lua [[
+ local work_fn = function()
+ return vim.loop.version()
+ end
+ local after_work_fn = function(ret)
+ vim.rpcnotify(1, ret)
+ end
+ local threadpool_test = Threadpool_Test.new(work_fn, after_work_fn)
+ threadpool_test:do_test()
+ ]]
+
+ local msg = next_msg()
+ eq(msg[1], 'notification')
+ assert(tonumber(msg[2]) >= 72961)
+ end)
+
+ it('mpack', function()
+ exec_lua [[
+ local work_fn = function()
+ local var = vim.mpack.encode({33, vim.NIL, 'text'})
+ return var
+ end
+ local after_work_fn = function(ret)
+ vim.rpcnotify(1, 'result', vim.mpack.decode(ret))
+ end
+ local threadpool_test = Threadpool_Test.new(work_fn, after_work_fn)
+ threadpool_test:do_test()
+ ]]
+
+ eq({'notification', 'result', {{33, NIL, 'text'}}}, next_msg())
+ end)
+
+ it('json', function()
+ exec_lua [[
+ local work_fn = function()
+ local var = vim.json.encode({33, vim.NIL, 'text'})
+ return var
+ end
+ local after_work_fn = function(ret)
+ vim.rpcnotify(1, 'result', vim.json.decode(ret))
+ end
+ local threadpool_test = Threadpool_Test.new(work_fn, after_work_fn)
+ threadpool_test:do_test()
+ ]]
+
+ eq({'notification', 'result', {{33, NIL, 'text'}}}, next_msg())
+ end)
+
+ it('work', function()
+ exec_lua [[
+ local work_fn = function()
+ return vim.diff('Hello\n', 'Helli\n')
+ end
+ local after_work_fn = function(ret)
+ vim.rpcnotify(1, 'result', ret)
+ end
+ local threadpool_test = Threadpool_Test.new(work_fn, after_work_fn)
+ threadpool_test:do_test()
+ ]]
+
+ eq({'notification', 'result',
+ {table.concat({
+ '@@ -1 +1 @@',
+ '-Hello',
+ '+Helli',
+ ''
+ }, '\n')}},
+ next_msg())
+ end)
+ end)
+end)
diff --git a/test/functional/lua/vim_spec.lua b/test/functional/lua/vim_spec.lua
index 7ec986acdd..5b4daf02ea 100644
--- a/test/functional/lua/vim_spec.lua
+++ b/test/functional/lua/vim_spec.lua
@@ -14,7 +14,7 @@ local feed = helpers.feed
local pcall_err = helpers.pcall_err
local exec_lua = helpers.exec_lua
local matches = helpers.matches
-local source = helpers.source
+local exec = helpers.exec
local NIL = helpers.NIL
local retry = helpers.retry
local next_msg = helpers.next_msg
@@ -23,9 +23,9 @@ local mkdir_p = helpers.mkdir_p
local rmdir = helpers.rmdir
local write_file = helpers.write_file
-before_each(clear)
describe('lua stdlib', function()
+ before_each(clear)
-- İ: `tolower("İ")` is `i` which has length 1 while `İ` itself has
-- length 2 (in bytes).
-- Ⱥ: `tolower("Ⱥ")` is `ⱥ` which has length 2 while `Ⱥ` itself has
@@ -743,7 +743,7 @@ describe('lua stdlib', function()
-- compat: nvim_call_function uses "special" value for vimL float
eq(false, exec_lua([[return vim.api.nvim_call_function('sin', {0.0}) == 0.0 ]]))
- source([[
+ exec([[
func! FooFunc(test)
let g:test = a:test
return {}
@@ -771,6 +771,12 @@ describe('lua stdlib', function()
-- error handling
eq({false, 'Vim:E897: List or Blob required'}, exec_lua([[return {pcall(vim.fn.add, "aa", "bb")}]]))
+
+ -- conversion between LuaRef and Vim Funcref
+ eq(true, exec_lua([[
+ local x = vim.fn.VarArg(function() return 'foo' end, function() return 'bar' end)
+ return #x == 2 and x[1]() == 'foo' and x[2]() == 'bar'
+ ]]))
end)
it('vim.fn should error when calling API function', function()
@@ -993,8 +999,11 @@ describe('lua stdlib', function()
exec_lua [[
local counter = 0
- vim.g.AddCounter = function() counter = counter + 1 end
- vim.g.GetCounter = function() return counter end
+ local function add_counter() counter = counter + 1 end
+ local function get_counter() return counter end
+ vim.g.AddCounter = add_counter
+ vim.g.GetCounter = get_counter
+ vim.g.funcs = {add = add_counter, get = get_counter}
]]
eq(0, eval('g:GetCounter()'))
@@ -1006,11 +1015,18 @@ describe('lua stdlib', function()
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([[vim.g.funcs.add()]])
+ eq(5, exec_lua([[return vim.g.funcs.get()]]))
+ exec_lua([[vim.api.nvim_get_var('funcs').add()]])
+ eq(6, exec_lua([[return vim.api.nvim_get_var('funcs').get()]]))
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)
+ local function add_counter() counter = counter + 1 end
+ local function get_counter() return counter end
+ vim.api.nvim_set_var('AddCounter', add_counter)
+ vim.api.nvim_set_var('GetCounter', get_counter)
+ vim.api.nvim_set_var('funcs', {add = add_counter, get = get_counter})
]]
eq(0, eval('g:GetCounter()'))
@@ -1022,6 +1038,10 @@ describe('lua stdlib', function()
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([[vim.g.funcs.add()]])
+ eq(5, exec_lua([[return vim.g.funcs.get()]]))
+ exec_lua([[vim.api.nvim_get_var('funcs').add()]])
+ eq(6, exec_lua([[return vim.api.nvim_get_var('funcs').get()]]))
-- Check if autoload works properly
local pathsep = helpers.get_pathsep()
@@ -1072,8 +1092,11 @@ describe('lua stdlib', function()
exec_lua [[
local counter = 0
- vim.b.AddCounter = function() counter = counter + 1 end
- vim.b.GetCounter = function() return counter end
+ local function add_counter() counter = counter + 1 end
+ local function get_counter() return counter end
+ vim.b.AddCounter = add_counter
+ vim.b.GetCounter = get_counter
+ vim.b.funcs = {add = add_counter, get = get_counter}
]]
eq(0, eval('b:GetCounter()'))
@@ -1085,11 +1108,18 @@ describe('lua stdlib', function()
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.b.funcs.add()]])
+ eq(5, exec_lua([[return vim.b.funcs.get()]]))
+ exec_lua([[vim.api.nvim_buf_get_var(0, 'funcs').add()]])
+ eq(6, exec_lua([[return vim.api.nvim_buf_get_var(0, 'funcs').get()]]))
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)
+ local function add_counter() counter = counter + 1 end
+ local function get_counter() return counter end
+ vim.api.nvim_buf_set_var(0, 'AddCounter', add_counter)
+ vim.api.nvim_buf_set_var(0, 'GetCounter', get_counter)
+ vim.api.nvim_buf_set_var(0, 'funcs', {add = add_counter, get = get_counter})
]]
eq(0, eval('b:GetCounter()'))
@@ -1101,6 +1131,10 @@ describe('lua stdlib', function()
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.b.funcs.add()]])
+ eq(5, exec_lua([[return vim.b.funcs.get()]]))
+ exec_lua([[vim.api.nvim_buf_get_var(0, 'funcs').add()]])
+ eq(6, exec_lua([[return vim.api.nvim_buf_get_var(0, 'funcs').get()]]))
exec_lua [[
vim.cmd "vnew"
@@ -1141,8 +1175,11 @@ describe('lua stdlib', function()
exec_lua [[
local counter = 0
- vim.w.AddCounter = function() counter = counter + 1 end
- vim.w.GetCounter = function() return counter end
+ local function add_counter() counter = counter + 1 end
+ local function get_counter() return counter end
+ vim.w.AddCounter = add_counter
+ vim.w.GetCounter = get_counter
+ vim.w.funcs = {add = add_counter, get = get_counter}
]]
eq(0, eval('w:GetCounter()'))
@@ -1154,11 +1191,18 @@ describe('lua stdlib', function()
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.w.funcs.add()]])
+ eq(5, exec_lua([[return vim.w.funcs.get()]]))
+ exec_lua([[vim.api.nvim_win_get_var(0, 'funcs').add()]])
+ eq(6, exec_lua([[return vim.api.nvim_win_get_var(0, 'funcs').get()]]))
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)
+ local function add_counter() counter = counter + 1 end
+ local function get_counter() return counter end
+ vim.api.nvim_win_set_var(0, 'AddCounter', add_counter)
+ vim.api.nvim_win_set_var(0, 'GetCounter', get_counter)
+ vim.api.nvim_win_set_var(0, 'funcs', {add = add_counter, get = get_counter})
]]
eq(0, eval('w:GetCounter()'))
@@ -1170,6 +1214,10 @@ describe('lua stdlib', function()
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.w.funcs.add()]])
+ eq(5, exec_lua([[return vim.w.funcs.get()]]))
+ exec_lua([[vim.api.nvim_win_get_var(0, 'funcs').add()]])
+ eq(6, exec_lua([[return vim.api.nvim_win_get_var(0, 'funcs').get()]]))
exec_lua [[
vim.cmd "vnew"
@@ -1205,8 +1253,11 @@ describe('lua stdlib', function()
exec_lua [[
local counter = 0
- vim.t.AddCounter = function() counter = counter + 1 end
- vim.t.GetCounter = function() return counter end
+ local function add_counter() counter = counter + 1 end
+ local function get_counter() return counter end
+ vim.t.AddCounter = add_counter
+ vim.t.GetCounter = get_counter
+ vim.t.funcs = {add = add_counter, get = get_counter}
]]
eq(0, eval('t:GetCounter()'))
@@ -1218,11 +1269,18 @@ describe('lua stdlib', function()
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.t.funcs.add()]])
+ eq(5, exec_lua([[return vim.t.funcs.get()]]))
+ exec_lua([[vim.api.nvim_tabpage_get_var(0, 'funcs').add()]])
+ eq(6, exec_lua([[return vim.api.nvim_tabpage_get_var(0, 'funcs').get()]]))
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)
+ local function add_counter() counter = counter + 1 end
+ local function get_counter() return counter end
+ vim.api.nvim_tabpage_set_var(0, 'AddCounter', add_counter)
+ vim.api.nvim_tabpage_set_var(0, 'GetCounter', get_counter)
+ vim.api.nvim_tabpage_set_var(0, 'funcs', {add = add_counter, get = get_counter})
]]
eq(0, eval('t:GetCounter()'))
@@ -1234,6 +1292,10 @@ describe('lua stdlib', function()
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.t.funcs.add()]])
+ eq(5, exec_lua([[return vim.t.funcs.get()]]))
+ exec_lua([[vim.api.nvim_tabpage_get_var(0, 'funcs').add()]])
+ eq(6, exec_lua([[return vim.api.nvim_tabpage_get_var(0, 'funcs').get()]]))
exec_lua [[
vim.cmd "tabnew"
@@ -2534,9 +2596,39 @@ describe('lua stdlib', function()
end)
end)
+describe('lua: builtin modules', function()
+ local function do_tests()
+ eq(2, exec_lua[[return vim.tbl_count {x=1,y=2}]])
+ eq('{ 10, "spam" }', exec_lua[[return vim.inspect {10, 'spam'}]])
+ end
+
+ it('works', function()
+ clear()
+ do_tests()
+ end)
+
+ it('works when disabled', function()
+ clear('--luamod-dev')
+ do_tests()
+ end)
+
+ it('works without runtime', function()
+ clear{env={VIMRUNTIME='fixtures/a'}}
+ do_tests()
+ end)
+
+
+ it('does not work when disabled without runtime', function()
+ clear{args={'--luamod-dev'}, env={VIMRUNTIME='fixtures/a'}}
+ -- error checking could be better here. just check that --luamod-dev
+ -- does anything at all by breaking with missing runtime..
+ eq(nil, exec_lua[[return vim.tbl_count {x=1,y=2}]])
+ end)
+end)
+
describe('lua: require("mod") from packages', function()
before_each(function()
- command('set rtp+=test/functional/fixtures pp+=test/functional/fixtures')
+ clear('--cmd', 'set rtp+=test/functional/fixtures pp+=test/functional/fixtures')
end)
it('propagates syntax error', function()
@@ -2559,6 +2651,8 @@ describe('lua: require("mod") from packages', function()
end)
describe('vim.keymap', function()
+ before_each(clear)
+
it('can make a mapping', function()
eq(0, exec_lua [[
GlobalCount = 0
diff --git a/test/functional/options/autochdir_spec.lua b/test/functional/options/autochdir_spec.lua
index 2fce0a5ed9..74959a8e76 100644
--- a/test/functional/options/autochdir_spec.lua
+++ b/test/functional/options/autochdir_spec.lua
@@ -1,7 +1,9 @@
+local lfs = require('lfs')
local helpers = require('test.functional.helpers')(after_each)
local clear = helpers.clear
local eq = helpers.eq
-local getcwd = helpers.funcs.getcwd
+local funcs = helpers.funcs
+local command = helpers.command
describe("'autochdir'", function()
it('given on the shell gets processed properly', function()
@@ -9,11 +11,34 @@ describe("'autochdir'", function()
-- By default 'autochdir' is off, thus getcwd() returns the repo root.
clear(targetdir..'/tty-test.c')
- local rootdir = getcwd()
+ local rootdir = funcs.getcwd()
local expected = rootdir .. '/' .. targetdir
-- With 'autochdir' on, we should get the directory of tty-test.c.
clear('--cmd', 'set autochdir', targetdir..'/tty-test.c')
- eq(helpers.iswin() and expected:gsub('/', '\\') or expected, getcwd())
+ eq(helpers.iswin() and expected:gsub('/', '\\') or expected, funcs.getcwd())
+ end)
+
+ it('is not overwritten by getwinvar() call #17609',function()
+ local curdir = string.gsub(lfs.currentdir(), '\\', '/')
+ local dir_a = curdir..'/Xtest-functional-options-autochdir.dir_a'
+ local dir_b = curdir..'/Xtest-functional-options-autochdir.dir_b'
+ lfs.mkdir(dir_a)
+ lfs.mkdir(dir_b)
+ clear()
+ command('set shellslash')
+ command('set autochdir')
+ command('edit '..dir_a..'/file1')
+ eq(dir_a, funcs.getcwd())
+ command('lcd '..dir_b)
+ eq(dir_b, funcs.getcwd())
+ command('botright vnew ../file2')
+ eq(curdir, funcs.getcwd())
+ command('wincmd w')
+ eq(dir_a, funcs.getcwd())
+ funcs.getwinvar(2, 'foo')
+ eq(dir_a, funcs.getcwd())
+ helpers.rmdir(dir_a)
+ helpers.rmdir(dir_b)
end)
end)
diff --git a/test/functional/plugin/lsp/diagnostic_spec.lua b/test/functional/plugin/lsp/diagnostic_spec.lua
index 1269a2350c..83d794b620 100644
--- a/test/functional/plugin/lsp/diagnostic_spec.lua
+++ b/test/functional/plugin/lsp/diagnostic_spec.lua
@@ -110,6 +110,7 @@ describe('vim.lsp.diagnostic', function()
}
]]
eq({code = 42, tags = {"foo", "bar"}, data = "Hello world"}, result[1].user_data.lsp)
+ eq(42, result[1].code)
eq(42, result[2].code)
eq({"foo", "bar"}, result[2].tags)
eq("Hello world", result[2].data)
diff --git a/test/functional/plugin/lsp/incremental_sync_spec.lua b/test/functional/plugin/lsp/incremental_sync_spec.lua
index 4e3eddb960..4985da9cd7 100644
--- a/test/functional/plugin/lsp/incremental_sync_spec.lua
+++ b/test/functional/plugin/lsp/incremental_sync_spec.lua
@@ -207,16 +207,16 @@ describe('incremental synchronization', function()
{
range = {
['start'] = {
- character = 0,
- line = 1
+ character = 11,
+ line = 0,
},
['end'] = {
character = 0,
line = 1
}
},
- rangeLength = 0,
- text = 'hello world\n'
+ rangeLength = 1,
+ text = '\nhello world\n'
}
}
test_edit({"hello world"}, {"yyp"}, expected_text_changes, 'utf-16', '\n')
@@ -226,19 +226,57 @@ describe('incremental synchronization', function()
{
range = {
['start'] = {
+ character = 11,
+ line = 0
+ },
+ ['end'] = {
character = 0,
line = 1
+ }
+ },
+ rangeLength = 1,
+ text = '\n\n'
+ }
+ }
+ test_edit({"hello world"}, {"o"}, expected_text_changes, 'utf-16', '\n')
+ end)
+ it('adding a line to an empty buffer', function()
+ local expected_text_changes = {
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 0
},
['end'] = {
character = 0,
line = 1
}
},
+ rangeLength = 1,
+ text = '\n\n'
+ }
+ }
+ test_edit({""}, {"o"}, expected_text_changes, 'utf-16', '\n')
+ end)
+ it('insert a line above the current line', function()
+ local expected_text_changes = {
+ {
+ range = {
+ ['start'] = {
+ character = 0,
+ line = 0
+ },
+ ['end'] = {
+ character = 0,
+ line = 0
+ }
+ },
rangeLength = 0,
text = '\n'
}
}
- test_edit({"hello world"}, {"o"}, expected_text_changes, 'utf-16', '\n')
+ test_edit({""}, {"O"}, expected_text_changes, 'utf-16', '\n')
end)
end)
describe('multi line edit', function()
diff --git a/test/functional/plugin/shada_spec.lua b/test/functional/plugin/shada_spec.lua
index a4d78682ad..6f22f865e6 100644
--- a/test/functional/plugin/shada_spec.lua
+++ b/test/functional/plugin/shada_spec.lua
@@ -1,7 +1,7 @@
local helpers = require('test.functional.helpers')(after_each)
local clear = helpers.clear
-local eq, nvim_eval, nvim_command, nvim, exc_exec, funcs, nvim_feed, curbuf =
- helpers.eq, helpers.eval, helpers.command, helpers.nvim, helpers.exc_exec,
+local eq, meths, nvim_eval, nvim_command, nvim, exc_exec, funcs, nvim_feed, curbuf =
+ helpers.eq, helpers.meths, helpers.eval, helpers.command, helpers.nvim, helpers.exc_exec,
helpers.funcs, helpers.feed, helpers.curbuf
local neq = helpers.neq
local read_file = helpers.read_file
@@ -2162,6 +2162,10 @@ describe('plugin/shada.vim', function()
wshada('\004\000\009\147\000\196\002ab\196\001a')
wshada_tmp('\004\000\009\147\000\196\002ab\196\001b')
+
+ local bufread_commands = meths.get_autocmds({ group = "ShaDaCommands", event = "BufReadCmd" })
+ eq(2, #bufread_commands--[[, vim.inspect(bufread_commands) ]])
+
-- Need to set nohidden so that the buffer containing 'fname' is not unloaded
-- after loading 'fname_tmp', otherwise the '++opt not supported' test below
-- won't work since the BufReadCmd autocmd won't be triggered.
diff --git a/test/functional/provider/clipboard_spec.lua b/test/functional/provider/clipboard_spec.lua
index 986db96a18..5bdfec574e 100644
--- a/test/functional/provider/clipboard_spec.lua
+++ b/test/functional/provider/clipboard_spec.lua
@@ -50,29 +50,33 @@ local function basic_register_test(noblock)
text, stuff and some more
some some text, stuff and some more]])
- -- deleting a word to named ("a) updates "1 (and not "-)
+ -- deleting a word to named ("a) doesn't update "1 or "-
feed('gg"adwj"1P^"-P')
expect([[
, stuff and some more
- some textsome some text, stuff and some more]])
+ some some random text
+ some some text, stuff and some more]])
-- deleting a line does update ""
feed('ggdd""P')
expect([[
, stuff and some more
- some textsome some text, stuff and some more]])
+ some some random text
+ some some text, stuff and some more]])
feed('ggw<c-v>jwyggP')
if noblock then
expect([[
stuf
- me t
+ me s
, stuff and some more
- some textsome some text, stuff and some more]])
+ some some random text
+ some some text, stuff and some more]])
else
expect([[
stuf, stuff and some more
- me tsome textsome some text, stuff and some more]])
+ me ssome some random text
+ some some text, stuff and some more]])
end
-- pasting in visual does unnamed delete of visual selection
diff --git a/test/functional/provider/python3_spec.lua b/test/functional/provider/python3_spec.lua
index 603f4d91b9..d9c44c3315 100644
--- a/test/functional/provider/python3_spec.lua
+++ b/test/functional/provider/python3_spec.lua
@@ -9,6 +9,7 @@ local missing_provider = helpers.missing_provider
local matches = helpers.matches
local pcall_err = helpers.pcall_err
local funcs = helpers.funcs
+local dedent = helpers.dedent
do
clear()
@@ -49,7 +50,12 @@ describe('python3 provider', function()
local very_long_symbol = string.rep('a', 1200)
feed_command(':silent! py3 print('..very_long_symbol..' b)')
-- Error message will contain this (last) line.
- eq('Error invoking \'python_execute\' on channel 3 (python3-script-host):\n File "<string>", line 1\n print('..very_long_symbol..' b)\n '..string.rep(' ',1200)..' ^\nSyntaxError: invalid syntax', eval('v:errmsg'))
+ matches(string.format(dedent([[
+ ^Error invoking 'python_execute' on channel 3 %%(python3%%-script%%-host%%):
+ File "<string>", line 1
+ print%%(%s b%%)
+ %%C*
+ SyntaxError: invalid syntax%%C*$]]), very_long_symbol), eval('v:errmsg'))
end)
it('python3_execute with nested commands', function()
diff --git a/test/functional/terminal/buffer_spec.lua b/test/functional/terminal/buffer_spec.lua
index beb43e0271..1cef771f0d 100644
--- a/test/functional/terminal/buffer_spec.lua
+++ b/test/functional/terminal/buffer_spec.lua
@@ -258,6 +258,7 @@ describe(':terminal buffer', function()
end)
it('it works with set rightleft #11438', function()
+ if helpers.pending_win32(pending) then return end
local columns = eval('&columns')
feed(string.rep('a', columns))
command('set rightleft')
diff --git a/test/functional/terminal/channel_spec.lua b/test/functional/terminal/channel_spec.lua
index 7223f5ba61..b5f3c2bd31 100644
--- a/test/functional/terminal/channel_spec.lua
+++ b/test/functional/terminal/channel_spec.lua
@@ -1,45 +1,94 @@
local helpers = require('test.functional.helpers')(after_each)
+local Screen = require('test.functional.ui.screen')
local clear = helpers.clear
local eq = helpers.eq
+local eval = helpers.eval
local command = helpers.command
local pcall_err = helpers.pcall_err
local feed = helpers.feed
-local sleep = helpers.sleep
local poke_eventloop = helpers.poke_eventloop
-describe('associated channel is closed and later freed for terminal', function()
- before_each(clear)
+describe('terminal channel is closed and later released if', function()
+ local screen
+
+ before_each(function()
+ clear()
+ screen = Screen.new()
+ screen:attach()
+ end)
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", 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')]]))
+ local chans = eval('len(nvim_list_chans())')
+ -- channel hasn't been released yet
+ eq("Vim(call):Can't send data to closed stream",
+ pcall_err(command, [[bdelete! | call chansend(id, 'test')]]))
+ -- channel has been released after one main loop iteration
+ eq(chans - 1, eval('len(nvim_list_chans())'))
+ end)
+
+ it('opened by nvim_open_term(), closed by chanclose(), and deleted by pressing a key', function()
+ command('let id = nvim_open_term(0, {})')
+ local chans = eval('len(nvim_list_chans())')
+ -- channel has been closed but not released
+ eq("Vim(call):Can't send data to closed stream",
+ pcall_err(command, [[call chanclose(id) | call chansend(id, 'test')]]))
+ screen:expect({any='%[Terminal closed%]'})
+ eq(chans, eval('len(nvim_list_chans())'))
+ -- delete terminal
+ feed('i<CR>')
+ -- need to first process input
+ poke_eventloop()
+ -- channel has been released after another main loop iteration
+ eq(chans - 1, eval('len(nvim_list_chans())'))
+ end)
+
+ it('opened by nvim_open_term(), closed by chanclose(), and deleted by :bdelete', function()
+ command('let id = nvim_open_term(0, {})')
+ local chans = eval('len(nvim_list_chans())')
+ -- channel has been closed but not released
+ eq("Vim(call):Can't send data to closed stream",
+ pcall_err(command, [[call chanclose(id) | call chansend(id, 'test')]]))
+ screen:expect({any='%[Terminal closed%]'})
+ eq(chans, eval('len(nvim_list_chans())'))
+ -- channel still hasn't been released yet
+ eq("Vim(call):Can't send data to closed stream",
+ pcall_err(command, [[bdelete | call chansend(id, 'test')]]))
+ -- channel has been released after one main loop iteration
+ eq(chans - 1, eval('len(nvim_list_chans())'))
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", pcall_err(command, [[call chansend(id, 'test')]]))
+ local chans = eval('len(nvim_list_chans())')
+ -- wait for process to exit
+ screen:expect({any='%[Process exited 0%]'})
+ -- process has exited but channel has't been released
+ eq("Vim(call):Can't send data to closed stream",
+ pcall_err(command, [[call chansend(id, 'test')]]))
+ eq(chans, eval('len(nvim_list_chans())'))
-- delete terminal
feed('i<CR>')
-- need to first process input
poke_eventloop()
- -- channel has been freed after another main loop iteration
- eq("Vim(call):E900: Invalid channel id", pcall_err(command, [[call chansend(id, 'test')]]))
+ -- channel has been released after another main loop iteration
+ eq(chans - 1, eval('len(nvim_list_chans())'))
end)
-- This indirectly covers #16264
it('opened by termopen(), exited, and deleted by :bdelete', function()
command([[let id = termopen('echo')]])
- sleep(500)
- -- process has exited
- 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", 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')]]))
+ local chans = eval('len(nvim_list_chans())')
+ -- wait for process to exit
+ screen:expect({any='%[Process exited 0%]'})
+ -- process has exited but channel hasn't been released
+ eq("Vim(call):Can't send data to closed stream",
+ pcall_err(command, [[call chansend(id, 'test')]]))
+ eq(chans, eval('len(nvim_list_chans())'))
+ -- channel still hasn't been released yet
+ eq("Vim(call):Can't send data to closed stream",
+ pcall_err(command, [[bdelete | call chansend(id, 'test')]]))
+ -- channel has been released after one main loop iteration
+ eq(chans - 1, eval('len(nvim_list_chans())'))
end)
end)
diff --git a/test/functional/terminal/cursor_spec.lua b/test/functional/terminal/cursor_spec.lua
index e9495f45a2..3b905f1f56 100644
--- a/test/functional/terminal/cursor_spec.lua
+++ b/test/functional/terminal/cursor_spec.lua
@@ -87,6 +87,7 @@ describe(':terminal cursor', function()
describe('when invisible', function()
it('is not highlighted and is detached from screen cursor', function()
+ if helpers.pending_win32(pending) then return end
hide_cursor()
screen:expect([[
tty ready |
@@ -176,6 +177,7 @@ describe('cursor with customized highlighting', function()
end)
describe('buffer cursor position is correct in terminal without number column', function()
+ if helpers.pending_win32(pending) then return end
local screen
local function setup_ex_register(str)
@@ -526,6 +528,7 @@ describe('buffer cursor position is correct in terminal without number column',
end)
describe('buffer cursor position is correct in terminal with number column', function()
+ if helpers.pending_win32(pending) then return end
local screen
local function setup_ex_register(str)
diff --git a/test/functional/terminal/edit_spec.lua b/test/functional/terminal/edit_spec.lua
index fabc5524ed..e7025d6739 100644
--- a/test/functional/terminal/edit_spec.lua
+++ b/test/functional/terminal/edit_spec.lua
@@ -36,6 +36,7 @@ describe(':edit term://*', function()
end)
it("runs TermOpen early enough to set buffer-local 'scrollback'", function()
+ if helpers.pending_win32(pending) then return end
local columns, lines = 20, 4
local scr = get_screen(columns, lines)
local rep = 97
diff --git a/test/functional/terminal/ex_terminal_spec.lua b/test/functional/terminal/ex_terminal_spec.lua
index 065dd72485..b4f29a586a 100644
--- a/test/functional/terminal/ex_terminal_spec.lua
+++ b/test/functional/terminal/ex_terminal_spec.lua
@@ -142,6 +142,7 @@ describe(':terminal (with fake shell)', function()
end
it('with no argument, acts like termopen()', function()
+ if helpers.pending_win32(pending) then return end
terminal_with_fake_shell()
retry(nil, 4 * screen.timeout, function()
screen:expect([[
@@ -165,6 +166,7 @@ describe(':terminal (with fake shell)', function()
end)
it("with no argument, but 'shell' has arguments, acts like termopen()", function()
+ if helpers.pending_win32(pending) then return end
nvim('set_option', 'shell', nvim_dir..'/shell-test -t jeff')
terminal_with_fake_shell()
screen:expect([[
@@ -176,6 +178,7 @@ describe(':terminal (with fake shell)', function()
end)
it('executes a given command through the shell', function()
+ if helpers.pending_win32(pending) then return end
command('set shellxquote=') -- win: avoid extra quotes
terminal_with_fake_shell('echo hi')
screen:expect([[
@@ -187,6 +190,7 @@ describe(':terminal (with fake shell)', function()
end)
it("executes a given command through the shell, when 'shell' has arguments", function()
+ if helpers.pending_win32(pending) then return end
nvim('set_option', 'shell', nvim_dir..'/shell-test -t jeff')
command('set shellxquote=') -- win: avoid extra quotes
terminal_with_fake_shell('echo hi')
@@ -199,6 +203,7 @@ describe(':terminal (with fake shell)', function()
end)
it('allows quotes and slashes', function()
+ if helpers.pending_win32(pending) then return end
command('set shellxquote=') -- win: avoid extra quotes
terminal_with_fake_shell([[echo 'hello' \ "world"]])
screen:expect([[
@@ -235,6 +240,7 @@ describe(':terminal (with fake shell)', function()
end)
it('works with :find', function()
+ if helpers.pending_win32(pending) then return end
terminal_with_fake_shell()
screen:expect([[
^ready $ |
@@ -253,6 +259,7 @@ describe(':terminal (with fake shell)', function()
end)
it('works with gf', function()
+ if helpers.pending_win32(pending) then return end
command('set shellxquote=') -- win: avoid extra quotes
terminal_with_fake_shell([[echo "scripts/shadacat.py"]])
retry(nil, 4 * screen.timeout, function()
diff --git a/test/functional/terminal/helpers.lua b/test/functional/terminal/helpers.lua
index d909888613..c5315d0185 100644
--- a/test/functional/terminal/helpers.lua
+++ b/test/functional/terminal/helpers.lua
@@ -94,7 +94,7 @@ local function screen_setup(extra_rows, command, cols, opts)
table.insert(expected, '{3:-- TERMINAL --}' .. ((' '):rep(cols - 14)))
screen:expect(table.concat(expected, '|\n')..'|')
else
- -- This eval also acts as a wait().
+ -- This eval also acts as a poke_eventloop().
if 0 == nvim('eval', "exists('b:terminal_job_id')") then
error("terminal job failed to start")
end
diff --git a/test/functional/terminal/highlight_spec.lua b/test/functional/terminal/highlight_spec.lua
index 8d3f0218af..ab4b4e9147 100644
--- a/test/functional/terminal/highlight_spec.lua
+++ b/test/functional/terminal/highlight_spec.lua
@@ -117,6 +117,7 @@ describe(':terminal highlight', function()
end)
it(':terminal highlight has lower precedence than editor #9964', function()
+ if helpers.pending_win32(pending) then return end
clear()
local screen = Screen.new(30, 4)
screen:set_default_attr_ids({
@@ -304,10 +305,17 @@ describe('synIDattr()', function()
eq('79', eval('synIDattr(hlID("Keyword"), "fg")'))
end)
- it('returns "1" if group has "strikethrough" attribute', function()
- eq('', eval('synIDattr(hlID("Normal"), "strikethrough")'))
- eq('1', eval('synIDattr(hlID("Keyword"), "strikethrough")'))
- eq('1', eval('synIDattr(hlID("Keyword"), "strikethrough", "gui")'))
+ it('returns "1" if group has given highlight attribute', function()
+ local hl_attrs = {
+ 'underline', 'underlineline', 'undercurl', 'underdot', 'underdash', 'strikethrough'
+ }
+ for _,hl_attr in ipairs(hl_attrs) do
+ local context = 'using ' .. hl_attr .. ' attr'
+ command('highlight Keyword cterm=' .. hl_attr .. ' gui=' .. hl_attr)
+ eq('', eval('synIDattr(hlID("Normal"), "'.. hl_attr .. '")'), context)
+ eq('1', eval('synIDattr(hlID("Keyword"), "' .. hl_attr .. '")'), context)
+ eq('1', eval('synIDattr(hlID("Keyword"), "' .. hl_attr .. '", "gui")'), context)
+ end
end)
end)
diff --git a/test/functional/terminal/scrollback_spec.lua b/test/functional/terminal/scrollback_spec.lua
index 11bdc73a47..d1cfc7e91b 100644
--- a/test/functional/terminal/scrollback_spec.lua
+++ b/test/functional/terminal/scrollback_spec.lua
@@ -345,6 +345,7 @@ end)
describe(':terminal prints more lines than the screen height and exits', function()
it('will push extra lines to scrollback', function()
+ if helpers.pending_win32(pending) then return end
clear()
local screen = Screen.new(30, 7)
screen:attach({rgb=false})
@@ -576,6 +577,7 @@ describe("pending scrollback line handling", function()
end)
it("does not crash after nvim_buf_call #14891", function()
+ if helpers.pending_win32(pending) then return end
exec_lua [[
local a = vim.api
local bufnr = a.nvim_create_buf(false, true)
diff --git a/test/functional/terminal/tui_spec.lua b/test/functional/terminal/tui_spec.lua
index faf44fa01d..c37cde06ab 100644
--- a/test/functional/terminal/tui_spec.lua
+++ b/test/functional/terminal/tui_spec.lua
@@ -323,7 +323,7 @@ describe('TUI', function()
feed_data('just paste it™')
feed_data('\027[201~')
screen:expect{grid=[[
- thisjust paste it™{1:3} is here |
+ thisjust paste it{1:™}3 is here |
|
{4:~ }|
{4:~ }|
@@ -379,7 +379,7 @@ describe('TUI', function()
end)
it('paste: normal-mode (+CRLF #10872)', function()
- feed_data(':set ruler')
+ feed_data(':set ruler | echo')
wait_for_mode('c')
feed_data('\n')
wait_for_mode('n')
@@ -423,13 +423,13 @@ describe('TUI', function()
expect_child_buf_lines(expected_crlf)
feed_data('u')
expect_child_buf_lines({''})
+ feed_data(':echo')
+ wait_for_mode('c')
+ feed_data('\n')
+ wait_for_mode('n')
-- CRLF input
feed_data('\027[200~'..table.concat(expected_lf,'\r\n')..'\027[201~')
- screen:expect{
- grid=expected_grid1:gsub(
- ':set ruler *',
- '3 fewer lines; before #1 0 seconds ago '),
- attr_ids=expected_attr}
+ screen:expect{grid=expected_grid1, attr_ids=expected_attr}
expect_child_buf_lines(expected_crlf)
end)
diff --git a/test/functional/terminal/window_spec.lua b/test/functional/terminal/window_spec.lua
index 9f278fd157..0d3295cf32 100644
--- a/test/functional/terminal/window_spec.lua
+++ b/test/functional/terminal/window_spec.lua
@@ -18,6 +18,7 @@ describe(':terminal window', function()
end)
it('sets topline correctly #8556', function()
+ if helpers.pending_win32(pending) then return end
-- Test has hardcoded assumptions of dimensions.
eq(7, eval('&lines'))
feed_data('\n\n\n') -- Add blank lines.
diff --git a/test/functional/ui/cmdline_highlight_spec.lua b/test/functional/ui/cmdline_highlight_spec.lua
index 9c746b99bd..384761ab17 100644
--- a/test/functional/ui/cmdline_highlight_spec.lua
+++ b/test/functional/ui/cmdline_highlight_spec.lua
@@ -33,7 +33,7 @@ before_each(function()
let g:NUM_LVLS = 4
function Redraw()
mode
- return ''
+ return "\<Ignore>"
endfunction
let g:id = ''
cnoremap <expr> {REDRAW} Redraw()
@@ -42,7 +42,7 @@ before_each(function()
let Cb = g:Nvim_color_input{g:id}
let out = input({'prompt': ':', 'highlight': Cb})
let g:out{id} = out
- return (a:do_return ? out : '')
+ return (a:do_return ? out : "\<Ignore>")
endfunction
nnoremap <expr> {PROMPT} DoPrompt(0)
cnoremap <expr> {PROMPT} DoPrompt(1)
@@ -410,7 +410,7 @@ describe('Command-line coloring', function()
end)
it('stops executing callback after a number of errors', function()
set_color_cb('SplittedMultibyteStart')
- start_prompt('let x = "«»«»«»«»«»"\n')
+ start_prompt('let x = "«»«»«»«»«»"')
screen:expect([[
{EOB:~ }|
{EOB:~ }|
@@ -419,7 +419,7 @@ describe('Command-line coloring', function()
:let x = " |
{ERR:E5405: Chunk 0 start 10 splits multibyte}|
{ERR: character} |
- ^:let x = "«»«»«»«»«»" |
+ :let x = "«»«»«»«»«»"^ |
]])
feed('\n')
screen:expect([[
@@ -432,6 +432,7 @@ describe('Command-line coloring', function()
{EOB:~ }|
|
]])
+ feed('\n')
eq('let x = "«»«»«»«»«»"', meths.get_var('out'))
local msg = '\nE5405: Chunk 0 start 10 splits multibyte character'
eq(msg:rep(1), funcs.execute('messages'))
@@ -474,14 +475,14 @@ describe('Command-line coloring', function()
]])
feed('\n')
screen:expect([[
- |
+ ^ |
{EOB:~ }|
{EOB:~ }|
{EOB:~ }|
{EOB:~ }|
{EOB:~ }|
{EOB:~ }|
- ^:echo 42 |
+ :echo 42 |
]])
feed('\n')
eq('echo 42', meths.get_var('out'))
diff --git a/test/functional/ui/cursor_spec.lua b/test/functional/ui/cursor_spec.lua
index 03cd4bfd06..4c51547e2c 100644
--- a/test/functional/ui/cursor_spec.lua
+++ b/test/functional/ui/cursor_spec.lua
@@ -212,10 +212,10 @@ describe('ui/cursor', function()
if m.blinkwait then m.blinkwait = 700 end
end
if m.hl_id then
- m.hl_id = 60
+ m.hl_id = 61
m.attr = {background = Screen.colors.DarkGray}
end
- if m.id_lm then m.id_lm = 61 end
+ if m.id_lm then m.id_lm = 62 end
end
-- Assert the new expectation.
diff --git a/test/functional/ui/decorations_spec.lua b/test/functional/ui/decorations_spec.lua
index 1575cab591..7e71ada02d 100644
--- a/test/functional/ui/decorations_spec.lua
+++ b/test/functional/ui/decorations_spec.lua
@@ -1362,3 +1362,372 @@ if (h->n_buckets < new_n_buckets) { // expand
end)
end)
+
+describe('decorations: signs', function()
+ local screen, ns
+ before_each(function()
+ clear()
+ screen = Screen.new(50, 10)
+ screen:attach()
+ screen:set_default_attr_ids {
+ [1] = {foreground = Screen.colors.Blue4, background = Screen.colors.Grey};
+ [2] = {foreground = Screen.colors.Blue1, bold = true};
+ [3] = {background = Screen.colors.Yellow1, foreground = Screen.colors.Blue1};
+ }
+
+ ns = meths.create_namespace 'test'
+ meths.win_set_option(0, 'signcolumn', 'auto:9')
+ end)
+
+ local example_text = [[
+l1
+l2
+l3
+l4
+l5
+]]
+
+ it('can add a single sign (no end row)', function()
+ insert(example_text)
+ feed 'gg'
+
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S'})
+
+ screen:expect{grid=[[
+ {1: }^l1 |
+ S l2 |
+ {1: }l3 |
+ {1: }l4 |
+ {1: }l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+
+ end)
+
+ it('can add a single sign (with end row)', function()
+ insert(example_text)
+ feed 'gg'
+
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S', end_row=1})
+
+ screen:expect{grid=[[
+ {1: }^l1 |
+ S l2 |
+ {1: }l3 |
+ {1: }l4 |
+ {1: }l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+
+ end)
+
+ it('can add multiple signs (single extmark)', function()
+ pending('TODO(lewis6991): Support ranged signs')
+ insert(example_text)
+ feed 'gg'
+
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S', end_row = 2})
+
+ screen:expect{grid=[[
+ {1: }^l1 |
+ S l2 |
+ S l3 |
+ {1: }l4 |
+ {1: }l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+
+ end)
+
+ it('can add multiple signs (multiple extmarks)', function()
+ pending('TODO(lewis6991): Support ranged signs')
+ insert(example_text)
+ feed'gg'
+
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S1'})
+ meths.buf_set_extmark(0, ns, 3, -1, {sign_text='S2', end_row = 4})
+
+ screen:expect{grid=[[
+ {1: }^l1 |
+ S1l2 |
+ {1: }l3 |
+ S2l4 |
+ S2l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+
+ end)
+
+ it('can add multiple signs (multiple extmarks) 2', function()
+ insert(example_text)
+ feed 'gg'
+
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S1'})
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S2'})
+
+ screen:expect{grid=[[
+ {1: }^l1 |
+ S2S1l2 |
+ {1: }l3 |
+ {1: }l4 |
+ {1: }l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+
+ -- TODO(lewis6991): Support ranged signs
+ -- meths.buf_set_extmark(1, ns, 1, -1, {sign_text='S3', end_row = 2})
+
+ -- screen:expect{grid=[[
+ -- {1: }^l1 |
+ -- S3S2S1l2 |
+ -- S3{1: }l3 |
+ -- {1: }l4 |
+ -- {1: }l5 |
+ -- {1: } |
+ -- {2:~ }|
+ -- {2:~ }|
+ -- {2:~ }|
+ -- |
+ -- ]]}
+
+ end)
+
+ it('can add multiple signs (multiple extmarks) 3', function()
+ pending('TODO(lewis6991): Support ranged signs')
+
+ insert(example_text)
+ feed 'gg'
+
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S1', end_row=2})
+ meths.buf_set_extmark(0, ns, 2, -1, {sign_text='S2', end_row=3})
+
+ screen:expect{grid=[[
+ {1: }^l1 |
+ S1{1: }l2 |
+ S2S1l3 |
+ S2{1: }l4 |
+ {1: }l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+ end)
+
+ it('can add multiple signs (multiple extmarks) 4', function()
+ insert(example_text)
+ feed 'gg'
+
+ meths.buf_set_extmark(0, ns, 0, -1, {sign_text='S1', end_row=0})
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S2', end_row=1})
+
+ screen:expect{grid=[[
+ S1^l1 |
+ S2l2 |
+ {1: }l3 |
+ {1: }l4 |
+ {1: }l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+ end)
+
+ it('works with old signs', function()
+ insert(example_text)
+ feed 'gg'
+
+ helpers.command('sign define Oldsign text=x')
+ helpers.command([[exe 'sign place 42 line=2 name=Oldsign buffer=' . bufnr('')]])
+
+ meths.buf_set_extmark(0, ns, 0, -1, {sign_text='S1'})
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S2'})
+ meths.buf_set_extmark(0, ns, 0, -1, {sign_text='S4'})
+ meths.buf_set_extmark(0, ns, 2, -1, {sign_text='S5'})
+
+ screen:expect{grid=[[
+ S4S1^l1 |
+ S2x l2 |
+ S5{1: }l3 |
+ {1: }l4 |
+ {1: }l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+ end)
+
+ it('works with old signs (with range)', function()
+ pending('TODO(lewis6991): Support ranged signs')
+ insert(example_text)
+ feed 'gg'
+
+ helpers.command('sign define Oldsign text=x')
+ helpers.command([[exe 'sign place 42 line=2 name=Oldsign buffer=' . bufnr('')]])
+
+ meths.buf_set_extmark(0, ns, 0, -1, {sign_text='S1'})
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='S2'})
+ meths.buf_set_extmark(0, ns, 0, -1, {sign_text='S3', end_row = 4})
+ meths.buf_set_extmark(0, ns, 0, -1, {sign_text='S4'})
+ meths.buf_set_extmark(0, ns, 2, -1, {sign_text='S5'})
+
+ screen:expect{grid=[[
+ S3S4S1^l1 |
+ S2S3x l2 |
+ S5S3{1: }l3 |
+ S3{1: }l4 |
+ S3{1: }l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+ end)
+
+ it('can add a ranged sign (with start out of view)', function()
+ pending('TODO(lewis6991): Support ranged signs')
+
+ insert(example_text)
+ command 'set signcolumn=yes:2'
+ feed 'gg'
+ feed '2<C-e>'
+
+ meths.buf_set_extmark(0, ns, 1, -1, {sign_text='X', end_row=3})
+
+ screen:expect{grid=[[
+ X {1: }^l3 |
+ X {1: }l4 |
+ {1: }l5 |
+ {1: } |
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ {2:~ }|
+ |
+ ]]}
+
+ end)
+
+ it('can add lots of signs', function()
+ screen:try_resize(40, 10)
+ command 'normal 10oa b c d e f g h'
+
+ for i = 1, 10 do
+ meths.buf_set_extmark(0, ns, i, 0, { end_col = 1, hl_group='Todo' })
+ meths.buf_set_extmark(0, ns, i, 2, { end_col = 3, hl_group='Todo' })
+ meths.buf_set_extmark(0, ns, i, 4, { end_col = 5, hl_group='Todo' })
+ meths.buf_set_extmark(0, ns, i, 6, { end_col = 7, hl_group='Todo' })
+ meths.buf_set_extmark(0, ns, i, 8, { end_col = 9, hl_group='Todo' })
+ meths.buf_set_extmark(0, ns, i, 10, { end_col = 11, hl_group='Todo' })
+ meths.buf_set_extmark(0, ns, i, 12, { end_col = 13, hl_group='Todo' })
+ meths.buf_set_extmark(0, ns, i, 14, { end_col = 15, hl_group='Todo' })
+ meths.buf_set_extmark(0, ns, i, -1, { sign_text='W' })
+ meths.buf_set_extmark(0, ns, i, -1, { sign_text='X' })
+ meths.buf_set_extmark(0, ns, i, -1, { sign_text='Y' })
+ meths.buf_set_extmark(0, ns, i, -1, { sign_text='Z' })
+ end
+
+ screen:expect{grid=[[
+ X Y Z W {3:a} {3:b} {3:c} {3:d} {3:e} {3:f} {3:g} {3:h} |
+ X Y Z W {3:a} {3:b} {3:c} {3:d} {3:e} {3:f} {3:g} {3:h} |
+ X Y Z W {3:a} {3:b} {3:c} {3:d} {3:e} {3:f} {3:g} {3:h} |
+ X Y Z W {3:a} {3:b} {3:c} {3:d} {3:e} {3:f} {3:g} {3:h} |
+ X Y Z W {3:a} {3:b} {3:c} {3:d} {3:e} {3:f} {3:g} {3:h} |
+ X Y Z W {3:a} {3:b} {3:c} {3:d} {3:e} {3:f} {3:g} {3:h} |
+ X Y Z W {3:a} {3:b} {3:c} {3:d} {3:e} {3:f} {3:g} {3:h} |
+ X Y Z W {3:a} {3:b} {3:c} {3:d} {3:e} {3:f} {3:g} {3:h} |
+ X Y Z W {3:a} {3:b} {3:c} {3:d} {3:e} {3:f} {3:g} {3:^h} |
+ |
+ ]]}
+ end)
+
+end)
+
+describe('decorations: virt_text', function()
+ local screen
+
+ before_each(function()
+ clear()
+ screen = Screen.new(50, 10)
+ screen:attach()
+ screen:set_default_attr_ids {
+ [1] = {foreground = Screen.colors.Brown};
+ [2] = {foreground = Screen.colors.Fuchsia};
+ [3] = {bold = true, foreground = Screen.colors.Blue1};
+ }
+ end)
+
+ it('avoids regression in #17638', function()
+ exec_lua[[
+ vim.wo.number = true
+ vim.wo.relativenumber = true
+ ]]
+
+ command 'normal 4ohello'
+ command 'normal aVIRTUAL'
+
+ local ns = meths.create_namespace('test')
+
+ meths.buf_set_extmark(0, ns, 2, 0, {
+ virt_text = {{"hello", "String"}},
+ virt_text_win_col = 20,
+ })
+
+ screen:expect{grid=[[
+ {1: 4 } |
+ {1: 3 }hello |
+ {1: 2 }hello {2:hello} |
+ {1: 1 }hello |
+ {1:5 }helloVIRTUA^L |
+ {3:~ }|
+ {3:~ }|
+ {3:~ }|
+ {3:~ }|
+ |
+ ]]}
+
+ -- Trigger a screen update
+ feed('k')
+
+ screen:expect{grid=[[
+ {1: 3 } |
+ {1: 2 }hello |
+ {1: 1 }hello {2:hello} |
+ {1:4 }hell^o |
+ {1: 1 }helloVIRTUAL |
+ {3:~ }|
+ {3:~ }|
+ {3:~ }|
+ {3:~ }|
+ |
+ ]]}
+ end)
+
+end)
diff --git a/test/functional/ui/diff_spec.lua b/test/functional/ui/diff_spec.lua
index bd2692d19a..3a25d7e813 100644
--- a/test/functional/ui/diff_spec.lua
+++ b/test/functional/ui/diff_spec.lua
@@ -6,7 +6,7 @@ local clear = helpers.clear
local command = helpers.command
local insert = helpers.insert
local write_file = helpers.write_file
-local source = helpers.source
+local exec = helpers.exec
describe('Diff mode screen', function()
local fname = 'Xtest-functional-diff-screen-1'
@@ -1075,10 +1075,8 @@ it('diff updates line numbers below filler lines', function()
[9] = {background = Screen.colors.LightMagenta},
[10] = {bold = true, foreground = Screen.colors.Brown},
[11] = {foreground = Screen.colors.Brown},
- [12] = {foreground = Screen.colors.Brown, bold = true, background = Screen.colors.Red};
- [13] = {background = Screen.colors.Gray90};
})
- source([[
+ exec([[
call setline(1, ['a', 'a', 'a', 'y', 'b', 'b', 'b', 'b', 'b'])
vnew
call setline(1, ['a', 'a', 'a', 'x', 'x', 'x', 'b', 'b', 'b', 'b', 'b'])
@@ -1135,24 +1133,6 @@ it('diff updates line numbers below filler lines', function()
{3:[No Name] [+] }{7:[No Name] [+] }|
|
]])
- command("set signcolumn number tgc cursorline cursorlineopt=number,line")
- command("hi CursorLineNr guibg=red")
- screen:expect{grid=[[
- {1: }a {3:│}{11: 2 }a |
- {1: }a {3:│}{11: 1 }a |
- {1: }a {3:│}{12:3 }{13:^a }|
- {1: }{8:x}{9: }{3:│}{11: 1 }{8:y}{9: }|
- {1: }{4:x }{3:│}{11: }{2:----------------}|
- {1: }{4:x }{3:│}{11: }{2:----------------}|
- {1: }b {3:│}{11: 2 }b |
- {1: }b {3:│}{11: 3 }b |
- {1: }b {3:│}{11: 4 }b |
- {1: }b {3:│}{11: 5 }b |
- {1: }b {3:│}{11: 6 }b |
- {6:~ }{3:│}{6:~ }|
- {3:[No Name] [+] }{7:[No Name] [+] }|
- signcolumn=auto |
- ]]}
end)
it('Align the filler lines when changing text in diff mode', function()
@@ -1169,7 +1149,7 @@ it('Align the filler lines when changing text in diff mode', function()
[7] = {foreground = Screen.colors.Blue1, bold = true};
[8] = {reverse = true, bold = true};
})
- source([[
+ exec([[
call setline(1, range(1, 15))
vnew
call setline(1, range(9, 15))
diff --git a/test/functional/ui/global_statusline_spec.lua b/test/functional/ui/global_statusline_spec.lua
new file mode 100644
index 0000000000..6b37e5e2f1
--- /dev/null
+++ b/test/functional/ui/global_statusline_spec.lua
@@ -0,0 +1,233 @@
+local helpers = require('test.functional.helpers')(after_each)
+local Screen = require('test.functional.ui.screen')
+local clear, command, feed = helpers.clear, helpers.command, helpers.feed
+
+describe('global statusline', function()
+ local screen
+
+ before_each(function()
+ clear()
+ screen = Screen.new(60, 16)
+ screen:attach()
+ command('set laststatus=3')
+ command('set ruler')
+ end)
+
+ it('works', function()
+ screen:expect{grid=[[
+ ^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {2:[No Name] 0,0-1 All}|
+ |
+ ]], attr_ids={
+ [1] = {bold = true, foreground = Screen.colors.Blue1};
+ [2] = {bold = true, reverse = true};
+ }}
+
+ feed('i<CR><CR>')
+ screen:expect{grid=[[
+ |
+ |
+ ^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {2:[No Name] [+] 3,1 All}|
+ {3:-- INSERT --} |
+ ]], attr_ids={
+ [1] = {bold = true, foreground = Screen.colors.Blue};
+ [2] = {bold = true, reverse = true};
+ [3] = {bold = true};
+ }}
+ end)
+
+ it('works with splits', function()
+ command('vsplit | split | vsplit | vsplit | wincmd l | split | 2wincmd l | split')
+ screen:expect{grid=[[
+ {1:│} {1:│} {1:│}^ |
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:├────────────────┤}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│} {1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:├────────────────────}|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│} |
+ {1:────────────────────┴────────────────┴─┤}{2:~ }|
+ {1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {3:[No Name] 0,0-1 All}|
+ |
+ ]], attr_ids={
+ [1] = {reverse = true};
+ [2] = {bold = true, foreground = Screen.colors.Blue1};
+ [3] = {bold = true, reverse = true};
+ }}
+ end)
+
+ it('works when switching between values of laststatus', function()
+ command('set laststatus=1')
+ screen:expect{grid=[[
+ ^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ 0,0-1 All |
+ ]], attr_ids={
+ [1] = {foreground = Screen.colors.Blue, bold = true};
+ }}
+
+ command('set laststatus=3')
+ screen:expect{grid=[[
+ ^ |
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {1:~ }|
+ {2:[No Name] 0,0-1 All}|
+ |
+ ]], attr_ids={
+ [1] = {foreground = Screen.colors.Blue, bold = true};
+ [2] = {reverse = true, bold = true};
+ }}
+
+ command('vsplit | split | vsplit | vsplit | wincmd l | split | 2wincmd l | split')
+ command('set laststatus=2')
+ screen:expect{grid=[[
+ {1:│} {1:│} {1:│}^ |
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│< Name] 0,0-1 │}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│} {1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{3:<No Name] 0,0-1 All}|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│} |
+ {1:<No Name] 0,0-1 All < Name] 0,0-1 <│}{2:~ }|
+ {1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {1:[No Name] 0,0-1 All <No Name] 0,0-1 All}|
+ |
+ ]], attr_ids={
+ [1] = {reverse = true};
+ [2] = {foreground = Screen.colors.Blue, bold = true};
+ [3] = {reverse = true, bold = true};
+ }}
+
+ command('set laststatus=3')
+ screen:expect{grid=[[
+ {1:│} {1:│} {1:│}^ |
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:├────────────────┤}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│} {1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:├────────────────────}|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│} |
+ {1:────────────────────┴────────────────┴─┤}{2:~ }|
+ {1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {3:[No Name] 0,0-1 All}|
+ |
+ ]], attr_ids={
+ [1] = {reverse = true};
+ [2] = {foreground = Screen.colors.Blue, bold = true};
+ [3] = {reverse = true, bold = true};
+ }}
+
+ command('set laststatus=0')
+ screen:expect{grid=[[
+ {1:│} {1:│} {1:│}^ |
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│< Name] 0,0-1 │}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│} {1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{3:<No Name] 0,0-1 All}|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│} |
+ {1:<No Name] 0,0-1 All < Name] 0,0-1 <│}{2:~ }|
+ {1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ 0,0-1 All |
+ ]], attr_ids={
+ [1] = {reverse = true};
+ [2] = {foreground = Screen.colors.Blue, bold = true};
+ [3] = {reverse = true, bold = true};
+ }}
+
+ command('set laststatus=3')
+ screen:expect{grid=[[
+ {1:│} {1:│} {1:│}^ |
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:├────────────────┤}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│} {1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:├────────────────────}|
+ {2:~ }{1:│}{2:~ }{1:│}{2:~}{1:│} |
+ {1:────────────────────┴────────────────┴─┤}{2:~ }|
+ {1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {2:~ }{1:│}{2:~ }|
+ {3:[No Name] 0,0-1 All}|
+ |
+ ]], attr_ids={
+ [1] = {reverse = true};
+ [2] = {foreground = Screen.colors.Blue, bold = true};
+ [3] = {reverse = true, bold = true};
+ }}
+ end)
+end)
diff --git a/test/functional/ui/highlight_spec.lua b/test/functional/ui/highlight_spec.lua
index 12643eec1e..64f0ba3419 100644
--- a/test/functional/ui/highlight_spec.lua
+++ b/test/functional/ui/highlight_spec.lua
@@ -840,7 +840,7 @@ describe("'listchars' highlight", function()
end)
end)
-describe('CursorLine highlight', function()
+describe('CursorLine and CursorLineNr highlights', function()
before_each(clear)
it('overridden by Error, ColorColumn if fg not set', function()
@@ -1081,7 +1081,7 @@ describe('CursorLine highlight', function()
]])
end)
- it('with split-windows in diff-mode', function()
+ it('with split windows in diff mode', function()
local screen = Screen.new(50,12)
screen:set_default_attr_ids({
[1] = {foreground = Screen.colors.DarkBlue, background = Screen.colors.WebGray},
@@ -1093,7 +1093,6 @@ describe('CursorLine highlight', function()
[7] = {background = Screen.colors.Red, foreground = Screen.colors.White},
[8] = {bold = true, foreground = Screen.colors.Blue1},
[9] = {bold = true, reverse = true},
- [10] = {bold = true},
})
screen:attach()
@@ -1170,6 +1169,61 @@ describe('CursorLine highlight', function()
background = Screen.colors.Red},
})
end)
+
+ it('CursorLineNr shows correctly just below filler lines', function()
+ local screen = Screen.new(50,12)
+ screen:set_default_attr_ids({
+ [1] = {foreground = Screen.colors.DarkBlue, background = Screen.colors.WebGray},
+ [2] = {background = Screen.colors.LightCyan1, bold = true, foreground = Screen.colors.Blue1},
+ [3] = {reverse = true},
+ [4] = {background = Screen.colors.LightBlue},
+ [5] = {background = Screen.colors.Red, foreground = Screen.colors.White},
+ [6] = {background = Screen.colors.White, bold = true, foreground = Screen.colors.Black},
+ [7] = {bold = true, foreground = Screen.colors.Blue1},
+ [8] = {bold = true, reverse = true},
+ [9] = {foreground = Screen.colors.Brown},
+ })
+ screen:attach()
+
+ command('hi CursorLine guibg=red guifg=white')
+ command('hi CursorLineNr guibg=white guifg=black gui=bold')
+ command('set cursorline number')
+ command('call setline(1, ["baz", "foo", "foo", "bar"])')
+ feed('2gg0')
+ command('vnew')
+ command('call setline(1, ["foo", "foo", "bar"])')
+ command('windo diffthis')
+ command('1wincmd w')
+ screen:expect([[
+ {1: }{9: }{2:-------------------}{3:│}{1: }{9: 1 }{4:baz }|
+ {1: }{6: 1 }{5:^foo }{3:│}{1: }{6: 2 }{5:foo }|
+ {1: }{9: 2 }foo {3:│}{1: }{9: 3 }foo |
+ {1: }{9: 3 }bar {3:│}{1: }{9: 4 }bar |
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {8:[No Name] [+] }{3:[No Name] [+] }|
+ |
+ ]])
+ command('set cursorlineopt=number')
+ screen:expect([[
+ {1: }{9: }{2:-------------------}{3:│}{1: }{9: 1 }{4:baz }|
+ {1: }{6: 1 }^foo {3:│}{1: }{6: 2 }{5:foo }|
+ {1: }{9: 2 }foo {3:│}{1: }{9: 3 }foo |
+ {1: }{9: 3 }bar {3:│}{1: }{9: 4 }bar |
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {7:~ }{3:│}{7:~ }|
+ {8:[No Name] [+] }{3:[No Name] [+] }|
+ |
+ ]])
+ end)
end)
describe('ColorColumn highlight', function()
diff --git a/test/functional/ui/hlstate_spec.lua b/test/functional/ui/hlstate_spec.lua
index 2a567b28ee..dcea2c76dd 100644
--- a/test/functional/ui/hlstate_spec.lua
+++ b/test/functional/ui/hlstate_spec.lua
@@ -59,7 +59,7 @@ describe('ext_hlstate detailed highlights', function()
it('work with cleared UI highlights', function()
screen:set_default_attr_ids({
- [1] = {{}, {{hi_name = "VertSplit", ui_name = "VertSplit", kind = "ui"}}},
+ [1] = {{}, {{hi_name = "VertSplit", ui_name = "WinSeparator", kind = "ui"}}},
[2] = {{bold = true, foreground = Screen.colors.Blue1},
{{hi_name = "NonText", ui_name = "EndOfBuffer", kind = "ui"}}},
[3] = {{bold = true, reverse = true},
@@ -179,6 +179,8 @@ describe('ext_hlstate detailed highlights', function()
end)
it("work with :terminal", function()
+ if helpers.pending_win32(pending) then return end
+
screen:set_default_attr_ids({
[1] = {{}, {{hi_name = "TermCursorNC", ui_name = "TermCursorNC", kind = "ui"}}},
[2] = {{foreground = tonumber('0x00ccff'), fg_indexed=true}, {{kind = "term"}}},
diff --git a/test/functional/ui/messages_spec.lua b/test/functional/ui/messages_spec.lua
index f038348253..949591870a 100644
--- a/test/functional/ui/messages_spec.lua
+++ b/test/functional/ui/messages_spec.lua
@@ -1206,6 +1206,7 @@ end)
describe('ui/msg_puts_printf', function()
it('output multibyte characters correctly', function()
+ if helpers.pending_win32(pending) then return end
local screen
local cmd = ''
local locale_dir = test_build_dir..'/share/locale/ja/LC_MESSAGES'
diff --git a/test/functional/ui/output_spec.lua b/test/functional/ui/output_spec.lua
index 50e5dfac84..7305baa761 100644
--- a/test/functional/ui/output_spec.lua
+++ b/test/functional/ui/output_spec.lua
@@ -14,6 +14,7 @@ local has_powershell = helpers.has_powershell
local set_shell_powershell = helpers.set_shell_powershell
describe("shell command :!", function()
+ if helpers.pending_win32(pending) then return end
local screen
before_each(function()
clear()
diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua
index c44e59cfd3..d521e3cd25 100644
--- a/test/functional/ui/popupmenu_spec.lua
+++ b/test/functional/ui/popupmenu_spec.lua
@@ -2324,7 +2324,7 @@ describe('builtin popupmenu', function()
it('is closed by :stopinsert from timer #12976', function()
screen:try_resize(32,14)
command([[call setline(1, ['hello', 'hullo', 'heeee', ''])]])
- feed('Gah<C-N>')
+ feed('Gah<c-x><c-n>')
screen:expect([[
hello |
hullo |
diff --git a/test/functional/ui/screen.lua b/test/functional/ui/screen.lua
index 61f19c3794..3e94fdbf44 100644
--- a/test/functional/ui/screen.lua
+++ b/test/functional/ui/screen.lua
@@ -576,16 +576,16 @@ to the test if they make sense.
print([[
warning: Screen changes were received after the expected state. This indicates
-indeterminism in the test. Try adding screen:expect(...) (or wait()) between
-asynchronous (feed(), nvim_input()) and synchronous API calls.
+indeterminism in the test. Try adding screen:expect(...) (or poke_eventloop())
+between asynchronous (feed(), nvim_input()) and synchronous API calls.
- Use screen:redraw_debug() to investigate; it may find relevant intermediate
states that should be added to the test to make it more robust.
- If the purpose of the test is to assert state after some user input sent
with feed(), adding screen:expect() before the feed() will help to ensure
the input is sent when Nvim is in a predictable state. This is preferable
- to wait(), for being closer to real user interaction.
- - wait() can trigger redraws and consequently generate more indeterminism.
- Try removing wait().
+ to poke_eventloop(), for being closer to real user interaction.
+ - poke_eventloop() can trigger redraws and thus generate more indeterminism.
+ Try removing poke_eventloop().
]])
did_warn = true
end
@@ -1559,10 +1559,11 @@ end
function Screen:_equal_attrs(a, b)
return a.bold == b.bold and a.standout == b.standout and
- a.underline == b.underline and a.undercurl == b.undercurl and
- a.italic == b.italic and a.reverse == b.reverse and
- a.foreground == b.foreground and a.background == b.background and
- a.special == b.special and a.blend == b.blend and
+ a.underline == b.underline and a.underlineline == b.underlineline and
+ a.undercurl == b.undercurl and a.underdot == b.underdot and
+ a.underdash == b.underdash and a.italic == b.italic and
+ a.reverse == b.reverse and a.foreground == b.foreground and
+ a.background == b.background and a.special == b.special and a.blend == b.blend and
a.strikethrough == b.strikethrough and
a.fg_indexed == b.fg_indexed and a.bg_indexed == b.bg_indexed
end
diff --git a/test/functional/ui/sign_spec.lua b/test/functional/ui/sign_spec.lua
index a0b7c98c51..dbc92ca222 100644
--- a/test/functional/ui/sign_spec.lua
+++ b/test/functional/ui/sign_spec.lua
@@ -446,7 +446,7 @@ describe('Signs', function()
{1:>>>>>>>>}{6: 1 }a |
{2: }{6: 2 }b |
{2: }{6: 3 }c |
- {2: }{6:^ 4 } |
+ {2: }{6: 4 }^ |
{0:~ }|
{0:~ }|
{0:~ }|
@@ -468,7 +468,7 @@ describe('Signs', function()
{1:>>>>>>>>>>}{6: 1 }a |
{2: }{6: 2 }b |
{2: }{6: 3 }c |
- {2: ^ }{6: 4 } |
+ {2: }{6: 4 }^ |
{0:~ }|
{0:~ }|
{0:~ }|
@@ -482,7 +482,7 @@ describe('Signs', function()
]])
end)
- it('ignores signs with no icon and text when calculting the signcolumn width', function()
+ it('ignores signs with no icon and text when calculating the signcolumn width', function()
feed('ia<cr>b<cr>c<cr><esc>')
command('set number')
command('set signcolumn=auto:2')
@@ -512,7 +512,7 @@ describe('Signs', function()
{1:>>}{6: 1 }a |
{2: }{6: 2 }b |
{2: }{6: 3 }c |
- {2: }{6: ^4 } |
+ {2: }{6: 4 }^ |
{0:~ }|
{0:~ }|
{0:~ }|
diff --git a/test/helpers.lua b/test/helpers.lua
index 333e98d495..7d2f8f760a 100644
--- a/test/helpers.lua
+++ b/test/helpers.lua
@@ -58,9 +58,9 @@ local check_logs_useless_lines = {
--- Invokes `fn` and includes the tail of `logfile` in the error message if it
--- fails.
---
----@param logfile Log file, defaults to $NVIM_LOG_FILE or '.nvimlog'
----@param fn Function to invoke
----@param ... Function arguments
+---@param logfile string Log file, defaults to $NVIM_LOG_FILE or '.nvimlog'
+---@param fn string Function to invoke
+---@param ... string Function arguments
local function dumplog(logfile, fn, ...)
-- module.validate({
-- logfile={logfile,'s',true},
@@ -102,8 +102,8 @@ end
--- Asserts that `pat` matches one or more lines in the tail of $NVIM_LOG_FILE.
---
----@param pat (string) Lua pattern to search for in the log file.
----@param logfile (string, default=$NVIM_LOG_FILE) full path to log file.
+---@param pat string Lua pattern to search for in the log file
+---@param logfile string Full path to log file (default=$NVIM_LOG_FILE)
function module.assert_log(pat, logfile)
logfile = logfile or os.getenv('NVIM_LOG_FILE') or '.nvimlog'
local nrlines = 10
diff --git a/test/unit/strings_spec.lua b/test/unit/strings_spec.lua
index e54c82b26a..e085ac749d 100644
--- a/test/unit/strings_spec.lua
+++ b/test/unit/strings_spec.lua
@@ -138,3 +138,15 @@ describe('vim_strchr()', function()
eq(nil, vim_strchr('«\237\175\191\237\188\128»', 0x10FF00))
end)
end)
+
+describe('strcase_save()' , function()
+ local strcase_save = function(input_string, upper)
+ local res = strings.strcase_save(to_cstr(input_string), upper)
+ return ffi.string(res)
+ end
+
+ itp('decodes overlong encoded characters.', function()
+ eq("A", strcase_save("\xc1\x81", true))
+ eq("a", strcase_save("\xc1\x81", false))
+ end)
+end)
diff --git a/test/unit/viml/expressions/parser_spec.lua b/test/unit/viml/expressions/parser_spec.lua
index 8342044b5e..51a703b593 100644
--- a/test/unit/viml/expressions/parser_spec.lua
+++ b/test/unit/viml/expressions/parser_spec.lua
@@ -48,6 +48,7 @@ local predefined_hl_defs = {
TermCursor=true,
VertSplit=true,
WildMenu=true,
+ WinSeparator=true,
EndOfBuffer=true,
QuickFixLine=true,
Substitute=true,
diff --git a/third-party/CMakeLists.txt b/third-party/CMakeLists.txt
index 174f1cbaba..8a8720fca3 100644
--- a/third-party/CMakeLists.txt
+++ b/third-party/CMakeLists.txt
@@ -144,8 +144,8 @@ endif()
include(ExternalProject)
-set(LIBUV_URL https://github.com/libuv/libuv/archive/v1.42.0.tar.gz)
-set(LIBUV_SHA256 371e5419708f6aaeb8656671f89400b92a9bba6443369af1bb70bcd6e4b3c764)
+set(LIBUV_URL https://github.com/libuv/libuv/archive/v1.44.1.tar.gz)
+set(LIBUV_SHA256 e91614e6dc2dd0bfdd140ceace49438882206b7a6fb00b8750914e67a9ed6d6b)
set(MSGPACK_URL https://github.com/msgpack/msgpack-c/releases/download/cpp-3.0.0/msgpack-3.0.0.tar.gz)
set(MSGPACK_SHA256 bfbb71b7c02f806393bc3cbc491b40523b89e64f83860c58e3e54af47de176e4)
@@ -169,9 +169,9 @@ set(LIBTERMKEY_SHA256 6945bd3c4aaa83da83d80a045c5563da4edd7d0374c62c0d35aec09eb3
set(LIBVTERM_URL https://www.leonerd.org.uk/code/libvterm/libvterm-0.1.4.tar.gz)
set(LIBVTERM_SHA256 bc70349e95559c667672fc8c55b9527d9db9ada0fb80a3beda533418d782d3dd)
-set(LUV_VERSION 1.42.0-1)
+set(LUV_VERSION 1.43.0-0)
set(LUV_URL https://github.com/luvit/luv/archive/${LUV_VERSION}.tar.gz)
-set(LUV_SHA256 a55563e6da9294ea26f77a2111598aa49188c5806b8bd1e1f4bdf402f340713e)
+set(LUV_SHA256 a36865f34db029e2caa01245a41341a067038c09e94459b50db1346d9fdf82f0)
set(LUA_COMPAT53_URL https://github.com/keplerproject/lua-compat-5.3/archive/v0.9.tar.gz)
set(LUA_COMPAT53_SHA256 ad05540d2d96a48725bb79a1def35cf6652a4e2ec26376e2617c8ce2baa6f416)
@@ -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/v0.20.3.tar.gz)
-set(TREESITTER_SHA256 ab52fe93e0c658cff656b9d10d67cdd29084247052964eba13ed6f0e9fa3bd36)
+set(TREESITTER_URL https://github.com/tree-sitter/tree-sitter/archive/v0.20.6.tar.gz)
+set(TREESITTER_SHA256 4d37eaef8a402a385998ff9aca3e1043b4a3bba899bceeff27a7178e1165b9de)
if(USE_BUNDLED_UNIBILIUM)
include(BuildUnibilium)
diff --git a/third-party/cmake/BuildGettext.cmake b/third-party/cmake/BuildGettext.cmake
index 9357456343..6128ecfa69 100644
--- a/third-party/cmake/BuildGettext.cmake
+++ b/third-party/cmake/BuildGettext.cmake
@@ -21,6 +21,7 @@ if(MSVC)
-DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN}
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DLIBICONV_INCLUDE_DIRS=${DEPS_INSTALL_DIR}/include
-DLIBICONV_LIBRARIES=${DEPS_LIB_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}libcharset${CMAKE_STATIC_LIBRARY_SUFFIX}$<SEMICOLON>${DEPS_LIB_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}libiconv${CMAKE_STATIC_LIBRARY_SUFFIX}
BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
diff --git a/third-party/cmake/BuildGperf.cmake b/third-party/cmake/BuildGperf.cmake
index 71c3cc1eef..5401191150 100644
--- a/third-party/cmake/BuildGperf.cmake
+++ b/third-party/cmake/BuildGperf.cmake
@@ -57,6 +57,7 @@ elseif(MSVC OR MINGW)
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
diff --git a/third-party/cmake/BuildLibiconv.cmake b/third-party/cmake/BuildLibiconv.cmake
index dc3d8fe4c3..5ff33e0cd3 100644
--- a/third-party/cmake/BuildLibiconv.cmake
+++ b/third-party/cmake/BuildLibiconv.cmake
@@ -21,6 +21,7 @@ if(MSVC)
-DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN}
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
INSTALL_COMMAND ${CMAKE_COMMAND} --build . --target install --config ${CMAKE_BUILD_TYPE})
diff --git a/third-party/cmake/BuildLibtermkey.cmake b/third-party/cmake/BuildLibtermkey.cmake
index 10e98fbab3..d44e09d734 100644
--- a/third-party/cmake/BuildLibtermkey.cmake
+++ b/third-party/cmake/BuildLibtermkey.cmake
@@ -22,6 +22,7 @@ ExternalProject_Add(libtermkey
# Hack to avoid -rdynamic in Mingw
-DCMAKE_SHARED_LIBRARY_LINK_C_FLAGS=""
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DUNIBILIUM_INCLUDE_DIRS=${DEPS_INSTALL_DIR}/include
-DUNIBILIUM_LIBRARIES=${DEPS_LIB_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}unibilium${CMAKE_STATIC_LIBRARY_SUFFIX}
BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
diff --git a/third-party/cmake/BuildLibuv.cmake b/third-party/cmake/BuildLibuv.cmake
index dce64c777b..42650308a8 100644
--- a/third-party/cmake/BuildLibuv.cmake
+++ b/third-party/cmake/BuildLibuv.cmake
@@ -63,10 +63,6 @@ elseif(WIN32)
set(BUILD_SHARED ON)
elseif(MINGW)
set(BUILD_SHARED OFF)
- set(LIBUV_PATCH_COMMAND
- ${GIT_EXECUTABLE} -C ${DEPS_BUILD_DIR}/src/libuv init
- COMMAND ${GIT_EXECUTABLE} -C ${DEPS_BUILD_DIR}/src/libuv apply --ignore-whitespace
- ${CMAKE_CURRENT_SOURCE_DIR}/patches/libuv-disable-typedef-MinGW.patch)
else()
message(FATAL_ERROR "Trying to build libuv in an unsupported system ${CMAKE_SYSTEM_NAME}/${CMAKE_C_COMPILER_ID}")
endif()
@@ -77,6 +73,7 @@ elseif(WIN32)
COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/libuv/CMakeLists.txt
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DBUILD_SHARED_LIBS=${BUILD_SHARED}
-DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
diff --git a/third-party/cmake/BuildLibvterm.cmake b/third-party/cmake/BuildLibvterm.cmake
index 09f2ba7f2c..2c300dda7c 100644
--- a/third-party/cmake/BuildLibvterm.cmake
+++ b/third-party/cmake/BuildLibvterm.cmake
@@ -47,6 +47,7 @@ if(WIN32)
COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/libvterm
-DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
"-DCMAKE_C_FLAGS:STRING=${CMAKE_C_COMPILER_ARG1} -fPIC"
-DCMAKE_GENERATOR=${CMAKE_GENERATOR})
set(LIBVTERM_BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE})
diff --git a/third-party/cmake/BuildLuv.cmake b/third-party/cmake/BuildLuv.cmake
index 69f3b60ecf..99822249c2 100644
--- a/third-party/cmake/BuildLuv.cmake
+++ b/third-party/cmake/BuildLuv.cmake
@@ -104,6 +104,7 @@ elseif(MSVC)
set(LUV_CONFIGURE_COMMAND
${LUV_CONFIGURE_COMMAND_COMMON}
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
# Same as Unix without fPIC
"-DCMAKE_C_FLAGS:STRING=${CMAKE_C_COMPILER_ARG1} ${LUV_INCLUDE_FLAGS}"
# Make sure we use the same generator, otherwise we may
diff --git a/third-party/cmake/BuildMsgpack.cmake b/third-party/cmake/BuildMsgpack.cmake
index 39a8a64d23..ee4f0eb080 100644
--- a/third-party/cmake/BuildMsgpack.cmake
+++ b/third-party/cmake/BuildMsgpack.cmake
@@ -63,6 +63,7 @@ elseif(MSVC)
-DMSGPACK_BUILD_EXAMPLES=OFF
-DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
"-DCMAKE_C_FLAGS:STRING=${CMAKE_C_COMPILER_ARG1}"
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
# Make sure we use the same generator, otherwise we may
diff --git a/third-party/cmake/BuildTreesitter.cmake b/third-party/cmake/BuildTreesitter.cmake
index 0aa2706d7d..01fdb837e2 100644
--- a/third-party/cmake/BuildTreesitter.cmake
+++ b/third-party/cmake/BuildTreesitter.cmake
@@ -42,6 +42,7 @@ if(MSVC)
COMMAND ${CMAKE_COMMAND} ${DEPS_BUILD_DIR}/src/tree-sitter/CMakeLists.txt
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
diff --git a/third-party/cmake/BuildTreesitterParsers.cmake b/third-party/cmake/BuildTreesitterParsers.cmake
index 5284a7fd62..4ceb402455 100644
--- a/third-party/cmake/BuildTreesitterParsers.cmake
+++ b/third-party/cmake/BuildTreesitterParsers.cmake
@@ -15,8 +15,8 @@ PATCH_COMMAND ${CMAKE_COMMAND} -E copy
${DEPS_BUILD_DIR}/src/treesitter-c/CMakeLists.txt
CMAKE_ARGS
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
- -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
# Pass toolchain
diff --git a/third-party/cmake/BuildUnibilium.cmake b/third-party/cmake/BuildUnibilium.cmake
index 74c1cbddb0..2f940bdfd3 100644
--- a/third-party/cmake/BuildUnibilium.cmake
+++ b/third-party/cmake/BuildUnibilium.cmake
@@ -18,6 +18,7 @@ if(WIN32)
-DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL_DIR}
# Pass toolchain
-DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN}
+ -DCMAKE_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
-DCMAKE_GENERATOR=${CMAKE_GENERATOR}
BUILD_COMMAND ${CMAKE_COMMAND} --build . --config ${CMAKE_BUILD_TYPE}
diff --git a/third-party/patches/libuv-disable-typedef-MinGW.patch b/third-party/patches/libuv-disable-typedef-MinGW.patch
deleted file mode 100644
index a47893cede..0000000000
--- a/third-party/patches/libuv-disable-typedef-MinGW.patch
+++ /dev/null
@@ -1,19 +0,0 @@
-diff --git a/include/uv/win.h b/include/uv/win.h
-index f5f1d3a3..64a0dfd9 100644
---- a/include/uv/win.h
-+++ b/include/uv/win.h
-@@ -45,7 +45,14 @@ typedef struct pollfd {
- #endif
-
- #include <mswsock.h>
-+// Disable the typedef in mstcpip.h of MinGW.
-+#define _TCP_INITIAL_RTO_PARAMETERS _TCP_INITIAL_RTO_PARAMETERS__
-+#define TCP_INITIAL_RTO_PARAMETERS TCP_INITIAL_RTO_PARAMETERS__
-+#define PTCP_INITIAL_RTO_PARAMETERS PTCP_INITIAL_RTO_PARAMETERS__
- #include <ws2tcpip.h>
-+#undef _TCP_INITIAL_RTO_PARAMETERS
-+#undef TCP_INITIAL_RTO_PARAMETERS
-+#undef PTCP_INITIAL_RTO_PARAMETERS
- #include <windows.h>
-
- #include <process.h>