Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Hubro opened this issue Apr 23, 2024 · 1 comment
Open

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

Hubro opened this issue Apr 23, 2024 · 1 comment

Comments

@Hubro
Copy link

Hubro commented Apr 23, 2024

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:

  • Fires when I open nvim, no matter if the current directory has a .envrc or not
  • If I'm in a project that uses direnv, DirenvLoaded fires every time I change focus to a different buffer (changing focus between two windows with the same buffer doesn't trigger the event)

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
Copy link
Author

Hubro commented Apr 23, 2024

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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant