Automatically Execute Anything In Nvim - TJ DeVries (11min)
TL;DR
Nice quick video showing the basic of how to setup automation with Neovim autocmd
-
Get the Neovim buffer number for the current window with:
:echo nvim_get_current_buf()
-
The primary way to set lines in buffers is
local bufnr = 41 vim.api.nvim_buf_set_lines(bufnr, 0, -1, false {"hello", "world" })
Where "bufnr" is the buffer number. "0" is the start line and "-1" is the last line, false just needs to be there, and the last thing are the lines too put in.
-
to add something at the start of the file (and push everything else after it) use "0" instead of "-1" for the third parameter:
vim.api.nvim_buf_set_lines(bufnr, 0, 0, false {"hello", "world" })
-
Auto commands are how to react to events in Neovim.
-
BurWritePost is what is triggered after a buffer is written. (Looking at this for auto executing embedded rust scripts)
-
This is what a basic setup for an autocommand looks like (note that I typed this in so there may be typos that I haven't caught yet)
vim.api.nvim_create_autocmd("BufWritePost", { group = vim.api.nvim_create_augroup("TutorailGroup", { clear = true }), pattern = "main.txt", callback = function() print("did the thing") end, })
-
without `pattern`` in there, that would execute on every file save
-
Using the `.nvim_create_augroup()`` prevents listeners from being added over and over again when you same the lua source files that contain them
-
Running external commands is done with `.jobstart()``
(note: I typed this code in by hand and don't have a way setup to test it yet so it still needs to be vetted)
vim.fn.jobstart( {"go", "run", "main.go"}, { stdout_buffered = true, on_stdout = function(_, data) if data then vim.api.nvim_buf_set_lines(bufnr, -1, -1, false, data) end end, on_stderr = function(_, data) if data then vim.api.nvim_buf_set_lines(bufnr, -1, -1, false, data) end end } )