saadparwaiz1 / cmp_luasnip

luasnip completion source for nvim-cmp
Apache License 2.0
687 stars 32 forks source link

Filter snippets by condition #52

Open petobens opened 1 year ago

petobens commented 1 year ago

Hi! If I have the following snippets

local ls = require('luasnip')
local i = ls.insert_node
local fmta = require('luasnip.extras.fmt').fmta
local line_begin = require('luasnip.extras.expand_conditions').line_begin

return {
    -- Lua
    s(
        { trig = 'rq', dscr = 'Require' },
        fmta(
            [[
                require('<>')
            ]],
            {
                i(1, 'package'),
            }
        ),
        { condition = line_begin }
    ),
}

then cmp shows the rq completion even when I'm not at the beginning of line. Is it possible to filter such snippet from the completion menu?

image

saadparwaiz1 commented 1 year ago

You can filter them out by either setting the snippet to hidden? Or overriding the show_condition for the snippet

petobens commented 1 year ago

You can filter them out by either setting the snippet to hidden?

I don't want to permanently hide the snippet. I just want it to show only when it's actually available (i.e at the beginning of a line).

Or overriding the show_condition for the snippet

Can you provide an example for my case? Thanks!

atticus-sullivan commented 11 months ago

Ok that has been quite some time. Basically the (not working) example would be

local ls = require('luasnip')
local i = ls.insert_node
local fmta = require('luasnip.extras.fmt').fmta
local line_begin = require('luasnip.extras.expand_conditions').line_begin

return {
    -- Lua
    s(
        { trig = 'rq', dscr = 'Require' },
        fmta(
            [[
                require('<>')
            ]],
            {
                i(1, 'package'),
            }
        ),
        { condition = line_begin, show_condition = line_begin }
    ),
}

The issue here is that the API of condition and show_condition differ (refer DOC.md#snippets -> condition) and the current implementation of line_begin doesn't work with the show_condition API.

Currently I don't see a way of changing/improving this, as we need the matched_trigger to be able to tell if the snippet begins at the beginning of the current line. If you have an idea here, please let me know. Adding matched_trigger to the API would be a (bigger) change in luasnip itself (not sure how hard that would be).

A quick and dirty (not quite) fix maybe would be to use something like show_condition = function(line_to_cursor) return #line_to_cursor <= 2 so that the snippet will only be shown if the cursor is near the beginning of the line. If I think about it, this might be even enough for your case.