neovim / neovim

Vim-fork focused on extensibility and usability
https://neovim.io
Other
82.46k stars 5.64k forks source link

Can not call functions or run command provided by a plugin in lua immediately after loading the plugin #29957

Closed jdhao closed 2 months ago

jdhao commented 2 months ago

Problem

When I add a plugin to the runtime path and try to call functions or run a command provided by this plugin, I see errors that indicate this is an unknown function or command.

Steps to reproduce

  1. Run the following bash script to create a simple plugin
mkdir -p nvim-demo-plugin/plugin

touch nvim-demo-plugin/plugin/demo-plugin.vim

cat << EOF > nvim-demo-plugin/plugin/demo-plugin.vim
command! Echo echo "hello world"

function Hello()
  return "hello from function"
endfunction
EOF
  1. start nvim with following minimal config nvim -u mini.lua:
local plugin_path = "./nvim-demo-plugin/"
vim.opt.rtp:prepend(plugin_path)

local success1, result1 = pcall(vim.cmd, "Echo")
vim.print("command Echo available?: ", success1)
local success2, result2 = pcall(vim.fn.Hello)
vim.print("function Hello available?: ", success2)

Expected behavior

I expect that running the command or calling the function should work with success, but actually it doesn't. I am seeing the following message:

command Echo available?:
false
function Hello available?:
false

However, if you then call the function (:lua =vim.fn.Hello()) or run the command (:lua =vim.cmd("Echo")) on the nvim command line, both work fine without error.

Neovim version (nvim -v)

NVIM v0.10.1 Build type: Release LuaJIT 2.1.1720049189

Vim (not Nvim) behaves the same?

no applicable

Operating system/version

macOS 13.6.6

Terminal name/version

wezterm

$TERM environment variable

xterm-256color

Installation

homebrew

clason commented 2 months ago

:h startup

(Just adding a directory to rtp doesn't immediately source its contents; that is done by Nvim during the startup sequence, which means after init.lua is processed. If you need them earlier, you'll have to explicitly runtime! them.)

jdhao commented 2 months ago

I thought that you can not call vim.cmd and vim.fn in vim?

Vim (not Nvim) behaves the same?

no applicable

How is this not applicable?

clason commented 2 months ago

Because you'll get the exact same behavior (in Vim as well) if you use an equivalent minimal.vim; it has nothing to do with Lua.

jdhao commented 2 months ago

okay, thanks, I thought the cause is using lua functions to call vim script command and function.