4

I have mapped my F5 key in vimrc file to run the code using the following command:

map <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ test.cpp && ./a.out

It is working well. But it only runs for test.cpp file. I want to make it generic by inserting the name of my current file. Is there any way of doing this?

2 Answers 2

3

You can use % to expand to the current filename.

See :help :!, which goes into quite some level of detail about that!

If {cmd} contains % it is expanded to the current file name. Special characters are not escaped, use quotes to avoid their special meaning:

:!ls "%"

Note also that :! will already run the command in a shell for you, so you don't really need a sh -c '...' around it.

The reference to the file will be relative to the current directory, so using cd here doesn't make much sense, since this will only work in ~/vscode. I'll assume that's the case and I'll remove that as well.

Putting it all together:

:map <F5> :!set -x; g++ "%" && ./a.out<cr>

Vim also has powerful features for building software. Those can be most useful when compiling projects spanning hundreds of source code files, but you could leverage them in your particular case too.

They can be quite complex, so it might take a while to get the hang of them. You can start at :help :make, though you might also try to find easier to digest tutorials about how to use :make for your specific language, compiler, build system, etc.

0
2

Use "Ex special characters" :h cmdline-special.

Specifically, % is always replaced in normal Ex commands with the current buffer/file name as long as it's not escaped. So a simple drop-in replacement of "test.cpp" is all that's needed...

noremap <F5> :!sh -xc 'cd "/home/hashir/vscode/" && g++ "%" && ./a.out'<CR>

(I corrected a couple omissions/typos in your mapping and use "noremap" as is recommended in almost all cases. Also, note quotes around % which is best practice kind of thing with shell commands.)

In addition to plain % there are a bunch of modifiers that can be appended that will do things like strip off the extension (%:r) or force the name to be a full path (%:p). See :h filename-modifiers.

There are also a couple other special chars such as # which will be replaced by the "alternate" file/buffer name.

By the way, if you wanted to use a plain % in your shell command you'd have to escape it by preceding it with backslash \ as I alluded to before.

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.