How to navigate to end/start of current programming block with nvim-treesitter

Have you found a way to go to the end/start of the current (where cursor is) most direct programming block (for-loop, if-else, let-block, struct, etc.) ?

This is something that in julia-vim is implemented and supported out-of-the-box by using %.

I believer it is possible with the current julia tree-sitter implementation, but it’s not out-of-the-box and it needs some magic.

Using nvim-treesitter-textobjects, one can navigate to the start/end of an if-statement (@conditional.inner/outer), for-loop @loop.inner/outer, funtion (@function.inner/outer), etc.
However each time you need to specify the exact nature.

I believe there could be a way to define to go inner/outer of the most direct block that currently the cursor is located. However, I am a rookie here and I don’t know how to do it (probably tree-sitter queries are needed ?).

Do you know how this could be integrated in the nvim-treesitter configuration ?

It might also help solving this issue

P.S. now that I think about it, this must be language-agnostic :sweat_smile:

I’m new to treesitter as well, but I was playing around with a similar problem a couple days ago. A simple implementation in bare Lua without any extra plugins is pretty easy to do, although I imagine there are more elegant solutions if you have a deeper knowledge of treesitter.

You can get the current node using vim.treesitter.get_node() and recurse through its parents until you find a node type that you want to stop at. You can check the node:type() against a set of types you want to stop at by pre-generating this list for Julia, and once you find the outermost node you want to stop at there are utilities for getting the start/end/range of a node.

Actually using queries to do this would be much more robust, cleaner, and probably language-agnostic. But if you just want to get something working for Julia, the Lua to make it “just work” is not too bad.

Most of the functionality/docs you would need is in here: Treesitter - Neovim docs

My (similar) work is here, although I was trying to select nodes with specific scoping rules: dotfiles/julia-repl.lua at d2353e56fe39ef95d002e3a69e51912fb70db4bc · SBuercklin/dotfiles · GitHub

I expect to dump some more time into this over the weekend. If I get a better solution that’s using more proper treesitter functionality, I’ll bump the thread

1 Like