I was trying to get cargo to use the custom esp toolchain from Espressif, but use stable for rust-analyzer because the esp toolchain does not include a rust-analyzer component.
Neovim has a built-in option to load user-defined config at the project level called excr, which can be enabled with:
vim.o.exrc = true -- enable project local config
With this enabled, the following .nvim.lua will merge the global configuration I have set for vim.g.rustaceanvim (and this is helpful because I have settings for use with the bacon-lsp as well):
local ra_settings = {
cargo = {
target = "xtensa-esp32s3-none-elf",
allTargets = false,
extraEnv = {
RUST_TOOLCHAIN = "esp",
RUSTUP_TOOLCHAIN = "esp",
},
},
}
-- Configure rustaceanvim via vim.g.rustaceanvim
local existing = vim.g.rustaceanvim
vim.g.rustaceanvim = function()
local base = type(existing) == "function" and existing() or (type(existing) == "table" and existing or {})
return vim.tbl_deep_extend("force", base, {
server = {
cmd = { "rustup", "run", "stable", "rust-analyzer" },
extra_env = { RUSTUP_TOOLCHAIN = "stable", RUST_TOOLCHAIN = "stable" },
default_settings = {
["rust-analyzer"] = ra_settings,
},
settings = function(project_root, default_settings)
local base_settings = type(base.server and base.server.settings) == "function"
and base.server.settings(project_root, default_settings)
or (base.server and base.server.settings)
or default_settings
or {}
return vim.tbl_deep_extend("force", base_settings, {
["rust-analyzer"] = ra_settings,
})
end,
},
})
end
-- Register in vim.lsp.config for rustaceanvim client configuration
vim.lsp.config("rust-analyzer", {
cmd = { "rustup", "run", "stable", "rust-analyzer" },
cmd_env = { RUSTUP_TOOLCHAIN = "stable" },
settings = {
["rust-analyzer"] = ra_settings,
},
})
Important notes
Using
RUST_TOOLCHAINvsRUSTUP_TOOLCHAIN- The project’s
rust-toolchain.tomlpins the toolchain to the customespchannel - When Neovim attempted to launch
rust-analyzer,rustuptried to locate it inside theesptoolchain (which lacksrust-analyzer) and failed rustuprequiresRUSTUP_TOOLCHAIN(notRUST_TOOLCHAIN) to override toolchain resolution.
- The project’s
rust-analyzerBinary Execution Path- Environment variables placed inside
settings["rust-analyzer"].server.extraEnvare not part ofrust-analyzer’s LSP settings schema and were ignored. - Explicitly setting
server.cmdto runrustup run stable rust-analyzer
- Environment variables placed inside
Global
vim.g.rustaceanvimConfiguration- In my
~/.config/nvim/lua/config/lsp.lua,vim.g.rustaceanvimis defined as a function - This lua script evaluates
existing()if it is a function
- In my
LSP Config Integration
rustaceanvimmerges client settings fromvim.lsp.config["rust-analyzer"]when starting up, andvim.lsp.config("rust-analyzer", ...)is updated to match the correct environment variable and command definitions