direnv / direnv.vim

vim plugin for direnv support
MIT License
183 stars 12 forks source link

DirenvLoaded event seems bugged, or doesn't work as expected #36

Open Hubro opened 6 months ago

Hubro commented 6 months ago

I'm having an issue where my LSP servers can't find my project's dependencies, because direnv activates a Python virtualenv after my LSP servers have already started up.

To fix this, I thought I'd use the DirenvLoaded event to restart my LSP servers whenever the direnv environment is loaded:

local group = vim.api.nvim_create_augroup("DirenvLoaded", { clear = true })
vim.api.nvim_create_autocmd({ "User" }, {
  group = group,
  pattern = "DirenvLoaded",
  callback = function()
    vim.notify("Loaded environment from direnv")

    if vim.cmd.LspRestart ~= nil then
      vim.notify("Restarting LSP servers")
      vim.cmd.LspRestart()
    end
  end
})

Unexpected behavior:

This behavior doesn't make any sense to me, so I'm assuming it's a bug.


$ nvim --version
NVIM v0.10.0-dev-2295+g672556525
Build type: RelWithDebInfo
LuaJIT 2.1.1707061634
Run "nvim -V1 -v" for more info
Hubro commented 6 months ago

Figured out a workaround using DIRENV_DIFF, seems to solve all the problems I had:

return {
  "direnv/direnv.vim",
  commit = "ab2a7e08dd630060cd81d7946739ac7442a4f269",
  init = function()
    vim.g.direnv_silent_load = true

    local cached_direnv_diff = nil

    local group = vim.api.nvim_create_augroup("DirenvLoaded", { clear = true })
    vim.api.nvim_create_autocmd({ "User" }, {
      group = group,
      pattern = "DirenvLoaded",
      callback = function()
        if vim.env.DIRENV_DIFF ~= cached_direnv_diff then
          cached_direnv_diff = vim.env.DIRENV_DIFF

          vim.notify("Loaded environment from direnv")

          if vim.cmd.LspRestart ~= nil then
            vim.notify("Restarting LSP servers")
            vim.cmd.LspRestart()
          end
        end
      end
    })
  end
}