I am trying to create some keybind "scripts" for specified file types in my .vimrc. Example :

 au BufNewFile,BufRead *.cpp
   \ nnoremap <C-P> :!g++ % -o %.exe <CR>

Ideally I would like to name output file type just the name of the file without any extension. Example :

filename : test.cpp

output of compilation : test

Another example - I am working with assembly and compiling test.asm will produce among some others test.hex which I would love to use in another keybind as an argument passed to an emulator. Is this achieveable in .vimrc?

  • 1
    This answer about "filename modifiers" should show the way: How can I see the full path of the current file? ... at least as far as your primary question about dropping the extension goes. I'm not quite sure what you're asking in the last part.
    – B Layer
    Commented Oct 15, 2020 at 19:45
  • Sorry about that, in last part I am asking pretty much the same thing. whether I can drop extension and add .hex so that I can use it as an argument in another program run from shell.
    – Victor
    Commented Oct 15, 2020 at 20:05

2 Answers 2


You can use:

au BufNewFile,BufRead *.cpp nnoremap <buffer> <C-P> :!g++ % -o %< <CR>

The %< will remove the extension from the current file. I use this for example to open the pdf version of the currently edited latex document using :!xpdf %<.pdf

See also the help section :h filename-modifiers It contains all the different modifiers as well as many examples.

Note: I changed your mapping to be buffer-local. This makes sense as you do want that action only to trigger for cpp files (and not also for other buffers where your cursor is in after the above autocommand triggered). See the help at :help :map-<buffer>

  • 2
    nnoremap <buffer>...
    – Maxim Kim
    Commented Oct 16, 2020 at 7:08
  • 2
    indeed. I just copied the example from OP verbatim Commented Oct 16, 2020 at 7:43

You can check this: vim.fandom.com/wiki/Get_the_name_of_the_current_file

Try these:

:echo expand('%:t')

:echo expand('%:e')

So % is the current file, the full path. The :t and :e modifiers are for the file name with extension and without, respectively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.