This fixes the following bugs:
`${1:else_text}` -> format with if_text: "else_text"
`${1:-else_text}` -> format with if_text: "else_text"
`${1:}` in `format` (eg. empty else_text) -> error.
`${1:}` (eg. empty placeholder) -> error.
Thanks hrsh7th :)
This is necessary in cases where filetype detection acts recursively.
For example, when matching files that end with .bak, the "root" of
the filename is matched again against the same buffer (e.g. a buffer
named "foo.c.bak" will be matched again with the filename "foo.c", using
the same underlying buffer).
This enables vim.filetype.match to match based on a buffer (most
accurate) or simply a filename or file contents, which are less accurate
but may still be useful for some scenarios.
When matching based on a buffer, the buffer's name and contents are both
used to do full filetype matching. When using a filename, if the file
exists the file is loaded into a buffer and full filetype detection is
performed. If the file does not exist then filetype matching is only
performed against the filename itself. Content-based matching does the
equivalent of scripts.vim, and matches solely based on file contents
without any information from the name of the file itself (e.g. for
shebangs).
BREAKING CHANGE: use `vim.filetype.match({buf = bufnr})` instead
of `vim.filetype.match(name, bufnr)`
This re-introduces the fix that the filetype.lua refactor inadvertently reverted.
The fix ensures that in the case when end_lnum is omitted, a string is always returned.
`nvim_get_option_value` and `nvim_set_option_value` better handle
unsetting local options. For instance, this is currently not possible:
vim.bo.tagfunc = nil
This does not work because 'tagfunc' is marked as "local to buffer" and
does not have a fallback global option. However, using :setlocal *does*
work as expected
:setlocal tagfunc=
`nvim_set_option_value` behaves more like :set and :setlocal (by
design), so using these as the underlying API functions beneath vim.bo
and vim.wo makes those two tables act more like :setlocal. Note that
vim.o *already* uses `nvim_set_option_value` under the hood, so that
vim.o behaves like :set.
Steps to reproduce:
1. setting `vim.highlight.on_yank`
```
vim.api.nvim_create_autocmd({ "TextYankPost" }, {
pattern = { "*" },
callback = function()
vim.highlight.on_yank({ timeout = 200 })
end,
})
```
2. repeat typing `yeye` ...
3. causes the following error.
```
Error executing vim.schedule lua callback: vim/_editor.lua:0: handle 0x01e96970 is already closing
stack traceback:
[C]: in function 'close'
vim/_editor.lua: in function ''
vim/_editor.lua: in function <vim/_editor.lua:0>
```
📝 Test result before fix:
[----------] Global test environment setup.
[----------] Running tests from test/functional/lua/highlight_spec.lua
[ RUN ] vim.highlight.on_yank does not show errors even if buffer is wiped before timeout: 15.07 ms OK
[ RUN ] vim.highlight.on_yank does not show errors even if executed between timeout and clearing highlight: 15.07 ms ERR
test/helpers.lua:73: Expected objects to be the same.
Passed in:
(string) 'Error executing vim.schedule lua callback: vim/_editor.lua:0: handle 0x02025260 is already closing
stack traceback:
[C]: in function 'close'
vim/_editor.lua: in function ''
vim/_editor.lua: in function <vim/_editor.lua:0>'
Expected:
(string) ''
Many filetypes from filetype.vim set buffer-local variables, meaning
vim.filetype.match cannot be used without side effects. Instead of
setting these buffer-local variables in the filetype detection functions
themselves, have vim.filetype.match return an optional function value
that, when called, sets these variables. This allows vim.filetype.match
to work without side effects.
Most LSP servers require the notification to correctly load the
settings and for those who don't it doesn't cause any harm.
So far this is done in lspconfig, but with the addition of vim.lsp.start
it should be part of core.
A alternative/subset of https://github.com/neovim/neovim/pull/18506 that should be forward compatible with a potential project system.
Configuration of LSP clients (without lspconfig) now looks like this:
vim.lsp.start({
name = 'my-server-name',
cmd = {'name-of-language-server-executable'},
root_dir = vim.fs.dirname(vim.fs.find({'setup.py', 'pyproject.toml'}, { upward = true })[1]),
})
When yanking another range while previous yank is still highlighted, the
pending timer could clear the highlight almost immediately (especially
when using larger `timeout`, i.e. 2000)
Fix a bug in lsp.buf.rename() where the range returned by the server in
textDocument/prepareRename was interpreted as a byte range directly,
instead of taking the negotiated offset encoding into account. This
caused the placeholder value in vim.ui.input to be incorrect in some
cases, for example when non-ascii characters are used earlier on the
same line.
Problem:
https://github.com/neovim/neovim/pull/18720#issuecomment-1142614996
The vim.health module is detected as a healthcheck, which produces spurious errors:
vim: require("vim.health").check()
========================================================================
- ERROR: Failed to run healthcheck for "vim" plugin. Exception:
function health#check, line 20
Vim(eval):E5108: Error executing lua [string "luaeval()"]:1: attempt to call field 'check' (a nil value)
stack traceback:
[string "luaeval()"]:1: in main chunk
Solution:
Skip vim.health when discovering healthchecks.
- Complete function:
There was lots of unnecessary C code for the complete function, therefore
moving it to Lua and use all the plumbing we have in place to retrieve the
results.
- Moving the module:
It's important we keep nvim lua modules name spaced, avoids conflict with
plugins, luarocks, etc.
Currently the `title`, `message` and `percentage` is stored for a
progress, but there is also an optional `cancellable` that comes in with
both the `WorkDoneProgressBegin` and also `WorkDoneProgressReport`. This
change also stores that value so that a plugin can access it when they
do a lookup in `client.messages`.
Previously the `offset!` directive populated the metadata in such a way
that the new range could be attributed to a specific capture. #14046
made it so the directive simply stored just the new range in the
metadata and information about what capture the range is based from is
lost.
This change reverts that whilst also correcting the docs.
The client state is cleaned up both in client.stop() as well as in the
client.on_exit() handler. Technically, the client has not actually
stopped until the on_exit handler is called, so we should just do this
cleanup there and remove it from client.stop().
This makes the common use case easier.
If one really needs access to all clients, they can create a filter
function which manually calls `get_active_clients`.
The current approach of using `on_attach` callbacks for configuring
buffers for LSP is suboptimal:
1. It does not use the standard Nvim interface for driving and hooking
into events (i.e. autocommands)
2. There is no way for "third parties" (e.g. plugins) to hook into the
event. This means that *all* buffer configuration must go into the
user-supplied on_attach callback. This also makes it impossible for
these configurations to be modular, since it all must happen in the
same place.
3. There is currently no way to do something when a client detaches from
a buffer (there is no `on_detach` callback).
The solution is to use the traditional method of event handling in Nvim:
autocommands. When a LSP client is attached to a buffer, fire a
`LspAttach`. Likewise, when a client detaches from a buffer fire a
`LspDetach` event.
This enables plugins to easily add LSP-specific configuration to buffers
as well as enabling users to make their own configurations more modular
(e.g. by creating multiple LspAttach autocommands that each do
something unique).
Problem:
vim.lsp: require("vim.lsp.health").check()
========================================================================
- ERROR: Failed to run healthcheck for "vim.lsp" plugin. Exception:
function health#check, line 20
Vim(eval):E5108: Error executing lua ...m/HEAD-6613f58/share/nvim/runtime/lua/vim/lsp/health.lua:20: attempt to index a nil value
stack traceback:
...m/HEAD-6613f58/share/nvim/runtime/lua/vim/lsp/health.lua:20: in function 'check'
[string "luaeval()"]:1: in main chunk
Solution:
Check for nil.
fix#18602
Implement filtering of actions based on the kind when passing the 'only'
parameter to code_action(). Action kinds are hierachical with a '.' as
the separator, and the filter thus allows, for example, both 'quickfix'
and 'quickfix.foo' when requestiong only 'quickfix'.
Fix https://github.com/neovim/neovim/pull/18221#issuecomment-1110179121
LSP servers should be daemonized (detached) so that they run in a
separate process group from Neovim's. Among other things, this ensures
the process does not inherit Neovim's TTY (#18475).
Make this configurable so that clients can explicitly opt-out of
detaching from Nvim.
Adds filter and id options to filter the client to use for rename.
Similar to the recently added `format` function.
rename will use all matching clients one after another and can handle a
mix of prepareRename/rename support. Also ensures the right
`offset_encoding` is used for the `make_position_params` calls
This fixes issues where subsequent calls to vim.lsp.codelens.refresh()
would have no effect due to the buffer not getting cleared from the
active_refresh table.
Examples of how such scenarios would occur are:
- A textDocument/codeLens result yielded an error.
- The 'textDocument/codeLens' handler was overriden in such a way that
it no longer called vim.lsp.codelens.on_codelens().
This is primarily intended to act as documentation for the developer so
they know exactly when and what to remove. This will help prevent the
situation of deprecated code lingering for far too long as developers
don't have to worry if a function is safe to remove.
Deprecates the existing `vim.lsp.buf.formatting` function.
With this, `vim.lsp.buf.format` will replace all three:
- vim.lsp.buf.formatting
- vim.lsp.buf.formatting_sync
- vim.lsp.buf.formatting_seq_sync
* feat(lsp)!: remove capabilities sanitization
Users must now access client.server_capabilities which matches the same
structure as the protocol.
https://microsoft.github.io/language-server-protocol/specification
client.resolved_capabilities is no longer used to gate capabilities, and
will be removed in a future release.
BREAKING CHANGE
Co-authored-by: Mathias Fussenegger <f.mathias@zignar.net>
Implement two new options to vim.lsp.buf.code_action():
- filter (function): predicate taking an Action as input, and returning
a boolean.
- apply (boolean): when set to true, and there is just one remaining
action (after filtering), the action is applied without user query.
These options can, for example, be used to filter out, and automatically
apply, the action indicated by the server to be preferred:
vim.lsp.buf.code_action({
filter = function(action)
return action.isPreferred
end,
apply = true,
})
Fix#17514.
Some language servers send empty `textDocument/publishDiagnostics`
messages after indexing the project with URIs corresponding to unopened buffers.
This commit guards against opening buffers corresponding to empty diagnostics.
`vim.keymap.del` takes an `opts` parameter that lets caller refer to and
delete buffer-local mappings. For some reason the implementation of
`vim.keymap.del` mutates the table that is passed in, setting
`opts.buffer` to `nil`. This is wrong and also undocumented.
The LSP progress handler would put non-progress messages (such as from
clangd or pyls; not part of the LSP spec) directly into
`client.messages`, while `vim.lsp.util.get_progress_messages()` would
try to fetch them from `client.messages.messages` instead (and come up
empty everytime). This would result in these messages never being
cleaned up by `get_progress_messages()`.
This commit fixes that by treating those messages like show-once
progress messages (by setting `done=true` immediately).
Problem: Supercollider filetype not recognized.
Solution: Match file extentions and check file contents to detect
supercollider. (closesvim/vim#10142)
8cac20ed42
Problem: HEEx and Surface templates do not need a separate filetype.
Solution: Use Eelixir for the similar filetypes. (Aaron Tinio, closesvim/vim#10124)
fa76a24109
Problem: Kuka Robot Language files not recognized.
Solution: Recognize *.src and *.dat files. (Patrick Meiser-Knosowski,
closesvim/vim#10096)
3ad2090316
Uses of `getline` in `filetype.lua` currently assume it always returns a
string. However, if the buffer is unloaded when filetype detection runs,
`getline` returns `nil`. Fixing this prevents errors when filetype
detection is run on unloaded buffers.
vim.tbl_get takes a table with subsequent string arguments (variadic) that
index into the table. If the value pointed to by the set of keys exists,
the function returns the value. If the set of keys does not exist, the
function returns nil.
The use of 'softtabstop' to set tabSize was introduced in 5d5b068,
replacing 'tabstop'. If we look past the name tabSize and at the actual
purpose of the field, it's the indentation width used when formatting.
This corresponds to the Vim option 'shiftwidth', not 'softtabstop'.
The latter has the comparatively mundane purpose of controlling what
happens when you hit the tab key (and even this is incomplete, as it
fails to account for 'smarttab').
Problem: Dtrace files are recognized as filetype D.
Solution: Add a pattern for Dtrace files. (Teubel György, closesvim/vim#9841)
Add some more testing.
4d56b971cb
Closes https://github.com/neovim/neovim/issues/17456
* treesitter uses the default highlight priority of 50
* diagnostic highlights have a priority of 150
* lsp reference highlights have a priority of 200
This ensures proper ordering.
LSP server might return an item which would replace a token to another.
For example in typescript for a `jest.Mock` object `getProductsMock.`
text I get the following response:
```
{
commitCharacters = {
".",
",",
"("
},
data = {
entryNames = {
"Symbol"
},
file = "/foo/bar/baz.service.spec.ts",
line = 268,
offset = 17
},
filterText = ".Symbol",
kind = 6,
label = "Symbol",
sortText = "11",
textEdit = {
newText = "[Symbol]",
range = {
end = {
character = 16,
line = 267
},
start = {
character = 15,
line = 267
}
}
}
},
```
In `lsp.omnifunc` to get a `prefix` we call the `adjust_start_col` which
then returns the `textEdit.range.start.character`.
Th `prefix` then be the `.` character. Then when filter the items with
`remove_unmatch_completion_items`, every item will be filtered out,
since no completion word starts `.`.
To fix we return the `end.character`, which in that particular case will
be the position after the `.`.
Problem: Basic and form filetype detection is incomplete.
Solution: Add a separate function for .frm files. (Doug Kearns, closesvim/vim#9675)
c570e9cf68
When trying to load a language parser, escape the value of
the language.
With language injection, the language might be picked up from the
buffer. If this value is erroneous it can cause `nvim_get_runtime_file`
to hard error.
E.g., the markdown expression `~~~{` will extract '{' as a language and
then try to get the parser using `parser/{*` as the pattern.
This commits introduces two performance improvements in incremental sync:
* avoiding expensive lua string reallocations on each on_lines call by requesting
only the changed chunk of the buffer as reported by firstline and new_lastline
parameters of on_lines
* re-using already allocated tables for storing the resulting lines to reduce the load on
the garbage collector
The majority of the performance improvement is from requesting only changed chunks
of the buffer.
Benchmark:
The following code measures the time required to perform a buffer edit to
that operates individually on each line, common to plugins such as vim-commentary.
set rtp+=~/.config/nvim/plugged/nvim-lspconfig
set rtp+=~/.config/nvim/plugged/vim-commentary
lua require('lspconfig')['ccls'].setup({})
function! Benchmark(tries) abort
let results_comment = []
let results_undo = []
for i in range(a:tries)
echo printf('run %d', i+1)
let begin = reltime()
normal gggcG
call add(results_comment, reltimefloat(reltime(begin)))
let begin = reltime()
silent! undo
call add(results_undo, reltimefloat(reltime(begin)))
redraw
endfor
let avg_comment = 0.0
let avg_undo = 0.0
for i in range(a:tries)
echomsg printf('run %3d: comment=%fs undo=%fs', i+1, results_comment[i], results_undo[i])
let avg_comment += results_comment[i]
let avg_undo += results_undo[i]
endfor
echomsg printf('average: comment=%fs undo=%fs', avg_comment / a:tries, avg_undo / a:tries)
endfunction
command! -bar Benchmark call Benchmark(10)
All text changes will be recorded within a single undo operation. Both the
comment operation itself and the undo operation will generate an on_lines event
for each changed line. Formatter plugins using setline() have also been found
to exhibit the same problem (neoformat, :RustFmt in rust.vim), as this function
too generates an on_lines event for every line it changes.
Using the neovim codebase as an example (commit 2ecf0a4)
with neovim itself built at 2ecf0a4 with
CMAKE_BUILD_TYPE=Release shows the following performance improvement:
src/nvim/lua/executor.c, 1432 lines:
- baseline, no optimizations: comment=0.540587s undo=0.440249s
- without double-buffering optimization: comment=0.183314s undo=0.060663s
- all optimizations in this commit: comment=0.174850s undo=0.052789s
src/nvim/search.c, 5467 lines:
- baseline, no optimizations: comment=7.420446s undo=7.656624s
- without double-buffering optimization: comment=0.889048s undo=0.486026s
- all optimizations in this commit: comment=0.662899s undo=0.243628s
src/nvim/eval.c, 11355 lines:
- baseline, no optimizations: comment=41.775695s undo=44.583374s
- without double-buffering optimization: comment=3.643933s undo=2.817158s
- all optimizations in this commit: comment=1.510886s undo=0.707928s
Co-authored-by: Dmytro Meleshko <dmytro.meleshko@gmail.com>
Closes https://github.com/neovim/neovim/issues/13647
This allows customizing the priority of the highlights.
* Add default priority of 50
* Use priority of 200 for highlight on yank
* use priority of 40 for highlight references (LSP)
This gives quickfix/location lists created by handlers which use
'response_to_list' (textDocument/documentSymbols and workspace/symbol by
default) the ability to set a more useful list title. This commit gives
lists created for documentSymbols a title of the form:
Symbols in <filename>
and lists for workspace/symbol a title of the form:
Symbols matching '<query>'
These are more informative than a standard "Language Server" list title
and can help disambiguate results when users have multiple quickfix
lists that they cycle through with `:colder` and `:cnewer`.
This removes the "fallback" to utf-16 in many of our helper functions. We
should always explicitly pass these around when possible except in two
locations:
* generating params with help utilities called by buf.lua functions
* the buf.lua functions themselves
Anything that is called by the handler should be passed the offset encoding.
omnisharp-roslyn can send negative values:
{
activeParameter = 0,
activeSignature = -1,
signatures = { {
documentation = "",
label = "TestEntity.TestEntity()",
parameters = {}
} }
}
In 3.16 of the specification `activeSignature` is defined as `uinteger`
and therefore negative values shouldn't be allowed, but within 3.15 it
was defined as `number` which makes me think we can be a bit lenient in
this case and handle them.
The expected behavior is quite clear:
The active signature. If omitted or the value lies outside the
range of `signatures` the value defaults to zero or is ignored if
the `SignatureHelp` has no signatures.
Fixes an error:
util.lua:1685: attempt to get length of local 'lines' (a nil value)
util.lua:1685: in function 'trim_empty_lines'
handlers.lua:334: in function 'textDocument/signatureHelp'
* vim-patch:8.2.4064: foam files are not detected
Problem: Foam files are not detected.
Solution: Detect the foam filetype by the path and file contents. (Mohammed
Elwardi Fadeli, closesvim/vim#9501)
2284f6cca3
* Port foam ft detection to filetype.lua
Co-authored-by: Gregory Anders <greg@gpanders.com>
Part of the `pending_change` closure in the `changetracking.prepare` was
a bit confusing because it has access to `bufnr` and `uri` but it could
actually contain pending changes batched for multiple buffers.
(We accounted for that by grouping `pending_changes` by a `uri`, but
it's not obvious what's going on)
This commit changes the approach to do everything per buffer to avoid
any ambiguity.
It also brings the debounce/no-debounce a bit closer together: The
only difference is now whether a timer is used or if it is triggered
immediately
Follow up to https://github.com/neovim/neovim/pull/16881
Document changes could get sent out of order to the server:
1. on_lines: debounce > 0; add to pending changes; setup timer
2. on_lines: debounce = 0; send new changes immediately
3. timer triggers, sending changes from 1.
Closes https://github.com/neovim/neovim/issues/16985
* get_lines checks if buf_loaded using bufnr 0, which is
typically used as a sentinel value, but here must be resolved
to the true bufnr
Negative priority patterns are those that act as catch-alls when all
other attempts at matching have failed (typically the patterns that use
the StarSetf functions).
The idea of the debounce is to avoid overloading a server with didChange
notifications. So far this used a constant value to group changes within
an interval together and send a single notification. A side effect of
this is that when you were idle, notifications are still delayed.
This commit changes the logic to take the time the last notification
happened into consideration, if it has been greater than the debounce
interval, the debouncing is skipped or at least reduced.
Because filetype.lua is gated behind an opt-in variable, it's not tested
during the "standard" test_filetype.vim test. So port the test into
filetype_spec where we enable the opt-in variable.
This means runtime Vim patches will need to update test_filetype in two
places. This can eventually be removed if/when filetype.lua is made
opt-out rather than opt-in.
Filetype detection runs on BufRead and BufNewFile autocommands, both of
which can fire without an underlying buffer, so it's incorrect to use
<abuf> to determine the file path. Instead, match on <afile> and assume
that the buffer we're operating on is the current buffer. This is the
same assumption that filetype.vim makes, so it should be safe.
Co-authored-by: Sean Dewar <seandewar@users.noreply.github.com>
Co-authored-by: Gregory Anders <greg@gpanders.com>
Co-authored-by: Sebastian Volland <seb@baunz.net>
Co-authored-by: Lewis Russell <lewis6991@gmail.com>
Co-authored-by: zeertzjq <zeertzjq@outlook.com>
This introduces two new functions `vim.keymap.set` & `vim.keymap.del`
differences compared to regular set_keymap:
- remap is used as opposite of noremap. By default it's true for <Plug> keymaps and false for others.
- rhs can be lua function.
- mode can be a list of modes.
- replace_keycodes option for lua function expr maps. (Default: true)
- handles buffer specific keymaps
Examples:
```lua
vim.keymap.set('n', 'asdf', function() print("real lua function") end)
vim.keymap.set({'n', 'v'}, '<leader>lr', vim.lsp.buf.references, {buffer=true})
vim.keymap.set('n', '<leader>w', "<cmd>w<cr>", {silent = true, buffer = 5 })
vim.keymap.set('i', '<Tab>', function()
return vim.fn.pumvisible() == 1 and "<C-n>" or "<Tab>"
end, {expr = true})
vim.keymap.set('n', '[%', '<Plug>(MatchitNormalMultiBackward)')
vim.keymap.del('n', 'asdf')
vim.keymap.del({'n', 'i', 'v'}, '<leader>w', {buffer = 5 })
```
As revealed by #16745, some functions pass a nil value to API functions,
which have been implicitly converted to 0. #16745 breaks this implicit
conversion, so explicitly pass a resolved buffer number to these API
functions.
Function arguments that expect a list should explicitly use tbl_islist
rather than just checking for a table. This helps catch some simple
errors where a single table item is passed as an argument, which passes
validation (since it's a table), but causes other errors later on.
This allows the user to detach an active buffer from the language
client. If no clients remain attached to a buffer, the on_lines callback
is used to cancel nvim_buf_attach.