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

How do I open a related file with a different extension using the current filename?

Answer

:e %:r.html

Explanation

In Vim's command line, % expands to the current buffer's filename. You can append filename modifiers to transform it — making it easy to open related files, split into a sibling directory, or construct paths without typing filenames manually.

How it works

Modifiers are appended after % with a colon:

  • %:rroot: strip the last extension (src/foo.csrc/foo)
  • %:eextension only (src/foo.cc)
  • %:ttail (basename, no directory) (src/foo.cfoo.c)
  • %:hhead (directory only) (src/foo.csrc)
  • %:pfull absolute path
  • %:p:h — directory of the current file (modifiers chain)

Example

Editing src/components/Button.tsx and you want to open its CSS module:

:e %:r.css

This expands to :e src/components/Button.css. Or to browse the same directory:

:e %:p:h/

This opens netrw in the current file's directory. Or to open the test file:

:e %:r.test.ts

Tips

  • Use <Tab> to complete after the modifier (e.g., :e %:p:h/<Tab>)
  • These modifiers also work in :read, :write, :split, :vsplit
  • %:t:r chains modifiers: basename without extension (src/foo.cfoo)
  • The # register holds the alternate filename and supports the same modifiers: #:r, #:h etc.
  • Preview the expansion without opening: :echo expand('%:p:h')

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?