Rob Bednark
Rob Bednark

Reputation: 28222

Why is current working directory in vim different from where vim was started?

vim is showing a different current working directory than the one I started vim with from the command-line. The problem goes away if I run without my .vimrc (vim -u NONE). How can I debug this to figure out why this is happening?

$ pwd
/Users/rbednark/Dropbox/git/quizme_personal_files/bin
$ vim --noplugin
:pwd 
/Users/rbednark/Dropbox/git/quizme_personal_files/bin
:edit settings.sh
:pwd 
/Users/rbednark/quizme-read-only-prod
(expected: 
  /Users/rbednark/Dropbox/git/quizme_personal_files/bin
 actual: 
  /Users/rbednark/quizme-read-only-prod
)

The problem goes away if I don't use my .vimrc:

$ vim -u NONE

Notes:

EDIT: I initially thought this was due to doing :edit other-file, but now I see it with just editing a single file, so I changed the above to remove that unnecessary aspect.

Upvotes: 2

Views: 1333

Answers (2)

Allen Zeng
Allen Zeng

Reputation: 1

I use the following snippet to save the fold state, while I am using auto-session to save my neovim session for each specific directory.

-- auto save fold view after exit a file
vim.api.nvim_create_autocmd({ "BufLeave", "BufWinLeave", "InsertLeave" }, {
    group = augroup("remenber_folds"),
    callback = function()
        vim.cmd("silent! mkview")
    end,
    group = general,
    desc = "save fold view",
})

-- auto load fold view after enter a file
vim.api.nvim_create_autocmd({ "BufRead", "BufWinEnter", "BufEnter", "FocusGained" }, {
-- vim.api.nvim_create_autocmd({"BufWinEnter"}, {
    group = augroup("remenber_folds"),
    callback = function()
        vim.cmd("silent! loadview")
    end,
    group = general,
    desc = "load fold view",
})

And adding vim.cmd [[set viewoptions-=curdir]] to my options.lua file perfectly solves the problem, I can automatically save the session and fold state after I leave a buffer or quit neovim, and load them when entering the buffer or opening neovim at the same dir.

Upvotes: 0

Rob Bednark
Rob Bednark

Reputation: 28222

Reason: I had done an :lcd at some point, and my .vimrc has autocmds to mkview and loadview when leaving and entering a buffer, so editing the file again was doing an :lcd to the other directory.

Solutions:

option 1 -- change the current working directory to the directory of the file being edited, and save:

cd %:p:h
:wq

option 2 -- remove the corresponding view file, e.g.,

$ rm ~/.vim/view/*myfile*

How I solved / debugged:
I bisected my .vimrc file to determine the offending line, which was:

autocmd BufWinEnter * silent! loadview

That indicated it was due to a view that was getting loaded. I then viewed the corresponding view file in ~/.vim/view and searched for the directory name, which yielded this line:

lcd ~/quizme-read-only-prod

See also: https://vi.stackexchange.com/questions/11903/working-directory-different-than-current-file-directory

Upvotes: 2

Related Questions