Search code examples
vimvim-plugin

load external command in the same split after repeating it


I want to load some text coming from a command line command into a new vim split. I got this working but if I run the command again it keeps opening new splits.

What I want to achieve is getting this into the same split. How can I do this?

nnoremap <leader>q :execute 'new <bar> 0read ! bq query --dry_run --use_legacy_sql=false < ' expand('%')<cr> 

Solution

  • I would suggest using the preview window via the :pedit command.

    nnoremap <leader>q :execute 'pedit <bar> wincmd p <bar> 0read ! bq query --dry_run --use_legacy_sql=false < ' expand('%')<cr>
    

    However we can do even better by doing the following:

    • Making a "query" operator using g@ and 'opfunc'
    • A query command (feels very vim-like to do so)
    • Using stdin instead of a filename

    Example:

    function! s:query(str)
        pedit [query]
        wincmd p
        setlocal buftype=nofile
        setlocal bufhidden=wipe
        setlocal noswapfile
        %delete _
        call setline(1, systemlist('awk 1', a:str))
    endfunction
    
    function! s:query_op(type, ...)
        let selection = &selection
        let &selection = 'inclusive'
        let reg = @@
    
        if a:0
            normal! gvy
        elseif a:type == 'line'
            normal! '[V']y
        else
            normal! `[v`]y
        endif
    
        call s:query(@@)
    
        let &selection = selection
        let @@ = reg
    endfunction
    
    command! -range=% Query call s:query(join(getline(<line1>, <line2>), "\n"))
    nnoremap \qq :.,.+<c-r>=v:count<cr>Query<cr>
    nnoremap \q :set opfunc=<SID>query_op<cr>g@
    xnoremap \q :<c-u>call <SID>query_op(visualmode(), 1)<cr>
    

    Note: I am using awk 1 as my "query" command. Change to meet your needs.

    For more help see:

    :h :pedit
    :h :windcmd
    :h operator
    :h g@
    :h 'opfunc'
    :h systemlist()