ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/vim/plugin/mcp-vim.vim
Revision: 1.4
Committed: Wed Oct 14 09:17:39 2026 UTC (3 weeks ago) by root
Branch: MAIN
Changes since 1.3: +8 -2 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 " mcp-vim.vim - Vim client for the mcp-vim broker (protocol version 1.0).
2 "
3 " The broker exposes live Vim buffers to MCP clients and also supports
4 " browser-initiated editing sessions. Vim itself uses a private protocol
5 " to talk to the broker; it is not an MCP client.
6 "
7 " Installation:
8 " In the Perl source distribution: vim/plugin/mcp-vim.vim
9 " Published URL: https://dist.schmorp.de/mcp-vim/1/mcp-vim.vim
10 " Copy the file to ~/.vim/plugin/mcp-vim.vim to load it at startup,
11 " or load it manually with :source /path/to/mcp-vim.vim.
12 "
13 " Usage:
14 " :Mcp http://HOST:PORT/COOKIE/TARGET
15 "
16 " The broker supplies the connection URL, including its authentication
17 " cookie and the target name. To avoid typing the common prefix, set
18 " this in your vimrc:
19 "
20 " let g:mcp_broker_url = 'http://HOST:PORT/COOKIE/'
21 "
22 " Then connect with :Mcp TARGET. Disconnected sessions are retried.
23 " McpHasTarget() reports whether a target URL has been configured.
24 "
25 " The /1/ in the distribution URL denotes the private Vim/broker
26 " protocol major version, not the MCP protocol version.
27 "
28 " Restart Vim after updating this file; re-sourcing does not reload it.
29
30 if exists ('g:loaded_mcp_vim')
31 finish
32 endif
33 let g:loaded_mcp_vim = 1
34
35 let s:prot_major = 1
36 let s:prot_minor = 0
37
38 let s:instance_id = hostname () . ':' . getpid () . ':' . localtime ()
39 if has ('reltime')
40 let s:instance_id .= ':' . reltimestr (reltime ())
41 endif
42
43 let s:channel = v:null
44 let s:sessions = {}
45 let s:popup = 0
46 let s:url = ''
47 let s:target = ''
48 let s:retry_timer = -1
49 let s:incoming = v:null
50
51 command! -nargs=1 Xpcse call s:connect (<f-args>)
52 command! -nargs=1 Mcp call s:connect (<f-args>)
53
54 function! McpHasTarget () abort
55 return !empty (s:url)
56 endfunction
57
58 function! s:stop_retry () abort
59 if s:retry_timer != -1
60 call timer_stop (s:retry_timer)
61 let s:retry_timer = -1
62 endif
63 endfunction
64
65 function! s:retry (timer) abort
66 if type (s:channel) != v:t_channel
67 echom 'mcp-vim: reconnecting to ' . s:target
68 call s:connect (s:url)
69 endif
70 endfunction
71
72 function! s:quit () abort
73 if type (s:channel) == v:t_channel
74 if ch_status (s:channel) ==# 'open'
75 call ch_sendexpr (s:channel, ['quit'])
76 endif
77 call ch_close (s:channel)
78 let s:channel = v:null
79 endif
80 endfunction
81
82 function! s:connect (url) abort
83 let url = a:url
84
85 if url !~# '^http://'
86 let url = get (g:, 'mcp_broker_url', '') . url
87 endif
88
89 let s:url = url
90
91 let m = matchlist (url, '^http://\([^:/]*\):\([0-9]\+\)/\([^/]\+\)/\(.*\)$')
92
93 if empty (m)
94 echoerr "Bad mcp-vim broker URL"
95 return
96 endif
97
98 call s:quit ()
99
100 let host = m[1]
101 let port = m[2]
102 let cookie = m[3]
103 let id = m[4]
104 let s:target = id
105
106 let s:channel = ch_open (host . ':' . port, {
107 \ 'callback': function ('s:receive'),
108 \ 'close_cb': function ('s:disconnected'),
109 \ })
110
111 if ch_status (s:channel) ==# 'open'
112 call s:stop_retry ()
113
114 call ch_sendexpr (s:channel, ['mcp-vim-connect', s:prot_major, s:prot_minor, cookie, id, s:instance_id])
115
116 for session in values (s:sessions)
117 call ch_sendexpr (s:channel, ['session', session.session, session.state])
118 endfor
119
120 call ch_sendexpr (s:channel, ['sessions-done'])
121 else
122 let s:channel = v:null
123 echom 'mcp-vim: connection failed'
124 endif
125 endfunction
126
127 function! s:disconnected (channel) abort
128 echom 'mcp-vim: disconnected from ' . s:target
129 let s:channel = v:null
130
131 if s:retry_timer == -1
132 let s:retry_timer = timer_start (1000, function ('s:retry'), { 'repeat': 60 })
133 endif
134 endfunction
135
136 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
137 " RPC support.
138 "
139 " broker -> vim: ['call', id, method, args...]
140 " vim -> broker: ['reply', id, success, result] " result is an exception string on failure
141 "
142 " Methods:
143 " state ()
144 " read_lines (buffer, ranges)
145 " grep (buffers, pattern, mode, max_results)
146 " replace_lines (buffer, line, old_lines, new_lines, expected_changedtick)
147 " apply_patch (buffer, patch, max_offsets, expected_changedtick) " requires ordinary unified diff; MCP wrapper may relax @@ headers
148 " substitute (buffer, range, pattern, replacement, flags, expected_changedtick)
149 " set_cursor (buffer, line, col [, expected_changedtick])
150 " ex (command) " unrestricted; broker checks exec permission before sending
151 "
152 " Explicit buffer ids are loaded on demand. In state, changedtick and line_count
153 " are v:null until a buffer has been loaded.
154
155 let s:rpc_sid = expand ('<SID>')
156
157 function! s:rpc_bufinfo (buf) abort
158 let info = getbufinfo (a:buf)
159
160 if empty (info)
161 throw 'rpc/no_such_buffer: ' . a:buf
162 endif
163
164 if !info[0].loaded
165 call bufload (a:buf)
166 let info = getbufinfo (a:buf)
167
168 if empty (info) || !info[0].loaded
169 throw 'rpc/cannot_load_buffer: ' . a:buf
170 endif
171 endif
172
173 return info[0]
174 endfunction
175
176 function! s:rpc_expect_tick (expected) abort
177 if b:changedtick != a:expected
178 throw printf ('rpc/stale_buffer: expected %d, got %d', a:expected, b:changedtick)
179 endif
180 endfunction
181
182 function! s:rpc_break_undo () abort
183 let &g:undolevels = &g:undolevels
184 endfunction
185
186 " Execute with {buf} current, while disturbing the user's window/buffer/cursor state as little as possible.
187 function! s:rpc_in_buffer (buf, fun, ...) abort
188 let restoreview = !a:0 || a:1
189
190 let info = s:rpc_bufinfo (a:buf)
191 let oldwin = win_getid ()
192 let oldbuf = bufnr ('%')
193 let oldview = winsaveview ()
194
195 try
196 if a:buf != oldbuf
197 if !empty (info.windows)
198 noautocmd call win_gotoid (info.windows[0])
199
200 if win_getid () != info.windows[0]
201 throw 'rpc/cannot_enter_window: ' . info.windows[0]
202 endif
203 else
204 execute 'noautocmd keepalt keepjumps hide buffer ' . a:buf
205 endif
206 endif
207
208 let targetwin = win_getid ()
209 let targetview = winsaveview ()
210
211 try
212 return call (a:fun, [])
213 finally
214 if restoreview
215 \ && win_getid () == targetwin
216 \ && bufnr ('%') == a:buf
217 call winrestview (targetview)
218 endif
219 endtry
220 finally
221 noautocmd call win_gotoid (oldwin)
222
223 if win_getid () != oldwin
224 throw 'rpc/cannot_restore_window: ' . oldwin
225 endif
226
227 if bufnr ('%') != oldbuf
228 execute 'noautocmd keepalt keepjumps hide buffer ' . oldbuf
229 endif
230
231 " Restore the caller's original view unless that is the buffer
232 " we deliberately modified and want Vim's adjustment to survive.
233 if restoreview || oldbuf != a:buf
234 call winrestview (oldview)
235 endif
236 endtry
237 endfunction
238
239 " Validate a small Ex-range subset, then let Ex resolve it.
240 " A range-function gets the resolved addresses in a:firstline/a:lastline.
241 "
242 " range := % | address ([,;] address)?
243 " address := base offset* | offset+
244 " base := . | $ | [1-9][0-9]* | /regexp/ | ?regexp?
245 " offset := [+-][0-9]*
246 " regexp := one or more non-delimiter characters; backslash escapes
247 " the following character, including the delimiter
248 let s:rpc_range_result = v:null
249
250 function! s:rpc_capture_range () range abort
251 let s:rpc_range_result = [a:firstline, a:lastline]
252 endfunction
253
254 function! s:rpc_validate_range (range) abort
255 if a:range =~# '[\r\n]'
256 throw 'rpc/bad_range: ' . a:range
257 endif
258
259 let fwd_char = '\%([^/\\]\|\\.\)'
260 let bwd_char = '\%([^?\\]\|\\.\)'
261 let fwd = '/' . fwd_char . '\+/'
262 let bwd = '?' . bwd_char . '\+?'
263 let base = '\%([.$]\|[1-9][0-9]*\|' . fwd . '\|' . bwd . '\)'
264 let offset = '[+-][0-9]*'
265 let address = '\%(' . base . '\%(' . offset . '\)*\|\%(' . offset . '\)\+\)'
266 let range = '\%(%\|' . address . '\%([,;]' . address . '\)\?\)'
267
268 if a:range !~# '^' . range . '$'
269 throw 'rpc/bad_or_unsupported_range: ' . a:range
270 endif
271 endfunction
272
273 function! s:rpc_range (range, line_count) abort
274 call s:rpc_validate_range (a:range)
275
276 let range = a:range
277 let start = matchlist (range, '^\([1-9][0-9]*\)\([,;]\)')
278 let end = matchlist (range, '\([,;]\)\([1-9][0-9]*\)$')
279
280 if !empty (start) && str2nr (start[1]) > a:line_count
281 throw printf ('rpc/range_start_beyond_eof: %d > %d', str2nr (start[1]), a:line_count)
282 endif
283
284 if !empty (end) && str2nr (end[2]) > a:line_count
285 let range = substitute (range, '\([,;]\)[1-9][0-9]*$', '\1' . a:line_count, '')
286 elseif range =~# '^[1-9][0-9]*$' && str2nr (range) > a:line_count
287 throw printf ('rpc/range_start_beyond_eof: %d > %d', str2nr (range), a:line_count)
288 endif
289
290 let pos = getpos ('.')
291 let s:rpc_range_result = v:null
292
293 try
294 execute 'silent keepjumps keeppatterns ' . range . ' call ' . s:rpc_sid . 'rpc_capture_range ()'
295 finally
296 call setpos ('.', pos)
297 endtry
298
299 if type (s:rpc_range_result) != v:t_list
300 throw 'rpc/bad_range: ' . a:range
301 endif
302
303 return s:rpc_range_result
304 endfunction
305
306 " execute() captures messages without suppressing command errors.
307 " Commands retain their full authority and run in the current editor context.
308 function! s:rpc_call_ex (command) abort
309 return {'output': execute (a:command)}
310 endfunction
311
312 function! s:rpc_call_state () abort
313 let buffers = []
314
315 for info in getbufinfo ()
316 call add (buffers, {
317 \ 'buffer': info.bufnr,
318 \ 'name': info.name,
319 \ 'listed': info.listed ? v:true : v:false,
320 \ 'modified': info.changed ? v:true : v:false,
321 \ 'changedtick': info.loaded ? info.changedtick : v:null,
322 \ 'line_count': info.loaded ? info.linecount : v:null,
323 \ 'buftype': getbufvar (info.bufnr, '&buftype'),
324 \ 'filetype': getbufvar (info.bufnr, '&filetype'),
325 \ })
326 endfor
327
328 return {
329 \ 'cwd': getcwd (),
330 \ 'current_buffer': bufnr ('%'),
331 \ 'cursor': {'line': line ('.'), 'column': col ('.')},
332 \ 'buffers': buffers,
333 \ }
334 endfunction
335
336 function! s:rpc_call_apply_patch (buf, patch, max_offsets, expected_changedtick) abort
337 return s:rpc_in_buffer (a:buf, {-> s:rpc_apply_patch (
338 \ a:patch,
339 \ a:max_offsets,
340 \ a:expected_changedtick
341 \ )}, v:false)
342 endfunction
343
344 function! s:rpc_apply_patch (patch, max_offsets, expected_changedtick) abort
345 call s:rpc_expect_tick (a:expected_changedtick)
346
347 if !&modifiable
348 throw 'rpc/not_modifiable'
349 endif
350
351 let old_lines = getline (1, '$')
352 let oldfile = tempname ()
353 let newfile = tempname ()
354
355 try
356 " Patch complete logical lines, independently of the buffer's &endofline.
357 " writefile(..., 'b') needs a final empty list item to write the last NL.
358 if writefile (old_lines + [''], oldfile, 'b')
359 throw 'rpc/patch_write_failed'
360 endif
361
362 " patch does all unified-diff parsing/matching. It never modifies the
363 " Vim buffer. Keep rejects out of the filesystem.
364 let cmd = 'LC_ALL=C patch --unified --batch --forward --get=0 --fuzz=0'
365 \ . ' --reject-file=- --no-backup-if-mismatch'
366 \ . ' -o ' . shellescape (newfile)
367 \ . ' ' . shellescape (oldfile)
368 \ . ' 2>&1'
369
370 let output = system (cmd, a:patch)
371 let status = v:shell_error
372
373 if status
374 throw printf (
375 \ 'rpc/patch_failed: exit=%d %s',
376 \ status,
377 \ substitute (trim (output), "\n", ' | ', 'g')
378 \ )
379 endif
380
381 " --fuzz=0 still permits relocating whole hunks. The MCP wrapper rejects
382 " ambiguous pure insertions and limits relocation by distinct old-side lines.
383 for line in split (output, "\n")
384 let match = matchlist (line, '^Hunk #\(\d\+\).*\<offset\s\+\([+-]\=\d\+\)\s\+lines\?\>')
385
386 if !empty (match)
387 let hunk = str2nr (match[1])
388 let offset = str2nr (match[2])
389
390 if hunk < 1 || hunk > len (a:max_offsets)
391 throw 'rpc/patch_bad_output: ' . substitute (trim (output), "\n", ' | ', 'g')
392 endif
393
394 if abs (offset) > a:max_offsets[hunk - 1]
395 throw printf ('rpc/patch_needs_more_context: hunk=%d offset=%d max=%d %s',
396 \ hunk, offset, a:max_offsets[hunk - 1],
397 \ substitute (trim (output), "\n", ' | ', 'g'))
398 endif
399 endif
400 endfor
401
402 " Require complete lines in nonempty patch output. A diff containing
403 " a new-side no-EOL marker can otherwise remove the final NL.
404 " Empty output represents Vim's single empty logical line.
405 let new_lines = readfile (newfile, 'b')
406
407 if !empty (new_lines)
408 if new_lines[-1] !=# ''
409 throw 'rpc/patch_missing_eol'
410 endif
411 call remove (new_lines, -1)
412 endif
413
414 " Vim always has at least one logical line.
415 if empty (new_lines)
416 let new_lines = ['']
417 endif
418
419 let hunks = diff (old_lines, new_lines, {'output': 'indices'})
420
421 if empty (hunks)
422 return {
423 \ 'changedtick': b:changedtick,
424 \ 'hunks': 0,
425 \ 'noop': v:true,
426 \ }
427 endif
428
429 " Nothing has touched the buffer yet. Recheck immediately before commit.
430 call s:rpc_expect_tick (a:expected_changedtick)
431 call s:rpc_break_undo ()
432
433 " diff() indices refer to the original buffer. Apply bottom-up so earlier
434 " line numbers never move underneath later hunks.
435 let changed = 0
436
437 for hunk in reverse (copy (hunks))
438 let first = hunk.from_idx + 1
439 let old_count = hunk.from_count
440 let new_count = hunk.to_count
441 let common = min ([old_count, new_count])
442
443 let replacement = new_count
444 \ ? new_lines[hunk.to_idx : hunk.to_idx + new_count - 1]
445 \ : []
446
447 " Pure insertion: from_idx is the zero-based insertion position.
448 if !old_count
449 if changed
450 undojoin
451 endif
452
453 if append (first - 1, replacement)
454 throw 'rpc/append_failed'
455 endif
456
457 let changed = 1
458 continue
459 endif
460
461 if common
462 if changed
463 undojoin
464 endif
465
466 if setline (first, replacement[:common - 1])
467 throw 'rpc/setline_failed'
468 endif
469
470 let changed = 1
471 endif
472
473 if new_count < old_count
474 if changed
475 undojoin
476 endif
477
478 if deletebufline (
479 \ bufnr ('%'),
480 \ first + new_count,
481 \ first + old_count - 1
482 \ )
483 throw 'rpc/deletebufline_failed'
484 endif
485
486 let changed = 1
487
488 elseif new_count > old_count
489 if changed
490 undojoin
491 endif
492
493 if append (
494 \ first + old_count - 1,
495 \ replacement[old_count:]
496 \ )
497 throw 'rpc/append_failed'
498 endif
499
500 let changed = 1
501 endif
502 endfor
503
504 return {
505 \ 'changedtick': b:changedtick,
506 \ 'hunks': len (hunks),
507 \ }
508
509 finally
510 call delete (oldfile)
511 call delete (newfile)
512 endtry
513 endfunction
514
515 function! s:rpc_read_ranges (buf, ranges) abort
516 let result = []
517 let line_count = s:rpc_bufinfo (a:buf).linecount
518
519 for range in a:ranges
520 let [first, last] = s:rpc_range (range, line_count)
521 call add (result, {'range': range, 'start': first, 'end': last, 'lines': getline (first, last)})
522 endfor
523
524 return {'changedtick': b:changedtick, 'ranges': result}
525 endfunction
526
527 function! s:rpc_call_read_lines (buf, ranges) abort
528 return s:rpc_in_buffer (a:buf, {-> s:rpc_read_ranges (a:buf, a:ranges)})
529 endfunction
530
531 " :global does the actual scan; this function merely collects matching lines.
532 let s:rpc_grep_result = []
533 let s:rpc_grep_pattern = ''
534 let s:rpc_grep_max = 0
535
536 function! s:rpc_grep_collect () abort
537 if len (s:rpc_grep_result) >= s:rpc_grep_max
538 return
539 endif
540
541 let text = getline ('.')
542
543 call add (s:rpc_grep_result, {
544 \ 'buffer': bufnr ('%'),
545 \ 'changedtick': b:changedtick,
546 \ 'line': line ('.'),
547 \ 'column': match (text, s:rpc_grep_pattern) + 1,
548 \ 'text': text,
549 \ })
550 endfunction
551
552 function! s:rpc_grep_buffer () abort
553 let save_search = @/
554
555 try
556 let @/ = s:rpc_grep_pattern
557 execute 'silent keepjumps keeppatterns global//call ' . s:rpc_sid . 'rpc_grep_collect()'
558 finally
559 let @/ = save_search
560 endtry
561 endfunction
562
563 function! s:rpc_call_grep (buffers, pattern, mode, max_results) abort
564 if a:max_results <= 0
565 throw 'rpc/bad_max_results: ' . a:max_results
566 endif
567
568 if a:mode ==# 'regex'
569 let s:rpc_grep_pattern = a:pattern
570 elseif a:mode ==# 'word'
571 let s:rpc_grep_pattern = '\V\<' . escape (a:pattern, '\') . '\>'
572 else
573 throw 'rpc/bad_grep_mode: ' . a:mode
574 endif
575
576 let s:rpc_grep_result = []
577 let s:rpc_grep_max = a:max_results
578 let buffers = empty (a:buffers) ? map (filter (getbufinfo (), 'v:val.loaded'), 'v:val.bufnr') : a:buffers
579
580 for buf in buffers
581 call s:rpc_in_buffer (buf, {-> s:rpc_grep_buffer ()})
582
583 if len (s:rpc_grep_result) >= s:rpc_grep_max
584 break
585 endif
586 endfor
587
588 return {'matches': s:rpc_grep_result, 'truncated': len (s:rpc_grep_result) >= s:rpc_grep_max}
589 endfunction
590
591 " Quote / as an Ex :substitute delimiter without changing replacement backslash semantics.
592 " A / preceded by an even-length run of backslashes needs one more backslash;
593 " with an odd-length run it is already quoted for the command parser. An odd
594 " trailing run also needs one more backslash so it cannot quote the closing /.
595 function! s:rpc_quote_substitute_replacement (text) abort
596 let result = ''
597 let backslashes = 0
598
599 for char in split (a:text, '\zs')
600 if char ==# '\'
601 let backslashes += 1
602 else
603 if char ==# '/' && backslashes % 2 == 0
604 let result .= '\'
605 endif
606
607 let backslashes = 0
608 endif
609
610 let result .= char
611 endfor
612
613 if backslashes % 2
614 let result .= '\'
615 endif
616
617 return result
618 endfunction
619
620 function! s:rpc_insert_lines (line, lines, expected_changedtick) abort
621 if a:line < 0 || a:line > line ('$')
622 throw printf ('rpc/bad_insert_line: %d', a:line)
623 endif
624
625 call s:rpc_expect_tick (a:expected_changedtick)
626 call s:rpc_break_undo ()
627
628 if append (a:line, a:lines)
629 throw 'rpc/append_failed'
630 endif
631
632 return {
633 \ 'changedtick': b:changedtick,
634 \ 'start': a:line + 1,
635 \ 'end': a:line + len (a:lines),
636 \ }
637 endfunction
638
639 function! s:rpc_call_insert_lines (buf, line, lines, expected_changedtick) abort
640 return s:rpc_in_buffer (a:buf, {-> s:rpc_insert_lines (
641 \ a:line,
642 \ a:lines,
643 \ a:expected_changedtick
644 \ )})
645 endfunction
646
647 function! s:rpc_substitute (range, pattern, replacement, flags, expected_changedtick) abort
648 call s:rpc_expect_tick (a:expected_changedtick)
649 call s:rpc_validate_range (a:range)
650
651 if a:flags !~# '^[egiInp#lr]*$'
652 throw 'rpc/bad_substitute_flags: ' . a:flags
653 endif
654
655 if strpart (a:replacement, 0, 2) ==# '\='
656 throw 'rpc/expression_replacement_not_allowed'
657 endif
658
659 let save_search = @/
660 let replacement = s:rpc_quote_substitute_replacement (a:replacement)
661
662 call s:rpc_break_undo ()
663
664 try
665 let @/ = a:pattern
666 execute 'silent keepjumps keeppatterns ' . a:range . 's//' . replacement . '/' . a:flags
667 finally
668 let @/ = save_search
669 endtry
670
671 return {'changedtick': b:changedtick, 'changed': b:changedtick != a:expected_changedtick}
672 endfunction
673
674 function! s:rpc_call_substitute (buf, range, pattern, replacement, flags, expected_changedtick) abort
675 return s:rpc_in_buffer (a:buf, {-> s:rpc_substitute (a:range, a:pattern, a:replacement, a:flags, a:expected_changedtick)})
676 endfunction
677
678 function! s:rpc_call_set_cursor (buf, line, col, ...) abort
679 let info = s:rpc_bufinfo (a:buf)
680
681 if a:0 && a:1 isnot v:null && info.changedtick != a:1
682 throw printf ('rpc/stale_buffer: expected %d, got %d', a:1, info.changedtick)
683 endif
684
685 if a:line < 1 || a:line > info.linecount || a:col < 1
686 throw printf ('rpc/bad_cursor: %d,%d', a:line, a:col)
687 endif
688
689 if a:buf != bufnr ('%')
690 if !empty (info.windows)
691 if !win_gotoid (info.windows[0])
692 throw 'rpc/cannot_enter_window: ' . info.windows[0]
693 endif
694 else
695 execute 'keepalt keepjumps hide buffer ' . a:buf
696 endif
697 endif
698
699 call cursor (a:line, a:col)
700
701 return {'buffer': bufnr ('%'), 'changedtick': b:changedtick, 'line': line ('.'), 'column': col ('.')}
702 endfunction
703
704 """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
705 " command receiver
706
707 function! s:receive (channel, msg) abort
708 if type (a:msg) != v:t_list || len (a:msg) == 0
709 return
710 endif
711
712 let cmd = a:msg[0]
713
714 if cmd ==# 'call'
715 let id = a:msg[1]
716 let method = a:msg[2]
717 let args = a:msg[3:]
718
719 try
720 let result = call (function('s:rpc_call_' . method), args)
721 call ch_sendexpr (s:channel, ['reply', id, 1, result])
722 catch
723 call ch_sendexpr (s:channel, ['reply', id, 0, v:exception]) " originallky also: v:throwpoint
724 endtry
725
726 elseif cmd ==# 'open'
727 let session = a:msg[1]
728 let filename = a:msg[2]
729 let extension = a:msg[3]
730 let state = a:msg[4]
731
732 let path = tempname() . '-' . filename . extension
733 let s:incoming = { 'path': path, 'session': session, 'state': state }
734 call writefile ([], path)
735
736 elseif cmd ==# 'data'
737 let data = base64_decode (a:msg[1])
738 call ch_sendexpr (s:channel, ['ack', len (data)])
739 call writefile (data, s:incoming.path, 'ab')
740
741 elseif cmd ==# 'ack'
742 " nop
743
744 elseif cmd ==# 'eof'
745 if a:msg[1]
746 execute 'edit ' . fnameescape (s:incoming.path)
747 let s:sessions[bufnr('%')] = { 'session': s:incoming.session, 'state': s:incoming.state, 'path': s:incoming.path }
748 else
749 call delete (s:incoming.path)
750 endif
751
752 let s:incoming = v:null
753
754 elseif cmd ==# 'ex'
755 execute a:msg[1]
756
757 elseif cmd ==# 'echo'
758 if s:popup
759 call popup_close (s:popup)
760 endif
761 echom 'mcp-vim: ' . a:msg[1]
762
763 elseif cmd ==# 'error'
764 if s:popup
765 call popup_close (s:popup)
766 endif
767 let s:popup = popup_create (split (a:msg[1], "\n", 1), { 'line': &lines - 2, 'col': 1, 'pos': 'botleft', 'maxheight': 10, 'maxwidth': &columns - 4, 'scrollbar': 1, 'padding': [0, 1, 0, 1] })
768
769 elseif cmd ==# 'goto'
770 for b in keys (s:sessions)
771 if s:sessions[b].session ==# a:msg[1]
772 execute 'buffer ' . b
773 call cursor (a:msg[2], a:msg[3])
774 break
775 endif
776 endfor
777
778 else
779 echom 'mcp-vim: unknown command ' . string (cmd)
780 endif
781 endfunction
782
783 function! s:save (file) abort
784 if type (s:channel) != v:t_channel
785 return
786 endif
787
788 let b = bufnr ('%')
789
790 if has_key (s:sessions, b) && a:file ==# s:sessions[b].path
791 call ch_sendexpr (s:channel, ['save', s:sessions[b].session])
792
793 let data = readblob (s:sessions[b].path)
794 call ch_sendexpr (s:channel, ['data', base64_encode (data)])
795 call ch_sendexpr (s:channel, ['eof', 1])
796
797 endif
798 endfunction
799
800 function! s:close (buf) abort
801 if has_key (s:sessions, a:buf)
802 call delete (s:sessions[a:buf].path)
803 if type (s:channel) == v:t_channel
804 call ch_sendexpr (s:channel, ['close', s:sessions[a:buf].session])
805 endif
806 call remove (s:sessions, a:buf)
807 endif
808 endfunction
809
810 augroup mcp_vim
811 autocmd!
812
813 autocmd BufWritePost * call s:save (expand ('<afile>:p'))
814 autocmd BufUnload * call s:close (str2nr (expand ('<abuf>')))
815 autocmd VimLeavePre * call s:quit ()
816 augroup END
817