vimtricks.wiki Concise Vim tricks, one at a time.

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
  • :h is 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:h to ensure you get the absolute directory path (:p makes the path absolute before :h strips the filename)
  • Use :lcd %:p:h to 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

Next

How do I duplicate the current line to the end of the file without yanking or moving the cursor?