Skip to content

Project local settings

Artyom Andreev edited this page Oct 18, 2023 · 16 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.

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

lua << EOF
  local nvim_lsp = require('lspconfig')

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

Be aware, after enabling exrc, neovim will execute any .nvimrc or .exrc owned by your user, including git clones.