LuaSnip icon indicating copy to clipboard operation
LuaSnip copied to clipboard

[Question] would this be possible with Luasnip?

Open kkrime opened this issue 1 year ago • 2 comments

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?

kkrime avatar Apr 23 '24 15:04 kkrime

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

L3MON4D3 avatar Apr 23 '24 20:04 L3MON4D3

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

kkrime avatar Apr 24 '24 07:04 kkrime