Luajob is a library that wraps |vim-loop| with a more |jobstart|-like interface, which simplifies using async jobs in lua.
If using vim-plug:
Plug 'TravonteD/luajob'
First you'll need to get load the library
local luajob = require('luajob')
Next create a new job
local ls = luajob:new({cmd = 'ls'})
Finally start the process
ls.start()
This example calls "git branch" and sets the current branch to g:git_branch
local luajob = require('luajob')
local git_branch = luajob:new({
cmd = 'git branch',
on_stdout = function(err, data)
if err then
print('error:', err)
elseif data then
lines = vim.fn.split(data, '\n')
for _, line in ipairs(lines) do
if line:find('*') then
vim.api.nvim_set_var('git_branch', (line:gsub('\n', '')))
end
end
end
end
})
git_branch:start()
Configuration for the luajob is done by passing a table as an argument to an instance of LuaJob the options are similar to that of |jobstart|
cmd : String The command to be run in the luajob.
Example:
{
cmd = 'sleep 3'
}
cwd : String (Optional) The working directory for the command defaults .
Example:
{
cwd = '~'
}
env : Table (Optional) A table of environment variables to be set for the command.
Example:
{
env = { MYENV = 'env' }
}
detach : Boolean (Optional) If set the luajob will continue running after Neovim has exited.
Example:
{
detach = true
}
on_stdout : Function (Optional) The function to be executed when the command outputs to standard output. It will be passed two arguments. The first representing a libuv err on reading, and the second representing the outputted data.
Example:
{
on_stdout = function(err, data)
if err then
print('error', err)
elseif data then
print('data', data)
end
end
}
on_stderr : Function (Optional) The function to be executed when the command outputs to standard error. It will be passed two arguments. The first representing libuv err on reading, and the second representing the outputted data.
Example:
{
on_stdout = function(err, data)
if err then
print('error', err)
elseif data then
print('data', data)
end
end
}
on_exit : Function (Optional) The function to be executed when the command exits. It will be passed two arguments. The first representing the exit code, and the second representing the signal.
Example:
{
on_exit = function(code, signal)
print('job exited', code, signal)
end
}
stop() : Exits the job
Example:
local luajob = require('luajob')
cat = luajob:new({cmd = 'cat'})
cat.start()
cat.stop()
send() : Takes a string and writes it to the standard input of the job. If the job continually waits for standard input, make sure to close it after the last write using stop().
Example:
local luajob = require('luajob')
cat = luajob:new({cmd = 'cat'})
cat.start()
cat.send('Hello World!')
cat.stop()