- https://github.com/neovim/tree-sitter-vimdoc v1.2.4 eliminates most
  errors in pi_netrw.txt, so we can remove that workaround from
  ignore_parse_error().
- improved codeblock
This commit is contained in:
Justin M. Keyes 2022-12-11 21:41:26 -05:00 committed by GitHub
parent b12bb97fee
commit 1c324cb192
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 156 additions and 195 deletions

View File

@ -2,7 +2,7 @@
<img src="https://raw.githubusercontent.com/neovim/neovim.github.io/master/logos/neovim-logo-300x87.png" alt="Neovim"> <img src="https://raw.githubusercontent.com/neovim/neovim.github.io/master/logos/neovim-logo-300x87.png" alt="Neovim">
</h1> </h1>
[Documentation](https://neovim.io/doc/general/) | [Documentation](https://neovim.io/doc/) |
[Chat](https://app.element.io/#/room/#neovim:matrix.org) | [Chat](https://app.element.io/#/room/#neovim:matrix.org) |
[Twitter](https://twitter.com/Neovim) [Twitter](https://twitter.com/Neovim)
@ -107,9 +107,9 @@ Apache 2.0 license, except for contributions copied from Vim (identified by the
encouraged to make a donation for needy children in Uganda. Please see the encouraged to make a donation for needy children in Uganda. Please see the
kcc section of the vim docs or visit the ICCF web site, available at these URLs: kcc section of the vim docs or visit the ICCF web site, available at these URLs:
http://iccf-holland.org/ https://iccf-holland.org/
http://www.vim.org/iccf/ https://www.vim.org/iccf/
http://www.iccf.nl/ https://www.iccf.nl/
You can also sponsor the development of Vim. Vim sponsors can vote for You can also sponsor the development of Vim. Vim sponsors can vote for
features. The money goes to Uganda anyway. features. The money goes to Uganda anyway.
@ -121,7 +121,7 @@ Apache 2.0 license, except for contributions copied from Vim (identified by the
[advanced UIs]: https://github.com/neovim/neovim/wiki/Related-projects#gui [advanced UIs]: https://github.com/neovim/neovim/wiki/Related-projects#gui
[Managed packages]: https://github.com/neovim/neovim/wiki/Installing-Neovim#install-from-package [Managed packages]: https://github.com/neovim/neovim/wiki/Installing-Neovim#install-from-package
[Debian]: https://packages.debian.org/testing/neovim [Debian]: https://packages.debian.org/testing/neovim
[Ubuntu]: http://packages.ubuntu.com/search?keywords=neovim [Ubuntu]: https://packages.ubuntu.com/search?keywords=neovim
[Fedora]: https://packages.fedoraproject.org/pkgs/neovim/neovim/ [Fedora]: https://packages.fedoraproject.org/pkgs/neovim/neovim/
[Arch Linux]: https://www.archlinux.org/packages/?q=neovim [Arch Linux]: https://www.archlinux.org/packages/?q=neovim
[Void Linux]: https://voidlinux.org/packages/?arch=x86_64&q=neovim [Void Linux]: https://voidlinux.org/packages/?arch=x86_64&q=neovim

View File

@ -3228,89 +3228,54 @@ nvim_create_augroup({name}, {*opts}) *nvim_create_augroup()*
|autocmd-groups| |autocmd-groups|
nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()* nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()*
Create an |autocommand| Creates an |autocommand| event handler, defined by `callback` (Lua function or Vimscript function name string) or `command` (Ex command string).
The API allows for two (mutually exclusive) types of actions to be
executed when the autocommand triggers: a callback function (Lua or
Vimscript), or a command (like regular autocommands).
Example using callback: >lua
-- Lua function
local myluafun = function() print("This buffer enters") end
-- Vimscript function name (as a string)
local myvimfun = "g:MyVimFunction"
Example using Lua callback: >lua
vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
pattern = {"*.c", "*.h"}, pattern = {"*.c", "*.h"},
callback = myluafun, -- Or myvimfun callback = function(ev)
print(string.format('event fired: s', vim.inspect(ev)))
end
}) })
< <
Lua functions receive a table with information about the autocmd event as Example using an Ex command as the handler: >lua
an argument. To use a function which itself accepts another (optional)
parameter, wrap the function in a lambda: >lua
-- Lua function with an optional parameter.
-- The autocmd callback would pass a table as argument but this
-- function expects number|nil
local myluafun = function(bufnr) bufnr = bufnr or vim.api.nvim_get_current_buf() end
vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
pattern = {"*.c", "*.h"},
callback = function() myluafun() end,
})
<
Example using command: >lua
vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
pattern = {"*.c", "*.h"}, pattern = {"*.c", "*.h"},
command = "echo 'Entering a C or C++ file'", command = "echo 'Entering a C or C++ file'",
}) })
< <
Example values for pattern: >lua Note: `pattern` is NOT automatically expanded (unlike with |:autocmd|), thus names like
pattern = "*.py" "$HOME" and "~" must be expanded explicitly: >lua
pattern = { "*.py", "*.pyi" }
<
Note: The `pattern` is passed to callbacks and commands as a literal string; environment
variables like `$HOME` and `~` are not automatically expanded as they are by |:autocmd|. Instead,
|expand()| such variables explicitly: >lua
pattern = vim.fn.expand("~") .. "/some/path/*.py" pattern = vim.fn.expand("~") .. "/some/path/*.py"
< <
Example values for event: >lua
event = "BufWritePre"
event = {"CursorHold", "BufWritePre", "BufWritePost"}
<
Parameters: ~ Parameters: ~
• {event} (string|array) The event or events to register this • {event} (string|array) Event(s) that will trigger the handler
autocommand (`callback` or `command`).
• {opts} Dictionary of autocommand options: • {opts} Options dict:
• group (string|integer) optional: the autocommand group name • group (string|integer) optional: autocommand group name or
or id to match against. id to match against.
• pattern (string|array) optional: pattern or patterns to • pattern (string|array) optional: pattern(s) to match
match literally against |autocmd-pattern|. literally |autocmd-pattern|.
• buffer (integer) optional: buffer number for buffer local • buffer (integer) optional: buffer number for buffer-local
autocommands |autocmd-buflocal|. Cannot be used with autocommands |autocmd-buflocal|. Cannot be used with
{pattern}. {pattern}.
• desc (string) optional: description of the autocommand. • desc (string) optional: description (for documentation and
• callback (function|string) optional: if a string, the name troubleshooting).
of a Vimscript function to call when this autocommand is • callback (function|string) optional: Lua function (or
triggered. Otherwise, a Lua function which is called when Vimscript function name, if string) called when the
this autocommand is triggered. Cannot be used with event(s) is triggered. Lua callback can return true to
{command}. Lua callbacks can return true to delete the delete the autocommand, and receives a table argument with
autocommand; in addition, they accept a single table these keys:
argument with the following keys: • id: (number) autocommand id
• id: (number) the autocommand id • event: (string) name of the triggered event
• event: (string) the name of the event that triggered the |autocmd-events|
autocommand |autocmd-events| • group: (number|nil) autocommand group id, if any
• group: (number|nil) the autocommand group id, if it • match: (string) expanded value of |<amatch>|
exists • buf: (number) expanded value of |<abuf>|
• match: (string) the expanded value of |<amatch>| • file: (string) expanded value of |<afile>|
• buf: (number) the expanded value of |<abuf>|
• file: (string) the expanded value of |<afile>|
• data: (any) arbitrary data passed to • data: (any) arbitrary data passed to
|nvim_exec_autocmds()| |nvim_exec_autocmds()|
@ -3322,7 +3287,7 @@ nvim_create_autocmd({event}, {*opts}) *nvim_create_autocmd()*
autocommands |autocmd-nested|. autocommands |autocmd-nested|.
Return: ~ Return: ~
Integer id of the created autocommand. Autocommand id (number)
See also: ~ See also: ~
|autocommand| |autocommand|

View File

@ -28,11 +28,9 @@ The Neo bits of Nvim should make it a better Vim, without becoming a
completely different editor. completely different editor.
- In matters of taste, prefer Vim/Unix tradition. If there is no relevant - In matters of taste, prefer Vim/Unix tradition. If there is no relevant
Vim/Unix tradition, consider the "common case". Vim/Unix tradition, consider the "common case".
- A feature that people do not know about is a useless feature. Don't add - There is no limit to the features that can be added. Select new features
obscure features, or at least add hints in documentation that they exist. based on (1) what users ask for, (2) how much effort it takes to implement
- There is no limit to the features that can be added. Selecting new features and (3) someone actually implementing it.
is based on (1) what users ask for, (2) how much effort it takes to
implement and (3) someone actually implementing it.
- Backwards compatibility is a feature. The RPC API in particular should - Backwards compatibility is a feature. The RPC API in particular should
never break. never break.
@ -48,7 +46,7 @@ NVIM IS... WELL DOCUMENTED *design-documented*
NVIM IS... FAST AND SMALL *design-speed-size* NVIM IS... FAST AND SMALL *design-speed-size*
Keep Nvim small and fast. Keep Nvim small and fast. This directly affects versatility and usability.
- Computers are becoming faster and bigger each year. Vim can grow too, but - Computers are becoming faster and bigger each year. Vim can grow too, but
no faster than computers are growing. Keep Vim usable on older systems. no faster than computers are growing. Keep Vim usable on older systems.
- Many users start Vim from a shell very often. Startup time must be short. - Many users start Vim from a shell very often. Startup time must be short.
@ -57,7 +55,8 @@ Keep Nvim small and fast.
- Don't forget that some people use Vim over a slow connection. Minimize the - Don't forget that some people use Vim over a slow connection. Minimize the
communication overhead. communication overhead.
- Vim is a component among other components. Don't turn it into a massive - Vim is a component among other components. Don't turn it into a massive
application, but have it work well together with other programs. application, but have it work well together with other programs
("composability").
NVIM IS... MAINTAINABLE *design-maintain* NVIM IS... MAINTAINABLE *design-maintain*
@ -250,13 +249,25 @@ vim.paste in runtime/lua/vim/_editor.lua like this: >
LUA *dev-lua* LUA *dev-lua*
- Keep the core Lua modules |lua-stdlib| simple. Avoid elaborate OOP or - Keep the core Lua modules |lua-stdlib| simple. Avoid elaborate OOP or
pseudo-OOP designs. Plugin authors just want functions to call, they don't pseudo-OOP designs. Plugin authors just want functions to call, not a big,
want to learn a big, fancy inheritance hierarchy. Thus avoid specialized fancy inheritance hierarchy.
objects; tables or values are usually better. - Avoid requiring or returning special objects in the Nvim stdlib. Plain
tables or values are easier to serialize, easier to construct from literals,
easier to inspect and print, and inherently compatible with all Lua plugins.
(This guideline doesn't apply to opaque, non-data objects like `vim.cmd`.)
API *dev-api* API *dev-api*
- Avoid "mutually exclusive" parameters--via constraints or limitations, if
necessary. For example nvim_create_autocmd() has mutually exclusive
"callback" and "command" args; but the "command" arg could be eliminated by
simply not supporting Vimscript function names, and treating a string
"callback" arg as an Ex command (which can call Vimscript functions). The
"buffer" arg could also be eliminated by treating a number "pattern" as
a buffer number.
*dev-api-naming*
Use this format to name new RPC |API| functions: Use this format to name new RPC |API| functions:
nvim_{thing}_{action}_{arbitrary-qualifiers} nvim_{thing}_{action}_{arbitrary-qualifiers}

View File

@ -423,9 +423,8 @@ Note that such expressions are only supported in places where a filename is
expected as an argument to an Ex-command. expected as an argument to an Ex-command.
*++opt* *[++opt]* *++opt* *[++opt]*
The [++opt] argument can be used to force the value of 'fileformat', The [++opt] argument can be used to set some options for one command, and to
'fileencoding' or 'binary' to a value for one command, and to specify the specify the behavior for bad characters. The form is: >
behavior for bad characters. The form is: >
++{optname} ++{optname}
Or: > Or: >
++{optname}={value} ++{optname}={value}
@ -436,13 +435,11 @@ Where {optname} is one of: *++ff* *++enc* *++bin* *++nobin* *++edit*
bin or binary sets 'binary' bin or binary sets 'binary'
nobin or nobinary resets 'binary' nobin or nobinary resets 'binary'
bad specifies behavior for bad characters bad specifies behavior for bad characters
edit for |:read| only: keep option values as if editing edit for |:read|: keeps options as if editing a file
a file p for |:write|: creates the file's parent directory
p creates the parent directory (or directories) of
a filename if they do not exist
{value} cannot contain white space. It can be any valid value for these {value} cannot contain whitespace. It can be any valid value for the options.
options. Examples: > Examples: >
:e ++ff=unix :e ++ff=unix
This edits the same file again with 'fileformat' set to "unix". > This edits the same file again with 'fileformat' set to "unix". >
@ -452,9 +449,24 @@ This writes the current buffer to "newfile" in latin1 format.
The message given when writing a file will show "[converted]" when The message given when writing a file will show "[converted]" when
'fileencoding' or the value specified with ++enc differs from 'encoding'. 'fileencoding' or the value specified with ++enc differs from 'encoding'.
There may be several ++opt arguments, separated by white space. They must all There may be several ++opt arguments, separated by whitespace. They must all
appear before any |+cmd| argument. appear before any |+cmd| argument.
*++p*
The "++p" flag creates the parent directory of the file if it does not exist.
For example if you edit "foo/bar/file.txt", the ":write ++p" command creates
"foo/bar/" if necessary before writing the file. >
:edit foo/bar/file.txt
:write ++p
If you want :write (without "++p") to always create missing parent
directories, add this autocmd to your config: >
" Auto-create parent directories (except for URIs "://").
au BufWritePre,FileWritePre * if @% !~# '\(://\)' | call mkdir(expand('<afile>:p:h'), 'p') | endif
<
*++bad* *++bad*
The argument of "++bad=" specifies what happens with characters that can't be The argument of "++bad=" specifies what happens with characters that can't be
converted and illegal bytes. It can be one of three things: converted and illegal bytes. It can be one of three things:
@ -895,11 +907,13 @@ Note: When the 'write' option is off, you are not able to write any file.
*E502* *E503* *E504* *E505* *E502* *E503* *E504* *E505*
*E512* *E514* *E667* *E949* *E512* *E514* *E667* *E949*
:w[rite] [++opt] Write the whole buffer to the current file. This is :w[rite] [++opt] Write the whole buffer to the current file. This is
the normal way to save changes to a file. It fails the normal way to save changes to a file. Fails when
when the 'readonly' option is set or when there is 'readonly' is set or when there is another reason why
another reason why the file can't be written. the file can't be written, such as when the parent
For ++opt see |++opt|, but only ++bin, ++nobin, ++ff directory doesn't exist (use |++p| to avoid that).
and ++enc are effective. For ++opt see |++opt|, but only ++p, ++bin, ++nobin,
++ff and ++enc are effective.
:w[rite]! [++opt] Like ":write", but forcefully write when 'readonly' is :w[rite]! [++opt] Like ":write", but forcefully write when 'readonly' is
set or there is another reason why writing was set or there is another reason why writing was

View File

@ -1708,13 +1708,13 @@ v:charconvert_to
*v:cmdarg* *cmdarg-variable* *v:cmdarg* *cmdarg-variable*
v:cmdarg This variable is used for two purposes: v:cmdarg This variable is used for two purposes:
1. The extra arguments given to a file read/write command. 1. The extra arguments ("++p", "++enc=", "++ff=") given to
Currently these are "++enc=" and "++ff=". This variable is a file read/write command. This is set before an
set before an autocommand event for a file read/write autocommand event for a file read/write command is
command is triggered. There is a leading space to make it triggered. There is a leading space to make it possible to
possible to append this variable directly after the append this variable directly after the read/write command.
read/write command. Note: The "+cmd" argument isn't Note: "+cmd" isn't included here, because it will be
included here, because it will be executed anyway. executed anyway.
2. When printing a PostScript file with ":hardcopy" this is 2. When printing a PostScript file with ":hardcopy" this is
the argument for the ":hardcopy" command. This can be used the argument for the ":hardcopy" command. This can be used
in 'printexpr'. in 'printexpr'.

View File

@ -325,7 +325,7 @@ To configure the behavior of a builtin |lsp-handler|, the convenient method
}, },
} }
< <
or if using 'nvim-lspconfig', you can use the {handlers} key of `setup()`: or if using "nvim-lspconfig", you can use the {handlers} key of `setup()`:
>lua >lua
require('lspconfig').rust_analyzer.setup { require('lspconfig').rust_analyzer.setup {
@ -1340,9 +1340,7 @@ start({bufnr}, {client_id}, {opts}) *vim.lsp.semantic_tokens.start()*
|vim.lsp.buf_attach_client()|. To opt-out of semantic highlighting with a |vim.lsp.buf_attach_client()|. To opt-out of semantic highlighting with a
server that supports it, you can delete the semanticTokensProvider table server that supports it, you can delete the semanticTokensProvider table
from the {server_capabilities} of your client in your |LspAttach| callback from the {server_capabilities} of your client in your |LspAttach| callback
or your configuration's `on_attach` callback. or your configuration's `on_attach` callback. >lua
>lua
client.server_capabilities.semanticTokensProvider = nil client.server_capabilities.semanticTokensProvider = nil
< <

View File

@ -24,8 +24,8 @@ Transitioning from Vim *nvim-from-vim*
1. To start the transition, create your |init.vim| (user config) file: >vim 1. To start the transition, create your |init.vim| (user config) file: >vim
:call mkdir(stdpath('config'), 'p')
:exe 'edit '.stdpath('config').'/init.vim' :exe 'edit '.stdpath('config').'/init.vim'
:write ++p
2. Add these contents to the file: >vim 2. Add these contents to the file: >vim

View File

@ -176,7 +176,7 @@ a |provider| which transparently uses shell commands to communicate with the
system clipboard or any other clipboard "backend". system clipboard or any other clipboard "backend".
To ALWAYS use the clipboard for ALL operations (instead of interacting with To ALWAYS use the clipboard for ALL operations (instead of interacting with
the '+' and/or '*' registers explicitly): >vim the "+" and/or "*" registers explicitly): >vim
set clipboard+=unnamedplus set clipboard+=unnamedplus
See 'clipboard' for details and options. See 'clipboard' for details and options.

View File

@ -127,7 +127,7 @@ nvim_cmdwin:
============================================================================== ==============================================================================
3. New Features *nvim-features* 3. New Features *nvim-features*
MAJOR COMPONENTS ~ MAJOR COMPONENTS
API |API| API |API|
Job control |job-control| Job control |job-control|
@ -145,7 +145,7 @@ Terminal emulator |terminal|
Vimscript parser |nvim_parse_expression()| Vimscript parser |nvim_parse_expression()|
XDG base directories |xdg| XDG base directories |xdg|
USER EXPERIENCE ~ USER EXPERIENCE
Working intuitively and consistently is a major goal of Nvim. Working intuitively and consistently is a major goal of Nvim.
@ -176,7 +176,7 @@ Some features are built in that otherwise required external plugins:
- Highlighting the yanked region, see |lua-highlight|. - Highlighting the yanked region, see |lua-highlight|.
ARCHITECTURE ~ ARCHITECTURE
External plugins run in separate processes. |remote-plugin| This improves External plugins run in separate processes. |remote-plugin| This improves
stability and allows those plugins to work without blocking the editor. Even stability and allows those plugins to work without blocking the editor. Even
@ -187,7 +187,7 @@ Platform and I/O facilities are built upon libuv. Nvim benefits from libuv
features and bug fixes, and other projects benefit from improvements to libuv features and bug fixes, and other projects benefit from improvements to libuv
by Nvim developers. by Nvim developers.
FEATURES ~ FEATURES
Command-line highlighting: Command-line highlighting:
The expression prompt (|@=|, |c_CTRL-R_=|, |i_CTRL-R_=|) is highlighted The expression prompt (|@=|, |c_CTRL-R_=|, |i_CTRL-R_=|) is highlighted
@ -206,6 +206,7 @@ Commands:
|:match| can be invoked before highlight group is defined |:match| can be invoked before highlight group is defined
|:source| works with Lua |:source| works with Lua
User commands can support |:command-preview| to show results as you type User commands can support |:command-preview| to show results as you type
|:write| with "++p" flag creates parent directories.
Events: Events:
|RecordingEnter| |RecordingEnter|
@ -226,6 +227,7 @@ Functions:
|stdpath()| |stdpath()|
|system()|, |systemlist()| can run {cmd} directly (without 'shell') |system()|, |systemlist()| can run {cmd} directly (without 'shell')
|matchadd()| can be called before highlight group is defined |matchadd()| can be called before highlight group is defined
|writefile()| with "p" flag creates parent directories.
Highlight groups: Highlight groups:
|highlight-blend| controls blend level for a highlight group |highlight-blend| controls blend level for a highlight group
@ -277,7 +279,20 @@ Variables:
|v:windowid| is always available (for use by external UIs) |v:windowid| is always available (for use by external UIs)
============================================================================== ==============================================================================
4. Changed features *nvim-features-changed* 4. Upstreamed features *nvim-upstreamed*
These Nvim features were later integrated into Vim.
- 'fillchars' flags: "eob"
- 'wildoptions' flags: "pum" enables popupmenu for wildmode completion
- |<Cmd>|
- |WinClosed|
- |WinScrolled|
- |:sign-define| "numhl" argument
- |:source| works with anonymous (no file) scripts
==============================================================================
5. Changed features *nvim-features-changed*
Nvim always builds with all features, in contrast to Vim which may have Nvim always builds with all features, in contrast to Vim which may have
certain features removed/added at compile-time. |feature-compile| certain features removed/added at compile-time. |feature-compile|
@ -499,7 +514,7 @@ Working directory (Vim implemented some of these later than Nvim):
working directory. Use `getcwd(-1, -1)` to get the global working directory. working directory. Use `getcwd(-1, -1)` to get the global working directory.
============================================================================== ==============================================================================
5. Missing legacy features *nvim-features-missing* 6. Missing legacy features *nvim-features-missing*
Some legacy Vim features are not yet implemented: Some legacy Vim features are not yet implemented:
@ -512,7 +527,7 @@ Some legacy Vim features are not yet implemented:
*:gvim* *:gvim*
============================================================================== ==============================================================================
6. Removed features *nvim-features-removed* 7. Removed features *nvim-features-removed*
These Vim features were intentionally removed from Nvim. These Vim features were intentionally removed from Nvim.

View File

@ -495,7 +495,6 @@ local M = {}
--- delete the semanticTokensProvider table from the {server_capabilities} of --- delete the semanticTokensProvider table from the {server_capabilities} of
--- your client in your |LspAttach| callback or your configuration's --- your client in your |LspAttach| callback or your configuration's
--- `on_attach` callback. --- `on_attach` callback.
---
--- <pre>lua --- <pre>lua
--- client.server_capabilities.semanticTokensProvider = nil --- client.server_capabilities.semanticTokensProvider = nil
--- </pre> --- </pre>

View File

@ -296,12 +296,11 @@ local function ignore_invalid(s)
) )
end end
local function ignore_parse_error(s, fname) local function ignore_parse_error(s)
local helpfile = vim.fs.basename(fname) return (
return (helpfile == 'pi_netrw.txt'
-- Ignore parse errors for unclosed tag. -- Ignore parse errors for unclosed tag.
-- This is common in vimdocs and is treated as plaintext by :help. -- This is common in vimdocs and is treated as plaintext by :help.
or s:find("^[`'|*]") s:find("^[`'|*]")
) )
end end
@ -370,7 +369,7 @@ local function visit_validate(root, level, lang_tree, opt, stats)
end end
if node_name == 'ERROR' then if node_name == 'ERROR' then
if ignore_parse_error(text, opt.fname) then if ignore_parse_error(text) then
return return
end end
-- Store the raw text to give context to the error report. -- Store the raw text to give context to the error report.
@ -582,7 +581,7 @@ local function visit_node(root, level, lang_tree, headings, opt, stats)
end end
return s return s
elseif node_name == 'ERROR' then elseif node_name == 'ERROR' then
if ignore_parse_error(trimmed, opt.fname) then if ignore_parse_error(trimmed) then
return text return text
end end

View File

@ -361,41 +361,20 @@ cleanup:
return autocmd_list; return autocmd_list;
} }
/// Create an |autocommand| /// Creates an |autocommand| event handler, defined by `callback` (Lua function or Vimscript
/// function _name_ string) or `command` (Ex command string).
/// ///
/// The API allows for two (mutually exclusive) types of actions to be executed when the autocommand /// Example using Lua callback:
/// triggers: a callback function (Lua or Vimscript), or a command (like regular autocommands).
///
/// Example using callback:
/// <pre>lua /// <pre>lua
/// -- Lua function
/// local myluafun = function() print("This buffer enters") end
///
/// -- Vimscript function name (as a string)
/// local myvimfun = "g:MyVimFunction"
///
/// vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { /// vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
/// pattern = {"*.c", "*.h"}, /// pattern = {"*.c", "*.h"},
/// callback = myluafun, -- Or myvimfun /// callback = function(ev)
/// print(string.format('event fired: %s', vim.inspect(ev)))
/// end
/// }) /// })
/// </pre> /// </pre>
/// ///
/// Lua functions receive a table with information about the autocmd event as an argument. To use /// Example using an Ex command as the handler:
/// a function which itself accepts another (optional) parameter, wrap the function
/// in a lambda:
/// <pre>lua
/// -- Lua function with an optional parameter.
/// -- The autocmd callback would pass a table as argument but this
/// -- function expects number|nil
/// local myluafun = function(bufnr) bufnr = bufnr or vim.api.nvim_get_current_buf() end
///
/// vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
/// pattern = {"*.c", "*.h"},
/// callback = function() myluafun() end,
/// })
/// </pre>
///
/// Example using command:
/// <pre>lua /// <pre>lua
/// vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, { /// vim.api.nvim_create_autocmd({"BufEnter", "BufWinEnter"}, {
/// pattern = {"*.c", "*.h"}, /// pattern = {"*.c", "*.h"},
@ -403,46 +382,28 @@ cleanup:
/// }) /// })
/// </pre> /// </pre>
/// ///
/// Example values for pattern: /// Note: `pattern` is NOT automatically expanded (unlike with |:autocmd|), thus names like "$HOME"
/// <pre>lua /// and "~" must be expanded explicitly:
/// pattern = "*.py"
/// pattern = { "*.py", "*.pyi" }
/// </pre>
///
/// Note: The `pattern` is passed to callbacks and commands as a literal string; environment
/// variables like `$HOME` and `~` are not automatically expanded as they are by |:autocmd|.
/// Instead, |expand()| such variables explicitly:
/// <pre>lua /// <pre>lua
/// pattern = vim.fn.expand("~") .. "/some/path/*.py" /// pattern = vim.fn.expand("~") .. "/some/path/*.py"
/// </pre> /// </pre>
/// ///
/// Example values for event: /// @param event (string|array) Event(s) that will trigger the handler (`callback` or `command`).
/// <pre>lua /// @param opts Options dict:
/// event = "BufWritePre" /// - group (string|integer) optional: autocommand group name or id to match against.
/// event = {"CursorHold", "BufWritePre", "BufWritePost"} /// - pattern (string|array) optional: pattern(s) to match literally |autocmd-pattern|.
/// </pre> /// - buffer (integer) optional: buffer number for buffer-local autocommands
///
/// @param event (string|array) The event or events to register this autocommand
/// @param opts Dictionary of autocommand options:
/// - group (string|integer) optional: the autocommand group name or
/// id to match against.
/// - pattern (string|array) optional: pattern or patterns to match literally
/// against |autocmd-pattern|.
/// - buffer (integer) optional: buffer number for buffer local autocommands
/// |autocmd-buflocal|. Cannot be used with {pattern}. /// |autocmd-buflocal|. Cannot be used with {pattern}.
/// - desc (string) optional: description of the autocommand. /// - desc (string) optional: description (for documentation and troubleshooting).
/// - callback (function|string) optional: if a string, the name of a Vimscript function /// - callback (function|string) optional: Lua function (or Vimscript function name, if
/// to call when this autocommand is triggered. Otherwise, a Lua function which is /// string) called when the event(s) is triggered. Lua callback can return true to
/// called when this autocommand is triggered. Cannot be used with {command}. Lua /// delete the autocommand, and receives a table argument with these keys:
/// callbacks can return true to delete the autocommand; in addition, they accept a /// - id: (number) autocommand id
/// single table argument with the following keys: /// - event: (string) name of the triggered event |autocmd-events|
/// - id: (number) the autocommand id /// - group: (number|nil) autocommand group id, if any
/// - event: (string) the name of the event that triggered the autocommand /// - match: (string) expanded value of |<amatch>|
/// |autocmd-events| /// - buf: (number) expanded value of |<abuf>|
/// - group: (number|nil) the autocommand group id, if it exists /// - file: (string) expanded value of |<afile>|
/// - match: (string) the expanded value of |<amatch>|
/// - buf: (number) the expanded value of |<abuf>|
/// - file: (string) the expanded value of |<afile>|
/// - data: (any) arbitrary data passed to |nvim_exec_autocmds()| /// - data: (any) arbitrary data passed to |nvim_exec_autocmds()|
/// - command (string) optional: Vim command to execute on event. Cannot be used with /// - command (string) optional: Vim command to execute on event. Cannot be used with
/// {callback} /// {callback}
@ -451,7 +412,7 @@ cleanup:
/// - nested (boolean) optional: defaults to false. Run nested /// - nested (boolean) optional: defaults to false. Run nested
/// autocommands |autocmd-nested|. /// autocommands |autocmd-nested|.
/// ///
/// @return Integer id of the created autocommand. /// @return Autocommand id (number)
/// @see |autocommand| /// @see |autocommand|
/// @see |nvim_del_autocmd()| /// @see |nvim_del_autocmd()|
Integer nvim_create_autocmd(uint64_t channel_id, Object event, Dict(create_autocmd) *opts, Integer nvim_create_autocmd(uint64_t channel_id, Object event, Dict(create_autocmd) *opts,
@ -472,8 +433,7 @@ Integer nvim_create_autocmd(uint64_t channel_id, Object event, Dict(create_autoc
} }
if (opts->callback.type != kObjectTypeNil && opts->command.type != kObjectTypeNil) { if (opts->callback.type != kObjectTypeNil && opts->command.type != kObjectTypeNil) {
api_set_error(err, kErrorTypeValidation, api_set_error(err, kErrorTypeValidation, "specify either 'callback' or 'command', not both");
"cannot pass both: 'callback' and 'command' for the same autocmd");
goto cleanup; goto cleanup;
} else if (opts->callback.type != kObjectTypeNil) { } else if (opts->callback.type != kObjectTypeNil) {
// TODO(tjdevries): It's possible we could accept callable tables, // TODO(tjdevries): It's possible we could accept callable tables,

View File

@ -14,14 +14,14 @@ before_each(clear)
describe('autocmd api', function() describe('autocmd api', function()
describe('nvim_create_autocmd', function() describe('nvim_create_autocmd', function()
it('does not allow "command" and "callback" in the same autocmd', function() it('"command" and "callback" are mutually exclusive', function()
local ok, _ = pcall(meths.create_autocmd, "BufReadPost", { local rv = pcall_err(meths.create_autocmd, "BufReadPost", {
pattern = "*.py,*.pyi", pattern = "*.py,*.pyi",
command = "echo 'Should Have Errored", command = "echo 'Should Have Errored",
callback = "not allowed", callback = "NotAllowed",
}) })
eq(false, ok) eq("specify either 'callback' or 'command', not both", rv)
end) end)
it('doesnt leak when you use ++once', function() it('doesnt leak when you use ++once', function()
@ -60,13 +60,13 @@ describe('autocmd api', function()
end) end)
it('does not allow passing buffer and patterns', function() it('does not allow passing buffer and patterns', function()
local ok = pcall(meths.create_autocmd, "Filetype", { local rv = pcall_err(meths.create_autocmd, "Filetype", {
command = "let g:called = g:called + 1", command = "let g:called = g:called + 1",
buffer = 0, buffer = 0,
pattern = "*.py", pattern = "*.py",
}) })
eq(false, ok) eq("cannot pass both: 'pattern' and 'buffer' for the same autocmd", rv)
end) end)
it('does not allow passing invalid buffers', function() it('does not allow passing invalid buffers', function()