I can see that I've got a terminal buffer open by running :ls R which finds all buffers with a running terminal job, but I don't know how to capture just the buffer number.

The closest I can get is echo bufnr("cmd.exe") because the buffer name has the command the terminal is using. This isn't crossplatform though.

bufnr("R") doesn't seem to search the flags the same was :ls R does.

2 Answers 2

  1. By :h 'buftype'

    echo filter(map(getbufinfo(), 'v:val.bufnr'), 'getbufvar(v:val, "&buftype") is# "terminal"')
  2. By :h getwininfo()

     echo uniq(map(filter(getwininfo(), 'v:val.terminal'), 'v:val.bufnr'))
  • Thanks for these! Makes sense there isn't a builtin way to get a terminal buffer's number directly given how you can have so many Commented Jun 10, 2020 at 0:02
  • Which one would be faster? just curious...
    – codepoet
    Commented Jan 26, 2021 at 11:07

You can do this now directly using term_list():

echo term_list()

This was introduced by Bram in v8.0.0803 (commit c6df10e5d (patch 8.0.0804: terminal window functions not yet implemented, 2017-07-29), which misidentifies the patch; the tag and change are correct).

  • 2
    Welcome to Vi and Vim! Noting in which versions this is available would be useful; you can edit to add this information.
    – D. Ben Knoble
    Commented Apr 28 at 23:44
  • @D.BenKnoble I couldn't find an explicit mention of term_list() in any changelog, so it might actually have been introduced together with all the other terminal functions in 8.1
    – DaviD.
    Commented Apr 30 at 12:24
  • 1
    Using git log -S term_list gave me v8.0.0803 (which the commit wrongly identifies as 8.0.0804; the patch number is correct in the changes, though).
    – D. Ben Knoble
    Commented Apr 30 at 21:32

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.