The context

I've the following mapping in ~/.vim/ftplugin/cpp/mappings.vim. What this mapping does is to compile an arbitrary C++ file and open two windows (a) and (b). (a) shows the output of the compiler and (b) shows the output of executing the resulting binary file.

01| fun! MyCPPFunction()
02|     sil wa
04|     let l:file = expand("%")
06|     exe "term g++ -Wunused-variable " . l:file
07|     exe "term ./a.out"
08| endfun
10| nnoremap <silent> <buffer> <c-p> :call MyCPPFunction()<CR>

There is no problem with this approach but I would like to make the buffer, which shows the compiler output, to be closed or not be opened if it is empty since opening an empty buffer is a nuisance.


  • If line 6 were to create an empty buffer (implies no errors and no warnings from the compiler), then close it or don't open it and execute line 7.
  • If line 6 were to create a nonempty buffer (implies errors or warnings from the compiler), then don't execute line 7.

Because of this, it is demandatory that line 6 finishes in order to execute command from line 7. However, line 7 is executed without waiting for line 6 to finish.

The question

So my question is: How can I implement this feature to my function? I'm currently reading the documentation on functions related to the :term command (term_start(), job_start()), but I haven't found something that might help me accomplish this.

Note that this would be easily accomplished if we were able to specify which function to execute once the job on a terminal buffer has finished. Thus, we would need to pass the number of lines in the current buffer, and execute the binary file if the number of lines equals 0.

PD1: I wrote the function using the term command because thus the output of both the compiler (line 6) and my program (line 7) is opened in a vim buffer which implies that I have all features that can be performed on a buffer (diff, regex search, copy, make changes, etc.)

  • 1
    Check :h exit_cb.
    – dedowsdi
    Commented May 25, 2020 at 6:22
  • You should probably use :make to build your program, not :term
    – Matt
    Commented May 25, 2020 at 8:02


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.