0

Using luasnip in neovim I created a snippet that creates console.log with function name

local luasnip = require("luasnip")
local sn = luasnip.snippet
local t = luasnip.text_node
local s = luasnip.snippet_node
local d = luasnip.dynamic_node
local fmt = require("luasnip.extras.fmt").fmt
local ts = vim.treesitter
local ts_query = ts.query

--- @param node TSNode | nil
--- @param ts_elements table<string>
--- @returns TSNode | nil
local function seek_function_root(node, ts_elements)
    if node == nil then
        return nil
    end
    local node_type = node:type()

    if vim.tbl_contains(ts_elements, node_type) then
        return node
    end

    local parent = node:parent()

    return seek_function_root(parent, ts_elements)
end

--- @param node TSNode | nil
local function get_data(node)
    local filetype = vim.bo.filetype
    local query_lang = filetype == "javascriptreact" and "javascript" or filetype
    if node == nil then
        return nil
    end
    if node:type() == "program" then
        return "global"
    end
    local parsed_query = ts_query.parse(query_lang, [[(identifier) @name]])
    -- print("[get_data]")
    for _, parsed_node, _ in parsed_query:iter_captures(node, 0, node:start(), node:end_()) do
        return ts.get_node_text(parsed_node, 0)
    end
end

local console = sn(
    "con",
    fmt([[ console.log("[{function_name}]","{test}")]], {
        test = t(""),
        function_name = d(1, function()
            local ts_node = ts.get_node()
            local function_root = seek_function_root(ts_node, { "function_declaration", "variable_declarator" })
            local data = function_root ~= nil and get_data(function_root) or ""
            return s(nil, { t(data) })
        end),
    })
)

return console

For JS and TS it works without crashing, but for jsx file it throws error: E5108: Error executing lua ...local/share/nvim/runtime/lua/vim/treesitter/language.lua:94: no parser for 'javascriptreact' language, see :help treesitter-parsers

I managed to find out that script was throwing this error on ts.get_node(), which takes the smallest node from cursor and I cannot find an answer to replace it or make it work for jsx and tsx files

I'm using recently released neovim v0.9.0

Neovim config: https://github.com/Herob527/nvim-config

I expected it to work for jsx and tsx like for js and ts files

Herob
  • 1
  • 1

0 Answers0