简体   繁体   中英

Vim key mapping mismatch

I code in ruby and python using vim, and my vimrc has a setting to enter breakpoints easily:

au FileType python  map <silent> <leader>b oimport ipdb; ipdb.set_trace()<esc>
au FileType python  map <silent> <leader>B Oimport ipdb; ipdb.set_trace()<esc>
au FileType ruby    map <silent> <leader>b orequire 'pry'; binding.pry<esc>
au FileType ruby    map <silent> <leader>B Orequire 'pry'; binding.pry<esc>

However, occasionally I get the wrong command, eg ipdb in a ruby file, and I have to restart vim. What could be the problem?

The problem is that you define your mappings globally.

The solution is simple : add the <buffer> argument to your mappings in order to make them "buffer-local".

au FileType python  map <buffer> <silent> <leader>b oimport ipdb; ipdb.set_trace()<esc>
au FileType python  map <buffer> <silent> <leader>B Oimport ipdb; ipdb.set_trace()<esc>
au FileType ruby    map <buffer> <silent> <leader>b orequire 'pry'; binding.pry<esc>
au FileType ruby    map <buffer> <silent> <leader>B Orequire 'pry'; binding.pry<esc>

See :help <buffer> .

Also:

  • You should use :nmap or :nnoremap instead of :map . Prefer :nnoremap .
  • You should wrap those lines in autocommand groups and reset them to prevent your autocommands to pile up when you re-source your vimrc :

     augroup python autocmd! autocmd FileType python nnoremap <buffer> <silent> <leader>b oimport ipdb; ipdb.set_trace()<esc> autocmd FileType python nnoremap <buffer> <silent> <leader>B Oimport ipdb; ipdb.set_trace()<esc> augroup END augroup ruby autocmd! autocmd FileType ruby nnoremap <buffer> <silent> <leader>b orequire 'pry'; binding.pry<esc> autocmd FileType ruby nnoremap <buffer> <silent> <leader>B Orequire 'pry'; binding.pry<esc> augroup END 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM