Vim Tips Wiki
Advertisement
Tip 2 Printable Monobook Previous Next

created February 24, 2001 · complexity intermediate · author scott · version 5.7


It was often frustrating when I would open a file deep in the code tree and then realize I wanted to open another file in that same directory. Douglas Potts taught me a nice way to do this. Add the following snippet to your vimrc:

" Edit another file in the same directory as the current file
" uses expression to extract path from current file's path
" (thanks Douglas Potts)
if has("unix")
  map ,e :e <C-R>=expand("%:p:h") . '/'<CR>
else
  map ,e :e <C-R>=expand("%:p:h") . '\'<CR>
endif

Then when you type ,e in normal mode you can use tab to complete to the file. You can also expand this to allow for splitting, etc.

An alternative is to expand the current file directory while you're on the command line with something like:

if has("unix")
  cmap %/ <C-R>=expand("%:p:h") . '/'<CR>
else
  cmap %/ <C-R>=expand("%:p:h") . '\'<CR>
endif

This has the advantage that you can use it with any command, such as :e, :w, :cd etc. For example, typing:

:cd %/

Would become something like:

:cd /home/username/foo/

Comments

See also Set_working_directory_to_the_current_file for another solution to this problem.


Advertisement