Saturday, August 25, 2012
Vim Directories
The present working directory can be displayed in Vim with:
:pwd
To change to the directory of the currently open file (this sets the current directory for all windows in Vim):
:cd %:p:h
You can also change the directory only for the current window (each window has a local current directory that can be different from Vim's global current directory):
:lcd %:p:h
In these commands, % gives the name of the current file, %:p gives its full path, and %:p:h gives its directory (the "head" of the full path).
Automatically change the current directory
Sometimes it is helpful if your working directory is always the same as the file you are editing. To achieve this, put the following in your vimrc:
set autochdir
That's it! Unfortunately, when this option is set some plugins may not work correctly if they make assumptions about the current directory. Sometimes, as an alternative to setting autochdir, the following command gives better results:
autocmd BufEnter * silent! lcd %:p:h
This autocmd changes the window-local current directory to be the same as the directory of the current file. It fails silently to prevent error messages when you edit files via ftp or new files. It works better in some cases because the autocmd is not nested, and will therefore not fire when switching buffers via another autocmd. It will also work in older versions of Vim or versions compiled without the 'autochdir' option. Note, however, that there is no easy way to test for this autocmd in a script like there is for the 'autochdir' option.
Either of these methods will "cd" to the directory of the file in the current window, each time you switch to that window.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment