Dronakurl / injectme.nvim

Neovim plugin to help setup language injections with treesitter
MIT License
39 stars 2 forks source link

Feature request: activate injection using a comment #3

Open massimiliano-della-rovere opened 6 months ago

massimiliano-della-rovere commented 6 months ago

When the buffer is parsed by treesitter, an ad-hoc written comment could activate one or more pre-saved injection

Dronakurl commented 6 months ago

Thank you for your request!

How could this work exactly? Maybe, something like this example? The injection given in the comment is activated?

# injectme: rst_for_docstring

def myfun():
    """ This should be formatted as rst"""
    pass

It is hard to get this to work, as injections are chosen by treesiter-nvim per filetype and not per buffer. Unless you wouldn't mind that this comment just triggers the injection for all files of same type, in this example rst formatting for all python files that are open in the current nvim session

massimiliano-della-rovere commented 6 months ago

My idea is "the comment activates injection for the next string".

This would be useful to reduce the amount of analysis that treesitter had to perform to identify other languages in every string: the comment would already be the analysis, like one key of an associative array where the values are treesitter functions that will interpret the string.

Dronakurl commented 5 months ago

This should be done by a treesitter query. When I monitor the strings with lua, only to activate treesitter on a certain comment, this would be much slower. Sorry, but I don't know what to make of this idea

cseickel commented 5 months ago

I used to have a query that conditionally marked the next text fragment to be parsed as an injected language. It just broke and I am trying to figure out why, I think what I had might be what @massimiliano-della-rovere is looking for.

For example, in typescript I would write:

export const CREATE = /* sql */ `
create or replace function safe_sqrt(double precision)
returns double precision
language sql IMMUTABLE PARALLEL SAFE
as $$
  SELECT CASE
    WHEN $1 is null THEN null
    WHEN $1 < 0 THEN null
    ELSE SQRT($1)
  END;
$$;
`;

and it would highlight it as sql, even if the given sql string does not fit the standard injection template that assumes a generic select query.

The injections.scm looked like this:

; extends

; /* html */ `<html>`
; /* sql */ `SELECT * FROM foo`
(variable_declarator
  (comment) @injection.language (#offset! @injection.language 0 3 0 -3)
  (template_string) @injection.content (#offset! @injection.content 0 1 0 -1)
  )

It broke on a recent update of treesitter. I have no idea why or how to make it work again. Do you think you can fix it?