Is it possible to send the contents of a buffer to a running terminal window. That window can be running e.g a REPL for python code.
I mean the new terminal feature of VIM rather than external plugins or previous versions.
Is it possible to send the contents of a buffer to a running terminal window. That window can be running e.g a REPL for python code.
I mean the new terminal feature of VIM rather than external plugins or previous versions.
You can use term_sendkeys()
to send data to a terminal buffer. However there are some considerations:
term_sendkeys()
often this is via yanking textHere is some code simplify and automate the send to terminal buffer workflow. Put inside vimrc
file or make a small plugin.
augroup send_to_term
autocmd!
autocmd TerminalOpen * if &buftype ==# 'terminal' |
\ let t:send_to_term = +expand('<abuf>') |
\ endif
augroup END
function! s:op(type, ...)
let [sel, rv, rt] = [&selection, @@, getregtype('"')]
let &selection = "inclusive"
if a:0
silent exe "normal! `<" . a:type . "`>y"
elseif a:type == 'line'
silent exe "normal! '[V']y"
elseif a:type == 'block'
silent exe "normal! `[\<C-V>`]y"
else
silent exe "normal! `[v`]y"
endif
call s:send_to_term(@@)
let &selection = sel
call setreg('"', rv, rt)
endfunction
function! s:send_to_term(keys)
let bufnr = get(t:, 'send_to_term', 0)
if bufnr > 0 && bufexists(bufnr) && getbufvar(bufnr, '&buftype') ==# 'terminal'
let keys = substitute(a:keys, '\n$', '', '')
call term_sendkeys(bufnr, keys . "\<cr>")
echo "Sent " . len(keys) . " chars -> " . bufname(bufnr)
else
echom "Error: No terminal"
endif
endfunction
command! -range -bar SendToTerm call s:send_to_term(join(getline(<line1>, <line2>), "\n"))
nmap <script> <Plug>(send-to-term-line) :<c-u>SendToTerm<cr>
nmap <script> <Plug>(send-to-term) :<c-u>set opfunc=<SID>op<cr>g@
xmap <script> <Plug>(send-to-term) :<c-u>call <SID>op(visualmode(), 1)<cr>
You can make setup your own mappings. Example:
nmap yrr <Plug>(send-to-term-line)
nmap yr <Plug>(send-to-term)
xmap R <Plug>(send-to-term)
You can now use :[range]SendToTerm
to send a [range]
of lines to the last used terminal buffer in a tab-page. You can also use yrr
to send a line, yr{motion}
to send a {motion}
text, or use R
to send visually selected text to the terminal buffer. Note: You must have a terminal buffer opened beforehand in the current tab-page.