nvim-ts-rainbow icon indicating copy to clipboard operation
nvim-ts-rainbow copied to clipboard

Highlight only current sub-tree?

Open HiPhish opened this issue 2 years ago • 4 comments

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?

HiPhish avatar Apr 18 '22 14:04 HiPhish

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

p00f avatar Apr 18 '22 14:04 p00f

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.

HiPhish avatar Apr 19 '22 22:04 HiPhish

This feature is useful, any progress on this?

damnever avatar Aug 10 '22 09:08 damnever

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.

HiPhish avatar Aug 10 '22 21:08 HiPhish