3

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the workaround. I'm using this for now. I requested a cleaner method in an issue: github.com/neovim/neovim/issues/19271
why not use :help exists() ?
@JustinM.Keyes exists() actually won't work because vim-plug is autoloaded, so exists() will return false until you trigger something in NeoVim to look for the plugin and load it, such as calling vim.fn['plug#begin']. AFTER you do that, then exists()'s output will be accurate.
0
let data_dir = has('nvim') ? stdpath('config') : '~/.vim'
if empty(glob(data_dir . '/autoload/plug.vim'))
  silent execute '!curl -fLo '.data_dir.'/autoload/plug.vim --create-dirs  https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
  autocmd VimEnter * PlugInstall --sync | source $MYVIMRC
endif

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.