I'd like to set some file-type dependent mappings to quickly run files. For example, I have some mappings like these:

nnoremap <silent><leader>z :w<CR> :!clear; gcc %; ./a.out<cr>
nnoremap <silent><leader>z :w<CR> :!clear; g++ %; ./a.out<cr>
nnoremap <silent><leader>z :w<CR> :!clear; ruby %<cr>

How can I set each mapping to its corresponding file type?


You can use the FileType autocmd.

autocmd FileType c    nnoremap <buffer><silent><leader>z :w<CR> :!clear; gcc %; ./a.out<cr>
autocmd FileType cpp  nnoremap <buffer><silent><leader>z :w<CR> :!clear; g++ %; ./a.out<cr>
autocmd FileType ruby nnoremap <buffer><silent><leader>z :w<CR> :!clear; ruby %<cr>

See :h autocmd and :h FileType for more info.

  • So for a set of mappings for C, would I need to prefix every line with autocmd FileType C or is there a check I can do with has() or something similar? – Bruno Ely Apr 21 '19 at 2:25
  • FileType C will trigger for any files ending in .c So yeah, that should work for your C files. You might add H as well. – Tumbler41 Apr 22 '19 at 4:29
  • 1
    Note the use of <buffer> - this is critical for getting it to work or the last one set (in this case ruby) will apply to all file types. – Biggsy Jul 28 '19 at 14:08
  • Of course, other types of mapping (e.g. map instead of nnnoremap) and other commands can be used; for example, I use: au FileType python map <buffer><F6> :vert res 85<CR> and au FileType fortran map <buffer><F6> :vert res 138<CR> – Biggsy Jul 28 '19 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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