L3MON4D3 / LuaSnip

Snippet Engine for Neovim written in Lua.
Apache License 2.0
3.18k stars 233 forks source link

[Question] would this be possible with Luasnip? #1165

Open kkrime opened 2 months ago

kkrime commented 2 months ago

Let say I have an if statement where the cursor is currently inside the first condition like;

if x == 1 {
<cursor>
}

of the cursor at the end of the if statement, like;

if x == 1 {

} <cursor>

Would it be possible to create a snippet with the cursor at either locations and have it add another branch to the if statement and have the first node at the new branch condition, like;

if x == 1 {

} else if <cursor>(first node)  {

}

Is there any way to achieve this with Luaship + Treesitter?

L3MON4D3 commented 2 months ago

Oh, that's possible, for sure: I whipped up one option for the trigger at the end, since that hides lots of the treesitter-fun (not :P) via treesitter_postfix

treesitter_postfix({
    trig = ".ei",
    matchTSNode = {
        query = "(if_statement) @prefix",
        query_lang = "c",
        select = "longest"
    },
    reparseBuffer = "live" }, {
    d(1, function(_, parent)
        if parent.env.LS_TSMATCH == nil then
            return s(nil, t"")
        end
        -- tricky: remove indent on lines containing LS_TSMATCH. The
        -- indentation is provided by the captured `if`, and should not
        -- be prepended again by us.
        return sn(nil, {
            isn(1, fmt([[
                {} else if ({}) {{]], {t(parent.env.LS_TSMATCH), i(1)}), ""),
            t{"",""},
            sn(2, fmt([[
                    {}
                }}
            ]], {i(1)})) })
    end)})

I've defined this one for c, it should be possible to adapt to other languages as well, as long as its treesitter-grammar can handle if in its entirety :D

kkrime commented 2 months ago

Awesome! Thanks I'll give it a try :)