Change the mapping of F5 on the basis of specific file type

≯℡__Kan透↙ 提交于 2019-12-21 02:41:18

问题


The current mapping of my F5 key is:

imap <F5> <esc>:w\|!python %<CR>

Now I want that if I'm editing any python file (it will be better if it also recognizes file other than standard .py format like .pyd etc) then this mapping works as it is. But, if I edit a Java file it is mapped to something like:

imap <F5> <esc>:w\|!javac %<CR>

And when I'm editing any .c or .cpp file then F5 is mapped to this:

imap <F5> <esc>:w\|!make %<CR>

I have no idea how to proceed.


回答1:


There are problems with both given answer and original mapping. First of all, for buffer-local mappings there is *map <buffer>. Second, with <buffer> you don’t need to use BufEnter events and can instead use Filetype which are launched only once. Third, you have one error (2.), one potential problem (1.) and one place that can be optimized in original mappings:

  1. you should not be using imap, it makes it very easy to accidentally break old mappings when adding new ones
  2. !python % will break once file contain a special symbol (space, semicolon, quot, dollar, …)
  3. using :update instead of :write avoids useless writes in some cases

My variant:

autocmd Filetype c,cpp  inoremap <buffer> <F5> <C-o>:update<Bar>execute '!make '.shellescape(expand('%:r'), 1)<CR>
autocmd Filetype python inoremap <buffer> <F5> <C-o>:update<Bar>execute '!python '.shellescape(@%, 1)<CR>
autocmd Filetype java   inoremap <buffer> <F5> <C-o>:update<Bar>execute '!javac '.shellescape(@%, 1)<CR>



回答2:


Try this:

au BufEnter *.py map <F5> <esc>:w\|!python %<CR>
au BufEnter *.java imap <F5> <esc>:w\|!javac %<CR>
au BufEnter *.c, *.cpp imap <F5> <esc>:w\|!make %<CR>

I'm not 100% sure about the comma separated file types, trying to verify...

The vim docs are usually pretty nasty to try to figure out how to use commands, but these should help get you started:

:h BufEnter
:h :autocmd

Note: You may have to restart vim for these changes to overwrite the current autocommand groups.



来源:https://stackoverflow.com/questions/12030965/change-the-mapping-of-f5-on-the-basis-of-specific-file-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!