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?

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

1 Answer 1

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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