let s:plugin_root = expand(':p:h:h') let s:complete_py = s:plugin_root . "/py/complete.py" let s:chat_py = s:plugin_root . "/py/chat.py" let s:debug = 0 function! ScratchWindow() below new setlocal buftype=nofile setlocal bufhidden=hide setlocal noswapfile endfunction function! AIRun(...) range let lines = trim(join(getline(a:firstline, a:lastline), "\n")) let selection = trim(@*) let is_selection = lines != "" && lines == selection let has_instruction = a:0 let prompt = "" if has_instruction if is_selection let prompt = a:1 . ":\n" . lines else let prompt = a:1 endif else let prompt = lines endif if s:debug echo prompt endif echo "Completing..." let output = system("echo " . shellescape(prompt) . " | python3 " . s:complete_py . " ") let output = trim(output) execute "normal! " . a:lastline . "G" set paste execute "normal! o" . output . "\" set nopaste execute "normal! " . a:lastline . "G" endfunction function! AIEditRun(...) range let has_instruction = a:0 let prompt = trim(join(getline(a:firstline, a:lastline), "\n")) if has_instruction let prompt = a:1 . ":\n" . prompt endif let buff_lastline = line('$') if s:debug echo prompt endif echo "Editing..." let output = system("echo " . shellescape(prompt) . " | python3 " . s:complete_py . " ") let output = trim(output) execute a:firstline . ',' . a:lastline . 'd' set paste if a:lastline == buff_lastline execute "normal! o" . output . "\" else execute "normal! O" . output . "\" endif set nopaste endfunction function! AIChatRun(...) range let lines = trim(join(getline(a:firstline, a:lastline), "\n")) let selection = trim(@*) let is_selection = lines != "" && lines == selection let has_instruction = a:0 let prompt = "" if search('^>>> user$', 'nw') != 0 " inside chat window let prompt = trim(join(getline(1, '$'), "\n")) else " outside chat window call ScratchWindow() if has_instruction if is_selection let prompt = a:1 . ":\n" . lines else let prompt = a:1 endif else if is_selection let prompt = lines else execute "normal i>>> user\\" return endif endif endif if s:debug echo prompt endif echo "Answering..." let output = system("echo " . shellescape(prompt) . " | python3 " . s:chat_py . " ") set paste execute "normal! ggdG" execute "normal! i" . output . "\" set nopaste endfunction command! -range -nargs=? AI ,call AIRun() command! -range -nargs=? AIEdit ,call AIEditRun() command! -range -nargs=? AIChat ,call AIChatRun()