Search code examples
vimautocmd

vim: new file's directory did not match the current working directory when autocmd was applied


I'm starting using vim to edit my python code and I want vim to save codes under different folders according to different suffixes like '.py'.

So, I added this into my gvimrc file (I'm using MacVim indeed, but the same problem appears on vim)

au BufWritePre *.py :cd /Users/username/Documents/folder

I think this changes the working directory into /Users/username/Documents/folder every time before I save my code ending in '.py'.

While I entered MacVim, opened a new file, typed something like

print("Hello")

and saved it by

:w hello_world.py

A file named hello_world.py appeared in /Users/username/Documents/folder, as I wished. The ":pwd" command in vim also returned "/Users/username/Documents/folder". But when I check the filename of hello_world.py in vim by

:!echo %

it returns

/Users/username/hello_world.py

instead of the expected filename

/Users/username/Documents/folder/hello_world.py # expected filename

Further more, When I tried to upgrade the code like

print("Hello")
print("World")

and saved it by

:w

The content in hello_world.py remained unchanged under /Users/username/Documents/folder. But a new file with the same hello_world.py name appeared in the /Users/username, which is consistent with the filename in vim.

I guess my autocmd script in gvimrc did changed the working directory before saving '.py' files, but I'm trying to figure out why the filename is not consistent with the working directory and how can I save my '.py' file into a specific folder.


Solution

  • For me (using Vim 7.4.52 on Ubuntu 14.04), the file consistently get created in the CWD, so the autocmd has no effect to file placement, but changes the directory. Internally, the file's eventual directory is determined when the buffer is created (as evidenced by :ls), not during the first write or naming of the buffer.

    I only managed to get closer to what you want via

    :au BufWritePost *.py file /Users/username/Documents/folder/%:t
    

    which still creates the initial file in the CWD, though.

    If you think Vim should handle this (better), you can try raising the issue on the vim_dev mailing list.