Tip: #2 - Easy edit of files in the same directory
Created: February 24, 2001 14:57 Complexity: intermediate Author: scott at kintana.com Version: 5.7 Karma: 441/154 Imported from: Tip#2
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/