I've implemented the vimscript code below to fix the issues with the escape sequences generated by my terminal emulator for the Ctrl + Arrow, Shift + Arrow, and Ctrl + Shift + Arrow keypresses; all these keypresses create issues on their own, so it's usually best to fix them all in one fell swoop.
Here's the vimscript code from my ~/.vimrc
:
" Just a temporary shorthand
function! NoRemapNXIC(lhs, rhs_nxi, rhs_c = v:null)
execute "nnoremap " .. a:lhs .. " " .. a:rhs_nxi
execute "xnoremap " .. a:lhs .. " " .. a:rhs_nxi
execute "inoremap " .. a:lhs .. " <C-O>" .. a:rhs_nxi
if a:rhs_c isnot v:null
execute "cnoremap " .. a:lhs .. " " .. a:rhs_c
endif
endfunction
" Make navigating through long lines easy
call NoRemapNXIC("<Up>", "gk")
call NoRemapNXIC("<Down>", "gj")
call NoRemapNXIC("<C-Left>", "b")
call NoRemapNXIC("<C-Right>", "e")
call NoRemapNXIC("<S-Left>", "B")
call NoRemapNXIC("<S-Right>", "E")
" Handle <Ctrl> + <Arrow> escape sequences
call NoRemapNXIC("<ESC>[1;5A", "gk", "<Nop>")
call NoRemapNXIC("<ESC>[1;5B", "gj", "<Nop>")
call NoRemapNXIC("<ESC>[1;5D", "b", "<C-Left>")
call NoRemapNXIC("<ESC>[1;5C", "e", "<C-Right>")
" Handle <Shift> + <Arrow> escape sequences
call NoRemapNXIC("<ESC>[1;2A", "<PageUp>", "<Nop>")
call NoRemapNXIC("<ESC>[1;2B", "<PageDown>", "<Nop>")
call NoRemapNXIC("<ESC>[1;2D", "B", "<S-Left>")
call NoRemapNXIC("<ESC>[1;2C", "E", "<S-Right>")
" Handle <Ctrl> + <Shift> + <Arrow> escape sequences
call NoRemapNXIC("<ESC>[1;6D", "ge", "<C-Left>")
call NoRemapNXIC("<ESC>[1;6C", "w", "<C-Right>")
delfunction NoRemapNXIC
Of course, you'll need to check what escape sequences for those keypresses are actually generated by your particular terminal emulator, and adjust this vimscript code appropriately. It's already described how to check that in another answer, but you can also simply run cat(1)
in a separate terminal emulator window or tab, and see what are you getting back for those keypresses.
As you can see, I also remapped the actual cursor movement commands a bit, to use b
, e
, B
, E
, ge
and w
, which makes them more suitable to my own preferences. Of course, you can tailor those to your own needs.
Please note that remapping <Up>
and <Down>
to gk
and gj
, respectively, and remapping to gk
and gj
commands in other places isn't directly related to the OP's question, but I included those here as well for the sake of completeness, and simply because my ~/.vimrc
does it that way. Having those remaps as well might be a good idea, see this question and this answer for more details.
See also :h i_CTRL-O
in vim
's built-in help.