开发者

change from insert to normal mode when switching to another tab?

开发者 https://www.devze.com 2023-03-17 19:54 出处:网络
Say I have multiple tabs with multiple buffers in split screens. When I am in edit mode in one buffer and switch to another tab (ctrl-pageDown), I am still in insert mode.

Say I have multiple tabs with multiple buffers in split screens.

When I am in edit mode in one buffer and switch to another tab (ctrl-pageDown), I am still in insert mode.

Is there a way to automatically switch to normal mode when changing开发者_StackOverflow中文版 tabs ?

Even better, is it possible to return to insert mode when coming back to the original buffer ?


You could try adding something very simple like

autocmd TabEnter * stopinsert

to your .vimrc.


In BufLeave you could call a function which would check what mode you're in and set a buffer variable and then in BufEnter check if it exists and go to that mode.

See help on mode(), b:var.

Here is some sample stuff for .vimrc. Having written it just now for this purpose, I've started using it myself and I think it'll be useful.

au BufLeave * call ModeSelectBufLeave()
au BufEnter * call ModeSelectBufEnter()

function! ModeSelectBufLeave()
    let b:mode_select_mode = mode()
    " A more complex addition you could make: if mode() == v, V, <C-V>, s, S, or <C-S>, store the selection and restore it in ModeSelectBufEnter
endfunction

function! ModeSelectBufEnter()
    let l:mode = mode()
    stopinsert  " First, go into normal mode
    if (l:mode == "i" || l:mode == "R" || l:mode == "Rv") && 
    \       (!exists('b:mode_select_mode') ||
    \       b:mode_select_mode == "n" ||
    \       b:mode_select_mode == "v" ||
    \       b:mode_select_mode == "V" ||
    \       b:mode_select_mode == "\<C-V>" ||
    \       b:mode_select_mode == "s" ||
    \       b:mode_select_mode == "S" ||
    \       b:mode_select_mode == "\<C-S>")
        normal l
        " Compensate for the left cursor shift in stopinsert if going from an
        " insert mode to a normal mode
    endif
    if !exists('b:mode_select_mode')
        return
    elseif b:mode_select_mode == "i"
        startinsert
    elseif b:mode_select_mode == "R"
        startreplace
    elseif b:mode_select_mode == "Rv"
        startgreplace
    endif
endfunction


I have the following in my .vimrc:

nmap <C-b> :b#<CR>
imap <C-b> <ESC>:b#<CR>

This lets me hit Ctrl+b when in normal or insert mode to switch to the alternate buffer but leaving me in normal mode.

As for your question, you could do this:

imap <C-b> <ESC>:bnext<CR>i

This will let you hit Ctrl+b when in insert mode and switch to the next buffer putting you in insert mode when you get there.

If you find yourself switching back and forth between the same two buffers, my original mappings above may be more useful. Of course if you use all three, you'll need a different key combination for the last one.

0

精彩评论

暂无评论...
验证码 换一张
取 消