0

I want the below function to return keybindings but all it returns is a string.

nmap <expr> <space>t ManageTerminal()

function ManageTerminal()
  if bufname('terminal') ==# 'terminal'
    if expand('%:t') ==# "terminal" 
      return '<C-\><C-N><C-w>q'
    else
      return ':sb terminal<CR>:resize -6<CR>i'
    endif
  else
    return ':split<CR>:resize -6<CR>:te<CR>:file terminal<CR>i'
  endif
endfunction

This works just fine.

nmap <expr> <space>t bufname('terminal') ==# 'terminal' ? (expand('%:t') ==# "terminal" ? '<C-\><C-N><C-w>q' : ':sb terminal<CR>:resize -6<CR>i') : ':split<CR>:resize -6<CR>:te<CR>:file terminal<CR>i'

But it is messy. So how do I return keybindings from a function?

5
  • What do you mean by "return keybindings"? Is the <space> t mapping supposed to run one of the commands that you're returning as strings? Why not just call the function and have the function run the appropriate command? – B Layer Jan 9 at 12:48
  • If, on the other hand, you're trying to dynamically create a mapping just do the entire thing in the function (nmap ....etc etc) . It doesn't seem worthwhile to make it happen in two places. Or, I suppose, you could build a string that contains the whole mapping (return "nmap ... etc etc") and do :exe ManageTerminal() or something like that. – B Layer Jan 9 at 12:50
  • Thank you for your time @BLayer. But I found out that this question has a pretty dumb answer. I assumed single quote and double quotes were the same thing in vimscript. But that turned out to be incorrect. return '<C-\><C-N><C-w>q' would just return it as a plain string with no meaning. Whereas what I wanted is return "\<C-\>\<C-N>\<C-w>q". This is what I meant by return keybinding – Akash Karnatak Jan 9 at 13:23
  • 1
    Okay. Glad you figured out what you wanted to figure out. However, I'd still recommend you try doing things more directly rather than in such a roundabout way. Cheers. – B Layer Jan 9 at 14:02
2

As the OP noted and can be found in What's the functional difference between the key notations "\<xxx>" and '<xxx>'?, we need :help expr-quote here:

" note that I prefer nnoremap
nnoremap <expr> <space>t ManageTerminal()

function ManageTerminal()
  if bufname('terminal') ==# 'terminal'
    if expand('%:t') ==# "terminal" 
      return "\<C-\>\<C-N>\<C-w>q"
    else
      return ":sbuffer terminal\<CR>:resize -6\<CR>i"
    endif
  else
    return ":split\<CR>:resize -6\<CR>:terminal\<CR>:file terminal\<CR>i"
  endif
endfunction

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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