I am using vim on Windows and have following mappings:

imap <f4> <ESC>:w<CR>:!clang -std=c++11 -o output\%.exe %<CR>
imap <f5> <ESC>:!output\%.exe<CR>

As we know in windows \ is path separator \ also used in escape sequences in vim-script and commands this command gives me out put as sown in pic.
output I am getting
What I want is shown in the following pic
enter image description here

My intention is to compile the source and return the output in the 'output' directory and execute from there.

Instead, I get 'output%' as output in the current directory.


1 Answer 1


First off, you should always use inoremap rather than imap (with a small number of exceptions that are not relevant here).

The difficulty here is that as soon as % is put after \, the backslash goes from path component to escaping character. The only way I could prevent that is to use an expression (<expr> on lhs of the mapping) so I could use expand("%") in it:

inoremap <expr> <f4> '<ESC>:w<CR><ESC>:!clang -std=c++11 -o output\' . expand("%") . '.exe ' . expand("%") . '<CR>'
inoremap <expr> <f5> '<ESC>:!output\' . expand("%") . '.exe<CR>'

Update : Actually I found a way to do this without <expr>. The second "Note" under :help E809 says that double quotes can be used to isolate % while retaining its special meaning. It looks a little strange on the cmd.exe command line but it works in my tests.

inoremap <f4> <ESC>:w<CR><ESC>:!clang -std=c++11 -o output\"%".exe %<CR>
inoremap <f5> <ESC>:!output\"%".exe<CR>
  • @B Layer my question was poorly worded. let me elaborate more clearly. I have a directory ` code` for source files for example a.cpp which will be value for expand("%:r") or % . I have a directory inside code called output I want output executable in this output directory. ` output%.exe expands to outputa.CPP.exe inside code directory. what I want is a.CPP.exe inside code\output
    – mage
    Nov 11, 2017 at 1:07
  • @mage Please edit your question and add the extra information. Include clear example of input and output filenames/directories. Also, pay close attention to what you write. "vim on window" isn't very clear. "vim on Windows" is.
    – B Layer
    Nov 11, 2017 at 1:56
  • @B Layer Windows has `` for path separator which is used in vim for escape sequences.
    – mage
    Nov 11, 2017 at 7:03
  • @mage The edit was a big improvement but you fundamentally changed at least one thing: going from nmap to imap. That kinda messes my answer up. Anyways, I just appended a new solution until I get a chance to completely rewrite it. I tested this on Windows.
    – B Layer
    Nov 11, 2017 at 10:03
  • @mage Were you able to apply my new solution?
    – B Layer
    Nov 12, 2017 at 1:20

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.