|
| 1 | +" dispatch.vim terminal strategy |
| 2 | + |
| 3 | +if exists('g:autoloaded_dispatch_terminal') |
| 4 | + finish |
| 5 | +endif |
| 6 | +let g:autoloaded_dispatch_terminal = 1 |
| 7 | + |
| 8 | +if !exists('s:waiting') |
| 9 | + let s:waiting = {} |
| 10 | +endif |
| 11 | + |
| 12 | +function! dispatch#terminal#handle(request) abort |
| 13 | + if !get(g:, 'dispatch_experimental', 1) |
| 14 | + return 0 |
| 15 | + endif |
| 16 | + if !(has('terminal') || has('nvim')) || a:request.action !=# 'start' |
| 17 | + return 0 |
| 18 | + endif |
| 19 | + |
| 20 | + let a:request.handler = 'terminal' |
| 21 | + let winid = win_getid() |
| 22 | + |
| 23 | + if has('nvim') |
| 24 | + exe a:request.mods 'new' |
| 25 | + let options = { |
| 26 | + \ 'on_exit': function('s:exit', [a:request]), |
| 27 | + \ } |
| 28 | + let job = termopen(a:request.expanded, options) |
| 29 | + let a:request.bufnr = bufnr('') |
| 30 | + let a:request.pid = jobpid(job) |
| 31 | + |
| 32 | + if !a:request.background |
| 33 | + startinsert |
| 34 | + endif |
| 35 | + else |
| 36 | + let winid = win_getid() |
| 37 | + exe a:request.mods 'split' |
| 38 | + let options = { |
| 39 | + \ 'exit_cb': function('s:exit', [a:request]), |
| 40 | + \ 'term_name': '!' . a:request.expanded, |
| 41 | + \ 'term_finish': 'open', |
| 42 | + \ 'curwin': 1, |
| 43 | + \ } |
| 44 | + let a:request.bufnr = term_start([&shell, &shellcmdflag, a:request.expanded], options) |
| 45 | + let job = term_getjob(a:request.bufnr) |
| 46 | + let a:request.pid = job_info(job).process |
| 47 | + endif |
| 48 | + |
| 49 | + if a:request.background |
| 50 | + call win_gotoid(winid) |
| 51 | + endif |
| 52 | + |
| 53 | + let s:waiting[a:request.pid] = a:request |
| 54 | + call writefile([a:request.pid], a:request.file . '.pid') |
| 55 | + |
| 56 | + return 1 |
| 57 | +endfunction |
| 58 | + |
| 59 | +function! s:exit(request, job, status, ...) abort |
| 60 | + unlet! s:waiting[a:request.pid] |
| 61 | + call writefile([a:status], a:request.file . '.complete') |
| 62 | + |
| 63 | + let wait = get(a:request, 'wait', 'error') |
| 64 | + if wait ==# 'never' || (wait !=# 'always' && a:status == 0) |
| 65 | + silent exec 'bdelete! ' . a:request.bufnr |
| 66 | + endif |
| 67 | +endfunction |
| 68 | + |
| 69 | +function! dispatch#terminal#activate(pid) abort |
| 70 | + if has_key(s:waiting, a:pid) |
| 71 | + let request = s:waiting[a:pid] |
| 72 | + let pre = &switchbuf |
| 73 | + |
| 74 | + try |
| 75 | + let &switchbuf = 'useopen,usetab' |
| 76 | + silent exe request.mods 'sbuffer' request.bufnr |
| 77 | + finally |
| 78 | + let &switchbuf = pre |
| 79 | + endtry |
| 80 | + return 1 |
| 81 | + endif |
| 82 | + |
| 83 | + return 0 |
| 84 | +endfunction |
0 commit comments