How do I open the directory containing the current file in netrw from within Vim?
Answer
:e %:h
Explanation
The command :e %:h opens netrw (Vim's built-in file browser) in the directory that contains the current file. It uses the % filename special character combined with the :h modifier, which strips the last component of the path to yield the directory.
How it works
%expands to the full path of the current buffer's file:his a filename modifier meaning "head" — it removes the filename, leaving just the directory:e(short for:edit) opens whatever path follows; when given a directory, it opens netrw
Example
If you are editing /home/user/projects/myapp/src/main.py, then:
:e %:h
Is equivalent to:
:e /home/user/projects/myapp/src
This opens netrw showing all files in src/, where you can navigate to open other files.
Tips
- Use
:e %:p:hto ensure you get the absolute directory path (:pmakes the path absolute before:hstrips the filename) - Use
:lcd %:p:hto change the local working directory to the current file's directory instead of opening netrw - Add a mapping for quick access:
nnoremap <leader>E :e %:h<CR> - From within netrw, press
<CR>to open files,-to go up a directory level, and%to create a new file