Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim autocmd not working with nnoremap

Tags:

vim

I am trying to setup vim for compiling and runing c and c++ programs right inside the editor, but these don't seem to work:

autocmd! filetype *.c        nnoremap <leader>cc :!gcc -o %:p:r %<cr>
autocmd! filetype *.c        nnoremap <leader>cr :!gcc -o %:p:r %<cr>:!%:p:r<cr>
autocmd! filetype *.cpp *.cc nnoremap <leader>cc :!g++ -o %:p:r %<cr>
autocmd! filetype *.cpp *.cc nnoremap <leader>cr :!g++ -o %:p:r %<cr>:!%:p:r<cr>
like image 933
qed Avatar asked Feb 27 '26 18:02

qed


1 Answers

The FileType autocommand uses the filetype not the filename to match against. You can instead use c and cpp. See :h FileType. However your problems do not end there:

  • These are global mappings. There for open up a c file and the mappings change. Open up a cpp file and the mappings change no matter what buffer you are in. Use nnoremap <buffer> instead. See :h :map-local
  • Using autocmd! without a group. autocmd! will remove all previously defined and add in the current autocommand. It would be best to create a group with augroup.
  • Optionally you can use %< instead of %:r.
  • You may also want to look into pushing this into an ftplugin or after/ftplugin variant. :h ftplugin and :h after-directory

All together:

augroup CBuild
  autocmd!
  autocmd filetype c   nnoremap <buffer> <leader>cc :!gcc -o %:p:r %<cr>
  autocmd filetype c   nnoremap <buffer> <leader>cr :!gcc -o %:p:r %<cr>:!%:p:r<cr>
  autocmd filetype cpp nnoremap <buffer> <leader>cc :!g++ -o %:p:r %<cr>
  autocmd filetype cpp nnoremap <buffer> <leader>cr :!g++ -o %:p:r %<cr>:!%:p:r<cr>
augroup END
like image 93
Peter Rincker Avatar answered Mar 02 '26 06:03

Peter Rincker