neovim - How do I set my CWD to relative to the open filefolder? - Stack Overflow

admin2025-04-29  2

When I have a folder or file open in nvim, if I want to edit or open a different file/folder, the context directory is always my home directory. Example:

I'm currently editing C:\Users\myUser\repos\my_repo\file1.txt. I want to edit C:\Users\myUser\repos\my_repo\file2.txt. I have to enter:

:e repos\my_repo\file2.txt

Or if I want to save as a different filename:

:w repos\my_repo\file3.txt

I want to open files relative to the directory of the file/folder I have currently open/active. Expected behavior:

:e file2.txt

or

:w file3.txt

How do I configure this? I'm using init.lua not init.vim.

Edit: Based on Tim Roberts' answer and this article, I added this to my init.lua:

vim.api.nvim_create_autocmd('TabNewEntered', {
  desc = 'Automatically change CWD for a tab',
  group = vim.api.nvim_create_augroup('tag-change-cwd', { clear = true }),
  callback = function()
    local dirname
    local path = vim.fn.expand '<amatch>'

    if vim.fn.isdirectory(dirname) == 1 then
      dirname = path
    else
      dirname = vim.fn.fnamemodify(path, ':h')
    end
    vim.cmd('tcd ' .. dirname)
  end,
})

This seemed to work when I first added it but now it is not. I also tried with the BufEnter event instead of TabNewEntered, but no luck.

Any assistance is appreciated!

转载请注明原文地址:http://anycun.com/QandA/1745940092a91408.html