Home  >  Q&A  >  body text

vimrc - How does vim map keys based on the file extension?

For example, when editing the .cpp file, you want to map <F5> to :call CompileCpp()<CR>.
When compiling the .html file, I want to map <F5> to :call RunHtml()<CR><Spcae>.
Can this be done?

某草草某草草2712 days ago588

reply all(1)I'll reply

  • 世界只因有你

    世界只因有你2017-05-16 16:38:29

    Probably use this

    autocmd FileType vim  call RunHtml()

    But it is recommended to set makeprg when using autocmd FileType, and then just make directly when using F5. This will display the error message to quickfix
    This is the other language I set

    
    augroup make_autocmd
        autocmd Filetype javascript setlocal makeprg=jsl\ -nologo\ -nofilelisting\ -nosummary\ -nocontext\ -conf\ /etc/jsl.conf\ -process\ %
        autocmd FileType json setlocal makeprg=
        autocmd FileType php
                    \ setlocal makeprg=php\ -l\ -n\ -d\ html_errors=off\ % |
                    \ setlocal errorformat=%m\ in\ %f\ on\ line\ %l
        autocmd BufWritePost * call Make()
        " auto close quickfix if it is the last window
        autocmd WinEnter * if winnr('$') == 1 && getbufvar(winbufnr(winnr()), "&buftype") == "quickfix" | quit | endif
    augroup END
    
    function! Make()
        if &modified | silent write | endif
        if &makeprg == 'make' | return | endif
        let regname = '"~'
        let old_pos = getpos('.')
        silent make
        execute 'cw'
        if !has('gui_running') | redraw! | end
        call setpos('.', old_pos)
    endfunction
    

    reply
    0
  • Cancelreply