Vim Tips Wiki

Changes: Change to directory of the opened file


Back to page

(Adjust previous/next navigation)
(Contents of this tip are covered by Set working directory to the current file)
Line 1: Line 1:
#REDIRECT [[Set working directory to the current file]]
|created=March 24, 2006
The present working directory can be displayed in Vim with:
To change to the directory of the currently opened file:
:cd %:h
Here's a mapping to make this easier:
nmap <silent> <Leader>cd :cd %:p:h<CR>
Note the use of <tt>:p</tt> first expand the % to a full path -- it takes care of the case where you're already in the correct directory. If that happens, %:h expands to an empty string and the :cd command throws an error. %:p:h is safe as it will never send an empty directory into the :cd command.
Note that 'autochdir' can be turned on to automatically switch to the directory of the current buffer upon entering the buffer. Alternatively, try:
nmap <silent> <Leader>sp :sp <c-r>=expand('%:p:h')<CR>/
(The last / can be changed to a backslash if on Windows.) Then, hitting <Leader>sp will produce a command-line all set to allow editing of a file in the same directory as the current buffer.
Also see [[VimTip64]] (Always set your working directory to the file you're editing)
This is very useful. Personally I have these commands defined:
command! CD cd %:p:h
command! LCD lcd %:p:h

Latest revision as of 20:18, August 7, 2011

  1. REDIRECT Set working directory to the current file

Around Wikia's network

Random Wiki