Open a sibling file in vim

I often find myself editing a file in vim in some nested directory, like app/templates/foo/bar/baz/banana.html, and needing to edit a "sibling" file, like app/templates/foo/bar/baz/apple.html. As with anything in vim, there are lots of ways to solve this problem. For I long time, I use to just edit/tabedit/vsplit etc. the full file name relative to my current working directory, but I recently discovered this gem (sub tabe, vsp, or sp based on your preference):

:e %:h/apple.html

In vim % is the filename of the current buffer relative to your current working directory (basically the way you'd open it from the command line with vim), but you can modify it with : + modifier (see :h filename-modifiers). The h modifier gives you the "head" of the file (the path of the file without the filename and extension) or in this (very fake) example, app/templates/foo/bar/baz, so then adding /apple.html opens the sibling file for editing. You can even use tab completion after typing /. The %:h will be expanded to the full path.

comments powered by Disqus