Skip to content

Instantly share code, notes, and snippets.

@beauwilliams
Last active May 13, 2024 13:23
Show Gist options
  • Save beauwilliams/05c02c7b957615498fd39012316b791b to your computer and use it in GitHub Desktop.
Save beauwilliams/05c02c7b957615498fd39012316b791b to your computer and use it in GitHub Desktop.
A simple function to safely require packages. Avoids vim crashing when packages not installed
-- @USAGE:
-- local foo = safe_require('foo')
-- if not foo then return end
_G.safe_require = function(module_name)
local package_exists, module = pcall(require, module_name)
if not package_exists then
vim.defer_fn(function()
vim.schedule(function()
vim.notify('Could not load module: ' .. module_name, 'error', { title = 'Module Not Found' })
end)
end, 1000)
return nil
else
return module
end
end
-- @USAGE: :lua safe_reload('foo')
function _G.safe_reload(module)
package.loaded[module] = nil
return safe_require(module)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment