Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lua/snippets/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,26 @@ function snippets.get_loaded_snippets()
return snippets.loaded_snippets
end

function snippets.expand_or_jump()
if vim.snippet.active({ direction = 1 }) then
return vim.schedule(function()
vim.snippet.jump(1)
end)
end
-- code
local snippet, prefix = snippets.utils.get_snippet_at_cursor()

if type(snippet) ~= "string" then
return
end

vim.schedule(function()
local lnum, col = unpack(vim.api.nvim_win_get_cursor(0))
vim.api.nvim_buf_set_text(0, lnum - 1, col - #prefix, lnum - 1, col, {})
vim.snippet.expand(snippet)
end)
end

---@param opts? table -- Make a better type for this
function snippets.setup(opts)
snippets.config.new(opts)
Expand Down
21 changes: 21 additions & 0 deletions lua/snippets/utils/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -341,4 +341,25 @@ function utils.find_snippet_prefix(prefix)
return Snippets.loaded_snippets[prefix]
end

---@type fun(snippets: table<string, table>|nil): string|nil, string
function utils.get_snippet_at_cursor()
local line = vim.api.nvim_get_current_line()
local offset = vim.fn.mode() == "i" and 0 or 1
local col = vim.api.nvim_win_get_cursor(0)[2] + offset

-- TODO: Probably make matching character configurable
local prefix = line:sub(1, col):match("[%w_-.]*$")
local res = utils.find_snippet_prefix(prefix)

if not res then
return nil, prefix
end

if vim.is_callable(res.body) then
return res.body(), prefix
end

return table.concat(res.body, "\n"), prefix
end

return utils