1

I'm new to vimscript and writing a function to toggle a terminal buffer. Here is what I tried:

let g:toggle_term = "<C-j>"

let g:term_buf_nr = -1
function! ToggleTerminal()
    if g:term_buf_nr == -1
        execute "bot term"
        let g:term_buf_nr = bufnr("$")
    else
        execute "bd! " .g:term_buf_nr
        let g:term_buf_nr = -1
    endif
endfunction

execute "nnoremap ".g:toggle_term ." :call ToggleTerminal()<CR>"

The function works fine and toggles the terminal buffer only in case the terminal buffer itself is not focused. If it is focused then pressing the g:toggle_term combination does nothing.

Is there a way make g:toggle_term to toggle terminal even if the terminal buffer is currently focused?

  • 2
    Don't you need to also create a tnoremap to have the mapping executed? :h :tnoremap – statox Nov 12 '19 at 17:19
  • @statox Not sure, because this will send a command to the terminal itself. – St.Antario Nov 12 '19 at 17:45
  • 1
    "Not sure" then read :h Terminal-Job. nnoremap only applies in Terminal-Normal mode. – Matt Nov 12 '19 at 19:13
  • @Matt There is no such manual entry. Did you mean Terminal-mode? – St.Antario Nov 13 '19 at 6:39
  • @Matt execute "tnoremap ".g:toggle_term ." exit<CR> :call ToggleTerminal<CR>" does not really call the function. – St.Antario Nov 13 '19 at 6:53
1

As @statox suggested in comments I should have used tnoremap to implement it. The following works fine:

execute "tnoremap ".g:toggle_term ." <C-w>:call ToggleTerminal()<CR>"

The mistake I initially made was the space right after the N

execute "tnoremap ".g:toggle_term ." <C-w>N :call ToggleTerminal()<CR>"

and since I rebound leader to <space> it did not work the way I wanted.

Also, the declaration

let g:term_buf_nr = -1

should be script private and replaced with

let s:term_buf_nr = -1
  • 1
    No need N, there is :h ctrl-w_: – dedowsdi Nov 13 '19 at 8:24
  • @dedowsdi Could you please expand? There is a manual entry specifying that C-w N is the combination to switch to a normal mode. :h terminal-use – St.Antario Nov 13 '19 at 8:29
  • 1
    :h ctrl-w_: is a valid command in vim, execute it, you should see everything. – dedowsdi Nov 13 '19 at 8:30
  • @dedowsdi Really, thanks. – St.Antario Nov 13 '19 at 8:40

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.