p00f / nvim-ts-rainbow

Rainbow parentheses for neovim using tree-sitter. Use https://sr.ht/~p00f/nvim-ts-rainbow instead
Apache License 2.0
869 stars 67 forks source link

Highlight only current sub-tree? #110

Open HiPhish opened 2 years ago

HiPhish commented 2 years ago

As a user I sometimes find it too noisy when the entire buffer is highlighted. I would like if it was possible to only highlight the current sub-tree of the buffer, i.e. the delimiters of the current node, the delimited of all its descendants and the delimiter of all its ancestors. Take the following s-expression as an example

(/ (+ (- b)
      (sqrt (- (* b b)
               (* 4 a c))))
   (* 2 a))

Now suppose the cursor is on the r of sqrt (or anywhere else inside that node). The highlighting should look as follows, where the square brackets denote highlighted parentheses:

[/ [+ (- b)
      [sqrt [- [* b b)
               [* 4 a c]]]]
   (* 2 a)]

All s-expressions inside sqrt are highlighted, but the sibling (- b) and uncle (* 2 a) are not. Since the highlighting can change whenever the cursor moves this would require re-computing the highlight groups on every cursor movement. I have hacked something together, but it only sort of works. My understanding of Tree-sitter is still too limited.

Screenshot_20220418_160935

The idea was to get the range of the parent of the query result and check whether the cursor is within that range. Obviously this won't work for descendants of the current node. I would need somehow to get the cursor node and then check whether the query node is inside it.

-- Inside the `for _, node, _ in ...` loop:
local y, x, Y, X = node:parent():range()
if y <= r and r <= Y and x <= c and c <= X then
    -- Do the highlighting
end

My hack does not work in HTML, but that might be because I am using the extended mode.

What's your opinion? Should we have such a feature? Would it be too costly? Advice on how to implement it?

p00f commented 2 years ago

The feature would be nice to have, I can't take a look rn - probably next week. It doesn't appear(???) costly

HiPhish commented 2 years ago

I managed to hack something together.

https://user-images.githubusercontent.com/4954650/164110406-ad143571-1e26-4601-88ee-29b0f8be480b.mp4

The code is quite a mess, but it works. I will have to test it with other languages and clean it up properly. It's a first step.

damnever commented 2 years ago

This feature is useful, any progress on this?

HiPhish commented 2 years ago

Right, I have been shoving this one under the rug. Here is work-in-progress pull request: #131

I don't know enough about Tree-sitter do it properly. Is there more in terms of resources other than the Tree-sitter website and the Neovim documentation? Something that walks me through the baby steps first and explains what all the terms mean.