1

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?

  • With an expr mapping/custom function, maybe, but what is it you want to accomplish in both cases? – D. Ben Knoble Jan 25 '18 at 22:47
4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.