Search code examples
vimexecution

Vim new window for program execution, similar to cwindow


I am using Vim to edit/compile individual cpp files (makepgr=g++\ -g\ %) and want to execute the resulting binaries ideally using a shortkey like F6. The desired behavior is then, to open a new window similar to :cwindow with a fixed maximal height (say 20 lines), which contains the program output. I also want to be able to close this window again with another shortkey like F7.

As a bonus, it would be great to have the execution time of the program shown in the windows title/status.

EDIT: the binaries I am talking about are non-interactive! They mostly read some input files, do data manipulation, write their results to other files and have some output while doing so.


Solution

  • This little script should do the trick:

    let s:title="ProgramOutput"
    
    function! Open_output_window()
        let winnr = bufwinnr(s:title)
        if winnr != -1
            exe winnr . 'wincmd w'
            return
        endif
    
        let bufnr = bufnr(s:title)
        if(bufnr == -1)
            let wcmd = s:title
        else
            let wcmd = '+buffer' . bufnr
        endif
    
        exe 'silent! botright vertical 80 split ' .wcmd
    
        silent! setlocal buftype=nofile
        silent! setlocal noswapfile
        silent! setlocal nobuflisted
    endfunction
    
    function! Close_output_window()
        let winnr = bufwinnr(s:title)
        if winnr != -1
            exe winnr . 'wincmd w'
            close
        endif
    endfunction
    
    nmap <F6> <ESC>:call Open_output_window()<CR>:r ! %:r.exe<CR>
    nmap <F5> <ESC>:call Close_output_window()<CR>
    

    Most of this code came from the taglist.vim plugin - it's reasonably simple to understand. You can modify the split command for your window size preferences.