4

I have a variable with a "key" in vim notation, <C-j>. How can I use it in <expr> mapping?

let g:key = "<C-j>"
inoremap <expr> <C-j> '\' .. g:key

" inserts \<C-j> instead of newline

The mapping I get from redirecting imap and extracting the <C-j> out of it, so I can't use let g:key = "\<C-j>".

1
  • Edit: feedkeys() won't work because it also requires "\<C-j>"-style strings
    – D. Ben Knoble
    Feb 24, 2022 at 14:18

2 Answers 2

5

You don't need backslash in map command. Simply

let g:key = "\<C-j>"
inoremap <expr><C-j> g:key

UPD. It looks as if you want :h nvim_replace_termcodes() function available in Neovim. There's no direct counterpart in Vim, but you can write your own (incomplete?) implementation:

function! Replace_termcodes(str) abort
    return a:str->substitute('<', '\\<', 'g')->printf('"%s"')->eval()
endfunction
3
  • The example in the question is simplified version of what I have. Basically I have only <C-j> in a variable I parsed out from output of imap. And I want to reuse it as a fallback in my expr mapping.
    – Maxim Kim
    Feb 24, 2022 at 13:47
  • imagine you have got '<C-j>' as an input into SomeFunction(key) and that function is in <expr> mapping, returning some key sequences plus "\<C-j>"
    – Maxim Kim
    Feb 24, 2022 at 13:55
  • @MaximKim Actually it looks to me as a questionable design, but I updated my answer.
    – Matt
    Feb 24, 2022 at 14:49
0

You can try using the maparg() function:

:echo maparg("<C-j>", 'i', 0, 1)
{'lnum': 0, 'script': 0, 'mode': 'i', 'silent': 0, 'buffer': 0, 'noremap': 1, 'lhs': '<C-J>', 'lhsraw': '<80><fc>^DJ', 'nowait': 0, 'expr': 1, 'sid': 0, 'rhs': '"\<C-j>"', 'lhsrawalt': '
', 'scriptversion': 0}

You can use the 'rhs' item from the returned dictionary.

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.