Search code examples
luaneovim

NeoVim - Check if a Vim function exists from Lua


I plan on using vim-plug with NeoVim. So, my init.lua file will have function calls such as

vim.fn['plug#begin'](vim.fn.stdpath('data') .. '/plugged')    
vim.fn['plug#']('hoob3rt/lualine.nvim')    

However, I don't want to assume vim-plug is definitely installed. I want my init.lua file to degrade gracefully if vim-plug is not installed, rather than throwing an error

E5113: Error while calling lua chunk: Vim:E117: Unknown function: plug#begin
stack traceback:
        [C]: in function 'plug#begin'
        /Users/andy/.config/nvim/init.lua:8: in main chunk

How can I check if the vim-plug functions exist before attempting to call them?

I tried print(vim.fn['plug#begin']) but that for some reason prints a non-null value: function: 0x0104ba36f0, even though the function doesn't exist.


Solution

  • I tried print(vim.fn['plug#begin']) but that for some reason prints a non-null value: function: 0x0104ba36f0, even though the function doesn't exist.

    Presumably it's returning a function that throws the error you are getting. I would thus recommend using pcall:

    local success, error = pcall(vim.fn['plug#begin'], vim.fn.stdpath('data') .. '/plugged')
    if not success then --[[fail gracefully]] end
    

    caveat: this will catch any error, so you'll probably want to perform some check like if error:find"Unknown function" then ... end to only catch this specific error.