Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kkrime opened this issue Apr 23, 2024 · 2 comments
Open

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

kkrime opened this issue Apr 23, 2024 · 2 comments

Comments

@kkrime
Copy link

kkrime commented Apr 23, 2024

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
Copy link
Owner

L3MON4D3 commented Apr 23, 2024

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
Copy link
Author

kkrime commented Apr 24, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants