Skip to content

Project local settings

Alejandro Exojo edited this page Nov 18, 2024 · 17 revisions

Use native server file configs

There are server configs for many LSP servers. For instance for the lua-language-server there is a project/workspace-relative config file called .luarc.json that is loaded from a root path of a workspace. If you came across an LSP server that doesn't provide a way to configure server via local files, please consider to fill an issue at its repo.

Use nlsp-settings.nvim

nlsp-settings.nvim is a plugin to configure Neovim LSP using json/yaml files like coc-settings.json.

Configure in your personal settings (init.lua)

If the only thing you care about configuring is the language server's settings, you might be able to use the on_init hook and the workspace/didChangeConfiguration notification:

local nvim_lsp = require('lspconfig')

nvim_lsp.rust_analyzer.setup {
  on_init = function(client)
    local path = client.workspace_folders[1].name

    if path == '/path/to/project1' then
      client.config.settings["rust-analyzer"].checkOnSave.overrideCommand = { "cargo", "check" }
    elseif path == '/path/to/rust' then
      client.config.settings["rust-analyzer"].checkOnSave.overrideCommand = { "python3", "x.py", "check", "--stage", "1" }
    end

    client.notify("workspace/didChangeConfiguration", { settings = client.config.settings })
    return true
  end,
  -- NOTE: you must spell out the config you wanna change in `on_init` inside `settings`, like:
  settings = {
    ['rust-analyzer'] = { checkOnSave = { overrideCommand = {} } } -- here
  }
}

Give it a shot if you want project settings are managed with project itself.

Use exrc

Before doing this, please familiarize yourself with the risk of automatically running project local code in the lua interpreter (see :h 'exrc').

Local settings can be configured by enabling the exrc option with set exrc in your init.vim and creating a .nvim.lua file in the project's root directory. If neovim is launched in the same directory as .nvim.lua, it will evaluate your user configuration first, followed by the local configuration. An example .nvim.lua might be as follows:

  local nvim_lsp = require('lspconfig')

  nvim_lsp.rust_analyzer.setup {
    root_dir = function()
      return vim.fn.getcwd()
    end
  }

Be aware, after enabling exrc, neovim will execute any .nvim.lua, .nvimrc or .exrc that you have added to the trust list and has not changed since you added it (neovim will prompt you for confirmation if it has changed). You might be still be tricked to run files that contain malicious code.