" autoload/deepseek_fim.vim -- async DeepSeek FIM completion engine. " The UI entry points (commands, autocmds, options) live in " plugin/deepseek_fim.vim; all logic lives here. if exists('g:loaded_deepseek_fim_autoload') finish endif let g:loaded_deepseek_fim_autoload = 1 let s:job = v:null let s:req_id = 0 let s:startcol = 0 let s:timer = -1 let s:restart_timer = -1 let s:enabled = 0 let s:root = expand(':p:h:h') let s:ghost_text = '' let s:ghost_win = -1 let s:ghost_row = -1 let s:ghost_col = -1 " --- public helpers ------------------------------------------------- function! deepseek_fim#version() abort return '1.0.0' endfunction function! deepseek_fim#is_enabled() abort return s:enabled endfunction function! deepseek_fim#is_running() abort return type(s:job) != v:t_none && s:job isnot v:null \ && job_status(s:job) ==# 'run' endfunction " --- setup ---------------------------------------------------------- function! s:backend_cmd() abort let l:cfg = get(g:, 'deepseek_fim_bin', '') if !empty(l:cfg) return split(l:cfg, ' ') + ['--stdio'] endif let l:c = s:root . '/bin/ds_fim' if executable(l:c) return [l:c, '--stdio'] endif let l:py = s:root . '/src/ds_fim.py' if filereadable(l:py) && executable('python3') return ['python3', l:py, '--stdio'] endif return [] endfunction function! deepseek_fim#enable() abort if s:enabled && deepseek_fim#is_running() return 1 endif let s:enabled = 1 if !deepseek_fim#is_running() if !deepseek_fim#start_backend() let s:enabled = 0 return 0 endif endif call deepseek_fim#maybe_attach() return 1 endfunction function! deepseek_fim#disable() abort let s:enabled = 0 call deepseek_fim#stop() endfunction function! deepseek_fim#restart() abort call deepseek_fim#stop() if s:enabled call deepseek_fim#start_backend() endif endfunction function! deepseek_fim#maybe_autostart() abort if get(g:, 'deepseek_fim_enabled', 1) call deepseek_fim#enable() endif endfunction " Set buffer-local completefunc unless the user already set one. function! deepseek_fim#maybe_attach() abort if s:enabled && empty(&completefunc) setlocal completefunc=deepseek_fim#complete endif endfunction function! deepseek_fim#start_backend() abort if deepseek_fim#is_running() return 1 endif let l:cmd = s:backend_cmd() if empty(l:cmd) echohl WarningMsg echom 'deepseek_fim: no backend found (build with "make" first)' echohl None return 0 endif try let s:job = job_start(l:cmd, { \ 'out_cb': function('deepseek_fim#on_stdout'), \ 'err_cb': function('deepseek_fim#on_stderr'), \ 'exit_cb': function('deepseek_fim#on_exit'), \ 'noblock': 1, \ }) catch echohl WarningMsg echom 'deepseek_fim: cannot start backend: ' . v:exception echohl None let s:job = v:null return 0 endtry if job_status(s:job) !=# 'run' let s:job = v:null return 0 endif return 1 endfunction function! deepseek_fim#stop() abort if s:timer != -1 call timer_stop(s:timer) let s:timer = -1 endif if s:restart_timer != -1 call timer_stop(s:restart_timer) let s:restart_timer = -1 endif call deepseek_fim#hide_ghost() if type(s:job) != v:t_none && s:job isnot v:null try call job_stop(s:job) catch endtry endif let s:job = v:null endfunction " --- completefunc protocol ------------------------------------------ " findstart=1 -> return keyword start column (0-based). " findstart=0 -> kick off the async request, return v:none so Vim shows " no "no matches" warning; results arrive via complete() in on_stdout. function! deepseek_fim#complete(findstart, base) abort if a:findstart let l:line = getline('.') let l:col = col('.') - 1 while l:col > 0 && l:line[l:col - 1] =~# '\k' let l:col -= 1 endwhile let s:startcol = l:col return l:col endif call deepseek_fim#schedule() return v:none endfunction " --- debounce + request --------------------------------------------- function! deepseek_fim#schedule() abort if !s:enabled return endif call deepseek_fim#hide_ghost() if s:timer != -1 call timer_stop(s:timer) endif let s:timer = timer_start( \ get(g:, 'deepseek_fim_debounce_ms', 250), \ function('deepseek_fim#fire')) endfunction function! deepseek_fim#on_insert_change() abort if !s:enabled || mode() !=# 'i' return endif " No keyword gate here: FIM also completes mid-line (after '(', " '.', whitespace, ...). The min_len gate on the full prefix lives in " deepseek_fim#fire(). call deepseek_fim#schedule() endfunction " Manual trigger (command DeepseekFimComplete): bypass the debounce timer. function! deepseek_fim#request_now() abort if !s:enabled && !deepseek_fim#enable() return endif if s:timer != -1 call timer_stop(s:timer) let s:timer = -1 endif call deepseek_fim#fire(-1) endfunction " Build {prefix, suffix} context around the cursor, bounded so no " request grows without limit. function! s:context() abort let l:max = get(g:, 'deepseek_fim_context_chars', 4000) let l:row = line('.') let l:col = col('.') let l:cur = getline('.') let l:before = l:col > 1 ? l:cur[:l:col - 2] : '' let l:after = l:cur[l:col - 1:] let l:heads = l:row > 1 ? getline(1, l:row - 1) : [] let l:tails = l:row < line('$') ? getline(l:row + 1, line('$')) : [] let l:prefix = join(l:heads, "\n") if !empty(l:prefix) && !empty(l:before) let l:prefix .= "\n" . l:before else let l:prefix .= l:before endif let l:suffix = l:after if !empty(l:tails) let l:suffix .= "\n" . join(l:tails, "\n") endif if len(l:prefix) > l:max let l:prefix = l:prefix[len(l:prefix) - l:max:] endif if len(l:suffix) > l:max let l:suffix = l:suffix[:l:max - 1] endif return [l:prefix, l:suffix] endfunction function! deepseek_fim#fire(timer) abort let s:timer = -1 if !s:enabled || mode() !=# 'i' return endif if !deepseek_fim#is_running() if !deepseek_fim#start_backend() return endif endif let [l:prefix, l:suffix] = s:context() if len(l:prefix) < get(g:, 'deepseek_fim_min_len', 2) return endif let s:req_id += 1 let s:startcol = col('.') - 1 let l:req = {'id': s:req_id, 'prefix': l:prefix, 'suffix': l:suffix} try call ch_sendraw(job_getchannel(s:job), json_encode(l:req) . "\n") catch echohl WarningMsg echom 'deepseek_fim: cannot send request: ' . v:exception echohl None endtry endfunction " --- backend callbacks ---------------------------------------------- function! s:handle_line(line) abort if empty(a:line) return endif try let l:resp = json_decode(a:line) catch return endtry if type(l:resp) != v:t_dict || get(l:resp, 'id', -1) != s:req_id return endif if !get(l:resp, 'ok', 0) echohl WarningMsg echom 'deepseek_fim: ' . get(l:resp, 'error', 'unknown error') echohl None return endif let l:text = get(l:resp, 'text', '') if empty(l:text) || mode() !=# 'i' return endif if get(g:, 'deepseek_fim_ghost', 1) call s:show_ghost(l:text) return endif let l:first = split(l:text, "\n")[0] let l:item = { \ 'word': l:text, \ 'abbr': l:first[:80], \ 'menu': '[DeepSeek]', \ 'info': l:text, \ 'kind': 'v', \ 'dup': 1, \ } call complete(s:startcol + 1, [l:item]) endfunction " --- ghost text (inline grijze voorspelling) -------------------------- " Vim 9.0 heeft geen virt_text, dus tonen we de suggestie als popup " direct achter de cursor. Tab voert hem in. function! deepseek_fim#has_ghost() abort return !empty(s:ghost_text) && s:ghost_win != -1 \ && !empty(popup_getpos(s:ghost_win)) endfunction function! deepseek_fim#get_ghost() abort return s:ghost_text endfunction function! deepseek_fim#hide_ghost() abort let s:ghost_text = '' let s:ghost_row = -1 let s:ghost_col = -1 if s:ghost_win != -1 try call popup_close(s:ghost_win) catch endtry let s:ghost_win = -1 endif endfunction function! deepseek_fim#dismiss() abort let s:req_id += 1 call deepseek_fim#hide_ghost() endfunction function! s:show_ghost(text) abort call deepseek_fim#hide_ghost() if mode() !=# 'i' || empty(a:text) return endif let s:ghost_text = a:text let s:ghost_row = line('.') let s:ghost_col = col('.') let l:lines = split(a:text, "\n", 1) let l:maxlines = get(g:, 'deepseek_fim_ghost_maxlines', 5) if len(l:lines) > l:maxlines let l:lines = l:lines[:l:maxlines - 1] + ['...'] endif let l:maxw = &columns - s:ghost_col - 2 if l:maxw < 20 let l:maxw = 20 endif let l:shown = [] for l:ln in l:lines if len(l:ln) > l:maxw call add(l:shown, l:ln[:l:maxw - 1] . '...') else call add(l:shown, l:ln) endif endfor try let s:ghost_win = popup_create(l:shown, { \ 'line': 'cursor', \ 'col': 'cursor', \ 'pos': 'topleft', \ 'wrap': 0, \ 'highlight': 'DeepseekFimGhost', \ 'padding': [0, 0, 0, 0], \ 'border': [], \ 'maxheight': l:maxlines + 1, \ 'zindex': 40, \ }) catch let s:ghost_win = -1 return endtry endfunction " Voer de grijze voorspelling in op de cursorpositie van het verzoek. " Aangeroepen via (zie tab()): draait als commando zonder " moduswissel, dus setline()/cursor() zijn toegestaan. Direct aanroepen " vanuit een -mapping zou E565 geven. function! deepseek_fim#accept() abort if empty(s:ghost_text) return 0 endif let l:text = s:ghost_text let l:row = s:ghost_row let l:col = s:ghost_col call deepseek_fim#hide_ghost() let s:req_id += 1 return deepseek_fim#insert_at(l:row, l:col, l:text) endfunction " Pure invoeghulp (ook headless te testen): zet {text} op {row},{col}, " cursor erachter. Ghost bestaat alleen in insert-mode (show_ghost eist " 'i', InsertLeave wist), dus is hier geen moduscheck nodig. function! deepseek_fim#insert_at(row, col, text) abort if a:row < 1 || a:row > line('$') || a:col < 1 return 0 endif let l:cur = getline(a:row) let l:before = a:col > 1 ? l:cur[:a:col - 2] : '' let l:after = l:cur[a:col - 1:] let l:parts = split(a:text, "\n", 1) if len(l:parts) == 1 call setline(a:row, l:before . l:parts[0] . l:after) call s:place_cursor(a:row, len(l:before . l:parts[0]) + 1) else call setline(a:row, l:before . l:parts[0]) let l:lnum = a:row for l:i in range(1, len(l:parts) - 2) call append(l:lnum, l:parts[l:i]) let l:lnum += 1 endfor call append(l:lnum, l:parts[-1] . l:after) call s:place_cursor(l:lnum + 1, len(l:parts[-1]) + 1) endif return 1 endfunction " Zet de cursor op de invoegpositie. cursor() klemt af op het laatste teken " van de regel, dus aan het regeleinde is nog een nodig om erachter " te komen; die gaat via feedkeys en landt na terugkeer in insert-mode. function! s:place_cursor(row, col) abort call cursor(a:row, a:col) if col('.') < a:col call feedkeys("\", 'n') endif endfunction " Voor in insert-mode. Moet puur zijn: een -mapping mag de " buffer niet wijzigen (E565), dus alleen toetsen teruggeven. De invoeging " loopt via , dat als onbeperkt commando zonder moduswissel draait. function! deepseek_fim#tab() abort if deepseek_fim#has_ghost() return "\call deepseek_fim#accept()\" endif return "\" endfunction function! deepseek_fim#on_stdout(channel, msg) abort if type(a:msg) == v:t_list for l:line in a:msg call s:handle_line(l:line) endfor else call s:handle_line(a:msg) endif endfunction function! deepseek_fim#on_stderr(channel, msg) abort if get(g:, 'deepseek_fim_debug', 0) echom 'deepseek_fim[backend]: ' . ( \ type(a:msg) == v:t_list ? join(a:msg, "\n") : a:msg) endif endfunction function! deepseek_fim#on_exit(job, status) abort let s:job = v:null if !s:enabled return endif echohl WarningMsg echom 'deepseek_fim: backend exited (status ' . a:status \ . '), restarting...' echohl None if s:restart_timer != -1 call timer_stop(s:restart_timer) endif let s:restart_timer = timer_start(2000, \ function('deepseek_fim#restart_cb')) endfunction function! deepseek_fim#restart_cb(timer) abort let s:restart_timer = -1 if s:enabled && !deepseek_fim#is_running() call deepseek_fim#start_backend() endif endfunction " Drop a stale in-flight request when the popup closes. function! deepseek_fim#on_complete_done() abort let s:req_id += 1 call deepseek_fim#hide_ghost() endfunction