vim如何根据文件的后缀名来进行按键的映射?

比如在编辑.cpp文件时,想把<F5>映射为 :call CompileCpp()<CR>.
在编译.html文件时,想把<F5>映射为:call RunHtml()<CR><Spcae>.
请问可以做到吗?

阅读 3.8k
1 个回答

大概使用这种

autocmd FileType vim  call RunHtml()

但是建议 autocmd FileType 时设置makeprg,然后F5的时候直接make就行了。这样可以显示错误消息到quickfix
这是我设置的其它语言的


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
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进