3

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?

1 Answer 1

4

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.

4
  • 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?
    – sleighty
    Commented Apr 21, 2019 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
    Commented Apr 22, 2019 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
    Commented Jul 28, 2019 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
    Commented Jul 28, 2019 at 14:08

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.