home ~ socials ~ projects ~ rss

Run Synchronous And Asynchronous External Commands In Neovim With Lua

March 2023

I need to write this up but here's the code in the mean time. It uses plenary which is a collection of helper functions. Installation instructions are on that page.)

Async

This is the one I usually want since it doesn't lock up the interface.

local asynchronous_command_example = function()
  local Job = require 'plenary.job'
  Job:new({
    command = 'bash',
    args = { '-c', 'sleep 3; echo ASYNC_COMPLETE'},
    on_exit = function(job, return_val)
      print(vim.inspect(job:result()))
    end,
  }):start() 
end

This is the synchronous version that does lock up neovim while it's running.

local synchronous_command_example = function()
  local Job = require 'plenary.job'
  Job:new({
    command = 'bash',
    args = { '-c', 'sleep 3; echo SYNC_COMPLETE'},
    on_exit = function(job, return_val)
      print(vim.inspect(job:result()))
    end,
  }):sync() 
end

References

  • https://github.com/nvim-lua/plenary.nvim
  • https://doriankarter.com/inspect-contents-of-lua-table-in-neovim/
  • An alternate way in post: 2nhsdbjkdvpq
end of line
Share link:
https://www.alanwsmith.com/en/2n/gt/ll/ok/?run-synchronous-and-asynchronous-external-commands-in-neovim-with-lua