Some stuff you might know already so don't mind those.
Vim/neovim works with buffers in general so looking for buffers in the docs
or in the :help
will show a lot of stuff.
What you are looking for is nvim_buf_set_text to set the text into the buffer. This method takes starting row and column positions.
This method is best suited for inserting text or delete/replace.
See the linked doc for other suggestions.
What you want to do is place the uuid in the buffer but we also need the row and column position for nvim_buf_set_text
for this we will use nvim_win_get_cursor
--[[ Your uuid function global and renamed for example --]]
function generate_uuid()
math.randomseed(os.time())
local random = math.random
local template = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
return string.gsub(template, "x", function()
local v = random(0, 0xf) -- v is a decimal number 0 to 15
return string.format("%x", v) --formatted as a hex number
end)
--[[ Generate a uuid and place it at current cursor position --]]
local insert_uuid = function()
-- Get row and column cursor,
-- use unpack because it's a tuple.
local row, col = unpack(vim.api.nvim_win_get_cursor(0))
local uuid = generate_uuid()
-- Notice the uuid is given as an array parameter, you can pass multiple strings.
-- Params 2-5 are for start and end of row and columns.
-- See earlier docs for param clarification or `:help nvim_buf_set_text.
vim.api.nvim_buf_set_text(0, row - 1, col, row - 1, col, { uuid })
end
-- Finally we map this somewhere to the key and mode we want.
-- i stands for insert mode next set the insert_uuid without invoking it.
-- For the last parameter see `:help map-arguments` and adjust accordingly.
vim.keymap.set('i', '\\', insert_uuid, { noremap = true, silent = true })
Now uuid is placed when in insert mode when typing '\', consider changing this and/or using leader.
For mapping see docs on keys and docs on set command :help vim.keymap.set
. The last one is in the online docs too but couldn't find it quickly. Afaik :help
and online docs should contain the same info.
Besides the tips given in the docs concerning nvim_buf_set_text
usage also consider looking at nvim_buf_get_lines()
and nvim_buf_set_lines()
for multiline operations.
This should work as desired.