Because I am used to autocompleting by pressing the return/enter key, I want to remap the return key to Ctrl-p in insert mode. However, I only want to remap it when the cursor is directly behind a letter (a-z).
Is this possible?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityBecause I am used to autocompleting by pressing the return/enter key, I want to remap the return key to Ctrl-p in insert mode. However, I only want to remap it when the cursor is directly behind a letter (a-z).
Is this possible?
Sure it is!
Try this expression mapping:
inoremap <expr> <CR> getline('.')[col('.') - 2] =~ '\a' ? "\<C-P>" : "\<CR>"
How this works:
getline('.')[col('.') - 2]
: This returns the character immediately before the cursor (i.e. the one you just typed).=~ '\a'
: This checks if the character is an alphabetic character a-z or A-Z? "\<C-P>" : "\<CR>"
: If the character is alphabetic then your keypress is mapped to <C-P>
. If not, it is mapped to <CR>
.For more details, see:
:help :map-expr
:help expr1
:help getline()
:help col()
:help \a