I am on Neovim, and have ToggleTerm installed. I would like to do

:nnoremap <leader><leader>r :ToggleTerm<cr>my_interpreter %<cr>

but this will just open ToggleTerm, and run my_interpreter %, which is of course wrong.

The filename isn't expanded, why is this not working?

  • I see a close vote this being "not about Vim". How's that? Even if we considered questions on plugins off-topic (IMHO, they're on-topic), the problem would be the same if OP used :terminal or :echo in their mapping.
    – Friedrich
    Commented Jun 28 at 10:21
  • I'm not sure how ToggleTerm works, but generally only some commands interpret % specially: :help cmdline-special
    – D. Ben Knoble
    Commented Jun 28 at 17:40

2 Answers 2


I would do:

:nnoremap <expr> <leader><leader>r ':ToggleTerm<cr>my_interpreter ' . expand('%') . '<cr>'

Or in lua:

vim.keymap.set('n', '<leader><leader>r', "':ToggleTerm<cr>my_interpreter ' . expand('%')", { expr=true })

If you are using and <expr> (expression) mapping the right hand side is not sent literally but considered as an expression and it is its evaluation that is sent.

More information with: :help map-<expr>

  • 1
    Thank you, this works as well - well, almost, there should be a space after "my_interpreter" :) Didn't know about expression mapping yet, time to git gud
    – CocoaNut
    Commented Jun 28 at 7:00

Ok, after more googling, I found that the following lua command works:

    function () 
        return ':ToggleTerm<cr>' .. 'my_interpreter ' .. vim.fn.expand("%") .. '<cr>' 
    { expr = true} 

Put this in your user specific init.lua, or do :lua the_command_from_above inside nvim.

See also the neovim docs on vim.keymap.set.

And as per Friedrich's request in the comments, something about how this works, or why it's equivalent to the other answer:

  • the 'n' means the mapped key works in normal mode, and vim.keymap.set is automatically nore
  • the anonymous function is called every time
  • and expr = true tells vim that this is a map-expression

But to be fair, I'm not entirely sure why this must be a function, and not a string. If I just use a string, then I get undefined variable ":ToggleTerm" 🤷‍♂️

  • 1
    @Friedrich expanded a bit
    – CocoaNut
    Commented Jun 28 at 7:21
  • "I'm not entirely sure why this must be a function, and not a string." - compare with Vivian's answer, he uses a string. The difference is that it's quoted twice. The outer string is executed as an expression and the command is a nested string within.
    – Friedrich
    Commented Jun 28 at 7:39

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.