1

In the following nnoremap:

nnoremap <expr> <leader>3 ToggleColors()
func ToggleColors()
    if g:colors_name == "OceanicNext"
        return ":colorscheme TextMate"
    else
        return ":colorscheme OceanicNext"
endfunc

I am able to get the function to return the proper command to 'enter', however, I have to actually press return for it to run. If I try entering either:

nnoremap <expr> <leader>3 ToggleColors()<CR>

I get:

E15: Invalid expression: ToggleColors() ^M

Or if I try doing:

return ":colorscheme TextMate <CR>"

It enters a literal and doesn't actually hit enter:

What would be the proper way to 'hit enter' at the end of the mapping so I don't have to do it manually?

1
  • Maybe add <cr> to in the return value directly?
    – muru
    Jun 13, 2020 at 4:49

1 Answer 1

1

First, the key code can be input and written into a file directly.

So let foo = 'FooCtrl-VEnterBar' looks like let foo = 'Foo^MBar'

But usually people want their sources do not contain control codes. So some sort of run-time substitution is preferred.

To put key code into a string in runtime one normally needs a backslash:

let foo = "Foo\<CR>Bar"

Note double quotes to allow string preprocessing.

When it's a part of a :map command, the substitution is made while reading a command before expression evaluation, so backslash is not needed:

nnoremap <A-X> :xit<CR>

or

nnoremap <expr><A-X> ':xit<CR>'

does not make a big difference.

If you want to stop such early expansion use <lt>:

nnoremap <expr><A-X> ":xit\<lt>CR>"

This one produces the same result as the previous. The expression is first expanded into ":xit\<CR>" (while reading the command) and then into ':xit^M' (while executing mapping).

2
  • oh, awesome, that makes it easy just adding in the actual (control) characters itself, so ^M to simulate enter.
    – David542
    Jun 13, 2020 at 5:44
  • @David542 This is how mappings work: they are stored as real key codes. This is why you normally needs -nore- thing to disable recursive interpretation.
    – Matt
    Jun 13, 2020 at 5:48

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.