neovimspacevim

Neovim: sending output of a terminal into a split window with focus


I'm trying to create a function that run some commands in terminal and I want it to show the output of terminal in a new split window. I'm using Neovim, (and spacevim).

function Gpt(prompt)
  " Get the full path of the current buffer
  let file = expand('%:p')
  " Open a vertical split with a terminal
  split new
  wincmd k  " Focus the newly opened window
  setlocal nobuflisted
  " setlocal bufhidden=wipe
  setlocal noswapfile
  call termopen('echo ' . a:prompt . ' | cat - ' . file . ' | tgpt')
  startinsert
endfunction

the problem is the window that has the output will be immediately closed if you press any keys! unless you click on it with your mouse.

UPDATE with stopinsert instead of startinsert, the problem will be solved temporarily, but if I try to go back to the terminal buffer again, it will be closed.


Solution

  • Using system() instead of termopen() make us to store our output inside a variable. later with the use of call setline(1, split(trim(output), "\n")) I can put the value of my variable into the current buffer(that I created newly using split new). problem solved and now it's fully functional.

    function Gpt(prompt)
      " Get the full path of the current buffer
      let file = expand('%:p')
      split new
      resize 12  " Adjust the window height to 10 lines
      setlocal nobuflisted
      setlocal bufhidden=wipe
      setlocal buftype=nofile
      setlocal noswapfile
      setlocal filetype=markdown
      setlocal wrap               " Enable line wrapping
      syntax on
      let output = system('echo "' . a:prompt . '" | cat - ' . file . ' | tgpt')
      let charsToRemove = ['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷', '
    ', "  Loading"]
      for theChar in charsToRemove
        let output = substitute(output, theChar, '', 'g')
      endfor
    
      call setline(1, split(trim(output), "\n"))
      stopinsert
    endfunction