nvim-treesitter / nvim-treesitter-context Goto Github PK
View Code? Open in Web Editor NEWShow code context
License: MIT License
Show code context
License: MIT License
nvim-treesitter has the feature of highlighting where a symbol is defined. Could make it also works on the context header?
what is the terminal used in the screenrecording? (is it finally a gtk terminal with ligatures 👀 ?)
please support draw a line to separate context like context.vim , then don't need different highlight TreesitterContext may be look better
This plugin is really cool and works seamlessly with nvim-treesitter. However, when I scroll to the side, there are some issues. This mostly happens with the line is longer than the window and nowrap
is set. When inserting from normal mode and the line is longer than the terminal window, inserting does not insert but the screen flashes and it inserts in the middle of the line. Typing text will not produce anything. When exiting out of insert mode, the cursor jumps back and the inserted text appears. Another issue is when side scrolling from the end of a line longer than the terminal width. The cursor should just scroll to the left but the whole window scrolls.
set nowrap
nvim --version
NVIM v0.5.0-828-g0a95549d6
Build type: RelWithDebInfo
LuaJIT 2.1.0-beta3
Compilation: /usr/bin/gcc-5 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -O2 -g -Og -g -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wmissing-prototypes -Wvla -fstack-protector-strong -fno-common -fdiagnostics-color=auto -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -DMIN_LOG_LEVEL=3 -I/home/travis/build/neovim/bot-ci/build/neovim/build/config -I/home/travis/build/neovim/bot-ci/build/neovim/src -I/home/travis/build/neovim/bot-ci/build/neovim/.deps/usr/include -I/usr/include -I/home/travis/build/neovim/bot-ci/build/neovim/build/src/nvim/auto -I/home/travis/build/neovim/bot-ci/build/neovim/build/include
Compiled by travis@travis-job-abaca5c2-51e7-4cf1-bc06-8cf3e644ab24
Features: +acl +iconv +tui
See ":help feature-compile"
system vimrc file: "$VIM/sysinit.vim"
fall-back for $VIM: "/share/nvim"
Run :checkhealth for more info
(ps, as you can see I'm using barbar and it is really nice.)
Found this startup loading error while loading treesitter-context
module:
packer.nvim: Error running config for nvim-treesitter-context: [string "..."]:0: loop or previous error loading module 'treesitter-context'
I'm using this following configuration on Packer
use {
"romgrk/nvim-treesitter-context",
config = function()
local ctx = require "treesitter-context"
ctx.setup({
patterns = { -- Match patterns for TS nodes. These get wrapped to match at word boundaries.
-- For all filetypes
-- Note that setting an entry here replaces all other patterns for this entry.
-- By setting the 'default' entry below, you can control which nodes you want to
-- appear in the context window.
default = {
'class',
'function',
'method',
'for', -- These won't appear in the context
'while',
'if',
'switch',
'case',
},
-- Example for a specific filetype.
-- If a pattern is missing, *open a PR* so everyone can benefit.
-- rust = {
-- 'impl_item',
-- },
},
})
end,
event = "BufWinEnter",
}
Run PackerInstall
then PackerCompile
after opening nvim, I found that error on startup.
It seems like module treesitter-context
is not loaded properly. Am I missed something?
nvim-treesitter
already provides locals queries which this plugin can use to provide better context for different languages instead of using hardcoded regex. For example, in this plugin only class
, function
, and method
are matches. In rust we might need context for structs
, enums
, and match
statements which are provided by the locals queries in nvim-treesitter
. Other languages would also work because there is already a locals query for each language. This is some sample code to replace the get_context
function:
function tbl_reverse(tbl)
for i=1, math.floor(#tbl / 2) do
tbl[i], tbl[#tbl - i + 1] = tbl[#tbl - i + 1], tbl[i]
end
end
function M.get_parent_matches()
local contains = vim.tbl_contains
local matches = queries.get_capture_matches(0, '@scope.node', 'locals')
local curr_node = ts_utils.get_node_at_cursor()
local parent_matches = {}
while true do
if contains(matches, curr_node) then
table.insert(parent_matches, curr_node)
end
curr_node = curr_node:parent()
if curr_node == nil then
break
end
end
tbl_reverse(parent_matches)
return parent_matches
end
Because this could return multiple lines we might need to enable multiple line context as right now there can only be context for one line.
While using this plugin, it occurred to me that it's actually rather counter intuitive that the context can appear and disappear depending on the cursor location.
Imagine the first two lines below are context.
func A() { // first virtual line of context
if x { // second virtual line of context
// there's more code in the `if x` block above not shown in the window
// this is the end of the `if x` block
}
if y {
// more code
}
}
It doesn't really matter to me where the cursor is when I'm reading this code, I just want to see that the code at the top of the window belongs to the if x
block, which belongs to func A
block. The context I'm looking for is only a function of what is and isn't visible on the screen.
As is, if I move my cursor to the if y
block, the if x
context would disappear.
Could we add an option to just use the topmost visible line of the buffer instead of the cursor position?
Firstly thank you for making the treesitter version context plugin, I am using it for daily development. It really helps.
Today I used it in tsx file, however the treesitter_context
window was not highlighted. I confirm I have tsx
parser installed and it works normally except in the treesitter_context
window. See the picture below
I have no idea whether it's the problem of this plugin or https://github.com/tree-sitter/tree-sitter-typescript, please help
When I cycle through autosuggestion popup, using nvim-compe, treesitter-context gives me this error:
Error executing vim.schedule lua callback: Vim(lua):E5108: Error executing lua ...start/nvim-treesitter-context/lua/treesitter-context.lua:341: Vim:E814: Cannot close window, only autocmd window would remai
Consider strategies to reduce the delay, such as doing some work asynchronously or throttling the context update.
I temporarily disabled the plugin, but still see the context in C files.
My config is
require'treesitter-context'.setup{
enable = false,
throttle = true,
max_lines = 0,
patterns = {
-- For all filetypes
-- Note that setting an entry here replaces all other patterns for this entry.
-- By setting the 'default' entry below, you can control which nodes you want to
-- appear in the context window.
default = {
'class',
'function',
'method',
-- 'for', -- These won't appear in the context
-- 'while',
-- 'if',
-- 'switch',
-- 'case',
},
-- Example for a specific filetype.
-- If a pattern is missing, *open a PR* so everyone can benefit.
-- rust = {
-- 'impl_item',
-- },
},
}
After digging into the code I found that this is because M.setup()
is called from within treesitter-context.lua unconditionally (for initializing config
if I get it right), but this leads to unconditional call to M.enable() -> M.throttled_update_context()
which is only good for toggling the plugin in run-time.
Here is a small patch that works well for me.
diff --git a/lua/treesitter-context.lua b/lua/treesitter-context.lua
index c64228e..3949c5c 100644
--- a/lua/treesitter-context.lua
+++ b/lua/treesitter-context.lua
@@ -496,7 +496,7 @@ function M.open()
end
end
-function M.enable()
+function M.enable(update)
local throttle = config.throttle and 'throttled_' or ''
nvim_augroup('treesitter_context', {
{'WinScrolled', '*', 'silent lua require("treesitter-context").' .. throttle .. 'update_context()'},
@@ -510,7 +510,10 @@ function M.enable()
{'User', 'SessionSavePost', 'silent lua require("treesitter-context").open()'},
})
- M.throttled_update_context()
+ if update then
+ M.throttled_update_context()
+ end
+
enabled = true
end
@@ -525,7 +528,7 @@ function M.toggleEnabled()
if enabled then
M.disable()
else
- M.enable()
+ M.enable(true)
end
end
@@ -551,7 +554,7 @@ end
M.setup()
-api.nvim_command('command! TSContextEnable lua require("treesitter-context").enable()')
+api.nvim_command('command! TSContextEnable lua require("treesitter-context").enable(true)')
api.nvim_command('command! TSContextDisable lua require("treesitter-context").disable()')
api.nvim_command('command! TSContextToggle lua require("treesitter-context").toggleEnabled()')
api.nvim_command('highlight default link TreesitterContext NormalFloat')
So the idea is running M.throttle_update_context()
from M.enable()
only on user commands :TsContext...
and not running this from M.setup()
. Notice that the default M.setup()
shall not be broken by this change as M.throttle_update_context()
will be called on BufEnter
.
Once more groups are added, it would be useful to be able to see class+function+internal structure context simultaneously as is possible with context.vim. This could be done by stacking the lines vertically, with outermost context at the top.
I hope treesitter-context can use setwinvar
to set a winvar like "treesitter_context_key: tree_sitter_context_val" so that users can use it to filter windows.
I personally have this function in my init.vim
, and I wish it to work with treesitter-context:
fun! s:IsOnlyWindow()
return len(filter(getwininfo(), '!has_key(v:val.variables, "scrollview_key")')) == 1
endfun
With #21 merged, issue #16 might be back oon some edge cases.
Reference: #21 (comment)
After deleting all other buffers except current I get this error:
Error detected while processing CursorMoved Autocommands for "*":
E5108: Error executing lua ...start/nvim-treesitter-context/lua/treesitter-context.lua:210: Vim(lua):E5108: Error executing lua ...start/nvim-treesitter-con
text/lua/treesitter-context.lua:181: Invalid buffer id: 2
Is the CursorMoved Autocommand meant to be running since I have treesiter + latest nigtly neovim installed?
I expect to see the method line instead of @Override
. Not sure if this is related to your plugin or Treesitter tho.
Well, there is not much to add to the title. 😆
If I'm inside a function where nvim-treesitter-context gets activated, than I'm getting this error message:
E5601: Cannot close window, only floating window would remain
So everytime when I want to quit, I need to move out of the nesting in order to close neovim.
When the context floating window is open, pressing q/
, q?
, or q:
opens the command-line window but with a floating window that displays the prior context, inside the command-line window.
I use zt
to scroll the current line to the top. A normal use case is to check a code block inside a long function.
However the top line will be overlapped by context line and this is annoying. Suggest remap zt
to move the scroll the current line to the 2nd top line.
I use this comand :
:confirm qa<CR>
To exit nvim, but with TSContext vim is now always asking about saving changes to 'Untitled'.
I tried to add :
:TSContextDisable<cr> | :confirm qa<CR>
But it still will ask about saving untitled... Is there way to kill TSContext buffer so that I do not have to confirm saving it on q ?
btw when I run :buffers - I do not see this untitled buffer...
Bug happens when using this plugin along with vim-which-key and with vim.g.which_key_use_floating_win = 1
.
After invoking which-key inside a context that is being displayed and exiting it, my screen seems to be vertically split with only one line at the top being active. In this line I can move up and down but not left and right and can't edit text. If I invoke which-key again this error is displayed:
Error detected while processing function which_key#start[49]..which_key#window#show[9]..<SNR>53_show_old_win[2]..<SNR>53_open_split_win[2]..<SNR>53_split_or_new:
Currently, there is no reliable way to display multi-line nodes for Scala (and other languages). This issue is similar to #65, but the solution implemented in #71 is inadequate here.
In Scala, function definitions can 1) have multiple argument lists and 2) an optional return type. i.e. these are all valid:
def func(a: String,
b: String) = {a}
def func(a: String,
b: String): String = {a}
def func(a: String)
(b: String) = {a}
This means that the node which would signal the end of the context could be either 1) the last parameters
node or 2) the return_type
node if it exists.
So, we can't just add a node to last_types
to solve this. Moreover, some users may prefer to only see the first parameter list and return type or other custom display logic. Python (optional return types), Haskell (multiple parameter lists), and other languages suffer from the same issues.
It would be nice to be able to provide my own implementation for get_text_for_node
via config
When you are in a function inside an implementation in Rust, this doesn't show the impl
line. It would be really helpful. context.vim
also doesn't show it (only sometimes, it's weird)
What is this licensed under?
When cursor is on comments, context window disappears. This is strange as coming from context.nvim.
For example if cursor is on the commeted line, function name disappears, but go one line up or down will show context.
def a():
print(1)
# print(1)
pass
I get this on startup:
Error detected while processing /home/p00f/.local/share/nvim/site/pack/packer/start/nvim-treesitter-context/plugin/treesitter-context.vim:
line 1:
E5108: Error executing lua ...start/nvim-treesitter-context/lua/treesitter-context.lua:58: Vim(autocmd):E216: No such group or event: Scroll * silent lua require("treesitter-cont
ext").update_context()
Also the TSContextEnable
and TSContextEnable
commands don't seem to be available.
I'm on master of both neovim and nvim-treesitter
Great plugin, thanks a lot!
When I am on last character of the file I get some extra (I guess) floating window displayed, as per video below.
Happens on v0.5.0-dev+7b65a9135
with 192baea (latest as of now).
I think it would be a good improvement to add the ability to add custom TYPE_PATTERNS
that match as a context item. For example, I am using tree-sitter-vhdl
, and this plugin doesn't register some of the tags that I would like as context items. Specifically process_statement
, architecture_body
, and entity_declaration
since they aren't normal ones. I manually edited the treesitter-context.lua
file to add these to TYPE_PATTERNS
local TYPE_PATTERNS = {
-- These catch most generic groups, eg "function_declaration" or "function_block"
'class',
'function',
'method',
'for',
'while',
'if',
'switch',
'case',
-- There are more specific
'impl_item', -- Rust
'process_statement',
'architecture_body',
'entity_declaration',
}
and this worked.
I think something should be added to the TS config invocation, like the following
require('nvim-treesitter.configs').setup {
context = {
enable = true,
extra_patterns = {
'process_statement',
'architecture_body',
'entity_declaration',
}
}
}
When the window's width doesn't cover all the text of the file horizontally (set nowrap
), the window really bugs out when you are on Insert mode and the window is scrolled horizontally. Here is a demo:
This only happens when the plugin is installed.
Loading the treesitter-context package in the latest nightly causes this error
Latest neovim 0.5
NVIM v0.5.0-dev+1152-gf5daf55c1
Build type: RelWithDebInfo
LuaJIT 2.1.0-beta3
Compilation: /usr/bin/cc -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1 -O2 -g -Og -g -Wall -Wextra -pedantic -Wno-unused-parameter -Wstrict-prototypes -std=gnu99 -Wshadow -Wconversion -Wmissing-prototypes -Wvla -fstack-protector-strong -fno-common -fdiagnostics-color=always -DINCLUDE_GENERATED_DECLARATIONS -D_GNU_SOURCE -DNVIM_MSGPACK_HAS_FLOAT32 -DNVIM_UNIBI_HAS_VAR_FROM -DMIN_LOG_LEVEL=3 -I/home/runner/work/neovim/neovim/build/config -I/home/runner/work/neovim/neovim/src -I/home/runner/work/neovim/neovim/.deps/usr/include -I/usr/include -I/home/runner/work/neovim/neovim/build/src/nvim/auto -I/home/runner/work/neovim/neovim/build/include
Compiled by runner@fv-az204-819```
Error detected while processing WinScrolled Autocommands for "*":
E5108: Error executing lua ...start/nvim-treesitter-context/lua/treesitter-context.lua:182:
'width' key must be a positive Integer
Neovim Version -
NVIM v0.5.0
System -
macOS Big Sur
v 11.4
I have a tmux session with 2 splits and neovim with two splits(with tmux zoomed in the neovim pane). As soon as I switch tmux pane, the zoomed-in pane is unzoomed and this error pops up in neovim.
Is there any way we to avoid this issue?
Say I have something like
if (condition) {
// ...
} else {
// Some really long code
}
When my cursor is inside the else clause, the context will be shown as if (condition)
, which can be a bit confusing. Is there some way to either add an additional context line saying else
or maybe even add a !
to the condition context in this case?
Some people may want to have if
/else
, etc.
Hi, would be great to have an option for the context to persist whenever another buffer is focused.
This will show context as int
, which is the first line of the function declaration but not what we want.
int
build_stl_str_hl(
win_T *wp,
char_u *out, // buffer to write into != NameBuff
size_t outlen, // length of out[]
char_u *fmt,
int use_sandbox UNUSED, // "fmt" was set insecurely, use sandbox
int fillchar,
int maxwidth,
struct stl_hlrec *hltab, // return: HL attributes (can be NULL)
struct stl_hlrec *tabtab) // return: tab page nrs (can be NULL)
{
/* ... */
}
This might require/want having a different list of nodes to use as context for each language (with the current patterns as the common default)
Maybe a more general mechanism would also be to let the user customized which nodes count as context nodes
If the top line shows the current context (e.g.: class), the line number on the left of it doesn't match the content.
That is, the line number shown is the number for the line that would be there if the context-line wasn't shown.
It gives error Cannot resolve symbol curwin_col_off
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.