7

I know that in vim, map <expr> allows us to map a key sequence to a new sequence as specified by the return value of an expression. For example:

function Wrap()
    if getline('.') == ''
        " can I return a <Plug> here?
        return "Ends an empty line\<cr>"
    else
        return "\<cr>"
    endif
endfunction
inoremap <expr> <cr> Wrap()

In the expression, \<cr> means to return the <cr> key.

We can also have <Plug> maps like:

inoremap <Plug>empty "Ends an empty line\<cr>"
imap <cr> <Plug>empty

My question is: if I want to return the <Plug>empty map only when cursor is in an empty line like in the first example, what should I do?


As @Mass suggested, the solution is:

inoremap <Plug>empty "Ends an empty line\<cr>"
function Wrap()
    if getline('.') == ''
        return "\<Plug>empty"
    else
        return "\<cr>"
    endif
endfunction
imap <expr> <cr> Wrap()

The last line must use imap instead of inoremap.

1 Answer 1

6

Simply return "\<plug>empty" This is doing the same basic thing as "\<cr>", returning a string with special characters instead of literal < c r, > etc. Also ensure your <expr> map is not using noremap so vim uses the <Plug> remap. (See the last line in the solution below, using imap instead of inoremap.)

The solution is:

inoremap <Plug>empty "Ends an empty line\<cr>"
function Wrap()
    if getline('.') == ''
        return "\<Plug>empty"
    else
        return "\<cr>"
    endif
endfunction
imap <expr> <cr> Wrap()
1
  • 1
    thank you very much. I tried this previously and when I type <cr>, the literal \<plug>empty is obtained and then I come here to seek your help. Now I realized that it is because I have defined the map using inoremap instead of imap, which prevents the expansion of the <plug>. Changing to imap solved the problem.
    – doraemon
    Commented Sep 5, 2017 at 3:08

Your Answer

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

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