tree-sitter / tree-sitter-rust

Rust grammar for tree-sitter
MIT License
340 stars 97 forks source link

Is it possible to highlight code examples in doc comments #130

Closed ModProg closed 5 months ago

ModProg commented 2 years ago

Not sure about the capabilities of treesitter, but would it be possible to highlight the code in doc comments? e.g.:

/// ```rs
/// enum Test {
///
/// }
/// ```
kellpossible commented 2 years ago

If tree-sitter adopts an official markdown parser implementation written in Rust, then this could perhaps be used as an embedded parser in a recursive fashion?

SeniorMars commented 1 year ago

This would be really cool. Many IDEs are using semantic highlighting for this, but I believe treesitter would be perfect for this.

maxcountryman commented 1 year ago

I haven't tried this yet, but I stumbled on a technique for highlighting embedded languages in this video that might work here.

SeniorMars commented 1 year ago

Hacky fix

This works for neovim:

In my $XDG_CONFIG_HOME/nvim/queries/rust I have a file called: injections.scm with the following:

 ; extends
(
 (line_comment) @_first 
 (_) @rust
 (line_comment) @_last 
 (#match? @_first "^/// ```$") 
 (#match? @_last "^/// ```$")
 (#offset! @rust 0 4 0 4)
)

(
 (line_comment) @_first
 (_) @rust
 (line_comment) @_last
 (#match? @_first "^/// ```rust$")
 (#match? @_last "^/// ```$")
 (#offset! @rust 0 4 0 4)
)

Now I get highlights like this:

image

The problem is that this makes neovim very slow, but it's a starting point...

amaanq commented 5 months ago

out of scope for this parser, but this is doable with some post processing via queries/injections or other mechanisms.