Basically what I want is a keyboard shortcut in vim that lets me [compile and] run the currently being edited C, C++ or Python program. In psuedocode:
when a shortcut key is pressed:
if current_extension == 'c' then
shell: gcc this_filename.c -o this_filename_without_extension
if retcode == 0 then shell: ./this_filename_without_extension
else if current_extension == 'cpp' then
shell: g++ this_filename.cpp -o this_filename_without_extension
if retcode == 0 then shell: ./this_filename_without_extension
else if current_extension == 'py' then
shell: python this_filename.py
end if
end key
I realise I might be asking a bit much but would love it if this was possible!
Something like this would work. Just create filetype autocmd that map <F4>
or whatever you want to save and compile and run the program. It uses exec to build the string and uses shellescape to escape the file name.
autocmd filetype python nnoremap <F4> :w <bar> exec '!python '.shellescape('%')<CR>
autocmd filetype c nnoremap <F4> :w <bar> exec '!gcc '.shellescape('%').' -o '.shellescape('%:r').' && ./'.shellescape('%:r')<CR>
autocmd filetype cpp nnoremap <F4> :w <bar> exec '!g++ '.shellescape('%').' -o '.shellescape('%:r').' && ./'.shellescape('%:r')<CR>
%
is the current buffer filename. %:r
is the buffer filename without extension
@DuncanNZ If you were going to be creating a lot of these you might want to write a function. Although I do think a solution with make is the proper way to go as this really only works if you only ever need to create a single source file. which might work for scratch files but will not work for any projects.
One thing I added was
&& echo Compilation complete
before the last&&
because the programming competition questions can't prompt for input so I don't know when it's compiled. But thanks again for the awesome solution!These mapping should be buffer-local. Moreover,
:make
is to be preferred over calling directly the compiler.Thanks for this handy answer, assuming that I would like to add C++ 11 flags, shall I just change
!g++ '
to'g++ -std=c++11 '
in(...) '!g++ '.shellescape('%').' (...)
?