From 4bbfa49d6fb7502bec0eeda79581e4fdca5631e9 Mon Sep 17 00:00:00 2001 From: Marko Korhonen Date: Wed, 28 Feb 2024 09:04:56 +0200 Subject: [PATCH] Nvim: Improve luasnip keymappings --- home/.config/nvim/lua/plugins/cmp.lua | 44 ++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/home/.config/nvim/lua/plugins/cmp.lua b/home/.config/nvim/lua/plugins/cmp.lua index 3891206..8af7348 100644 --- a/home/.config/nvim/lua/plugins/cmp.lua +++ b/home/.config/nvim/lua/plugins/cmp.lua @@ -26,6 +26,12 @@ return { local cmp = require("cmp") local luasnip = require("luasnip") + local has_words_before = function() + unpack = unpack or table.unpack + local line, col = unpack(vim.api.nvim_win_get_cursor(0)) + return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil + end + -- Set completeopt to have a better completion experience vim.o.completeopt = "menuone,noselect" @@ -46,20 +52,44 @@ return { behavior = cmp.ConfirmBehavior.Replace, select = true, }), - [""] = cmp.mapping(function(fallback) - if cmp.visible() then - cmp.select_next_item() - elseif luasnip.expand_or_jumpable() then - luasnip.expand_or_jump() + -- Snippet placeholder forward + [""] = cmp.mapping(function(fallback) + if luasnip.jumpable(1) then + luasnip.jump(1) else fallback() end end, { "i", "s" }), + -- Snippet placeholder backward + [""] = cmp.mapping(function(fallback) + if luasnip.jumpable(-1) then + luasnip.jump(-1) + else + fallback() + end + end, { "i", "s" }), + -- Completion menu forward + [""] = cmp.mapping(function(fallback) + if cmp.visible() then + -- If only one entry, select it + if #cmp.get_entries() == 1 then + cmp.confirm({ select = true }) + else + cmp.select_next_item() + end + elseif has_words_before() then + cmp.complete() + if #cmp.get_entries() == 1 then + cmp.confirm({ select = true }) + end + else + fallback() + end + end, { "i", "s" }), + -- Completion menu backward [""] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() - elseif luasnip.jumpable(-1) then - luasnip.jump(-1) else fallback() end